All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.braintreepayments.http.serializer.Multipart Maven / Gradle / Ivy

There is a newer version: 1.3.1
Show newest version
package com.braintreepayments.http.serializer;


import com.braintreepayments.http.Headers;
import com.braintreepayments.http.HttpRequest;
import com.braintreepayments.http.exceptions.SerializeException;
import com.braintreepayments.http.multipart.FormData;
import com.braintreepayments.http.multipart.MultipartBody;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import static com.braintreepayments.http.serializer.StreamUtils.writeOutputStream;

public class Multipart implements Serializer {

	public static final String CRLF = "\r\n";

	@Override
	public String contentType() {
		return "^multipart\\/.*";
	}

	@Override
	@SuppressWarnings("unchecked")
	public byte[] encode(HttpRequest request) throws IOException {
		if (!(request.requestBody() instanceof MultipartBody)) {
			throw new SerializeException("Request requestBody must be MultipartBody when Content-Type is multipart/*");
		} else {
			String contentType = request.headers().header(Headers.CONTENT_TYPE);
			String boundary = "boundary" + System.currentTimeMillis();
			contentType = contentType + "; boundary=" + boundary;
			request.header(Headers.CONTENT_TYPE, contentType); // Rewrite header with boundary

			MultipartBody body = (MultipartBody) request.requestBody();
			ByteArrayOutputStream os = new ByteArrayOutputStream();

			for (FormData formData : body) {
				writePart(os, formData, boundary);
			}

			writeOutputStream(os, "--" + boundary + "--");
			writeOutputStream(os, CRLF);
			writeOutputStream(os, CRLF);

			return os.toByteArray();
		}
	}

	@Override
	public  T decode(String source, Class cls) throws IOException {
		throw new UnsupportedEncodingException("Unable to decode Content-Type: multipart/form-data.");
	}

	private void writePart(OutputStream writer, FormData part, String boundary) throws IOException {
		writeOutputStream(writer,"--" + boundary);
		writeOutputStream(writer, CRLF);
		writeOutputStream(writer, part.header());
		writeOutputStream(writer, CRLF);
		writeOutputStream(writer, CRLF);

		part.writeData(writer);
		writeOutputStream(writer, CRLF);
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy