I am reading xml files , gathering records and storing it in DB.My objective is to log the file name if there is any exeception when storing record of this xml in DB. I was hoping to the execution context at listner level where I can get the file name.But I think spring batch does not have the feature.
I wish to pass the file name to the listener using execution context from partitioner.
this partitinor we have give executioncontext to send the file name has string to the item writer listener.
public class MultiFileResourcePartitioner implements Partitioner {
private String inboundDir;
@Override
public Map<String, ExecutionContext> partition(int gridSize) {
Map<String, ExecutionContext> partitionMap = new HashMap<String, ExecutionContext>();
File payloadFileDir = new File(inboundDir);
if (payloadFileDir.isDirectory()) {
File[] payloadFiles = payloadFileDir.listFiles();
for (File payloadFile : payloadFiles) {
ExecutionContext context = new ExecutionContext();
context.putString("name", "Thread" +payloadFile.getName());
context.putString("payloadfile", payloadFile.getName());
context.put("fileResource", payloadFile.toURI().toString());
partitionMap.put(payloadFile.getName(), context);
}
}
//System.out.println("partitionMap::"+partitionMap.size());
return partitionMap;
}
public String getInboundDir() {
return inboundDir;
}
public void setInboundDir(String inboundDir) {
this.inboundDir = inboundDir;
}
}
this is item listener class for which it has filename has string datatype and it will take the file name from step execution context.
public class CustomItemWriterListener implements ItemWriteListener<ItemMaintenance> {
private String filename;
Logger logger = Logger.getLogger("MyLog");
FileHandler fh;
@Override
public void beforeWrite(List<? extends ItemMaintenance> items) {
System.out.println("ItemWriteListener - beforeWrite");
}
@Override
public void afterWrite(List<? extends ItemMaintenance> items) {
System.out.println("ItemWriteListener - afterWrite:"+items.size());
}
@Override
public void onWriteError(Exception exception, List<? extends ItemMaintenance> items) {
try {
fh = new FileHandler("D:/temp/ErrorWriter.txt");
logger.addHandler(fh);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
logger.info("duplicate record"+"::"+exception.getMessage().subSequence(450, 453)+filename);
}
catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
this bean will take file name from step execution context.
<bean id="CustomItemWriterListener"
class="com.listeners.CustomItemWriterListener">
<property name="filename" value="#{stepExecutionContext['payloadfile']}" />
</bean>