Created
January 4, 2012 14:53
-
-
Save marianogonzalez/1560364 to your computer and use it in GitHub Desktop.
MultipartHttpToMapTransformer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.ByteArrayOutputStream; | |
import java.io.InputStream; | |
import java.util.HashMap; | |
import java.util.Map; | |
import org.apache.commons.fileupload.MultipartStream; | |
import org.apache.log4j.Logger; | |
import org.mule.api.MuleMessage; | |
import org.mule.api.transport.PropertyScope; | |
import org.mule.transformer.AbstractMessageTransformer; | |
public class MultipartHttpToMapTransformer extends AbstractMessageTransformer { | |
private static final Logger logger = Logger.getLogger(MultipartHttpToMapTransformer.class); | |
@Override | |
public Object transformMessage(MuleMessage message, String outputEncoding) { | |
try { | |
String contentType = (String) message.getProperty("Content-Type", PropertyScope.INBOUND); | |
int boundaryIndex = contentType.indexOf("boundary="); | |
byte[] boundary = (contentType.substring(boundaryIndex + 9)).getBytes(); | |
//Read MultipartStream and iterate through parts | |
@SuppressWarnings("deprecation") | |
MultipartStream multipartStream = new MultipartStream((InputStream)message.getPayload(), boundary); | |
Map<String, String> payload = new HashMap<String, String>(); | |
message.setPayload(payload); | |
boolean nextPart = multipartStream.skipPreamble(); | |
while(nextPart) { | |
//Get headers | |
Map<String, String> headers = parseHeaders(multipartStream.readHeaders()); | |
//Read body data | |
ByteArrayOutputStream data = new ByteArrayOutputStream(); | |
multipartStream.readBodyData(data); | |
String contentDisposition = (String)headers.get("content-disposition"); | |
String[] cdParts = contentDisposition.split(";"); | |
for (int i = 0; i < cdParts.length; i++) { | |
if (cdParts[i].trim().startsWith("name")) { | |
String propertyName = cdParts[i].replaceAll("name=", " ").replaceAll("\"", " ").trim(); | |
payload.put(propertyName, data.toString()); | |
break; | |
} | |
} | |
nextPart = multipartStream.readBoundary(); | |
} | |
} catch (Throwable e) { | |
throw new RuntimeException(e); | |
} | |
return message; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment