List of usage examples for javax.mail.internet MimeBodyPart getHeader
@Override public String[] getHeader(String name) throws MessagingException
From source file:com.adaptris.core.mail.attachment.MimeMailCreator.java
private static String getContentTransferEncoding(MimeBodyPart p) throws Exception { String result = null;// ww w . ja v a 2s . c o m String[] hdr = p.getHeader(MimeConstants.HEADER_CONTENT_ENCODING); if (hdr != null) { result = hdr[0]; } return defaultIfBlank(result, "base64"); }
From source file:com.adaptris.core.mail.attachment.MimeMailCreator.java
private static ContentType getContentType(MimeBodyPart p) throws Exception { ContentType result = null;//w w w.j av a 2s .c om String[] hdr = p.getHeader(MimeConstants.HEADER_CONTENT_TYPE); if (hdr != null) { result = new ContentType(hdr[0]); } return result; }
From source file:com.adaptris.core.mail.attachment.MimeMailCreator.java
private String getAttachmentFileName(MimeBodyPart p) throws Exception { String filename = null;/*from w ww . ja v a 2s.c o m*/ String[] hdr = p.getHeader("Content-Disposition"); if (hdr != null) { ContentDisposition cd = new ContentDisposition(hdr[0]); filename = cd.getParameter("filename"); } if (filename == null) { hdr = p.getHeader("Content-Type"); if (hdr != null) { ContentType ct = new ContentType(hdr[0]); filename = ct.getParameter("name"); } } if (filename == null) { filename = idGenerator.create(p); logR.warn("Could not determine filename for MimeBodyPart, assigning unique filename of {}", filename); } return filename; }
From source file:dtw.webmail.util.FormdataMultipart.java
/** * Processes a body part of the form-data. * Extracts parameters and set values, and * leaves over the attachments./*from w ww . j av a2s.c o m*/ * * @param mbp the <tt>MimeBodyPart</tt> to be processed. * * @throws IOException if i/o operations fail. * @throws MessagingException if parsing or part handling with * Mail API classes fails. */ private void processBodyPart(MimeBodyPart mbp) throws MessagingException, IOException { //String contenttype=new String(mbp.getContentType()); //JwmaKernel.getReference().debugLog().write("Processing "+contenttype); //check if a content-type is given String[] cts = mbp.getHeader("Content-Type"); if (cts == null || cts.length == 0) { //this is a parameter, get it out and //remove the part. String controlname = extractName((mbp.getHeader("Content-Disposition"))[0]); //JwmaKernel.getReference().debugLog().write("Processing control:"+controlname); //retrieve value observing encoding InputStream in = mbp.getInputStream(); String[] encoding = mbp.getHeader("Content-Transfer-Encoding"); if (encoding != null && encoding.length > 0) { in = MimeUtility.decode(in, encoding[0]); } String value = extractValue(in); if (value != null || !value.trim().equals("")) { addParameter(controlname, value); } //flag removal m_Removed = true; removeBodyPart(mbp); } else { String filename = extractFileName((mbp.getHeader("Content-Disposition"))[0]); //normally without file the control should be not successful. //but neither netscape nor mircosoft iexploder care much. //the only feature is an empty filename. if (filename.equals("")) { //kick it out too m_Removed = true; removeBodyPart(mbp); } else { //JwmaKernel.getReference().debugLog().write("Incoming filename="+filename); //IExploder sends files with complete path. //jwma doesnt want this. int lastindex = filename.lastIndexOf("\\"); if (lastindex != -1) { filename = filename.substring(lastindex + 1, filename.length()); } //JwmaKernel.getReference().debugLog().write("Outgoing filename="+filename); //Observe a possible encoding InputStream in = mbp.getInputStream(); String[] encoding = mbp.getHeader("Content-Transfer-Encoding"); if (encoding != null && encoding.length > 0) { in = MimeUtility.decode(in, encoding[0]); } ByteArrayOutputStream bout = new ByteArrayOutputStream(); OutputStream out = (OutputStream) bout; int i = 0; while ((i = in.read()) != -1) { //maybe more efficient in buffers, but well out.write(i); } out.flush(); out.close(); //create the datasource MimeBodyPartDataSource mbpds = new MimeBodyPartDataSource( // contenttype,filename,bout.toByteArray() cts[0], filename, bout.toByteArray()); //Re-set the Content-Disposition header, in case //the file name was changed mbp.removeHeader("Content-Disposition"); mbp.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); //set a base64 transferencoding und the data handler mbp.addHeader("Content-Transfer-Encoding", "base64"); mbp.setDataHandler(new DataHandler(mbpds)); } } }
From source file:com.stimulus.archiva.store.MessageStore.java
public String getHeader(MimeBodyPart mbp, String name) throws MessagingException { String header[] = mbp.getHeader(name); if (header != null && header.length > 0) return header[0]; else//from ww w . java2s . c o m return null; }
From source file:org.xwiki.mail.internal.AttachmentMimeBodyPartFactoryTest.java
@Test public void createAttachmentBodyPartWithHeader() throws Exception { Environment environment = this.mocker.getInstance(Environment.class); when(environment.getTemporaryDirectory()).thenReturn(new File(TEMPORARY_DIRECTORY)); Attachment attachment = mock(Attachment.class); when(attachment.getContent()).thenReturn("Lorem Ipsum".getBytes()); when(attachment.getFilename()).thenReturn("image.png"); when(attachment.getMimeType()).thenReturn("image/png"); Map<String, Object> parameters = Collections.singletonMap("headers", (Object) Collections.singletonMap("Content-Transfer-Encoding", "quoted-printable")); MimeBodyPart part = this.mocker.getComponentUnderTest().create(attachment, parameters); assertEquals("<image.png>", part.getContentID()); // JavaMail adds some extra params to the content-type header // (e.g. image/png; name=attachment8219195155963823979.tmp) , we just verify the content type that we passed. assertTrue(part.getContentType().startsWith("image/png")); // We verify the format of the generated temporary file containing our attachment data assertTrue(part.getFileName().matches("attachment.*\\.tmp")); assertArrayEquals(new String[] { "quoted-printable" }, part.getHeader("Content-Transfer-Encoding")); assertEquals("Lorem Ipsum", IOUtils.toString(part.getDataHandler().getInputStream())); }
From source file:org.xwiki.mail.internal.factory.attachment.AttachmentMimeBodyPartFactoryTest.java
@Test public void createAttachmentBodyPartWithHeader() throws Exception { Environment environment = this.mocker.getInstance(Environment.class); when(environment.getTemporaryDirectory()).thenReturn(new File(TEMPORARY_DIRECTORY)); Attachment attachment = mock(Attachment.class); when(attachment.getContent()).thenReturn("Lorem Ipsum".getBytes()); when(attachment.getFilename()).thenReturn("image.png"); when(attachment.getMimeType()).thenReturn("image/png"); Map<String, Object> parameters = Collections.singletonMap("headers", (Object) Collections.singletonMap("Content-Transfer-Encoding", "quoted-printable")); MimeBodyPart part = this.mocker.getComponentUnderTest().create(attachment, parameters); assertEquals("<image.png>", part.getContentID()); // JavaMail adds some extra params to the content-type header // (e.g. image/png; name=image.png) , we just verify the content type that we passed. assertTrue(part.getContentType().startsWith("image/png")); // We verify that the Content-Disposition has the correct file namr assertTrue(part.getFileName().matches("image\\.png")); assertArrayEquals(new String[] { "quoted-printable" }, part.getHeader("Content-Transfer-Encoding")); assertEquals("Lorem Ipsum", IOUtils.toString(part.getDataHandler().getInputStream())); }
From source file:voldemort.coordinator.CoordinatorRestAPITest.java
private TestVersionedValue doGet(String key, Map<String, Object> options) { HttpURLConnection conn = null; String response = null;// w w w . j a va 2 s.c o m TestVersionedValue responseObj = null; int expectedResponseCode = 200; try { // Create the right URL and Http connection String base64Key = new String(Base64.encodeBase64(key.getBytes())); URL url = new URL(this.coordinatorURL + "/" + STORE_NAME + "/" + base64Key); conn = (HttpURLConnection) url.openConnection(); // Set the right headers conn.setRequestMethod("GET"); conn.setDoInput(true); conn.setRequestProperty(RestMessageHeaders.X_VOLD_REQUEST_TIMEOUT_MS, "1000"); conn.setRequestProperty(RestMessageHeaders.X_VOLD_REQUEST_ORIGIN_TIME_MS, Long.toString(System.currentTimeMillis())); // options if (options != null) { if (options.get("timeout") != null && options.get("timeout") instanceof String) { conn.setRequestProperty(RestMessageHeaders.X_VOLD_REQUEST_TIMEOUT_MS, (String) options.get("timeout")); } if (options.get("responseCode") != null && options.get("responseCode") instanceof Integer) { expectedResponseCode = (Integer) options.get("responseCode"); } } // Check for the right response code if (conn.getResponseCode() != expectedResponseCode) { System.err.println("Illegal response during GET : " + conn.getResponseMessage()); fail("Incorrect response received for a HTTP GET request :" + conn.getResponseCode()); } if (conn.getResponseCode() == 404 || conn.getResponseCode() == 408) { return null; } // Buffer the result into a string ByteArrayDataSource ds = new ByteArrayDataSource(conn.getInputStream(), "multipart/mixed"); MimeMultipart mp = new MimeMultipart(ds); assertEquals("The number of body parts expected is not 1", 1, mp.getCount()); MimeBodyPart part = (MimeBodyPart) mp.getBodyPart(0); VectorClock vc = RestUtils .deserializeVectorClock(part.getHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK)[0]); response = (String) part.getContent(); responseObj = new TestVersionedValue(response, vc); } catch (Exception e) { e.printStackTrace(); fail("Error in sending the REST request"); } finally { if (conn != null) { conn.disconnect(); } } return responseObj; }
From source file:voldemort.restclient.R2Store.java
private List<Versioned<byte[]>> parseGetResponse(ByteString entity) { List<Versioned<byte[]>> results = new ArrayList<Versioned<byte[]>>(); try {//from w w w . ja v a 2 s . c o m // Build the multipart object byte[] bytes = new byte[entity.length()]; entity.copyBytes(bytes, 0); ByteArrayDataSource ds = new ByteArrayDataSource(bytes, "multipart/mixed"); MimeMultipart mp = new MimeMultipart(ds); for (int i = 0; i < mp.getCount(); i++) { MimeBodyPart part = (MimeBodyPart) mp.getBodyPart(i); String serializedVC = part.getHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK)[0]; int contentLength = Integer.parseInt(part.getHeader(RestMessageHeaders.CONTENT_LENGTH)[0]); if (logger.isDebugEnabled()) { logger.debug("Received VC : " + serializedVC); } VectorClockWrapper vcWrapper = mapper.readValue(serializedVC, VectorClockWrapper.class); InputStream input = part.getInputStream(); byte[] bodyPartBytes = new byte[contentLength]; input.read(bodyPartBytes); VectorClock clock = new VectorClock(vcWrapper.getVersions(), vcWrapper.getTimestamp()); results.add(new Versioned<byte[]>(bodyPartBytes, clock)); } } catch (MessagingException e) { throw new VoldemortException("Messaging exception while trying to parse GET response " + e.getMessage(), e); } catch (JsonParseException e) { throw new VoldemortException( "JSON parsing exception while trying to parse GET response " + e.getMessage(), e); } catch (JsonMappingException e) { throw new VoldemortException( "JSON mapping exception while trying to parse GET response " + e.getMessage(), e); } catch (IOException e) { throw new VoldemortException("IO exception while trying to parse GET response " + e.getMessage(), e); } return results; }
From source file:voldemort.restclient.R2Store.java
private Map<ByteArray, List<Versioned<byte[]>>> parseGetAllResults(ByteString entity) { Map<ByteArray, List<Versioned<byte[]>>> results = new HashMap<ByteArray, List<Versioned<byte[]>>>(); try {// w w w . j a v a2 s.c o m // Build the multipart object byte[] bytes = new byte[entity.length()]; entity.copyBytes(bytes, 0); // Get the outer multipart object ByteArrayDataSource ds = new ByteArrayDataSource(bytes, "multipart/mixed"); MimeMultipart mp = new MimeMultipart(ds); for (int i = 0; i < mp.getCount(); i++) { // Get an individual part. This contains all the versioned // values for a particular key referenced by content-location MimeBodyPart part = (MimeBodyPart) mp.getBodyPart(i); // Get the key String contentLocation = part.getHeader("Content-Location")[0]; String base64Key = contentLocation.split("/")[2]; ByteArray key = new ByteArray(RestUtils.decodeVoldemortKey(base64Key)); if (logger.isDebugEnabled()) { logger.debug("Content-Location : " + contentLocation); logger.debug("Base 64 key : " + base64Key); } // Create an array list for holding all the (versioned values) List<Versioned<byte[]>> valueResultList = new ArrayList<Versioned<byte[]>>(); // Get the nested Multi-part object. This contains one part for // each unique versioned value. ByteArrayDataSource nestedDS = new ByteArrayDataSource((String) part.getContent(), "multipart/mixed"); MimeMultipart valueParts = new MimeMultipart(nestedDS); for (int valueId = 0; valueId < valueParts.getCount(); valueId++) { MimeBodyPart valuePart = (MimeBodyPart) valueParts.getBodyPart(valueId); String serializedVC = valuePart.getHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK)[0]; int contentLength = Integer.parseInt(valuePart.getHeader(RestMessageHeaders.CONTENT_LENGTH)[0]); if (logger.isDebugEnabled()) { logger.debug("Received serialized Vector Clock : " + serializedVC); } VectorClockWrapper vcWrapper = mapper.readValue(serializedVC, VectorClockWrapper.class); // get the value bytes InputStream input = valuePart.getInputStream(); byte[] bodyPartBytes = new byte[contentLength]; input.read(bodyPartBytes); VectorClock clock = new VectorClock(vcWrapper.getVersions(), vcWrapper.getTimestamp()); valueResultList.add(new Versioned<byte[]>(bodyPartBytes, clock)); } results.put(key, valueResultList); } } catch (MessagingException e) { throw new VoldemortException("Messaging exception while trying to parse GET response " + e.getMessage(), e); } catch (JsonParseException e) { throw new VoldemortException( "JSON parsing exception while trying to parse GET response " + e.getMessage(), e); } catch (JsonMappingException e) { throw new VoldemortException( "JSON mapping exception while trying to parse GET response " + e.getMessage(), e); } catch (IOException e) { throw new VoldemortException("IO exception while trying to parse GET response " + e.getMessage(), e); } return results; }