List of usage examples for javax.mail.internet ContentType ContentType
public ContentType(String s) throws ParseException
From source file:com.cubusmail.server.services.RetrieveAttachmentServlet.java
@Override public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { WebApplicationContext context = WebApplicationContextUtils .getRequiredWebApplicationContext(request.getSession().getServletContext()); try {/*w w w . ja v a 2 s. c o m*/ String messageId = request.getParameter("messageId"); String attachmentIndex = request.getParameter("attachmentIndex"); boolean view = "1".equals(request.getParameter("view")); if (messageId != null) { IMailbox mailbox = SessionManager.get().getMailbox(); Message msg = mailbox.getCurrentFolder().getMessageById(Long.parseLong(messageId)); List<MimePart> attachmentList = MessageUtils.attachmentsFromPart(msg); int index = Integer.valueOf(attachmentIndex); MimePart retrievePart = attachmentList.get(index); ContentType contentType = new ContentType(retrievePart.getContentType()); String fileName = retrievePart.getFileName(); if (StringUtils.isEmpty(fileName)) { fileName = context.getMessage("message.unknown.attachment", null, SessionManager.get().getLocale()); } StringBuffer contentDisposition = new StringBuffer(); if (!view) { contentDisposition.append("attachment; filename=\""); contentDisposition.append(fileName).append("\""); } response.setHeader("cache-control", "no-store"); response.setHeader("pragma", "no-cache"); response.setIntHeader("max-age", 0); response.setIntHeader("expires", 0); if (!StringUtils.isEmpty(contentDisposition.toString())) { response.setHeader("Content-disposition", contentDisposition.toString()); } response.setContentType(contentType.getBaseType()); // response.setContentLength( // MessageUtils.calculateSizeFromPart( retrievePart ) ); BufferedInputStream bufInputStream = new BufferedInputStream(retrievePart.getInputStream()); OutputStream outputStream = response.getOutputStream(); byte[] inBuf = new byte[1024]; int len = 0; int total = 0; while ((len = bufInputStream.read(inBuf)) > 0) { outputStream.write(inBuf, 0, len); total += len; } bufInputStream.close(); outputStream.flush(); outputStream.close(); } } catch (Exception ex) { log.error(ex.getMessage(), ex); } }
From source file:com.vmware.identity.openidconnect.common.AuthenticationErrorResponse.java
private HTTPResponse formPostResponse() throws SerializeException { HTTPResponse httpResponse = new HTTPResponse(HTTPResponse.SC_OK); try {/*from w w w.j av a 2 s. com*/ httpResponse.setContentType(new ContentType("text/html;charset=UTF-8")); } catch (ParseException e) { throw new SerializeException("could not set response type header", e); } httpResponse.setCacheControl("no-cache, no-store"); httpResponse.setPragma("no-cache"); httpResponse.setContent( String.format(HTML_RESPONSE, super.getRedirectionURI().toString(), super.getState().getValue(), super.getErrorObject().getCode(), super.getErrorObject().getDescription())); return httpResponse; }
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);// ww w .j av a 2 s . c om 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:org.wso2.carbon.connector.util.ResultPayloadCreater.java
public static boolean buildFile(FileObject file, MessageContext msgCtx, String contentType, String streaming) throws SynapseException { ManagedDataSource dataSource = null; try {/*from ww w. ja v a 2 s . c o m*/ if (contentType == null || contentType.trim().equals("")) { if (file.getName().getExtension().toLowerCase().endsWith("xml")) { contentType = "text/xml"; } else if (file.getName().getExtension().toLowerCase().endsWith("txt")) { contentType = "text/plain"; } } else { // Extract the charset encoding from the configured content type and // set the CHARACTER_SET_ENCODING property as e.g. SOAPBuilder relies on this. String charSetEnc = null; try { if (contentType != null) { charSetEnc = new ContentType(contentType).getParameter("charset"); } } catch (ParseException ex) { log.warn("Invalid encoding type.", ex); } msgCtx.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc); } if (log.isDebugEnabled()) { log.debug("Processed file : " + file + " of Content-type : " + contentType); } org.apache.axis2.context.MessageContext axis2MsgCtx = ((org.apache.synapse.core.axis2.Axis2MessageContext) msgCtx) .getAxis2MessageContext(); // Determine the message builder to use Builder builder; if (contentType == null) { log.debug("No content type specified. Using RELAY builder."); builder = new BinaryRelayBuilder(); } else { int index = contentType.indexOf(';'); String type = index > 0 ? contentType.substring(0, index) : contentType; builder = BuilderUtil.getBuilderFromSelector(type, axis2MsgCtx); if (builder == null) { if (log.isDebugEnabled()) { log.debug( "No message builder found for type '" + type + "'. Falling back to RELAY builder."); } builder = new BinaryRelayBuilder(); } } // set the message payload to the message context InputStream in; if (builder instanceof DataSourceMessageBuilder && "true".equals(streaming)) { in = null; dataSource = ManagedDataSourceFactory.create(new FileObjectDataSource(file, contentType)); } else { in = new AutoCloseInputStream(file.getContent().getInputStream()); dataSource = null; } // Inject the message to the sequence. OMElement documentElement; if (in != null) { documentElement = builder.processDocument(in, contentType, axis2MsgCtx); } else { documentElement = ((DataSourceMessageBuilder) builder).processDocument(dataSource, contentType, axis2MsgCtx); } //We need this to build the complete message before closing the stream documentElement.toString(); msgCtx.setEnvelope(TransportUtils.createSOAPEnvelope(documentElement)); } catch (SynapseException se) { throw se; } catch (Exception e) { log.error("Error while processing the file/folder", e); throw new SynapseException("Error while processing the file/folder", e); } finally { if (dataSource != null) { dataSource.destroy(); } } return true; }
From source file:com.zotoh.crypto.MICUte.java
private static Object fromMP(Multipart mp) throws Exception { ContentType ct = new ContentType(mp.getContentType()); BodyPart bp;/* ww w . j a va 2 s.c om*/ Object contents; Object rc = null; int count = mp.getCount(); if ("multipart/mixed".equalsIgnoreCase(ct.getBaseType())) { if (count > 0) { bp = mp.getBodyPart(0); contents = bp.getContent(); // check for EDI payload sent as attachment String ctype = bp.getContentType(); boolean getNextPart = false; if (ctype.indexOf("text/plain") >= 0) { if (contents instanceof String) { String bodyText = "This is a generated cryptographic message in MIME format"; if (((String) contents).startsWith(bodyText)) { getNextPart = true; } } if (!getNextPart) { // check for a content disposition // if disposition type is attachment, then this is a doc getNextPart = true; String disp = bp.getDisposition(); if (disp != null && disp.toLowerCase().equals("attachment")) getNextPart = false; } } if ((count >= 2) && getNextPart) { bp = mp.getBodyPart(1); contents = bp.getContent(); } if (contents instanceof String) { rc = asBytes((String) contents); } else if (contents instanceof byte[]) { rc = contents; } else if (contents instanceof InputStream) { rc = contents; } else { String cn = contents == null ? "null" : contents.getClass().getName(); throw new Exception("Unsupport MIC object: " + cn); } } } else if (count > 0) { bp = mp.getBodyPart(0); contents = bp.getContent(); if (contents instanceof String) { rc = asBytes((String) contents); } else if (contents instanceof byte[]) { rc = contents; } else if (contents instanceof InputStream) { rc = contents; } else { String cn = contents == null ? "null" : contents.getClass().getName(); throw new Exception("Unsupport MIC object: " + cn); } } return rc; }
From source file:org.apache.axis2.transport.mail.MailRequestResponseClient.java
public IncomingMessage<byte[]> sendMessage(ClientOptions options, ContentType contentType, byte[] message) throws Exception { String msgId = sendMessage(contentType, message); Message reply = waitForReply(msgId); Assert.assertNotNull("No response received", reply); Assert.assertEquals(channel.getSender().getAddress(), ((InternetAddress) reply.getRecipients(Message.RecipientType.TO)[0]).getAddress()); Assert.assertEquals(channel.getRecipient().getAddress(), ((InternetAddress) reply.getFrom()[0]).getAddress()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); reply.getDataHandler().writeTo(baos); return new IncomingMessage<byte[]>(new ContentType(reply.getContentType()), baos.toByteArray()); }
From source file:com.cubusmail.server.services.RetrieveImageServlet.java
@Override public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {// ww w. j ava 2s .c o m String messageId = request.getParameter("messageId"); String attachmentIndex = request.getParameter("attachmentIndex"); boolean isThumbnail = Boolean.valueOf(request.getParameter("thumbnail")).booleanValue(); if (messageId != null) { IMailbox mailbox = SessionManager.get().getMailbox(); Message msg = mailbox.getCurrentFolder().getMessageById(Long.parseLong(messageId)); if (isThumbnail) { List<MimePart> attachmentList = MessageUtils.attachmentsFromPart(msg); int index = Integer.valueOf(attachmentIndex); MimePart retrievePart = attachmentList.get(index); ContentType contentType = new ContentType(retrievePart.getContentType()); response.setContentType(contentType.getBaseType()); BufferedInputStream bufInputStream = new BufferedInputStream(retrievePart.getInputStream()); OutputStream outputStream = response.getOutputStream(); writeScaledImage(bufInputStream, outputStream); bufInputStream.close(); outputStream.flush(); outputStream.close(); } else { Part imagePart = findImagePart(msg); if (imagePart != null) { ContentType contentType = new ContentType(imagePart.getContentType()); response.setContentType(contentType.getBaseType()); BufferedInputStream bufInputStream = new BufferedInputStream(imagePart.getInputStream()); OutputStream outputStream = response.getOutputStream(); byte[] inBuf = new byte[1024]; int len = 0; int total = 0; while ((len = bufInputStream.read(inBuf)) > 0) { outputStream.write(inBuf, 0, len); total += len; } bufInputStream.close(); outputStream.flush(); outputStream.close(); } } } } catch (Exception ex) { log.error(ex.getMessage(), ex); } }
From source file:org.esxx.Response.java
public void writeResult(OutputStream out) throws IOException { try {/* w w w. jav a 2 s. c o m*/ writeObject(resultObject, new ContentType(guessContentType()), out); } catch (javax.mail.internet.ParseException ex) { throw new IOException("Invalid content-type: " + ex.getMessage(), ex); } }
From source file:org.wso2.carbon.connector.util.ResultPayloadCreator.java
/** * Read the file content and set those content as the current SOAPEnvelope. * * @param file File which needs to be read. * @param msgCtx Message Context that is used in the file read mediation flow. * @param contentType content type.// w ww. j a v a 2 s .c o m * @param streaming streaming mode (true/false). * @return true, if file content is read successfully. */ public static boolean buildFile(FileObject file, MessageContext msgCtx, String contentType, boolean streaming) { ManagedDataSource dataSource = null; InputStream in = null; try { if (StringUtils.isEmpty(contentType)) { if (file.getName().getExtension().toLowerCase().endsWith("xml")) { contentType = "application/xml"; } else if (file.getName().getExtension().toLowerCase().endsWith("txt")) { contentType = "text/plain"; } } else { // Extract the charset encoding from the configured content type and // set the CHARACTER_SET_ENCODING property as e.g. SOAPBuilder relies on this. try { String charSetEnc = new ContentType(contentType).getParameter("charset"); msgCtx.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc); } catch (ParseException ex) { throw new SynapseException("Invalid encoding type.", ex); } } if (log.isDebugEnabled()) { log.debug("Processed file : " + file + " of Content-type : " + contentType); } org.apache.axis2.context.MessageContext axis2MsgCtx = ((org.apache.synapse.core.axis2.Axis2MessageContext) msgCtx) .getAxis2MessageContext(); // Determine the message builder to use Builder builder; if (StringUtils.isEmpty(contentType)) { log.debug("No content type specified. Using RELAY builder."); builder = new BinaryRelayBuilder(); } else { int index = contentType.indexOf(';'); String type = index > 0 ? contentType.substring(0, index) : contentType; builder = BuilderUtil.getBuilderFromSelector(type, axis2MsgCtx); if (builder == null) { if (log.isDebugEnabled()) { log.debug( "No message builder found for type '" + type + "'. Falling back to RELAY builder."); } builder = new BinaryRelayBuilder(); } } // set the message payload to the message context OMElement documentElement; if (builder instanceof DataSourceMessageBuilder && streaming) { dataSource = ManagedDataSourceFactory.create(new FileObjectDataSource(file, contentType)); documentElement = ((DataSourceMessageBuilder) builder).processDocument(dataSource, contentType, axis2MsgCtx); } else { in = new AutoCloseInputStream(file.getContent().getInputStream()); documentElement = builder.processDocument(in, contentType, axis2MsgCtx); } // We need this to build the complete message before closing the stream if (!streaming && documentElement != null) { //msgCtx.getEnvelope().build(); documentElement.toString(); } msgCtx.setEnvelope(TransportUtils.createSOAPEnvelope(documentElement)); } catch (Exception e) { throw new SynapseException("Error while processing the file/folder", e); } finally { if (dataSource != null) { dataSource.destroy(); } if (in != null) { try { in.close(); } catch (IOException e) { log.error("Error while closing the InputStream"); } } try { file.close(); } catch (FileSystemException e) { log.error("Error while closing the FileObject", e); } } return true; }
From source file:com.adaptris.core.mail.attachment.MimeMailCreator.java
private static ContentType getContentType(MimeBodyPart p) throws Exception { ContentType result = null;/*from w w w .jav a 2 s. c o m*/ String[] hdr = p.getHeader(MimeConstants.HEADER_CONTENT_TYPE); if (hdr != null) { result = new ContentType(hdr[0]); } return result; }