Read more : http://www.ehow.com/how_8498918_remove-title-blogger-pages.html

Thursday, 14 August 2014

Spring Batch Condition Based Example

Hi,

It is possible to apply if else logic in spring batch, usually we will call this as condition based execution of steps.
In brief if the condition is true go and execute step1 or go and execute step2.
To achieve if - else logic in spring batch we have to use decision tag provided by spring batch.

Following example explains how to achieve if else logic in spring batch.

For More examples on Spring batch and Java .. Please refer

jobs.xml

<!-- *************************************************************************************************************************************** -->
<!-- Condition Based excutions (Same as If/Else logic in Java) -->
*************************************************************************************************************************************** -->

<batch:job id="conditionJob" parent="simpleJob">
<batch:step id="masterBrain" next="decision">
<batch:tasklet ref="dummyJob" />
</batch:step>
<batch:decision decider="decider" id="decision">
<batch:next on="masterMind" to="masterMind" />
<batch:next on="dummyMind" to="dummyMind" />
</batch:decision>

<batch:step id="masterMind">
<batch:tasklet ref="sayHello"/>
</batch:step>
<batch:step id="dummyMind">
 <batch:tasklet ref="sayBye"/>
</batch:step>
</batch:job>

           <!-- Decision maker -->
<bean id="decider" class="com.springbatchdemo.utils.Decider"/>
<bean id="dummyJob" class="com.springbatchdemo.tasklet.Dummy" />
        <bean id="sayHello" class="com.springbatchdemo.tasklet.SayHello" />
        <bean id="sayBye" class="com.springbatchdemo.tasklet.SayBye" />

Decider.java
public class Decider implements JobExecutionDecider{
@Override
public FlowExecutionStatus decide(JobExecution arg0, StepExecution arg1) {
if(true){
return new FlowExecutionStatus("masterMind");
}else{
return new FlowExecutionStatus("dummyMind");
}

}

Dummy.java
public class Dummy implements Tasklet
{
 @Override public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception
{
 return RepeatStatus.FINISHED;
 }
 }


SayHello.java

public class SayHello implements Tasklet 

{
 @Override public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception
{
System.out.println("From Hi");
 return RepeatStatus.FINISHED;
 }
 }

SayBye.java
public class SayBye implements Tasklet 

{
 @Override public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception
{
System.out.println("From Bye");
 return RepeatStatus.FINISHED;
 }
 }

Hope  above small example help you in designing condition based implementation in spring batch. 

Friday, 1 August 2014

Abstract Factory Design Pattern Example in Java

Hi,

"Abstarct factory " design pattern is used to creating objects of same type(family of same/related objects), without exposing their actual classes to the client or without specifying their classes explicitly.
Here we are mainly concentrating on creating the objects of family of  same type, and hence  this concept comes under creational pattern.

Please refer the below example for better understanding.


I have a factory interface  as follows

public interface FactoryInterface {
void sayHi();
void sayBye();
}

Below two classes implements factory interface

Women Implementation and
public class WomenImplementation implements FactoryInterface{

@Override
public void sayBye() {
System.out.println("Women saying Bye");
}

@Override
public void sayHi() {
System.out.println("Women saying Hi");
}

}

Men Implementation
public class MenImplementation implements FactoryInterface {

@Override
public void sayBye() {
System.out.println("Men saying Bye");
}

@Override
public void sayHi() {
System.out.println("Men Saying Hi");
}

}

If you observe women and men implemenations are belongs to same group or family of type FactoryInterface.

I have a factory controller which actually creates the objects of the classes.

public class FactoryController {
private static FactoryInterface factoryInterface=null;
public static FactoryInterface getInstance(String choice){
if(choice.equalsIgnoreCase("men")){
factoryInterface=new MenImplementation();
}else if(choice.equalsIgnoreCase("women")){
factoryInterface=new WomenImplementation();
}
return factoryInterface;
}

}

And my client class as follows

public class ClientFactory {
public static void main(String[] args) {
FactoryInterface fact1=FactoryController.getInstance("Men");
fact1.sayHi();
fact1.sayBye();
}
}

If you observe , client actually calling controller class by specifieng type of object he wants to create, he is not creating the object of the class, controller will takes care of creating the object of the class based on the client input , and we are completely hiding the data to the client, and only controller is visible to the client.

Please refer the class diagram for the above example.

Sunday, 20 July 2014

Compare two text files in java

Hi,

Some times it is better to know how we can compare two text files using java.
In this post we will see how to compare two text files and writing the missed  data into another text files

Scenorio:

Need to compare database table  unique  column values before modification of sql query and after modification of sql query,After modification of the sql query few records are inserted into the table and few records are deleted from the tables  need to find what are all the records deleted from the table  and what are all the records inserted into the table.


Approaches:

1). There are several ways to compare table data : By taking table data into a temporary table and writing sql join query to achieve it.
2). Get table data into a text files and compare the text files using a java program etc etc.

In this  post we will discuss how to compare two text files using java.

In this example we  are using two text files one text file(File1) contains actual unique ids of the table, and  the other contains unique ids (create and deleted) after performing sql operations on the table.


public class IdCompare {

public static void main(String[] args) throws Exception {

List<String> firstFileList= new ArrayList<String>();
List<String> secondFileList= new ArrayList<String>();

List<String> missingRecordsInFile2= new ArrayList<String>();
List<String> missingRecordsInFile1= new ArrayList<String>();

//read file 1
Scanner firstFile=  new Scanner(new FileReader(new File("C://Users//Desktop//CompareFiles//Main.txt")));

//read file 2

Scanner secondFile=  new Scanner(new FileReader(new File("C://Users//Desktop//CompareFiles//Store6_0509.txt")));

//Write data to a file -- exits in file1 and not in file 2

FileWriter fWriteOne= new FileWriter(new File("C://Users//Desktop//CompareFiles//Output//Store6_0509.txt"));

//Write data to a file -- exits in file2 and not in file 1

FileWriter fWriteTwo= new FileWriter(new File("C://Users//Desktop//CompareFiles//Output//Main_0509.txt"));

while(firstFile.hasNext()){
firstFileList.add(firstFile.next());
}


while(secondFile.hasNext()){
secondFileList.add(secondFile.next());
}


try{

int firstCount= firstFileList.size();
int secondCount= secondFileList.size();

for(String fileOne:firstFileList){
boolean value=secondFileList.contains(fileOne);

if(!value){
missingRecordsInFile2.add(fileOne);
fWriteOne.write(fileOne);
fWriteOne.write(System.getProperty("line.separator"));
}

}

System.out.println("Total Number of records exits in file 1-->  "+firstCount+" Not exists in file 2 --> " +missingRecordsInFile2.size() );


for(String fileTwo:secondFileList){
boolean value=firstFileList.contains(fileTwo);

if(!value){
missingRecordsInFile1.add(fileTwo);
fWriteTwo.write(fileTwo);
fWriteTwo.write(System.getProperty("line.separator"));
}
}
System.out.println("Total Number of records exits in file 2-->  "+secondCount+" Not exists in file 1-->  " +missingRecordsInFile1.size() );

}finally{
fWriteOne.close();
fWriteTwo.close();
}

}
}


Hope this will help you ..

Saturday, 17 May 2014

Calculating Business days in Java

Hi ,

Some times we will get a requirement to calculate business days between given dates or days.
Below program explains you how we can achieve  working days(Business days) by excluding holidays in java.

In the below example I am considering only single day as holiday.
If you want to specify >1 holiday ,  you can use a list and  add all the holidays to list and use the list for calculation.


public class CalculatingBusinessDays {
      public static void main(String[] args) throws ParseException {
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
            Date date = dateFormat.parse("24/12/2012");// Specify the  a date

            int duration = 3;//Specify the duration how many days to increment
            //call the method to get the working days
            getWorkingDaysForADate(date, duration);

      }

      public static Date getWorkingDaysForADate(Date date, int duration) {
            Date dateValue = new Date();
            ArrayList<Integer> holidayList = new ArrayList<Integer>();
            /***************************
            * Holiday date is 25 Dec 2012 So we need to convert this day to actual
            * day in the year Use below code to convert actual date to a day in the
            * year
            *
             * SimpleDateFormat dateFormat=new SimpleDateFormat("dd/MM/yyyy");
             * Date date = dateFormat.parse("25/12/2012");
            * Calendar cal = Calendar.getInstance();
            * cal.setTime(date)
            * cal.get(Calendar.DAY_OF_YEAR)
            *
             ************************************ */

            holidayList.add(360); // 360 is the integer Value of Holiday date(25 dec 2012)
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            for (int i = 0; i < duration; i++) {
                  cal.add(Calendar.DAY_OF_MONTH, 1);
                  while (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY
                              || cal.get(Calendar.DAY_OF_WEEK) == cal.SUNDAY
                              || holidayList.contains((Integer) cal.get(Calendar.DAY_OF_YEAR))) {
                        cal.add(Calendar.DAY_OF_MONTH, 1);

                  }
            }
            dateValue=cal.getTime();
            /******************
            As per the logic we are incrementing days of the date by 3
             so, 24 +3 is 27 but the holiday date is 25 so we are excluding holiday from the day hence the new date
             is 28.
            **********************/
            System.out.println("Date  value is " +dateValue);
            return dateValue;
      }

}

Saturday, 10 May 2014

Calling a Jasper Report that resides in a jasper server

Jasper server is a powerful server which is used to create a jasper report and to save the reports in server.
Which  helps in compiling and generating the reports with huge data.

Mainly jasper server is used to store the reports.So, that we can clearly seperate reports and the application code.

Jasper server provides different ways to call a report  that exists in the jasper server  from a java program.
Jasper server by default provides a REST service to call/down load a report.


Below sample code explains how to call a report/down load a report that exists in jasper server.

Pre requisites:
I assume you have some knowledge on Jasper server and Jasper API.


public class OneMoreTry {
                public static Document stringToDom(String xmlSource) throws SAXException, ParserConfigurationException, IOException {
                 
                                ByteArrayInputStream stream = new ByteArrayInputStream(xmlSource.getBytes());

                                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder builder = factory.newDocumentBuilder();
                                //StringReader sr = new StringReader(xmlSource);
                                //InputSource is = new InputSource(sr);
                 
                    return builder.parse(stream);
                }

                public static String domToString( Document xml ) throws Exception{
                                TransformerFactory tf = TransformerFactory.newInstance();
                                Transformer transformer = tf.newTransformer();
                                transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                                StringWriter writer = new StringWriter();
                                transformer.transform(new DOMSource(xml), new StreamResult(writer));
                                return writer.getBuffer().toString();
                }

public static void main(String[] args) throws Exception {
               //URL on which jasper server is ruuning
                String serverURL = "http://localhost:8080/jasperserver/";
              //report name (in jasper sever we have some sample reports I am using some sample report for the example, below is the path to the report)
                String reportName = "reports/samples/Department";
                String reportFormat = "HTML";

           //Use HTTP clinet,POST,PUT methods to consume REST service of the jasper server

                HttpClient client = new HttpClient();

                // Setting Login URL in a POST method
                String loginURL = serverURL+"rest/login";
                PostMethod postMethod = new PostMethod(loginURL);

                // Set authentication parameters(To connect the jasper server through post methods)
                postMethod.addParameter("j_username", "XXX");
                postMethod.addParameter("j_password", "XXXX");

                // Send POST with login request
                int statusCode = client.executeMethod(postMethod);

                //  Check correct login process
                if (statusCode != HttpStatus.SC_OK) {
                                System.out.println("Login failed: " + postMethod.getStatusLine());
                                return;
                }
                // Settting resource URL in a GET method to get descriptor                      
                String resourceURL = serverURL+"rest/resource/"+reportName;
                GetMethod getMethod = new GetMethod(resourceURL);

                // Send GET request for descriptor
                statusCode = client.executeMethod(getMethod);

                //  Check correct descriptor process
                if (statusCode != HttpStatus.SC_OK) {
                                System.out.println("Descriptor failed: " + getMethod.getStatusLine());
                }

                // Get the response body as String
                String descriptorSource = getMethod.getResponseBodyAsString();

                //Transform descriptor from String into XML Document
                Document descriptorXML = stringToDom(descriptorSource);
                System.out.println("doc:" + descriptorXML.toString());
             
                // Settting PUT method to run report, the url contains the RUN_OUTPUT_FORMAT parameter
                String reportURL = serverURL+"rest/report/"+reportName+"?RUN_OUTPUT_FORMAT="+reportFormat;
                PutMethod putMethod = new PutMethod(reportURL);

                // Setting the request Body. The descriptor XML Document is transform to String and add to the request body.
                putMethod.setRequestBody(domToString(descriptorXML));

                // Send PUT request to execute the report.
                statusCode = client.executeMethod(putMethod);

                //  Check correct report process
                if (statusCode != 201) {
                                System.out.println("Report failed: " + putMethod.getStatusLine());
                }

                // Get the response body
                String reportSource = putMethod.getResponseBodyAsString();

                // Transform report information into XML Document.
                Document reportXML = stringToDom(reportSource);

                // Extrac from XML Document the report's UUID
                NodeList nodes = reportXML.getElementsByTagName("uuid");
                String reportUuid = nodes.item(0).getTextContent();

                // Setting GET request to download the report
                String reportFileURL = serverURL+"rest/report/"+reportUuid;//+"?file=report";
                GetMethod getMethodFile = new GetMethod( reportFileURL );

                //Send GET request to download the report
                statusCode = client.executeMethod(getMethodFile);
             
                //  Check correct report process
                if (statusCode != 200) {
                                System.out.println("Downlaod failed: " + putMethod.getStatusLine());
                }
                // Getting the report body
                byte inbytes[] = new byte[1024];
                InputStream is=  getMethodFile.getResponseBodyAsStream();
                is.read(inbytes);
                String in = new String(inbytes, "cp1252");
                DataOutputStream out = new DataOutputStream(new FileOutputStream("d:/Myjars/hai.pdf"));
                out.writeUTF(in);
             
                //File file = new File("d:/Myjars/hai.pdf");

                //bis.close();
             
             
}
}

Hope this will help you..

Saturday, 3 May 2014

Parsing XML file with JAXB

JAXB is one of the powerful parser, which is used to parse xml file to java object and java object to xml file(i.e; Marshalling and Un marshalling xml files).

Below sample code explains how to use jaxb parser to parse an xml

Jaxb uses xml and xsd to parse xml to java objects.
Jaxb provides xjc compiler which can be used to compile the xsd file , after compiling xsd file with xjc compiler we will get  java class files of each node of the  xml file

I assume you have xsd , xml file and you compiled the xsd file with xjc compiler.

public class JAXBParser {
 //in my xml the root node is student
//get the root node from the xml
//below is the class that we got after compiling the xsd with xjc
jaxbGenerated.Student  studentElement=null; 

private JAXBParser () throws SAXException, JAXBException {
    loadXML();
    }

// Making the class as singleton
    public static synchronized JAXBParser getXMLParserInstance()
            throws SAXException, JAXBException {
        if (xmlParserObj == null) {
            xmlParserObj = new JAXBParser();
        }
        return xmlParserObj;
    }

public void loadXML() throws SAXException, JAXBException {
File xmlDocument = new File("test.xml");
//to get jaxb context object you need to specify the  generated classes contained package
//in my case the package name  jaxbGenerated
JAXBContext jaxbContext = JAXBContext.newInstance("jaxbGenerated");

// Unmarshaller creation which used to convert XML to Java object
        Unmarshaller unMarshaller = jaxbContext.createUnmarshaller();
        // Set the schema on the Unmarshaller object
        SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        javax.xml.validation.Schema schema = schemaFactory.newSchema(new File("test.xsd"));
        unMarshaller.setSchema(schema);
        // Calling unMarshall
        unMarshall(xmlDocument, unMarshaller);
}

/**
     * This method is used to unmarshal the xml Document which identifies rootnode of the xml 
     * @param xmlDocument
     * @param unMarshaller
     */
    public void unMarshall(File xmlDocument, Unmarshaller unMarshaller) {
        try {
            // UnMarshall the XML using unmarshal()
            countryElement = (jaxbGenerated.Student) unMarshaller.unmarshal(xmlDocument);
        }
        catch (JAXBException e) {
                   }
        catch(Exception excep)
        {
                    }

    }


/**
     * This method will give studentnode
     * @return student
     */
    private  Student getStudent(){
        Student studentObj=null;
        studentObj= studentElement;
              return studentObj;
    }

//By using student object we will get student property values
/**
     * This method will give studentName
     *
     * @return  studentName
     */

    public String getStudentName() {
         String studentName= null;
        Student student= getStudent();
        studentName= student.getName();
        return studentName;
    }
   

}

test.xml looks like as follows

<student name="xyz" language="abc">
<child nodes/>
</student>

hope this will help you


Thursday, 1 May 2014

Parallel Step Example

Hi,

Spring batch provides so many features for java batch processing , parallel step process is one of the feature of spring batch frame work.

In the parallel step process we can execute / process independent steps at a time, this will reduce Process time of the job.

Parallel step process is a flavor of multi-threaded process provided by spring batch frame work

Please note this feature will be  used when there is no dependency exists between the steps of a job process.

Following examples explain you how to configure parallel step execution

In this example I am using two tasklets for two steps

1) Tasklet1 prints Hello From Tasklet1
2) Tasklet2  prints Hello from Tasklet2

Job Configuration is as follows:

<batch:job id="parallelStepProcessing">
 <batch:split id="parallelSplit"  task-executor="parallelExecutor">
 <batch:flow>
  <batch:step id="hiTaskelt1">
<batch:tasklet ref="helloTasklet1" />
</batch:step>
</batch:flow>
<batch:flow>
<batch:step id="hiTasklet2">
<batch:tasklet ref="haiTasklet2" />
</batch:step>
</batch:flow>
</batch:split>
</batch:job>
 <bean id="parallelExecutor" class="org.springframework.core.task.SimpleAsyncTaskExecutor"/>

<bean id="helloTasklet1" class="packagename.Tasklet1"/>

<bean id="haiTasklet2" class="packagename.Tasklet2"/>

Please note that a flow should have atleast one step

class Tasklet1 implements Tasklet{
@Override
public RepeatStatus execute(StepContribution stepContri, ChunkContext context) throws Exception{
                 System.out.println("Hello from tasklet1");
return RepeatStatus.FINISHED;

}
}

class Tasklet2 implements Tasklet{
@Override
public RepeatStatus execute(StepContribution stepContri, ChunkContext context) throws Exception{
                 System.out.println("Hello from tasklet2");
return RepeatStatus.FINISHED;

}
}

Please refer http://docs.spring.io/spring-batch/reference/html/scalability.html for more details
Hope this will help you in designing spring batch parallel step process..