}
@SuppressWarnings("unchecked")
public void marshal(Exchange exchange, Object body, OutputStream outputStream) throws Exception {
PackageScanClassResolver resolver = exchange.getContext().getPackageScanClassResolver();
BindyFixedLengthFactory factory = (BindyFixedLengthFactory) getFactory(resolver);
ObjectHelper.notNull(factory, "not instantiated");
// Get CRLF
byte[] bytesCRLF = ConverterUtils.getByteReturn(factory.getCarriageReturn());
List<Map<String, Object>> models;
// the body is not a prepared list so help a bit here and create one for us
if (exchange.getContext().getTypeConverter().convertTo(List.class, body) == null) {
models = new ArrayList<Map<String, Object>>();
Iterator<?> it = ObjectHelper.createIterator(body);
while (it.hasNext()) {
Object model = it.next();
String name = model.getClass().getName();
Map<String, Object> row = new HashMap<String, Object>();
row.put(name, body);
models.add(row);
}
} else {
// cast to the expected type
models = (List<Map<String, Object>>) body;
}
// add the header if it is in the exchange header
Map<String, Object> headerRow = (Map<String, Object>) exchange.getIn().getHeader(CAMEL_BINDY_FIXED_LENGTH_HEADER);
if (headerRow != null) {
models.add(0, headerRow);
}
// add the footer if it is in the exchange header
Map<String, Object> footerRow = (Map<String, Object>) exchange.getIn().getHeader(CAMEL_BINDY_FIXED_LENGTH_FOOTER);
if (headerRow != null) {
models.add(models.size(), footerRow);
}
int row = 0;
for (Map<String, Object> model : models) {
row++;
String result = null;
if (row == 1 && headerFactory != null) {
// marshal the first row as a header if the models match
Set<String> modelClassNames = model.keySet();
// only use the header factory if the row is the header
if (headerFactory.supportsModel(modelClassNames)) {
if (factory.skipHeader()) {
LOG.info("Skipping marshal of header row; 'skipHeader=true'");
continue;
} else {
result = headerFactory.unbind(model);
}
}
} else if (row == models.size() && footerFactory != null) {
// marshal the last row as a footer if the models match
Set<String> modelClassNames = model.keySet();
// only use the header factory if the row is the header
if (footerFactory.supportsModel(modelClassNames)) {
if (factory.skipFooter()) {
LOG.info("Skipping marshal of footer row; 'skipFooter=true'");
continue;
} else {
result = footerFactory.unbind(model);
}
}
}
if (result == null) {
// marshal as a normal / default row
result = factory.unbind(model);
}
byte[] bytes = exchange.getContext().getTypeConverter().convertTo(byte[].class, exchange, result);
outputStream.write(bytes);