List of usage examples for javax.activation DataHandler DataHandler
public DataHandler(URL url)
DataHandler
instance referencing a URL. From source file:se.inera.axel.shs.camel.ShsMessageDataFormatTest.java
@DirtiesContext @Test//from ww w. j ava 2 s . c o m public void testMarshalJpg() throws Exception { Assert.assertNotNull(testShsMessage); Assert.assertNotNull(testJpgFile); testShsMessage.getDataParts().remove(0); DataPart dataPart = new DataPart( new DataHandler(new ByteArrayDataSource(testJpgFile.getInputStream(), "image/jpeg"))); dataPart.setContentType("image/jpeg"); dataPart.setFileName(testJpgFile.getFilename()); dataPart.setTransferEncoding("base64"); dataPart.setDataPartType("jpg"); testShsMessage.getDataParts().add(dataPart); resultEndpoint.expectedMessageCount(1); template.sendBody("direct:marshalRoundtrip", testShsMessage); resultEndpoint.assertIsSatisfied(); List<Exchange> exchanges = resultEndpoint.getReceivedExchanges(); Exchange exchange = exchanges.get(0); ShsMessage shsMessage = exchange.getIn().getMandatoryBody(ShsMessage.class); Assert.assertNotSame(shsMessage, testShsMessage); ShsLabel label = shsMessage.getLabel(); Assert.assertNotNull(label, "label should not be null"); Assert.assertEquals(label.getSubject(), testShsMessage.getLabel().getSubject()); Assert.assertEquals(label.getDatetime().toString(), testShsMessage.getLabel().getDatetime().toString()); Assert.assertNotNull(testShsMessage.getDataParts()); DataPart dataPartResponse = testShsMessage.getDataParts().get(0); Assert.assertTrue(isSame(testJpgFile.getInputStream(), dataPartResponse.getDataHandler().getInputStream()), "Response data stream is not same as source data stream"); }
From source file:mitm.application.djigzo.james.mailets.BlackberrySMIMEAdapter.java
private void replaceSMIMEAttachment(MimeMessage containerMessage, MimeMessage sourceMessage) throws MessagingException, IOException, PartException { Part smimePart = findAttachment(containerMessage); if (sourceMessage.getSize() > directSizeLimit) { /*// w w w . ja v a 2 s. c o m * The message is too large to be sent to the BB directly so we should * sent it as an attachment that can be downloaded and handled using * a content handler on the BB */ String filename = downloadAttachmentName + DOWNLOAD_ATTACHMENT_EXTENSION; smimePart.setFileName(filename); } smimePart.setDataHandler(new DataHandler( new ByteArrayDataSource(sourceMessage.getInputStream(), "application/octet-stream"))); }
From source file:org.apache.stratos.theme.mgt.ui.processors.AddThemeResourceProcessor.java
private static DataHandler scaleImage(DataHandler dataHandler, int height, int width) throws IOException { Image image = ImageIO.read(new BufferedInputStream(dataHandler.getInputStream())); // Check if the image has transparent pixels boolean hasAlpha = ((BufferedImage) image).getColorModel().hasAlpha(); // Maintain Aspect ratio int thumbHeight = height; int thumbWidth = width; double thumbRatio = (double) width / (double) height; double imageRatio = (double) image.getWidth(null) / (double) image.getHeight(null); if (thumbRatio < imageRatio) { thumbHeight = (int) (thumbWidth / imageRatio); } else {/*w w w .j av a 2s. co m*/ thumbWidth = (int) (thumbHeight * imageRatio); } BufferedImage thumb; // Check if transparent pixels are available and set the color mode accordingly if (hasAlpha) { thumb = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_ARGB); } else { thumb = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); } Graphics2D graphics2D = thumb.createGraphics(); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); // Save the image as PNG so that transparent images are rendered as intended ByteArrayOutputStream output = new ByteArrayOutputStream(); ImageIO.write(thumb, "PNG", output); DataSource dataSource = new ByteArrayDataSource(output.toByteArray(), "application/octet-stream"); return new DataHandler(dataSource); }
From source file:de.extra.client.plugins.responseprocessplugin.filesystem.FileSystemResponseProcessPlugin.java
@Override public IResponseData processResponse(final ResponseTransport extraResponse) { final IResponseData responseData = new ResponseData(); try {/*from w ww .ja v a 2s .com*/ // Ausgabe der Response im log ExtraMessageReturnDataExtractor.printResult(marshaller, extraResponse); pruefeVerzeichnis(); final ResponseTransportHeader transportHeader = extraResponse.getTransportHeader(); final ITransportInfo transportInfo = transportInfoBuilder.createTransportInfo(transportHeader); transportObserver.responseFilled(transportInfo); final ResponseDetailsType responseDetails = transportHeader.getResponseDetails(); final RequestDetailsType requestDetails = transportHeader.getRequestDetails(); if (!isBodyEmpty(extraResponse.getTransportBody())) { final List<ResponsePackage> packageList = extraResponse.getTransportBody().getPackage(); if (packageList == null || packageList.size() == 0) { final String responseId = responseDetails.getResponseID().getValue(); LOG.debug("Keine Pakete vorhanden"); final DataHandler dataHandler = extraResponse.getTransportBody().getData() .getBase64CharSequence().getValue(); if (saveBodyToFilesystem(responseId, dataHandler)) { LOG.debug("Speicheren des Body auf Filesystem erfolgreich"); } final ReportType report = responseDetails.getReport(); final SingleReportData reportData = returnCodeExtractor.extractReportData(report); final String returnCode = reportData.getReturnCode(); final boolean returnCodeSuccessful = extraReturnCodeAnalyser.isReturnCodeSuccessful(returnCode); // Status (DONE oder FAIL) final PersistentStatus persistentStatus = returnCodeSuccessful ? PersistentStatus.DONE : PersistentStatus.FAIL; final String outputIdentifier = baueDateiname(); final ISingleResponseData singleResponseData = new SingleResponseData( requestDetails.getRequestID().getValue(), returnCode, reportData.getReturnText(), responseId, returnCodeSuccessful, persistentStatus, outputIdentifier); responseData.addSingleResponse(singleResponseData); } else { for (final Iterator<ResponsePackage> iter = packageList.iterator(); iter.hasNext();) { final ResponsePackage extraPackage = iter.next(); final String responseId = extraPackage.getPackageHeader().getResponseDetails() .getResponseID().getValue(); DataType data = new DataType(); data = extraPackage.getPackageBody().getData(); DataHandler packageBodyDataHandler = null; if (data.getBase64CharSequence() != null) { packageBodyDataHandler = data.getBase64CharSequence().getValue(); } else { if (data.getCharSequence() != null) { final byte[] packageBody = data.getCharSequence().getValue().getBytes(); final DataSource source = new ByteArrayDataSource(packageBody, "application/octet-stream"); packageBodyDataHandler = new DataHandler(source); } } if (packageBodyDataHandler != null) { if (saveBodyToFilesystem(responseId, packageBodyDataHandler)) { if (LOG.isDebugEnabled()) { LOG.debug("Speichern fr RespId " + responseId + " erfolgreich"); } } } else { LOG.error("RequestPackageBody nicht gefllt"); } } } } else { final ReportType report = responseDetails.getReport(); final String requestId = requestDetails.getRequestID().getValue(); final String responseId = responseDetails.getResponseID().getValue(); saveReportToFilesystem(report, responseId, requestId); final ISingleResponseData singleResponseData = new SingleResponseData(requestId, "C00", "RETURNTEXT", responseId, true, PersistentStatus.DONE, "OUTPUT-ID"); responseData.addSingleResponse(singleResponseData); LOG.info("Body leer"); } } catch (final XmlMappingException xmlMappingException) { throw new ExtraResponseProcessPluginRuntimeException(xmlMappingException); } catch (final IOException ioException) { throw new ExtraResponseProcessPluginRuntimeException(ioException); } return responseData; }
From source file:org.apache.synapse.transport.fix.FIXUtils.java
/** * Constructs the XML infoset for the FIX message body * * @param message the FIX message//from w w w .j a v a2s . c o m * @param body the body element of the XML infoset * @param soapFactory the SOAP factory to create XML elements * @param msgCtx the Axis2 Message context * @throws AxisFault on error */ private void convertFIXBodyToXML(FieldMap message, OMElement body, SOAPFactory soapFactory, MessageContext msgCtx) throws AxisFault { if (log.isDebugEnabled()) { log.debug("Generating FIX message body (Message ID: " + msgCtx.getMessageID() + ")"); } Iterator<Field<?>> iter = message.iterator(); if (iter != null) { while (iter.hasNext()) { Field<?> field = iter.next(); OMElement msgField = soapFactory.createOMElement(FIXConstants.FIX_FIELD, null); msgField.addAttribute(soapFactory.createOMAttribute(FIXConstants.FIX_FIELD_ID, null, String.valueOf(field.getTag()))); Object value = field.getObject(); if (value instanceof byte[]) { DataSource dataSource = new ByteArrayDataSource((byte[]) value); DataHandler dataHandler = new DataHandler(dataSource); String contentID = msgCtx.addAttachment(dataHandler); OMElement binaryData = soapFactory.createOMElement(FIXConstants.FIX_BINARY_FIELD, null); String binaryCID = "cid:" + contentID; binaryData.addAttribute(FIXConstants.FIX_MESSAGE_REFERENCE, binaryCID, null); msgField.addChild(binaryData); } else { createOMText(soapFactory, msgField, value.toString()); } body.addChild(msgField); } } //process FIX repeating groups Iterator<Integer> groupKeyItr = message.groupKeyIterator(); if (groupKeyItr != null) { while (groupKeyItr.hasNext()) { int groupKey = groupKeyItr.next(); OMElement groupsField = soapFactory.createOMElement(FIXConstants.FIX_GROUPS, null); groupsField.addAttribute(FIXConstants.FIX_FIELD_ID, String.valueOf(groupKey), null); List<Group> groupList = message.getGroups(groupKey); Iterator<Group> groupIterator = groupList.iterator(); while (groupIterator.hasNext()) { Group msgGroup = groupIterator.next(); OMElement groupField = soapFactory.createOMElement(FIXConstants.FIX_GROUP, null); // rec. call the method to process the repeating groups convertFIXBodyToXML(msgGroup, groupField, soapFactory, msgCtx); groupsField.addChild(groupField); } body.addChild(groupsField); } } }
From source file:org.sakaiproject.tool.assessment.util.SamigoEmailService.java
public String send() { List attachmentList = null;/*from w ww. j a va 2s . co m*/ AttachmentData a = null; try { Properties props = new Properties(); // Server if (smtpServer == null || smtpServer.equals("")) { log.info("samigo.email.smtpServer is not set"); smtpServer = ServerConfigurationService.getString("smtp@org.sakaiproject.email.api.EmailService"); if (smtpServer == null || smtpServer.equals("")) { log.info("smtp@org.sakaiproject.email.api.EmailService is not set"); log.error( "Please set the value of samigo.email.smtpServer or smtp@org.sakaiproject.email.api.EmailService"); return "error"; } } props.setProperty("mail.smtp.host", smtpServer); // Port if (smtpPort == null || smtpPort.equals("")) { log.warn("samigo.email.smtpPort is not set. The default port 25 will be used."); } else { props.setProperty("mail.smtp.port", smtpPort); } Session session; session = Session.getInstance(props); session.setDebug(true); MimeMessage msg = new MimeMessage(session); InternetAddress fromIA = new InternetAddress(fromEmailAddress, fromName); msg.setFrom(fromIA); InternetAddress[] toIA = { new InternetAddress(toEmailAddress, toName) }; msg.setRecipients(Message.RecipientType.TO, toIA); if ("yes".equals(ccMe)) { InternetAddress[] ccIA = { new InternetAddress(fromEmailAddress, fromName) }; msg.setRecipients(Message.RecipientType.CC, ccIA); } msg.setSubject(subject); EmailBean emailBean = (EmailBean) ContextUtil.lookupBean("email"); attachmentList = emailBean.getAttachmentList(); StringBuilder content = new StringBuilder(message); ArrayList fileList = new ArrayList(); ArrayList fileNameList = new ArrayList(); if (attachmentList != null) { if (prefixedPath == null || prefixedPath.equals("")) { log.error("samigo.email.prefixedPath is not set"); return "error"; } Iterator iter = attachmentList.iterator(); while (iter.hasNext()) { a = (AttachmentData) iter.next(); if (a.getIsLink().booleanValue()) { log.debug("send(): url"); content.append("<br/>\n\r"); content.append("<br/>"); // give a new line content.append(a.getFilename()); } else { log.debug("send(): file"); File attachedFile = getAttachedFile(a.getResourceId()); fileList.add(attachedFile); fileNameList.add(a.getFilename()); } } } Multipart multipart = new MimeMultipart(); MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(content.toString(), "text/html"); multipart.addBodyPart(messageBodyPart); msg.setContent(multipart); for (int i = 0; i < fileList.size(); i++) { messageBodyPart = new MimeBodyPart(); FileDataSource source = new FileDataSource((File) fileList.get(i)); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName((String) fileNameList.get(i)); multipart.addBodyPart(messageBodyPart); } msg.setContent(multipart); Transport.send(msg); } catch (UnsupportedEncodingException e) { log.error("Exception throws from send()" + e.getMessage()); return "error"; } catch (MessagingException e) { log.error("Exception throws from send()" + e.getMessage()); return "error"; } catch (ServerOverloadException e) { log.error("Exception throws from send()" + e.getMessage()); return "error"; } catch (PermissionException e) { log.error("Exception throws from send()" + e.getMessage()); return "error"; } catch (IdUnusedException e) { log.error("Exception throws from send()" + e.getMessage()); return "error"; } catch (TypeException e) { log.error("Exception throws from send()" + e.getMessage()); return "error"; } catch (IOException e) { log.error("Exception throws from send()" + e.getMessage()); return "error"; } finally { if (attachmentList != null) { if (prefixedPath != null && !prefixedPath.equals("")) { StringBuilder sbPrefixedPath; Iterator iter = attachmentList.iterator(); while (iter.hasNext()) { sbPrefixedPath = new StringBuilder(prefixedPath); sbPrefixedPath.append("/email_tmp/"); a = (AttachmentData) iter.next(); if (!a.getIsLink().booleanValue()) { deleteAttachedFile(sbPrefixedPath.append(a.getResourceId()).toString()); } } } } } return "send"; }
From source file:app.logica.gestores.GestorEmail.java
/** * Create a MimeMessage using the parameters provided. * * @param to// w ww. j a va2 s. c o m * Email address of the receiver. * @param from * Email address of the sender, the mailbox account. * @param subject * Subject of the email. * @param bodyText * Body text of the email. * @param file * Path to the file to be attached. * @return MimeMessage to be used to send email. * @throws MessagingException */ private MimeMessage createEmailWithAttachment(String to, String from, String subject, String bodyText, File file) throws MessagingException, IOException { Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); MimeMessage email = new MimeMessage(session); email.setFrom(new InternetAddress(from)); email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to)); email.setSubject(subject); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(bodyText, "text/plain"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeBodyPart); mimeBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(file); mimeBodyPart.setDataHandler(new DataHandler(source)); mimeBodyPart.setFileName(file.getName()); multipart.addBodyPart(mimeBodyPart); email.setContent(multipart); return email; }
From source file:com.gamesalutes.utils.email.DefaultEmailServiceImpl.java
public void send(EmailModel model) throws EmailException { if (LOGGER.isDebugEnabled()) LOGGER.debug("Sending email: " + model); if (model == null) throw new NullPointerException("model"); Properties emailProps;//from www. ja va2 s . co m Session emailSession; // set the relay host as a property of the email session emailProps = new Properties(); emailProps.setProperty("mail.transport.protocol", "smtp"); emailProps.put("mail.smtp.host", host); emailProps.setProperty("mail.smtp.port", String.valueOf(port)); // set the timeouts emailProps.setProperty("mail.smtp.connectiontimeout", String.valueOf(SOCKET_CONNECT_TIMEOUT_MS)); emailProps.setProperty("mail.smtp.timeout", String.valueOf(SOCKET_IO_TIMEOUT_MS)); if (LOGGER.isDebugEnabled()) LOGGER.debug("Email properties: " + emailProps); // set up email session emailSession = Session.getInstance(emailProps, null); emailSession.setDebug(false); String from; String displayFrom; String body; String subject; List<EmailAttachment> attachments; if (model.getFrom() == null) throw new NullPointerException("from"); if (MiscUtils.isEmpty(model.getTo()) && MiscUtils.isEmpty(model.getBcc()) && MiscUtils.isEmpty(model.getCc())) throw new IllegalArgumentException("model has no addresses"); from = model.getFrom(); displayFrom = model.getDisplayFrom(); body = model.getBody(); subject = model.getSubject(); attachments = model.getAttachments(); MimeMessage emailMessage; InternetAddress emailAddressFrom; // create an email message from the current session emailMessage = new MimeMessage(emailSession); // set the from try { emailAddressFrom = new InternetAddress(from, displayFrom); emailMessage.setFrom(emailAddressFrom); } catch (Exception e) { throw new IllegalStateException(e); } if (!MiscUtils.isEmpty(model.getTo())) setEmailRecipients(emailMessage, model.getTo(), RecipientType.TO); if (!MiscUtils.isEmpty(model.getCc())) setEmailRecipients(emailMessage, model.getCc(), RecipientType.CC); if (!MiscUtils.isEmpty(model.getBcc())) setEmailRecipients(emailMessage, model.getBcc(), RecipientType.BCC); try { if (!MiscUtils.isEmpty(subject)) emailMessage.setSubject(subject); Multipart multipart = new MimeMultipart(); if (body != null) { // create the message part MimeBodyPart messageBodyPart = new MimeBodyPart(); //fill message String bodyContentType; // body = Utils.base64Encode(body); bodyContentType = "text/html; charset=UTF-8"; messageBodyPart.setContent(body, bodyContentType); //Content-Transfer-Encoding : base64 // messageBodyPart.addHeader("Content-Transfer-Encoding", "base64"); multipart.addBodyPart(messageBodyPart); } // Part two is attachment if (attachments != null && !attachments.isEmpty()) { try { for (EmailAttachment a : attachments) { MimeBodyPart attachBodyPart = new MimeBodyPart(); // don't base 64 encode DataSource source = new StreamDataSource( new DefaultStreamFactory(a.getInputStream(), false), a.getName(), a.getContentType()); attachBodyPart.setDataHandler(new DataHandler(source)); attachBodyPart.setFileName(a.getName()); attachBodyPart.setHeader("Content-Type", a.getContentType()); attachBodyPart.addHeader("Content-Transfer-Encoding", "base64"); // add the attachment to the message multipart.addBodyPart(attachBodyPart); } } // close all the input streams finally { for (EmailAttachment a : attachments) MiscUtils.closeStream(a.getInputStream()); } } // set the content emailMessage.setContent(multipart); emailMessage.saveChanges(); if (LOGGER.isDebugEnabled()) LOGGER.debug("Sending email message: " + emailMessage); Transport.send(emailMessage); if (LOGGER.isDebugEnabled()) LOGGER.debug("Sending email complete."); } catch (Exception e) { throw new EmailException(e); } }
From source file:sendhtml.java
public void collect(BufferedReader in, Message msg) throws MessagingException, IOException { String line;//from w w w . j a v a 2 s. c om String subject = msg.getSubject(); StringBuffer sb = new StringBuffer(); sb.append("<HTML>\n"); sb.append("<HEAD>\n"); sb.append("<TITLE>\n"); sb.append(subject + "\n"); sb.append("</TITLE>\n"); sb.append("</HEAD>\n"); sb.append("<BODY>\n"); sb.append("<H1>" + subject + "</H1>" + "\n"); while ((line = in.readLine()) != null) { sb.append(line); sb.append("\n"); } sb.append("</BODY>\n"); sb.append("</HTML>\n"); msg.setDataHandler(new DataHandler(new ByteArrayDataSource(sb.toString(), "text/html"))); }
From source file:eu.openanalytics.rsb.component.SoapMtomJobHandler.java
private ResultType buildResult(final JobType job, final MultiFilesResult multiFilesResult) throws FileNotFoundException, IOException { Validate.notNull(multiFilesResult, NULL_RESULT_RECEIVED); final boolean isOneZipJob = job.getPayload().size() == 1 && Constants.ZIP_CONTENT_TYPES.contains(job.getPayload().get(0).getContentType()); final File[] resultFiles = isOneZipJob ? new File[] { MultiFilesResult.zipResultFilesIfNotError(multiFilesResult) } : multiFilesResult.getPayload(); final ResultType result = createResult(multiFilesResult); for (final File resultFile : resultFiles) { final PayloadType payload = soapOF.createPayloadType(); payload.setContentType(Util.getContentType(resultFile)); payload.setName(resultFile.getName()); payload.setData(new DataHandler(new FileDataSource(resultFile))); result.getPayload().add(payload); }/* ww w . j a v a2 s.c o m*/ return result; }