Skip to content

Instantly share code, notes, and snippets.

@akkida746
Created January 5, 2017 11:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akkida746/a04b09cbbdef2b2a46736d24da434915 to your computer and use it in GitHub Desktop.
Save akkida746/a04b09cbbdef2b2a46736d24da434915 to your computer and use it in GitHub Desktop.
Spring batch job execution listener
package com.xyz.batch.listener;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobExecutionListener;
import org.springframework.beans.factory.annotation.Value;
import com.godiva.batch.util.GdiSomConstants;
import com.godiva.util.XmlFormatter;
/**
* @author Akash
*
* This class is Spring batch job execution listener.
*
*/
public class OrderArchiveErrorJobListener implements JobExecutionListener {
@Value("${ackFileStatus}")
private String ackFileStatus;
private static final Logger logger = Logger.getLogger(OrderArchiveErrorJobListener.class);
protected String sourceFileLocation;
protected String archiveLocation;
protected String errorLocation;
protected String acknowledgeLocation;
protected DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd-HHmmss");
protected Date date = null;
public String getAcknowledgeLocation() {
return acknowledgeLocation;
}
public void setAcknowledgeLocation(String acknowledgeLocation) {
this.acknowledgeLocation = acknowledgeLocation;
}
public String getSourceFileLocation() {
return sourceFileLocation;
}
public void setSourceFileLocation(String sourceFileLocation) {
this.sourceFileLocation = sourceFileLocation;
}
public String getArchiveLocation() {
return archiveLocation;
}
public void setArchiveLocation(String archiveLocation) {
this.archiveLocation = archiveLocation;
}
public String getErrorLocation() {
return errorLocation;
}
public void setErrorLocation(String errorLocation) {
this.errorLocation = errorLocation;
}
/**
* Reads file from source location, archive and acknowledge files.
*/
public void afterJob(JobExecution arg0) {
try
{
if(arg0.getJobParameters().getString("input.order.file.name") != null)
{
File inputFile = new File(((String) arg0.getJobParameters().getString("input.order.file.name")));
if((inputFile.exists()))
{
date = new Date();
File fromDir = new File(sourceFileLocation);
File arcDir = new File(archiveLocation);
File errDir = new File(errorLocation);
File ackDir = new File(acknowledgeLocation);
File toDir = null;
String exitCode = arg0.getExitStatus().getExitCode();
if (exitCode.equals(ExitStatus.COMPLETED.getExitCode())) {
toDir = arcDir;
}else {
toDir = errDir;
}
String oldFilePath=((String) arg0.getJobParameters().getString("input.order.file.name"));
String oldfilename = oldFilePath.substring(oldFilePath.lastIndexOf(File.separator)+1, oldFilePath.length());
String ackFilename = new String(oldfilename);
ackFilename = ackFilename.replaceAll("(?i)storeorder", "orderstatus");
int underScorePos = ackFilename.lastIndexOf("_");
ackFilename = ackFilename.substring(0, underScorePos);
StringBuffer sbAck=new StringBuffer(ackFilename);
sbAck.insert(underScorePos,"_"+ dateFormat.format(date));
String ackFileNameDate=sbAck.toString();
int dotPos = oldfilename.lastIndexOf(".");
StringBuffer sb=new StringBuffer(oldfilename);
sb.insert(dotPos,"-"+ dateFormat.format(date));
String newFileName=sb.toString();
File oldfile=new File(fromDir.getPath().concat("//" + oldfilename));
File newFile=new File(toDir.getPath().concat("//" + newFileName));
File ackFile=new File(ackDir.getPath().concat("//" + ackFileNameDate + ".xml"));
logger.info("Old File Path : "+oldfile.getPath());
logger.info("New File Path : "+newFile.getPath());
// Acknowledge processed file and add shipment status (as defined in GdiSomConstants.ACKNOWLEDGEMENT_FILE_STATUS).
InputStream fileInputStream = acknowledgeFile(new FileInputStream(oldfile));
FileUtils.copyInputStreamToFile(fileInputStream, ackFile);
if(newFile.exists())
oldfile.delete();
else
FileUtils.moveFile(oldfile, newFile);
}
}
}catch(Exception e) {
logger.error("Error while performing post processing activity ="+ e);
e.printStackTrace();
}
}
public void beforeJob(JobExecution arg0) {
// TODO Auto-generated method stub
}
/**
* Acknowledge processed file, creates xml including order-no, shipment-id and order status in below format.
*
* <?xml version="1.0" encoding="UTF-8"?>
* <order order-no="133">
* <shipment shipment-id="00192010" status="RECEIVED"/>
* </order>
*
* @param is an input stream for Order xml.
*/
private InputStream acknowledgeFile(InputStream is) {
BufferedReader br = null;
InputStream inputStream = null;
String orderId = null;
String shipmentID = null;
try {
br = new BufferedReader(new InputStreamReader(is));
String line = "";
while ((line = br.readLine()) != null) {
if(line.contains("<order order-no"))
{
orderId = line.split("=")[1].split(">")[0];
}
if(line.contains("<shipment shipment-id"))
{
shipmentID = line.split("shipment-id=\"")[1].split("\"")[0];
break;
}
}
String xml = "<order order-no=" + orderId + ">" +
"<shipment shipment-id=\"" + shipmentID + "\" status=\"" + ackFileStatus + "\"/>" +
"</order>";
String formattedXml = XmlFormatter.format(xml);
inputStream = new ByteArrayInputStream(formattedXml.getBytes());
} catch (IOException e) {
e.printStackTrace();
logger.error(e.getMessage());
} finally{
if(br != null)
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
logger.error(e.getMessage());
}
}
return inputStream;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment