Example usage for javax.activation DataHandler DataHandler

List of usage examples for javax.activation DataHandler DataHandler

Introduction

In this page you can find the example usage for javax.activation DataHandler DataHandler.

Prototype

public DataHandler(URL url) 

Source Link

Document

Create a DataHandler instance referencing a URL.

Usage

From source file:com.haulmont.cuba.core.app.EmailSender.java

protected MimeBodyPart createAttachmentPart(SendingAttachment attachment) throws MessagingException {
    DataSource source = new MyByteArrayDataSource(attachment.getContent());

    String mimeType = FileTypesHelper.getMIMEType(attachment.getName());
    String encodedFileName = encodeAttachmentName(attachment);

    String contentId = attachment.getContentId();
    if (contentId == null) {
        contentId = encodedFileName;/*from   w  w w. j  a va 2 s  . c o m*/
    }

    String disposition = attachment.getDisposition() != null ? attachment.getDisposition() : Part.INLINE;
    String charset = MimeUtility.mimeCharset(
            attachment.getEncoding() != null ? attachment.getEncoding() : StandardCharsets.UTF_8.name());
    String contentTypeValue = String.format("%s; charset=%s; name=\"%s\"", mimeType, charset, encodedFileName);

    MimeBodyPart attachmentPart = new MimeBodyPart();
    attachmentPart.setDataHandler(new DataHandler(source));
    attachmentPart.setHeader("Content-ID", "<" + contentId + ">");
    attachmentPart.setHeader("Content-Type", contentTypeValue);
    attachmentPart.setFileName(encodedFileName);
    attachmentPart.setDisposition(disposition);

    return attachmentPart;
}

From source file:it.cnr.icar.eric.server.security.authentication.CertificateAuthority.java

/** Extension request to sign specified cert and return the signed cert. */
@SuppressWarnings("static-access")
public RegistryResponseHolder signCertificateRequest(UserType user, RegistryRequestType req,
        Map<?, ?> idToRepositoryItemMap) throws RegistryException {

    RegistryResponseHolder respHolder = null;
    RegistryResponseType ebRegistryResponseType = null;
    ServerRequestContext context = null;

    try {/*from  w ww  .j a va2  s.c  o  m*/
        context = new ServerRequestContext("CertificateAUthority.signCertificateRequest", req);
        context.setUser(user);

        if (idToRepositoryItemMap.keySet().size() == 0) {
            throw new MissingRepositoryItemException(
                    ServerResourceBundle.getInstance().getString("message.KSRepItemNotFound"));
        }

        String id = (String) idToRepositoryItemMap.keySet().iterator().next();

        Object obj = idToRepositoryItemMap.get(id);
        if (!(obj instanceof RepositoryItem)) {
            throw new InvalidContentException();
        }
        RepositoryItem ri = (RepositoryItem) obj; //This is the JKS keystore containing cert to be signed            

        //Read original cert from keystore
        InputStream is = ri.getDataHandler().getInputStream();
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(is, bu.FREEBXML_REGISTRY_KS_PASS_REQ.toCharArray());
        is.close();
        X509Certificate cert = (X509Certificate) keyStore
                .getCertificate(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_REQ);

        //Sign the cert
        cert = signCertificate(cert);

        //Replace cert with signed cert in keystore
        keyStore.deleteEntry(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_REQ);
        keyStore.setCertificateEntry(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_RESP, cert);

        //Add CA root cert (RegistryOPerator's cert) to keystore.
        keyStore.setCertificateEntry(bu.FREEBXML_REGISTRY_CACERT_ALIAS, getCACertificate());

        Certificate[] certChain = new Certificate[2];
        certChain[0] = cert;
        certChain[1] = getCACertificate();
        validateChain(certChain);

        File repositoryItemFile = File.createTempFile(".eric-ca-resp", ".jks");
        repositoryItemFile.deleteOnExit();
        FileOutputStream fos = new java.io.FileOutputStream(repositoryItemFile);
        keyStore.store(fos, bu.FREEBXML_REGISTRY_KS_PASS_RESP.toCharArray());
        fos.flush();
        fos.close();

        DataHandler dh = new DataHandler(new FileDataSource(repositoryItemFile));
        RepositoryItemImpl riNew = new RepositoryItemImpl(id, dh);

        ebRegistryResponseType = bu.rsFac.createRegistryResponseType();
        ebRegistryResponseType.setStatus(BindingUtility.CANONICAL_RESPONSE_STATUS_TYPE_ID_Success);

        HashMap<String, Object> respIdToRepositoryItemMap = new HashMap<String, Object>();
        respIdToRepositoryItemMap.put(id, riNew);

        respHolder = new RegistryResponseHolder(ebRegistryResponseType, respIdToRepositoryItemMap);

    } catch (RegistryException e) {
        context.rollback();
        throw e;
    } catch (Exception e) {
        context.rollback();
        throw new RegistryException(e);
    }

    context.commit();
    return respHolder;
}

From source file:org.linagora.linshare.core.service.impl.MailNotifierServiceImpl.java

@Override
public void sendNotification(String smtpSender, String replyTo, String recipient, String subject,
        String htmlContent, String inReplyTo, String references) throws SendFailedException {

    if (smtpServer.equals("")) {
        logger.warn("Mail notifications are disabled.");
        return;//from  ww w. ja  va  2 s.  c  o m
    }
    // get the mail session
    Session session = getMailSession();

    // Define message
    MimeMessage messageMim = new MimeMessage(session);

    try {
        messageMim.setFrom(new InternetAddress(smtpSender));

        if (replyTo != null) {
            InternetAddress reply[] = new InternetAddress[1];
            reply[0] = new InternetAddress(replyTo);
            messageMim.setReplyTo(reply);
        }

        messageMim.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(recipient));

        if (inReplyTo != null && inReplyTo != "") {
            // This field should contain only ASCCI character (RFC 822)
            if (isPureAscii(inReplyTo)) {
                messageMim.setHeader("In-Reply-To", inReplyTo);
            }
        }

        if (references != null && references != "") {
            // This field should contain only ASCCI character (RFC 822)  
            if (isPureAscii(references)) {
                messageMim.setHeader("References", references);
            }
        }

        messageMim.setSubject(subject, charset);

        // Create a "related" Multipart message
        // content type is multipart/alternative
        // it will contain two part BodyPart 1 and 2
        Multipart mp = new MimeMultipart("alternative");

        // BodyPart 2
        // content type is multipart/related
        // A multipart/related is used to indicate that message parts should
        // not be considered individually but rather
        // as parts of an aggregate whole. The message consists of a root
        // part (by default, the first) which reference other parts inline,
        // which may in turn reference other parts.
        Multipart html_mp = new MimeMultipart("related");

        // Include an HTML message with images.
        // BodyParts: the HTML file and an image

        // Get the HTML file
        BodyPart rel_bph = new MimeBodyPart();
        rel_bph.setDataHandler(
                new DataHandler(new ByteArrayDataSource(htmlContent, "text/html; charset=" + charset)));
        html_mp.addBodyPart(rel_bph);

        // Create the second BodyPart of the multipart/alternative,
        // set its content to the html multipart, and add the
        // second bodypart to the main multipart.
        BodyPart alt_bp2 = new MimeBodyPart();
        alt_bp2.setContent(html_mp);
        mp.addBodyPart(alt_bp2);

        messageMim.setContent(mp);

        // RFC 822 "Date" header field
        // Indicates that the message is complete and ready for delivery
        messageMim.setSentDate(new GregorianCalendar().getTime());

        // Since we used html tags, the content must be marker as text/html
        // messageMim.setContent(content,"text/html; charset="+charset);

        Transport tr = session.getTransport("smtp");

        // Connect to smtp server, if needed
        if (needsAuth) {
            tr.connect(smtpServer, smtpPort, smtpUser, smtpPassword);
            messageMim.saveChanges();
            tr.sendMessage(messageMim, messageMim.getAllRecipients());
            tr.close();
        } else {
            // Send message
            Transport.send(messageMim);
        }
    } catch (SendFailedException e) {
        logger.error("Error sending notification on " + smtpServer + " port " + smtpPort + " to " + recipient,
                e);
        throw e;
    } catch (MessagingException e) {
        logger.error("Error sending notification on " + smtpServer + " port " + smtpPort, e);
        throw new TechnicalException(TechnicalErrorCode.MAIL_EXCEPTION, "Error sending notification", e);
    } catch (Exception e) {
        logger.error("Error sending notification on " + smtpServer + " port " + smtpPort, e);
        throw new TechnicalException(TechnicalErrorCode.MAIL_EXCEPTION, "Error sending notification", e);
    }
}

From source file:org.shredzone.cilla.ws.impl.PageWsImpl.java

@Override
public DataHandler getMediumImage(long mediumId, ImageProcessing process) throws CillaServiceException {
    Medium medium = mediumDao.fetch(mediumId);
    if (medium == null) {
        throw new CillaNotFoundException("medium", mediumId);
    }//w  ww. j a  v a 2s .c o  m

    return new DataHandler(pageService.getMediumImage(medium, process));
}

From source file:org.apache.axis2.transport.mail.EMailSender.java

private void createMailMimeMessage(final MimeMessage msg, MailToInfo mailToInfo, OMOutputFormat format)
        throws MessagingException {

    // Create the message part
    BodyPart messageBodyPart = new MimeBase64BodyPart();
    messageBodyPart.setText("");
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);

    DataSource source = null;//from  ww w  .j ava  2  s.  c  om

    // Part two is attachment
    if (outputStream instanceof ByteArrayOutputStream) {
        source = new ByteArrayDataSource(((ByteArrayOutputStream) outputStream).toByteArray());
    }
    messageBodyPart = new MimeBase64BodyPart();
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setDisposition(Part.ATTACHMENT);

    messageBodyPart.addHeader("Content-Description", "\"" + mailToInfo.getContentDescription() + "\"");

    String contentType = format.getContentType() != null ? format.getContentType()
            : Constants.DEFAULT_CONTENT_TYPE;
    if (contentType.indexOf(SOAP11Constants.SOAP_11_CONTENT_TYPE) > -1) {
        if (messageContext.getSoapAction() != null) {
            messageBodyPart.setHeader(Constants.HEADER_SOAP_ACTION, messageContext.getSoapAction());
        }
    }

    if (contentType.indexOf(SOAP12Constants.SOAP_12_CONTENT_TYPE) > -1) {
        if (messageContext.getSoapAction() != null) {
            messageBodyPart.setHeader("Content-Type", contentType + "; charset=" + format.getCharSetEncoding()
                    + " ; action=\"" + messageContext.getSoapAction() + "\"");
        }
    } else {
        messageBodyPart.setHeader("Content-Type", contentType + "; charset=" + format.getCharSetEncoding());
    }

    multipart.addBodyPart(messageBodyPart);
    msg.setContent(multipart);

}

From source file:org.github.alexwibowo.opentext.client.AxiomVRDClient.java

@Override
public String storeDocument(String documentSource, Map<String, Object> sourceAttributes, String mimeType,
        File file) throws Exception {
    OMNamespace ns1 = factory.createOMNamespace("http://record.webservices.rd.vignette.com/", "");

    OMElement addRecordMappedElement = factory.createOMElement("addRecordMapped", ns1);

    OMElement licenseElement = factory.createOMElement("license", ns1);
    addRecordMappedElement.addChild(licenseElement);

    OMElement docSourceNameElement = factory.createOMElement("docSourceName", ns1);
    docSourceNameElement.setText(documentSource);
    addRecordMappedElement.addChild(docSourceNameElement);

    OMElement sourceVREFElement = factory.createOMElement("sourceVREF", ns1);
    sourceVREFElement.setText("");
    addRecordMappedElement.addChild(sourceVREFElement);

    for (Map.Entry<String, Object> attributeEntry : sourceAttributes.entrySet()) {
        addRecordMappedElement.addChild(createAttributeElement(factory, ns1, attributeEntry));
    }/*from w  ww.j a v a2s .  c o m*/

    OMElement contentElement = factory.createOMElement("content", ns1);
    OMElement sectionIDElement = factory.createOMElement("sectionID", ns1);
    sectionIDElement.setText("1");
    contentElement.addChild(sectionIDElement);
    OMElement sectionDataElement = factory.createOMElement("sectionData", ns1);
    DataHandler dataHandler = new DataHandler(new FileDataSource(file));
    sectionDataElement.addChild(factory.createOMText(dataHandler, true));
    contentElement.addChild(sectionDataElement);
    OMElement renditionTypeElement = factory.createOMElement("renditionType", ns1);
    renditionTypeElement.setText(mimeType);
    contentElement.addChild(renditionTypeElement);

    addRecordMappedElement.addChild(contentElement);
    addRecordMappedElement.addChild(getOptionElement(factory, ns1));

    SOAPMessageBuilder soap11MessageBuilder = new AxiomSOAP11MessageBuilder(jaxbContext, soap11Factory)
            .withPayload(addRecordMappedElement)
            .withUsernameToken(configuration.getUsername(), configuration.getPassword());

    SOAPEnvelope envelope = (SOAPEnvelope) soap11MessageBuilder.build();
    HttpResponse httpResponse = postAsMultipart(envelope, VRDOperationQName.AddRecordMapped.getQName());

    dataHandler.getInputStream().close();

    if (httpResponse.getEntity() != null && httpResponse.getEntity().getContent() != null) {
        InputStream in = httpResponse.getEntity().getContent();
        Attachments attachments = new Attachments(in, httpResponse.getEntity().getContentType().getValue());
        SOAPEnvelope response = OMXMLBuilderFactory.createSOAPModelBuilder(attachments).getSOAPEnvelope();

        // retrieveContentResponse is addRecordMappedResponse
        OMElement addRecordMappedResponseElement = response.getBody().getFirstElement();

        // Unfortunately, our beautiful VRD responds with 'recDesc' in a null namespace. Hence if we use JAXB to unmarshall the response, we will get
        // null recDesc inside AddRecordMappedResponse object. such is life..
        OMElement recordDescElement = addRecordMappedResponseElement.getFirstElement();

        String recordID = recordDescElement.getFirstChildWithName(new QName("recordID")).getText();
        IOUtils.closeQuietly(in);
        return recordID;
    }
    return null;
}

From source file:eu.openanalytics.rsb.component.SoapMtomJobHandler.java

private ResultType buildResult(final AbstractFunctionCallResult functionCallResult) throws IOException {
    Validate.notNull(functionCallResult, NULL_RESULT_RECEIVED);

    final String resultContentType = functionCallResult.getMimeType().toString();

    final PayloadType payload = soapOF.createPayloadType();
    payload.setContentType(resultContentType);
    payload.setName(functionCallResult.getResultFileName());
    payload.setData(//from   w  w  w .j  a  v a  2  s  .  c  o  m
            new DataHandler(new ByteArrayDataSource(functionCallResult.getPayload(), resultContentType)));

    final ResultType result = createResult(functionCallResult);
    result.getPayload().add(payload);
    return result;
}

From source file:org.openhealthtools.openxds.repository.filesystem.FileSystemRepositoryServiceImpl.java

public XdsRepositoryItem getRepositoryItem(String documentUniqueId, RepositoryRequestContext context)
        throws RepositoryException {
    XdsRepositoryItemImpl repositoryItem = null;
    // Strip off the "urn:uuid:"
    documentUniqueId = Utility.getInstance().stripId(documentUniqueId);
    try {//from  ww w  .  j  a  v  a2s.c om
        IActorDescription actorDescription = context.getActorDescription();
        if (actorDescription == null) {
            throw new RepositoryException("Missing required ActorDescription in RepositoryRequestContext");
        }

        CodeSet mimeTypeCodeSet = actorDescription.getCodeSet("mimeType");
        Set<Pair<String, String>> mimeTypes = mimeTypeCodeSet.getCodeSetKeys();
        String targetFileMimeType = null;
        File targetFile = null;

        //look up the file
        for (Pair<String, String> code : mimeTypes) {
            String mimeType = code.first;
            String ext = mimeTypeCodeSet.getExt(mimeType, null);
            File file = new File(repositoryRoot, documentUniqueId + "." + ext);
            if (file.exists()) {
                targetFileMimeType = mimeType;
                targetFile = file;
                if (log.isDebugEnabled())
                    log.debug("Repository File " + file.getPath() + " found");
            } else if (log.isDebugEnabled())
                log.debug("Repository File " + file.getPath() + " does not exist");
        }

        if (targetFile == null) {
            return null;
        }

        DataHandler contentDataHandler = new DataHandler(new FileDataSource(targetFile));
        repositoryItem = new XdsRepositoryItemImpl(documentUniqueId, contentDataHandler);
        repositoryItem.setMimeType(targetFileMimeType);

    } catch (Exception e) {
        throw new RepositoryException(e);
    }
    return repositoryItem;

}

From source file:org.unitime.commons.Email.java

public void addAttachement(DataSource source) throws MessagingException {
    BodyPart attachement = new MimeBodyPart();
    attachement.setDataHandler(new DataHandler(source));
    attachement.setFileName(source.getName());
    attachement.setHeader("Content-ID", source.getName());
    iBody.addBodyPart(attachement);/* w w w . j  ava 2 s .c o m*/
}

From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java

public static void SendEmailPassed(String from, String to1, String subject, String filename)
        throws FileNotFoundException, IOException {

    try {/*from  w  w w.  j  av  a  2  s  .c om*/

        //Get properties object    
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
        //get Session   
        Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, "anda.cristea");
            }
        });
        //compose message    
        try {
            MimeMessage message = new MimeMessage(session);
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to1));
            //message.addRecipient(Message.RecipientType.BCC, new InternetAddress(grupSephora));

            message.setSubject(subject);
            // message.setText(msg);

            BodyPart messageBodyPart = new MimeBodyPart();

            messageBodyPart.setText("Raport teste automate");

            Multipart multipart = new MimeMultipart();

            multipart.addBodyPart(messageBodyPart);

            messageBodyPart = new MimeBodyPart();

            DataSource source = new FileDataSource(filename);

            messageBodyPart.setDataHandler(new DataHandler(source));

            messageBodyPart.setFileName(filename);

            multipart.addBodyPart(messageBodyPart);

            message.setContent(multipart);

            //send message  
            Transport.send(message);
            System.out.println("message sent successfully");
        } catch (Exception ex) {
            System.out.println("eroare trimitere email-uri");
            System.out.println(ex.getMessage());

        }

    } catch (Exception ex) {
        System.out.println("eroare trimitere email-uri");
        System.out.println(ex.getMessage());

    }

}