package sample; import com.sap.aii.mapping.api.*; import java.io.*; public class MyMessageAsAttachment extends AbstractTransformation { // Main class for local test public static void main(String[] args) { try { InputStream in = new FileInputStream(new File("in.xml")); OutputStream out = new FileOutputStream(new File("out.xml")); MyMessageAsAttachment myMapping = new MyMessageAsAttachment(); myMapping.execute(in, out); } catch (Exception e) { e.getMessage(); } } public void transform(TransformationInput arg0, TransformationOutput arg1) throws StreamTransformationException { this.execute(arg0.getInputPayload().getInputStream(), arg1.getOutputPayload().getOutputStream()); } public void execute(InputStream in, OutputStream out) throws StreamTransformationException { String mailSubject = "OrderResponse"; String mailSender = "\"Me\"<MyName@MyCompany.com>"; String mailReceiver = "\"You\"<YourName@YourCompany.com>"; String attachmentName = "file.xml"; String boundary = "--AaZz"; String mailContent = "This is a sample file"; String CRLF = "\r\n"; try { // create XML structure of mail package String output = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<ns:Mail xmlns:ns=\"http://sap.com/xi/XI/Mail/30\">" + "<Subject>" + mailSubject + "</Subject>" + "<From>" + mailSender + "</From>" + "<To>" + mailReceiver + "</To>" + "<Content_Type>multipart/mixed; boundary=\"" + boundary + "\"</Content_Type>" + "<Content>"; out.write(output.getBytes()); // create the declaration of the MIME parts //First part output = "--" + boundary + CRLF + "Content-Type: text/plain; charset=UTF-8" + CRLF + "Content-Disposition: inline" + CRLF + CRLF + mailContent + CRLF + CRLF //Second part + "--" + boundary + CRLF + "Content-Type: application/xml; name=" + attachmentName + CRLF + "Content-Disposition: attachment; filename=" + attachmentName + CRLF + CRLF; out.write(output.getBytes()); //Source is taken as attachment copySource(in, out); // last boundary output = CRLF + CRLF +"--" + boundary + "--" + CRLF; out.write(output.getBytes()); // finish mail package out.write("</Content></ns:Mail>".getBytes()); } catch (IOException e) { throw new StreamTransformationException(e.getMessage()); } } protected static void copySource(InputStream in, OutputStream out) throws IOException { byte[] buf = new byte[in.available()]; in.read(buf); String sbuf = new String(buf); // replace all control characters with escape sequences sbuf = sbuf.replaceAll("&", "&"); sbuf = sbuf.replaceAll("\"", """); sbuf = sbuf.replaceAll("'", "'"); sbuf = sbuf.replaceAll("<", "<"); sbuf = sbuf.replaceAll(">", ">"); out.write(sbuf.getBytes("UTF-8")); } } |