Tuesday 12 February 2013

Apache Camel message file name set or change

The file name of the current message can be retrieved from the Message header of the Exchange object as follows:

String filename = new String();
filename = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);

The Exchange class provides a whole host of constants for easy access, here we use FILE_NAME in conjuction with the getHeader() method to retrieve the current name of the file.

This example will replace the .csv file extension to .xml

Using the FILE_NAME again with setHeader() we can set the filename to our choosing:

exchange.getIn().setHeader(Exchange.FILE_NAME, filename.replaceFirst(".csv", ".xml"));

Below is the entire process() method from a class implementing Processor.

public class FileRename implements Processor {

public void process(Exchange exchange) throws Exception {
    String filename = new String();
    filename = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
    exchange.getIn().setHeader(Exchange.FILE_NAME, filename.replaceFirst(".csv", ".xml"));
}
}


public class FileRename implements Processor {

  public void process(Exchange exchange) throws Exception {
    String filename = new String();
    filename = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
    exchange.getIn().setHeader(Exchange.FILE_NAME, filename.replaceFirst(".csv", ".xml"));
  }
}

No comments:

Post a Comment