List of usage examples for javax.mail.internet MimeMultipart writeTo
@Override public synchronized void writeTo(OutputStream os) throws IOException, MessagingException
From source file:com.ctriposs.r2.message.rest.QueryTunnelUtil.java
/** * @param request a RestRequest object to be encoded as a tunneled POST * @param threshold the size of the query params above which the request will be encoded * * @return an encoded RestRequest// ww w.j a va2 s .c om */ public static RestRequest encode(final RestRequest request, int threshold) throws URISyntaxException, MessagingException, IOException { URI uri = request.getURI(); // Check to see if we should tunnel this request by testing the length of the query // if the query is NULL, we won't bother to encode. // 0 length is a special case that could occur with a url like http://www.foo.com? // which we don't want to encode, because we'll lose the "?" in the process // Otherwise only encode queries whose length is greater than or equal to the // threshold value. String query = uri.getRawQuery(); if (query == null || query.length() == 0 || query.length() < threshold) { return request; } RestRequestBuilder requestBuilder = new RestRequestBuilder(request); // reconstruct URI without query uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), null, uri.getFragment()); // If there's no existing body, just pass the request as x-www-form-urlencoded ByteString entity = request.getEntity(); if (entity == null || entity.length() == 0) { requestBuilder.setHeader(HEADER_CONTENT_TYPE, FORM_URL_ENCODED); requestBuilder.setEntity(ByteString.copyString(query, Data.UTF_8_CHARSET)); } else { // If we have a body, we must preserve it, so use multipart/mixed encoding MimeMultipart multi = createMultiPartEntity(entity, request.getHeader(HEADER_CONTENT_TYPE), query); requestBuilder.setHeader(HEADER_CONTENT_TYPE, multi.getContentType()); ByteArrayOutputStream os = new ByteArrayOutputStream(); multi.writeTo(os); requestBuilder.setEntity(ByteString.copy(os.toByteArray())); } // Set the base uri, supply the original method in the override header, and change method to POST requestBuilder.setURI(uri); requestBuilder.setHeader(HEADER_METHOD_OVERRIDE, requestBuilder.getMethod()); requestBuilder.setMethod(RestMethod.POST); return requestBuilder.build(); }
From source file:com.linkedin.r2.message.rest.QueryTunnelUtil.java
/** * @param request a RestRequest object to be encoded as a tunneled POST * @param requestContext a RequestContext object associated with the request * @param threshold the size of the query params above which the request will be encoded * * @return an encoded RestRequest//from w ww. j ava2 s .co m */ public static RestRequest encode(final RestRequest request, RequestContext requestContext, int threshold) throws URISyntaxException, MessagingException, IOException { URI uri = request.getURI(); // Check to see if we should tunnel this request by testing the length of the query // if the query is NULL, we won't bother to encode. // 0 length is a special case that could occur with a url like http://www.foo.com? // which we don't want to encode, because we'll lose the "?" in the process // Otherwise only encode queries whose length is greater than or equal to the // threshold value. String query = uri.getRawQuery(); boolean forceQueryTunnel = requestContext.getLocalAttr(R2Constants.FORCE_QUERY_TUNNEL) != null && (Boolean) requestContext.getLocalAttr(R2Constants.FORCE_QUERY_TUNNEL); if (query == null || query.length() == 0 || (query.length() < threshold && !forceQueryTunnel)) { return request; } RestRequestBuilder requestBuilder = new RestRequestBuilder(request); // reconstruct URI without query uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), null, uri.getFragment()); // If there's no existing body, just pass the request as x-www-form-urlencoded ByteString entity = request.getEntity(); if (entity == null || entity.length() == 0) { requestBuilder.setHeader(HEADER_CONTENT_TYPE, FORM_URL_ENCODED); requestBuilder.setEntity(ByteString.copyString(query, Data.UTF_8_CHARSET)); } else { // If we have a body, we must preserve it, so use multipart/mixed encoding MimeMultipart multi = createMultiPartEntity(entity, request.getHeader(HEADER_CONTENT_TYPE), query); requestBuilder.setHeader(HEADER_CONTENT_TYPE, multi.getContentType()); ByteArrayOutputStream os = new ByteArrayOutputStream(); multi.writeTo(os); requestBuilder.setEntity(ByteString.copy(os.toByteArray())); } // Set the base uri, supply the original method in the override header, and change method to POST requestBuilder.setURI(uri); requestBuilder.setHeader(HEADER_METHOD_OVERRIDE, requestBuilder.getMethod()); requestBuilder.setMethod(RestMethod.POST); return requestBuilder.build(); }
From source file:com.adaptris.util.text.mime.MultiPartOutput.java
private void writeViaTempfile(OutputStream out, File tempFile) throws MessagingException, IOException { try (FileOutputStream fileOut = new FileOutputStream(tempFile); CountingOutputStream counter = new CountingOutputStream(fileOut)) { MimeMultipart multipart = new MimeMultipart(); mimeHeader.setHeader(HEADER_CONTENT_TYPE, multipart.getContentType()); // Write the part out to the stream first. for (KeyedBodyPart kbp : parts) { multipart.addBodyPart(kbp.getData()); }//from w w w. j av a2s . c o m multipart.writeTo(counter); counter.flush(); mimeHeader.setHeader(HEADER_CONTENT_LENGTH, String.valueOf(counter.count())); } writeHeaders(mimeHeader, out); try (InputStream in = new FileInputStream(tempFile)) { IOUtils.copy(in, out); } }
From source file:com.adaptris.util.text.mime.MultiPartOutput.java
private void inMemoryWrite(OutputStream out) throws MessagingException, IOException { MimeMultipart multipart = new MimeMultipart(); ByteArrayOutputStream partOut = new ByteArrayOutputStream(); mimeHeader.setHeader(HEADER_CONTENT_TYPE, multipart.getContentType()); // Write the part out to the stream first. for (KeyedBodyPart kbp : parts) { multipart.addBodyPart(kbp.getData()); }/*from w w w. j a v a 2 s .c o m*/ multipart.writeTo(partOut); mimeHeader.setHeader(HEADER_CONTENT_LENGTH, String.valueOf(partOut.size())); writeHeaders(mimeHeader, out); out.write(partOut.toByteArray()); }
From source file:com.boundlessgeo.geoserver.AppIntegrationTest.java
void createMultiPartFormContent(MimeMultipart body, MockHttpServletRequest request) throws Exception { ByteArrayOutputStream bout = new ByteArrayOutputStream(); body.writeTo(bout); request.setContent(bout.toByteArray()); }
From source file:de.betterform.connector.serializer.MultipartRelatedSerializer.java
public void serialize(Submission submission, Node node, SerializerRequestWrapper wrapper, String defaultEncoding) throws Exception { Map cache = new HashMap(); MimeMultipart multipart = new MimeMultipart(); MimeBodyPart part = new MimeBodyPart(); multipart.addBodyPart(part);/*from www . j av a2 s .c om*/ String encoding = defaultEncoding; if (submission.getEncoding() != null) { encoding = submission.getEncoding(); } if (node.getNodeType() == Node.ELEMENT_NODE || node.getNodeType() == Node.DOCUMENT_NODE) { part.setText(new String(serializeXML(multipart, cache, submission, node, encoding), encoding), encoding); } else { part.setText(node.getTextContent()); } part.setContentID("<instance.xml@start>"); part.addHeader("Content-Type", "application/xml"); part.addHeader("Content-Transfer-Encoding", "base64"); part.setDisposition("attachment"); part.setFileName("instance.xml"); multipart.setSubType("related; type=\"" + submission.getMediatype() + "\"; start=\"instance.xml@start\""); // FIXME: Is this a global http header or a local mime header? wrapper.getBodyStream() .write(("Content-Type: " + multipart.getContentType() + "\n\nThis is a MIME message.\n") .getBytes(encoding)); multipart.writeTo(wrapper.getBodyStream()); }
From source file:com.boundlessgeo.geoserver.AppIntegrationTest.java
void createMultiPartFormContent(MockHttpServletRequest request, String contentDisposition, String contentType, byte[] content) throws Exception { MimeMultipart body = new MimeMultipart(); request.setContentType(body.getContentType()); InternetHeaders headers = new InternetHeaders(); headers.setHeader("Content-Disposition", contentDisposition); headers.setHeader("Content-Type", contentType); body.addBodyPart(new MimeBodyPart(headers, content)); ByteArrayOutputStream bout = new ByteArrayOutputStream(); body.writeTo(bout); request.setContent(bout.toByteArray()); }
From source file:com.googlecode.ddom.mime.JavaMailTest.java
private void test(boolean preamble) throws Exception { MimeMultipart multipart = new MimeMultipart(); MimeBodyPart bodyPart1 = new MimeBodyPart(); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < 1000; i++) { buffer.append('('); buffer.append(i);/*from www .j a v a 2 s . co m*/ buffer.append(')'); } String content1 = buffer.toString(); bodyPart1 .setDataHandler(new DataHandler(new ByteArrayDataSource(content1.getBytes("UTF-8"), "text/plain"))); Map<String, String> headers1 = new HashMap<String, String>(); headers1.put("Content-ID", "<1@example.com>"); headers1.put("Content-Type", "text/plain; charset=UTF-8"); setHeaders(bodyPart1, headers1); multipart.addBodyPart(bodyPart1); MimeBodyPart bodyPart2 = new MimeBodyPart(); byte[] content2 = new byte[10000]; new Random().nextBytes(content2); bodyPart2.setDataHandler(new DataHandler(new ByteArrayDataSource(content2, "application/octet-stream"))); Map<String, String> headers2 = new HashMap<String, String>(); headers2.put("Content-ID", "<2@example.com>"); headers2.put("Content-Type", "application/octet-stream"); setHeaders(bodyPart2, headers2); multipart.addBodyPart(bodyPart2); if (preamble) { multipart.setPreamble("This is a MIME multipart."); } String boundary = new ContentType(multipart.getContentType()).getParameter("boundary"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); multipart.writeTo(baos); MultipartReader mpr = new MultipartReader(new ByteArrayInputStream(baos.toByteArray()), boundary); assertTrue(mpr.nextPart()); assertEquals(headers1, readHeaders(mpr)); assertEquals(content1, IOUtils.toString(mpr.getContent(), "UTF-8")); assertTrue(mpr.nextPart()); assertEquals(headers2, readHeaders(mpr)); assertArrayEquals(content2, IOUtils.toByteArray(mpr.getContent())); assertFalse(mpr.nextPart()); }
From source file:voldemort.coordinator.HttpGetAllRequestExecutor.java
public void writeResponse(Map<ByteArray, List<Versioned<byte[]>>> versionedResponses) throws Exception { // multiPartKeys is the outer multipart MimeMultipart multiPartKeys = new MimeMultipart(); ByteArrayOutputStream keysOutputStream = new ByteArrayOutputStream(); for (Entry<ByteArray, List<Versioned<byte[]>>> entry : versionedResponses.entrySet()) { ByteArray key = entry.getKey();// www . jav a 2 s . c om String contentLocationKey = "/" + this.storeName + "/" + new String(Base64.encodeBase64(key.get())); // Create the individual body part - for each key requested MimeBodyPart keyBody = new MimeBodyPart(); try { // Add the right headers keyBody.addHeader(CONTENT_TYPE, "multipart/binary"); keyBody.addHeader(CONTENT_TRANSFER_ENCODING, "binary"); keyBody.addHeader(CONTENT_LOCATION, contentLocationKey); } catch (MessagingException me) { logger.error("Exception while constructing key body headers", me); keysOutputStream.close(); throw me; } // multiPartValues is the inner multipart MimeMultipart multiPartValues = new MimeMultipart(); for (Versioned<byte[]> versionedValue : entry.getValue()) { byte[] responseValue = versionedValue.getValue(); VectorClock vectorClock = (VectorClock) versionedValue.getVersion(); String serializedVC = CoordinatorUtils.getSerializedVectorClock(vectorClock); // Create the individual body part - for each versioned value of // a key MimeBodyPart valueBody = new MimeBodyPart(); try { // Add the right headers valueBody.addHeader(CONTENT_TYPE, "application/octet-stream"); valueBody.addHeader(CONTENT_TRANSFER_ENCODING, "binary"); valueBody.addHeader(VoldemortHttpRequestHandler.X_VOLD_VECTOR_CLOCK, serializedVC); valueBody.setContent(responseValue, "application/octet-stream"); multiPartValues.addBodyPart(valueBody); } catch (MessagingException me) { logger.error("Exception while constructing value body part", me); keysOutputStream.close(); throw me; } } try { // Add the inner multipart as the content of the outer body part keyBody.setContent(multiPartValues); multiPartKeys.addBodyPart(keyBody); } catch (MessagingException me) { logger.error("Exception while constructing key body part", me); keysOutputStream.close(); throw me; } } try { multiPartKeys.writeTo(keysOutputStream); } catch (Exception e) { logger.error("Exception while writing mutipart to output stream", e); throw e; } ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer(); responseContent.writeBytes(keysOutputStream.toByteArray()); // Create the Response object HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); // Set the right headers response.setHeader(CONTENT_TYPE, "multipart/binary"); response.setHeader(CONTENT_TRANSFER_ENCODING, "binary"); // Copy the data into the payload response.setContent(responseContent); response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes()); // Update the stats if (this.coordinatorPerfStats != null) { long durationInNs = System.nanoTime() - startTimestampInNs; this.coordinatorPerfStats.recordTime(Tracked.GET_ALL, durationInNs); } // Write the response to the Netty Channel this.getRequestMessageEvent.getChannel().write(response); keysOutputStream.close(); }
From source file:voldemort.coordinator.HttpGetAllRequestExecutor.java
public void writeResponseOld(Map<ByteArray, Versioned<byte[]>> responseVersioned) { // Multipart response MimeMultipart mp = new MimeMultipart(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try {// w w w . j a va 2 s. c om for (Entry<ByteArray, Versioned<byte[]>> entry : responseVersioned.entrySet()) { Versioned<byte[]> value = entry.getValue(); ByteArray keyByteArray = entry.getKey(); String base64Key = new String(Base64.encodeBase64(keyByteArray.get())); String contentLocationKey = "/" + this.storeName + "/" + base64Key; byte[] responseValue = value.getValue(); VectorClock vc = (VectorClock) value.getVersion(); VectorClockWrapper vcWrapper = new VectorClockWrapper(vc); ObjectMapper mapper = new ObjectMapper(); String eTag = ""; try { eTag = mapper.writeValueAsString(vcWrapper); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if (logger.isDebugEnabled()) { logger.debug("ETAG : " + eTag); } // Create the individual body part MimeBodyPart body = new MimeBodyPart(); body.addHeader(CONTENT_TYPE, "application/octet-stream"); body.addHeader(CONTENT_LOCATION, contentLocationKey); body.addHeader(CONTENT_TRANSFER_ENCODING, "binary"); body.addHeader(CONTENT_LENGTH, "" + responseValue.length); body.addHeader(ETAG, eTag); body.setContent(responseValue, "application/octet-stream"); mp.addBodyPart(body); } // At this point we have a complete multi-part response mp.writeTo(outputStream); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer(); responseContent.writeBytes(outputStream.toByteArray()); // 1. Create the Response object HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); // 2. Set the right headers response.setHeader(CONTENT_TYPE, "multipart/binary"); response.setHeader(CONTENT_TRANSFER_ENCODING, "binary"); // 3. Copy the data into the payload response.setContent(responseContent); response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes()); // Update the stats if (this.coordinatorPerfStats != null) { long durationInNs = System.nanoTime() - startTimestampInNs; this.coordinatorPerfStats.recordTime(Tracked.GET_ALL, durationInNs); } // Write the response to the Netty Channel this.getRequestMessageEvent.getChannel().write(response); }