1 13 package info.magnolia.cms.exchange.simple; 14 15 import info.magnolia.cms.exchange.ActivationContent; 16 import info.magnolia.cms.exchange.ExchangeException; 17 18 import java.io.DataOutputStream ; 19 import java.io.FileInputStream ; 20 import java.io.IOException ; 21 import java.net.URLConnection ; 22 import java.util.Iterator ; 23 24 import org.apache.commons.lang.ClassUtils; 25 import org.slf4j.Logger; 26 import org.slf4j.LoggerFactory; 27 28 29 33 public class Transporter { 34 35 38 private static Logger log = LoggerFactory.getLogger(Transporter.class); 39 40 43 private static final String BOUNDARY = "mgnlExchange-cfc93688d385"; 44 45 48 private static final int BUFFER_SIZE = 1024; 49 50 56 public static void transport(URLConnection connection, ActivationContent activationContent) 57 throws ExchangeException { 58 FileInputStream fis = null; 59 DataOutputStream outStream = null; 60 try { 61 byte[] buffer = new byte[BUFFER_SIZE]; 62 connection.setDoOutput(true); 63 connection.setDoInput(true); 64 connection.setUseCaches(false); 65 connection.setRequestProperty("Content-type", "multipart/form-data; boundary=" + BOUNDARY); 66 connection.setRequestProperty("Cache-Control", "no-cache"); 67 68 outStream = new DataOutputStream (connection.getOutputStream()); 69 outStream.writeBytes("--" + BOUNDARY + "\r\n"); 70 71 Iterator fileNameIterator = activationContent.getFiles().keySet().iterator(); 73 while (fileNameIterator.hasNext()) { 74 String fileName = (String ) fileNameIterator.next(); 75 fis = new FileInputStream (activationContent.getFile(fileName)); 76 outStream.writeBytes("content-disposition: form-data; name=\"" 77 + fileName 78 + "\"; filename=\"" 79 + fileName 80 + "\"\r\n"); 81 outStream.writeBytes("content-type: application/octet-stream" + "\r\n\r\n"); 82 while (true) { 83 synchronized (buffer) { 84 int amountRead = fis.read(buffer); 85 if (amountRead == -1) { 86 break; 87 } 88 outStream.write(buffer, 0, amountRead); 89 } 90 } 91 fis.close(); 92 outStream.writeBytes("\r\n" + "--" + BOUNDARY + "\r\n"); 93 } 94 outStream.flush(); 95 outStream.close(); 96 97 log.debug("Activation content sent as multipart/form-data"); 98 } 99 catch (Exception e) { 100 throw new ExchangeException("Simple exchange transport failed: " 101 + ClassUtils.getShortClassName(e.getClass()), e); 102 } 103 finally { 104 if (fis != null) { 105 try { 106 fis.close(); 107 } 108 catch (IOException e) { 109 log.error("Exception caught", e); 110 } 111 } 112 if (outStream != null) { 113 try { 114 outStream.close(); 115 } 116 catch (IOException e) { 117 log.error("Exception caught", e); 118 } 119 } 120 } 121 122 } 123 124 } 125 | Popular Tags |