List of usage examples for javax.activation DataHandler DataHandler
public DataHandler(URL url)
DataHandler
instance referencing a URL. From source file:it.cnr.icar.eric.client.xml.registry.util.CertificateUtil.java
@SuppressWarnings("static-access") private static Certificate[] getCertificateSignedByRegistry(LifeCycleManager lcm, X509Certificate inCert) throws JAXRException { Certificate[] certChain = new Certificate[2]; try {// w w w . j av a 2 s . c o m // Save cert in a temporary keystore file which is sent as // repository item to server so it can be signed KeyStore tmpKeystore = KeyStore.getInstance("JKS"); tmpKeystore.load(null, bu.FREEBXML_REGISTRY_KS_PASS_REQ.toCharArray()); tmpKeystore.setCertificateEntry(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_REQ, inCert); File repositoryItemFile = File.createTempFile(".eric-ca-req", ".jks"); repositoryItemFile.deleteOnExit(); FileOutputStream fos = new java.io.FileOutputStream(repositoryItemFile); tmpKeystore.store(fos, bu.FREEBXML_REGISTRY_KS_PASS_REQ.toCharArray()); fos.flush(); fos.close(); // Now have server sign the cert using extensionRequest javax.activation.DataHandler repositoryItem = new DataHandler(new FileDataSource(repositoryItemFile)); String id = it.cnr.icar.eric.common.Utility.getInstance().createId(); HashMap<String, Object> idToRepositoryItemsMap = new HashMap<String, Object>(); idToRepositoryItemsMap.put(id, repositoryItem); HashMap<String, String> slotsMap = new HashMap<String, String>(); slotsMap.put(BindingUtility.FREEBXML_REGISTRY_PROTOCOL_SIGNCERT, "true"); RegistryRequestType req = bu.rsFac.createRegistryRequestType(); bu.addSlotsToRequest(req, slotsMap); RegistryResponseHolder respHolder = ((LifeCycleManagerImpl) lcm).extensionRequest(req, idToRepositoryItemsMap); DataHandler responseRepositoryItem = (DataHandler) respHolder.getAttachmentsMap().get(id); InputStream is = responseRepositoryItem.getInputStream(); KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(is, bu.FREEBXML_REGISTRY_KS_PASS_RESP.toCharArray()); is.close(); certChain[0] = keyStore.getCertificate(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_RESP); if (certChain[0] == null) { throw new JAXRException(JAXRResourceBundle.getInstance().getString("message.CannotFindUserCert")); } certChain[1] = keyStore.getCertificate(bu.FREEBXML_REGISTRY_CACERT_ALIAS); if (certChain[1] == null) { throw new JAXRException(JAXRResourceBundle.getInstance().getString("message.CannotFindCARootCert")); } } catch (Exception e) { throw new JAXRException(JAXRResourceBundle.getInstance().getString("message.CertSignFailed"), e); } return certChain; }
From source file:org.shredzone.cilla.ws.impl.PageWsImpl.java
@Override public DataHandler getGalleryImage(long pictureId, ImageProcessing process) throws CillaServiceException { Picture pic = pictureDao.fetch(pictureId); if (pic == null) { throw new CillaNotFoundException("picture", pictureId); }//from w w w . jav a 2 s . c om return new DataHandler(pictureService.getImage(pic, process)); }
From source file:org.jboss.bpm.console.server.FormProcessingFacade.java
private FieldMapping createFieldMapping(MultipartFormDataInput payload) { FieldMapping mapping = new FieldMapping(); Map<String, InputPart> formData = payload.getFormData(); Iterator<String> partNames = formData.keySet().iterator(); while (partNames.hasNext()) { final String partName = partNames.next(); final InputPart part = formData.get(partName); final MediaType mediaType = part.getMediaType(); String mType = mediaType.getType(); String mSubtype = mediaType.getSubtype(); if ("text".equals(mType) && "plain".equals(mSubtype)) { // RFC2045: Each part has an optional "Content-Type" header // that defaults to "text/plain". // Can go into process without conversion if (mapping.isReserved(partName)) mapping.directives.put(partName, part.getBodyAsString()); else/*from w w w. j a v a2 s .c om*/ mapping.processVars.put(partName, part.getBodyAsString()); } else { // anything else turns into a DataHandler final byte[] data = part.getBodyAsString().getBytes(); DataHandler dh = new DataHandler(new DataSource() { public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(data); } public OutputStream getOutputStream() throws IOException { throw new RuntimeException("This is a readonly DataHandler"); } public String getContentType() { return mediaType.getType(); } public String getName() { return partName; } }); mapping.processVars.put(partName, dh); } } return mapping; }
From source file:com.eviware.soapui.impl.wsdl.submit.transports.http.support.attachments.AttachmentUtils.java
public static boolean prepareMessagePart(WsdlAttachmentContainer container, MimeMultipart mp, MessageXmlPart messagePart, StringToStringMap contentIds) throws Exception, MessagingException { boolean isXop = false; XmlObjectTreeModel treeModel = null; XmlCursor cursor = messagePart.newCursor(); XmlObject rootXmlObject = cursor.getObject(); try {/* w w w .j av a 2 s. c o m*/ while (!cursor.isEnddoc()) { if (cursor.isContainer()) { // could be an attachment part (as of "old" SwA specs which // specify a content // element referring to the attachment) if (messagePart.isAttachmentPart()) { String href = cursor.getAttributeText(XOP_HREF_QNAME); if (href != null && href.length() > 0) { contentIds.put(messagePart.getPart().getName(), href); } break; } XmlObject xmlObj = cursor.getObject(); SchemaType schemaType = xmlObj.schemaType(); if (schemaType.isNoType()) { if (treeModel == null) { treeModel = new XmlObjectTreeModel(messagePart.getSchemaType().getTypeSystem(), rootXmlObject); } XmlTreeNode tn = treeModel.getXmlTreeNode(xmlObj); if (tn != null) schemaType = tn.getSchemaType(); } if (AttachmentUtils.isSwaRefType(schemaType)) { String textContent = XmlUtils.getNodeValue(cursor.getDomNode()); if (StringUtils.hasContent(textContent) && textContent.startsWith("cid:")) { textContent = textContent.substring(4); try { // is the textcontent already a URI? new URI(textContent); contentIds.put(textContent, textContent); } catch (RuntimeException e) { // not a URI.. try to create one.. String contentId = textContent + "@soapui.org"; cursor.setTextValue("cid:" + contentId); contentIds.put(textContent, contentId); } } } else if (AttachmentUtils.isXopInclude(schemaType)) { String contentId = cursor.getAttributeText(new QName("href")); if (contentId != null && contentId.length() > 0) { contentIds.put(contentId, contentId); isXop = true; Attachment[] attachments = container.getAttachmentsForPart(contentId); if (attachments.length == 1) { XmlCursor cur = cursor.newCursor(); if (cur.toParent()) { String contentType = getXmlMimeContentType(cur); if (contentType != null && contentType.length() > 0) attachments[0].setContentType(contentType); } cur.dispose(); } } } else { // extract contentId String textContent = XmlUtils.getNodeValue(cursor.getDomNode()); if (StringUtils.hasContent(textContent)) { Attachment attachment = null; boolean isXopAttachment = false; // is content a reference to a file? if (container.isInlineFilesEnabled() && textContent.startsWith("file:")) { String filename = textContent.substring(5); if (container.isMtomEnabled()) { MimeBodyPart part = new PreencodedMimeBodyPart("binary"); String xmimeContentType = getXmlMimeContentType(cursor); if (StringUtils.isNullOrEmpty(xmimeContentType)) xmimeContentType = ContentTypeHandler.getContentTypeFromFilename(filename); part.setDataHandler(new DataHandler(new XOPPartDataSource(new File(filename), xmimeContentType, schemaType))); part.setContentID("<" + filename + ">"); mp.addBodyPart(part); isXopAttachment = true; } else { if (new File(filename).exists()) { inlineData(cursor, schemaType, new FileInputStream(filename)); } else { Attachment att = getAttachmentForFilename(container, filename); if (att != null) inlineData(cursor, schemaType, att.getInputStream()); } } } else { Attachment[] attachmentsForPart = container.getAttachmentsForPart(textContent); if (textContent.startsWith("cid:")) { textContent = textContent.substring(4); attachmentsForPart = container.getAttachmentsForPart(textContent); Attachment[] attachments = attachmentsForPart; if (attachments.length == 1) { attachment = attachments[0]; } else if (attachments.length > 1) { attachment = buildMulitpartAttachment(attachments); } isXopAttachment = container.isMtomEnabled(); contentIds.put(textContent, textContent); } // content should be binary data; is this an XOP element // which should be serialized with MTOM? else if (container.isMtomEnabled() && (SchemaUtils.isBinaryType(schemaType) || SchemaUtils.isAnyType(schemaType))) { if ("true".equals(System.getProperty("soapui.mtom.strict"))) { if (SchemaUtils.isAnyType(schemaType)) { textContent = null; } else { for (int c = 0; c < textContent.length(); c++) { if (Character.isWhitespace(textContent.charAt(c))) { textContent = null; break; } } } } if (textContent != null) { MimeBodyPart part = new PreencodedMimeBodyPart("binary"); String xmimeContentType = getXmlMimeContentType(cursor); part.setDataHandler(new DataHandler( new XOPPartDataSource(textContent, xmimeContentType, schemaType))); textContent = "http://www.soapui.org/" + System.nanoTime(); part.setContentID("<" + textContent + ">"); mp.addBodyPart(part); isXopAttachment = true; } } else if (container.isInlineFilesEnabled() && attachmentsForPart != null && attachmentsForPart.length > 0) { attachment = attachmentsForPart[0]; } } // add XOP include? if (isXopAttachment && container.isMtomEnabled()) { buildXopInclude(cursor, textContent); isXop = true; } // inline? else if (attachment != null) { inlineAttachment(cursor, schemaType, attachment); } } } } cursor.toNextToken(); } } finally { cursor.dispose(); } return isXop; }
From source file:com.nokia.helium.core.EmailDataSender.java
/** * Send xml data// w w w . j a va 2 s . c om * * @param String purpose of this email * @param String file to send * @param String mime type * @param String subject of email * @param String header of mail * @param boolean compress data if true */ public void sendData(String purpose, File fileToSend, String mimeType, String subject, String header, boolean compressData) throws EmailSendException { try { log.debug("sendData:Send file: " + fileToSend + " and mimetype: " + mimeType); if (fileToSend != null && fileToSend.exists()) { InternetAddress[] toAddresses = getToAddressList(); Properties props = new Properties(); if (smtpServerAddress != null) { log.debug("sendData:smtp address: " + smtpServerAddress); props.setProperty("mail.smtp.host", smtpServerAddress); } Session mailSession = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(mailSession); message.setSubject(subject == null ? "" : subject); MimeMultipart multipart = new MimeMultipart("related"); BodyPart messageBodyPart = new MimeBodyPart(); ByteArrayDataSource dataSrc = null; String fileName = fileToSend.getName(); if (compressData) { log.debug("Sending compressed data"); dataSrc = compressFile(fileToSend); dataSrc.setName(fileName + ".gz"); messageBodyPart.setFileName(fileName + ".gz"); } else { log.debug("Sending uncompressed data:"); dataSrc = new ByteArrayDataSource(new FileInputStream(fileToSend), mimeType); message.setContent(FileUtils.readFileToString(fileToSend), "text/html"); multipart = null; } String headerToSend = null; if (header == null) { headerToSend = ""; } messageBodyPart.setHeader("helium-bld-data", headerToSend); messageBodyPart.setDataHandler(new DataHandler(dataSrc)); if (multipart != null) { multipart.addBodyPart(messageBodyPart); // add to the // multipart message.setContent(multipart); } try { message.setFrom(getFromAddress()); } catch (AddressException e) { throw new EmailSendException("Error retrieving the from address: " + e.getMessage(), e); } catch (LDAPException e) { throw new EmailSendException("Error retrieving the from address: " + e.getMessage(), e); } message.addRecipients(Message.RecipientType.TO, toAddresses); log.info("Sending email alert: " + subject); Transport.send(message); } } catch (MessagingException e) { String fullErrorMessage = "Failed sending e-mail: " + purpose; if (e.getMessage() != null) { fullErrorMessage += ": " + e.getMessage(); } throw new EmailSendException(fullErrorMessage, e); } catch (IOException e) { String fullErrorMessage = "Failed sending e-mail: " + purpose; if (e.getMessage() != null) { fullErrorMessage += ": " + e.getMessage(); } // We are Ignoring the errors as no need to fail the build. throw new EmailSendException(fullErrorMessage, e); } }
From source file:it.cnr.icar.eric.server.repository.filesystem.FileSystemRepositoryManager.java
/** * Returns the RepositoryItem with the given unique ID. * * @param id Unique id for repository item * @return RepositoryItem instance/*from ww w .j ava 2 s .co m*/ * @exception RegistryException */ @SuppressWarnings({ "unused", "deprecation" }) public RepositoryItem getRepositoryItem(String id) throws RegistryException { RepositoryItem repositoryItem = null; String origId = id; // Strip off the "urn:uuid:" id = Utility.getInstance().stripId(id); try { String path = getRepositoryItemPath(id); File riFile = new File(path); if (!riFile.exists()) { String errmsg = ServerResourceBundle.getInstance().getString("message.RepositoryItemDoesNotExist", new Object[] { id }); log.error(errmsg); throw new RegistryException(errmsg); } DataHandler contentDataHandler = new DataHandler(new FileDataSource(riFile)); Element sigElement = null; path += ".sig"; File sigFile = new File(path); if (!sigFile.exists()) { String errmsg = "Payload signature for repository item id=\"" + id + "\" does not exist!"; //log.error(errmsg); throw new RegistryException(errmsg); } else { javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory .newInstance(); dbf.setNamespaceAware(true); javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder(); org.w3c.dom.Document sigDoc = db.parse(new FileInputStream(sigFile)); repositoryItem = new RepositoryItemImpl(id, sigDoc.getDocumentElement(), contentDataHandler); } } catch (RegistryException e) { throw e; } catch (Exception e) { throw new RegistryException(e); } return repositoryItem; }
From source file:fr.paris.lutece.portal.service.mail.MailUtil.java
/** * Send a text message.//from ww w .ja va 2s . co m * * @param strRecipientsTo * The list of the main recipients email.Every recipient must be * separated by the mail separator defined in config.properties * @param strRecipientsCc * The recipients list of the carbon copies . * @param strRecipientsBcc * The recipients list of the blind carbon copies . * @param strSenderName * The sender name. * @param strSenderEmail * The sender email address. * @param strSubject * The message subject. * @param strMessage * The message. * @param transport * the smtp transport object * @param session * the smtp session object * @throws AddressException * If invalid address * @throws SendFailedException * If an error occured during sending * @throws MessagingException * If a messaging error occured */ protected static void sendMessageText(String strRecipientsTo, String strRecipientsCc, String strRecipientsBcc, String strSenderName, String strSenderEmail, String strSubject, String strMessage, Transport transport, Session session) throws MessagingException, AddressException, SendFailedException { Message msg = prepareMessage(strRecipientsTo, strRecipientsCc, strRecipientsBcc, strSenderName, strSenderEmail, strSubject, session); msg.setDataHandler(new DataHandler( new ByteArrayDataSource(strMessage, AppPropertiesService.getProperty(PROPERTY_MAIL_TYPE_PLAIN) + AppPropertiesService.getProperty(PROPERTY_CHARSET)))); sendMessage(msg, transport); }
From source file:com.aurel.track.util.emailHandling.MailBuilder.java
private void includeImageLogo(MimeMultipart mimeMultipart) { BodyPart messageBodyPart;/* www .ja v a 2 s. com*/ ArrayList<String> imageFiles = new ArrayList<String>(); imageFiles.add("tracklogo.gif"); // more images can be added here ArrayList<String> cids = new ArrayList<String>(); cids.add("logo"); // for each image there should be a cid here URL imageURL = null; for (int i = 0; i < imageFiles.size(); ++i) { try { DataSource ds = null; messageBodyPart = new MimeBodyPart(); InputStream in = null; in = ImageAction.class.getClassLoader().getResourceAsStream(imageFiles.get(i)); int length = imageFiles.get(i).length(); String type = imageFiles.get(i).substring(length - 4, length - 1); if (in != null) { ds = new ByteArrayDataSource(in, "image/" + type); System.err.println(type); } else { String theResource = "/WEB-INF/classes/resources/MailTemplates/" + imageFiles.get(i); imageURL = servletContext.getResource(theResource); ds = new URLDataSource(imageURL); } messageBodyPart.setDataHandler(new DataHandler(ds)); messageBodyPart.setHeader("Content-ID", cids.get(i)); messageBodyPart.setDisposition("inline"); // add it mimeMultipart.addBodyPart(messageBodyPart); } catch (Exception e) { LOGGER.error(ExceptionUtils.getStackTrace(e)); // what shall we do here? } } }
From source file:com.basp.trabajo_al_minuto.model.business.BusinessUtils.java
/** * Se encarga de enviar el mensaje de correo electronico * */// w w w . j a v a 2 s. co m public static Boolean sendEmail(final EmailMessage emdto) throws BusinessException { try { Session session; Properties properties = System.getProperties(); properties.put("mail.host", emdto.getHost()); properties.put("mail.transport.protocol", "smtp"); properties.put("mail.smtp.port", emdto.getPort()); properties.put("mail.smtp.starttls.enable", emdto.getStarttls()); if (emdto.getUser() != null && emdto.getPassword() != null) { properties.put("mail.smtp.auth", "true"); session = Session.getDefaultInstance(properties, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(emdto.getUser(), emdto.getPassword()); } }); } else { properties.put("mail.smtp.auth", "false"); session = Session.getDefaultInstance(properties); } message = new MimeMessage(session); message.setFrom(new InternetAddress(emdto.getFrom(), emdto.getMask())); message.setSubject(emdto.getSubject()); for (String to : emdto.getToList()) { message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); } if (emdto.getCcList() != null) { for (String cc : emdto.getCcList()) { message.addRecipient(Message.RecipientType.CC, new InternetAddress(cc)); } } if (emdto.getCcoList() != null) { for (String cco : emdto.getCcoList()) { message.addRecipient(Message.RecipientType.BCC, new InternetAddress(cco)); } } bodyPart = new MimeBodyPart(); bodyPart.setContent(emdto.getBodyMessage(), emdto.getMimeTypeMessage()); multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); if (emdto.getFilePaths() != null) { for (String filePath : emdto.getFilePaths()) { File file = new File(filePath); if (file.exists()) { dataSource = new FileDataSource(file); bodyPart = new MimeBodyPart(); bodyPart.setDataHandler(new DataHandler(dataSource)); bodyPart.setFileName(file.getName()); multipart.addBodyPart(bodyPart); } } } message.setContent(multipart); Transport.send(message); } catch (MessagingException | UnsupportedEncodingException ex) { Logger.getLogger(BusinessUtils.class.getName()).log(Level.SEVERE, "BusinessUtils.sendEmail Exception", ex); throw new BusinessException(ex); } return Boolean.TRUE; }
From source file:org.entermedia.email.PostMail.java
public void postMail(List<InternetAddress> recipients, List<InternetAddress> blindrecipients, String subject, String inHtml, String inText, String from, List inAttachments, Map inProperties) throws MessagingException { // Set the host smtp address Properties props = new Properties(); // create some properties and get the default Session props.put("mail.smtp.host", fieldSmtpServer); props.put("mail.smtp.port", String.valueOf(getPort())); props.put("mail.smtp.auth", new Boolean(fieldSmtpSecured).toString()); if (isSslEnabled()) { props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); }//from w ww. j a v a 2 s. c om Session session = null; if (isEnableTls()) { props.put("mail.smtp.starttls.enable", "true"); session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(getSmtpUsername(), getSmtpPassword()); } }); } else if (fieldSmtpSecured) { SmtpAuthenticator auth = new SmtpAuthenticator(); session = Session.getInstance(props, auth); } else { session = Session.getInstance(props); } // session.setDebug(debug); // create a message Message msg = new MimeMessage(session); MimeMultipart mp = null; // msg.setDataHandler(new DataHandler(new ByteArrayDataSource(message, // "text/html"))); if (inAttachments != null && inAttachments.size() == 0) { inAttachments = null; } if (inText != null && inHtml != null || inAttachments != null) { // Create an "Alternative" Multipart message mp = new MimeMultipart("mixed"); if (inText != null) { BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(inText, "text/plain"); mp.addBodyPart(messageBodyPart); } if (inHtml != null) { BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(inHtml, "text/html"); mp.addBodyPart(messageBodyPart); } if (inAttachments != null) { for (Iterator iterator = inAttachments.iterator(); iterator.hasNext();) { String filename = (String) iterator.next(); File file = new File(filename); if (file.exists() && !file.isDirectory()) { // create the second message part MimeBodyPart mbp = new MimeBodyPart(); FileDataSource fds = new FileDataSource(file); mbp.setDataHandler(new DataHandler(fds)); mbp.setFileName(fds.getName()); mp.addBodyPart(mbp); } } } msg.setContent(mp); } else if (inHtml != null) { msg.setContent(inHtml, "text/html"); } else { msg.setContent(inText, "text/plain"); } // set the from and to address InternetAddress addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); //msg.setRecipient(RecipientType.BCC, addressFrom); msg.setSentDate(new Date()); if (recipients == null || recipients.isEmpty()) { throw new MessagingException("No recipients specified"); } InternetAddress[] addressTo = recipients.toArray(new InternetAddress[recipients.size()]); msg.setRecipients(Message.RecipientType.TO, addressTo); //add bcc if (blindrecipients != null && !blindrecipients.isEmpty()) { InternetAddress[] addressBcc = blindrecipients.toArray(new InternetAddress[blindrecipients.size()]); msg.setRecipients(Message.RecipientType.BCC, addressBcc); } // Optional : You can also set your custom headers in the Email if you // Want // msg.addHeader("MyHeaderName", "myHeaderValue"); // Setting the Subject and Content Type msg.setSubject(subject); // Transport tr = session.getTransport("smtp"); // tr.connect(serverandport[0], null, null); // msg.saveChanges(); // don't forget this // tr.sendMessage(msg, msg.getAllRecipients()); // tr.close(); // msg.setContent(msg, "text/plain"); Transport.send(msg); log.info("sent email " + subject); }