Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

January 3, 2013

[Algorithms by Robert Sedgewick] - Solution for problem 1.3.4

Given below is solution to problem 1.3.4 from Algorithms 4th Edition by Robert Sedgewick

1.3.4 Write a stack client Parentheses that reads in a text stream from standard input and uses a stack to determine whether its parentheses are properly balanced. For example, your program should print true for [()]{}{[()()]()} and false for [(]).



May 25, 2012

My Google Code Project : classjarsearch

Working as Java Developer I have faced frequent ClassNotFoundException which is very difficult to resolve unless maven or ivy is being used. I frequently get these errors while integrating a new framework or setting up a new project. Most of the times developer has existing library sitting on their machine but not a quick way to search for the same. I have been working on a simple utility to locate jar files which contain the missing class. This project has been on Google Code for last 2 years. Initially I has used SWT for UI and recently switched to Swing.

This project is available at https://code.google.com/p/classjarsearch/. This tool is very simple and it only has 2 inputs. First text input should be class name that we want to search. Class Name can be either full or partial. It can also be '.' or '/' seperated. Second text input is directory location in which search should be conducted. This can be provided using Browse button which displys a basic file browser. Hit Search button and any jar file which has class that matches input would be displayed.






May 16, 2012

Quartz Scheduler : Trigger in ERROR state

Recently I was working on an old application which uses Quartz 1.8.x for job scheduling. Quartz is my favourite framework for scheduling. I have worked with Quartz for last 5 years and never ever complained about the implemntation and features. Overall I had good development experience with Quartz.

Yesterday I came across a particular issue in which TRIGGER associated with quartz job was moving to ERROR state all of a sudden after job was executed. This was very surprising as there were no logs and I was completely lost. I went through Quartz source code. Recompiled Quartz jar with more verbose logging added. Even these measures did not help.

Then I looked into SCHEDULER_STATE table and came to know that we had two scheduler instances connecting to the same server. One of these had the latest deployment which had no errors in logs and the other instance had old build which was missing my job implementation.

Magic text logged was 'Error retrieving job, setting trigger state to ERROR., class.method=JobStoreTX.triggerFired'

org.quartz.JobPersistenceException: Couldn't retrieve job because a required class was not found: org.xxx.ClassName [See nested exception: java.lang.ClassNotFoundException: org.xxx.ClassName]

If anyone is worried about Trigger setting to ERROR with no logs check all the instance which connect to quartz database. Most probably there will be an error logged in one of the log files. Setting log level to DEBUG would surely help.

September 22, 2011

JRebel - Reload classes at runtime

JRebel is a quality product from ZeroTurnaround.

JRebel aids development process by loading class changes at runtime. It may appear similar to Eclipse WTP platform which also has these capabilities. JRebel is different as it has support for multiple frameworks like Spring, JSF etc.

Currently for any class file changes in Eclipse, if the build is set to automatic, Spring Context is reloaded. Using JRebel we can avoid re-loading the entire context and just load the single class change. It has ability to load Controllers, Entities, Spring Aware Beans and anything else with .java extension. It has helped a lot in reducing development time by saving deployment effort.

More on JRebel at http://www.zeroturnaround.com/jrebel/ and some enjoyable presentations at http://www.zeroturnaround.com/jrebel/presentations/

Evaluation License is valid for 30 days and it is worth a try.

September 4, 2011

How to implement Factory Pattern in Spring Framework ?

Factory design pattern is the simplest creational design pattern. Spring Framework creates and manages life-cycle of multiple beans and provides features like dependency injection. This post documents using Factory Pattern in Spring.

Building Blocks of Implementation - Taking example of Ford Car

Common Interface : A common interface is required to signify an abstract product from factory.
package org.pattern.factory;

public abstract class Ford {

    public abstract String getEngineType();

    public String getCar() {
        return this.getClass().getSimpleName();
    }
}

Concrete Car:
package org.pattern.factory.concrete;

import org.pattern.factory.Ford;

public class Endeavour extends Ford {

    @Override
    public String getEngineType() {
        return "DIESEL";
    }
}

Factory Class: This looks for implementations of Ford.class declared in spring configuration and adds them to HashMap. Factory method to return concrete object uses this HashMap.
package org.pattern.factory;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class FordFactory implements ApplicationContextAware {

    private static ApplicationContext mApplicationContext;

    private static Map<String, String> processorBeanMap = new HashMap<String, String>();

    public static Ford getFord(String carName) throws Exception {

        if (processorBeanMap.size() == 0) {
            throw new Exception("No Car in configuration. Check Spring Context");
        } else {
            String beanName = processorBeanMap.get(carName);

            if (beanName == null) {
                throw new Exception(
                        "No Matching Car found. Check Spring Context");
            }

            Ford bean = (Ford) mApplicationContext.getBean(beanName);

            return bean;
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {

        mApplicationContext = applicationContext;

        Map<String, Ford> processorMap = mApplicationContext
                .getBeansOfType(Ford.class);

        if (processorMap.isEmpty()) {
            Error noProcessorError = new Error(
                    "No Car configured. Check Spring Context");
            throw noProcessorError;
        }

        Set<Entry<String, Ford>> processorEntrySet = processorMap.entrySet();

        Iterator<Entry<String, Ford>> iterator = processorEntrySet.iterator();

        while (iterator.hasNext()) {
            Entry<String, Ford> entry = iterator.next();

            processorBeanMap.put(entry.getValue().getCar(), entry.getKey());
        }
    }
}

Spring Configuration File:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <bean name="CarFactory" class="org.pattern.factory.FordFactory" />

    <bean name="Endevour" class="org.pattern.factory.concrete.Endeavour" />
</beans>

JUnit Test Case:
package org.pattern.factory.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.pattern.factory.Ford;
import org.pattern.factory.FordFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class FactoryTest {

    @Test
    public void testFactory() throws Exception {
        Ford car = FordFactory.getFord("Endeavour");
        System.out.println(car.getCar() + " is of Type " + car.getEngineType());
    }

}

Output:

Endeavour is of Type DIESEL

This is a very simple example of using factory pattern in Spring.

Above post uses Syntax Highlighter from tohtml.com




March 29, 2010

Notes from a long term Eclipse user moving to IntelliJ IDEA

This post is here to document issues/challenges faced when using IntelliJ Idea editor.

I have been using Eclipse as an IDE for development purpose where the main development language is Java. For expanding my existing knowledge base, I am working on a Groovy Project. A quick Google search revealed IntelliJ Idea as having the best Groovy Language support. Very quickly I downloaded the Community Edition of Idea and fired it up. This editor is Swing based and it shows from the look and feel, but I would admit that it is quick and doesn't block the user interaction as Eclipse does. Below I am documenting few issues I have faced and a working resolution.

  • Using Eclipse keyboard shortcuts in Intellij IDEA - For any IDE user, when moving to a completely new IDE the first and foremost challenge faced is different set of keyboard shortcuts in new IDE compared to the one previously used. Thankfully JetBrains (the company behind IDEA) developers acknowledge the presence of other IDE's. It is very easy to set the keymap same as that of Eclipse. In IDEA go to File -> Settings. Search for ‘keymap’ in the textbox. Select ‘Eclipse’ from the keymap dropdown as shown below. Click on ‘OK’. After this configuration change, your default Eclipse keymap will work.


  • Removing svn: unknown host exception in Intellij IDEA SVN Plug-in - While trying to configure a remote subversion repository, I received the error below.

This error was happening because the IDEA needed a proxy configuration to access internet. I had configured proxy at IDE level (using HTTP Proxy from settings). After searching through few forums and IDEA bug tracker, I found that proxy needs to be configured separately for subversion plug-in.  Go to File -> Setings. Search for 'sunversion' and you will get setting page located at 'Version Control -> VCS -> Subversion'. 


Select the checkbox for using proxy configured for IDEA or Select Edit Network options button to configure proxy.