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:org.apache.axis2.swa.EchoRawSwATest.java

public void testEchoXMLSync() throws Exception {

    Options options = new Options();
    options.setTo(targetEPR);//  w  w w . j av a2 s. c o  m
    options.setProperty(Constants.Configuration.ENABLE_SWA, Constants.VALUE_TRUE);
    options.setTransportInProtocol(Constants.TRANSPORT_HTTP);
    options.setSoapVersionURI(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI);
    options.setTimeOutInMilliSeconds(100000);
    options.setAction(Constants.AXIS2_NAMESPACE_URI + "/" + operationName.getLocalPart());
    options.setTo(targetEPR);

    ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(
            TestingUtils.prefixBaseDirectory("target/test-resources/integrationRepo"), null);

    ServiceClient sender = new ServiceClient(configContext, null);
    sender.setOptions(options);
    OperationClient mepClient = sender.createClient(ServiceClient.ANON_OUT_IN_OP);

    MessageContext mc = new MessageContext();
    mc.setEnvelope(createEnvelope());
    FileDataSource fileDataSource = new FileDataSource(
            TestingUtils.prefixBaseDirectory("test-resources/mtom/test.jpg"));
    DataHandler dataHandler = new DataHandler(fileDataSource);
    mc.addAttachment("FirstAttachment", dataHandler);

    mepClient.addMessageContext(mc);
    mepClient.execute(true);
    MessageContext response = mepClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
    DataHandler dataHandler2 = response.getAttachment("FirstAttachment");
    assertNotNull(dataHandler);
    compareDataHandlers(dataHandler, dataHandler2);
}

From source file:com.mylab.mail.OpenCmsMailService.java

public void sendMultipartMail(MessageConfig config, DataSource ds, String filename) throws MessagingException {
    log.debug("Sending multipart message " + config);

    Session session = getSession();/*from ww  w .  j a  v a  2s  .  c  om*/
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart html = new MimeBodyPart();
    html.setContent(config.getContent(), config.getContentType());
    html.setHeader("MIME-Version", "1.0");
    html.setHeader("Content-Type", html.getContentType());
    multipart.addBodyPart(html);

    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setDataHandler(new DataHandler(ds));
    messageBodyPart.setFileName(filename);
    multipart.addBodyPart(messageBodyPart);

    final MimeMessage message = new MimeMessage(session);
    message.setContent(multipart);
    try {
        message.setFrom(new InternetAddress(config.getFrom(), config.getFromName()));
        addRecipientsWhitelist(message, config.getTo(), config.getToName(), config.getCardconfig());
    } catch (UnsupportedEncodingException ex) {
        throw new MessagingException("Setting from or to failed", ex);
    }

    message.setSubject(config.getSubject());

    // we don't send in a new Thread so that we get the Exception
    Transport.send(message);
}

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

@Override
public DataHandler getHeaderImage(long headerId, ImageProcessing process) throws CillaServiceException {
    Header hdr = headerDao.fetch(headerId);
    if (hdr == null) {
        throw new CillaNotFoundException("header", headerId);
    }//from  w w w . j a v a2  s .  c  o m

    return new DataHandler(headerService.getHeaderImage(hdr, process));
}

From source file:org.codice.alliance.core.email.impl.EmailSenderImpl.java

/** sendEmail method sends email after receiving input parameters */
@Override//from   w w w .  jav a  2  s  .  c o  m
public void sendEmail(String fromEmail, String toEmail, String subject, String body,
        List<Pair<String, InputStream>> attachments) throws IOException {
    notNull(fromEmail, "fromEmail must be non-null");
    notNull(toEmail, "toEmail must be non-null");
    notNull(subject, "subject must be non-null");
    notNull(body, "body must be non-null");
    notNull(attachments, "attachments must be non-null");

    if (StringUtils.isBlank(mailHost)) {
        throw new IOException("the mail server hostname has not been configured");
    }

    List<File> tempFiles = new LinkedList<>();

    try {
        InternetAddress emailAddr = new InternetAddress(toEmail);
        emailAddr.validate();

        Properties properties = createSessionProperties();

        Session session = Session.getDefaultInstance(properties);

        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setFrom(new InternetAddress(fromEmail));
        mimeMessage.addRecipient(Message.RecipientType.TO, emailAddr);
        mimeMessage.setSubject(subject);

        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(body);

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);

        Holder<Long> bytesWritten = new Holder<>(0L);

        for (Pair<String, InputStream> attachment : attachments) {

            messageBodyPart = new MimeBodyPart();
            File file = File.createTempFile("email-sender-", ".dat");
            tempFiles.add(file);

            copyDataToTempFile(file, attachment.getValue(), bytesWritten);
            messageBodyPart.setDataHandler(new DataHandler(new FileDataSource(file)));
            messageBodyPart.setFileName(attachment.getKey());
            multipart.addBodyPart(messageBodyPart);
        }

        mimeMessage.setContent(multipart);

        send(mimeMessage);

        LOGGER.debug("Email sent to " + toEmail);

    } catch (AddressException e) {
        throw new IOException("invalid email address: email=" + toEmail, e);
    } catch (MessagingException e) {
        throw new IOException("message error occurred on send", e);
    } finally {
        tempFiles.forEach(file -> {
            if (!file.delete()) {
                LOGGER.debug("unable to delete tmp file: path={}", file);
            }
        });
    }
}

From source file:mitm.djigzo.web.pages.dlp.patterns.PatternsImport.java

public void onSuccess() {
    try {//  ww w .  j a  va 2  s  .co  m
        if (file == null) {
            throw new IllegalStateException("file is null");
        }

        SizeLimitedInputStream limit = new SizeLimitedInputStream(file.getStream(), MAX_XML_SIZE,
                true /* exception */);

        DataSource source = new ByteArrayDataSource(limit, file.getContentType());
        DataHandler dataHandler = new DataHandler(source);

        BinaryDTO xml = new BinaryDTO(dataHandler);

        policyPatternManagerWS.importFromXML(xml, skipExisting);

        importSuccess = true;
    } catch (Exception e) {
        logger.error("Error importing patterns", e);

        importError = true;
        importErrorMessage = e.getMessage();
    }
}

From source file:org.apache.synapse.transport.fix.FIXUtils.java

/**
 * FIX messages are non-XML. So convert them into XML using the AXIOM API.
 * Put the FIX message into an Axis2 MessageContext.The basic format of the
 * generated SOAP envelope;/* www.ja  v a  2  s.c  o  m*/
 * <p/>
 * <soapEnvelope>
 * <soapBody>
 * <message>
 * <header> ....</header>
 * <body> .... </body>
 * <trailer> .... </trailer>
 * </message>
 * </soapBody>
 * </soapEnvelope>
 *
 * @param message   the FIX message
 * @param counter   application level sequence number of the message
 * @param sessionID the incoming session
 * @param msgCtx    the Axis2 MessageContext to hold the FIX message
 * @throws AxisFault the exception thrown when invalid soap envelopes are set to the msgCtx
 */
public void setSOAPEnvelope(Message message, int counter, String sessionID, MessageContext msgCtx)
        throws AxisFault {

    if (log.isDebugEnabled()) {
        log.debug("Creating SOAP envelope for FIX message...");
    }

    SOAPFactory soapFactory = new SOAP11Factory();
    OMElement msg = soapFactory.createOMElement(FIXConstants.FIX_MESSAGE, null);
    msg.addAttribute(soapFactory.createOMAttribute(FIXConstants.FIX_MESSAGE_INCOMING_SESSION, null, sessionID));
    msg.addAttribute(
            soapFactory.createOMAttribute(FIXConstants.FIX_MESSAGE_COUNTER, null, String.valueOf(counter)));

    OMElement header = soapFactory.createOMElement(FIXConstants.FIX_HEADER, null);
    OMElement body = soapFactory.createOMElement(FIXConstants.FIX_BODY, null);
    OMElement trailer = soapFactory.createOMElement(FIXConstants.FIX_TRAILER, null);

    //process FIX header
    Iterator<Field<?>> iter = message.getHeader().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());
            }
            header.addChild(msgField);
        }
    }
    //process FIX body
    convertFIXBodyToXML(message, body, soapFactory, msgCtx);

    //process FIX trailer
    iter = message.getTrailer().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());
            }
            trailer.addChild(msgField);
        }
    }

    msg.addChild(header);
    msg.addChild(body);
    msg.addChild(trailer);
    SOAPEnvelope envelope = soapFactory.getDefaultEnvelope();
    envelope.getBody().addChild(msg);
    msgCtx.setEnvelope(envelope);
}

From source file:org.webcurator.core.store.arc.ArcDigitalAssetStoreSOAPService.java

/** @see DigitalAssetStoreSOAP#getResource(String, int, HarvestResourceDTO). */
public DataHandler getResource(String targetInstanceName, int harvestResultNumber,
        HarvestResourceDTO resource) {/*  ww w. j ava2 s  .c o m*/
    File file = null;
    try {
        file = service.getResource(targetInstanceName, harvestResultNumber, resource);
    } catch (DigitalAssetStoreException e) {
        if (log.isWarnEnabled()) {
            log.warn("SOAP Service Failed to get resource : " + e.getMessage());
        }
    }
    return new DataHandler(new TempFileDataSource(file));

}

From source file:es.pode.catalogadorWeb.presentacion.importar.ImportarControllerImpl.java

public String submit(ActionMapping mapping, SubmitForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    String resultado = "";
    String action = form.getAccion();

    //String idiomaLocale=((Locale)request.getSession().getAttribute(ConstantesAgrega.DEFAULT_LOCALE)).getLanguage();
    ResourceBundle i18n = I18n.getInstance().getResource("application-resources",
            (Locale) request.getSession().getAttribute(ConstantesAgrega.DEFAULT_LOCALE));

    if (action != null) {
        if (action.equals(i18n.getString("catalogadorAvanzado.importar.aceptar"))) {
            resultado = "Aceptar";
            if (form.getFichero() == null || form.getFichero().getFileName().equals("")
                    || form.getFichero().getFileSize() == 0)
                throw new ValidatorException("{catalogadorAvanzado.importar.error.ficherovacio}");

            //crear el datahandler
            InternetHeaders ih = new InternetHeaders();
            MimeBodyPart mbp = null;//from  w  ww  .ja  v  a2  s  .c om
            DataSource source = null;
            DataHandler dh = null;
            try {
                FormFile ff = (FormFile) form.getFichero();
                mbp = new MimeBodyPart(ih, ff.getFileData());
                source = new MimePartDataSource(mbp);
                dh = new DataHandler(source);
            } catch (Exception e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("error al crear el datahandler");
                }
                throw new ValidatorException("{catalogadorAvanzado.importar.error}");
            }

            //validar el fichero
            Boolean valido = new Boolean(false);
            try {
                valido = this.getSrvValidadorService().obtenerValidacionLomes(dh);
            } catch (Exception e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("error al llamar al servicio de validacin");
                }
                throw new ValidatorException("{catalogadorAvanzado.importar.error.novalido}");
            }

            if (!valido.booleanValue())
                throw new ValidatorException("{catalogadorAvanzado.importar.error.novalido}");

            //agregar el datahandler a sesion
            this.getCatalogadorAvSession(request).setLomesImportado(dh);

        } else if (action.equals(i18n.getString("catalogadorAvanzado.importar.cancelar")))
            resultado = "Cancelar";
    }
    return resultado;
}

From source file:bioLockJ.module.agent.MailAgent.java

private BodyPart getAttachment(final String filePath) throws Exception {
    try {//  w w  w. j ava  2s.  c o  m
        final DataSource source = new FileDataSource(filePath);
        final File logFile = new File(filePath);
        final double fileSize = logFile.length() / 1000000;
        if (fileSize < emailMaxAttachmentMB) {
            final BodyPart attachPart = new MimeBodyPart();
            attachPart.setDataHandler(new DataHandler(source));
            attachPart.setFileName(filePath.substring(filePath.lastIndexOf(File.separator) + 1));
            return attachPart;
        } else {
            Log.out.warn("File [" + filePath
                    + "] too large to attach.  Max file size configured in prop file set to = "
                    + emailMaxAttachmentMB + " MB");

        }
    } catch (final Exception ex) {
        Log.out.error("Unable to attach file", ex);
    }

    return null;
}

From source file:de.kp.ames.web.function.domain.model.TransformatorObject.java

/**
 * Create RegistryObject representation of TransformatorObject
 * // www .j a  va2 s.  c o m
 * @param data
 * @return
 * @throws Exception
 */
public RegistryObjectImpl create(String data) throws Exception {

    /*
     * Initialize data
     */
    JSONObject jForm = new JSONObject(data);

    /* 
     * Create extrinsic object that serves as a wrapper 
     * for the respective transformator
     */
    // 
    ExtrinsicObjectImpl eo = jaxrLCM.createExtrinsicObject();
    if (eo == null)
        throw new JAXRException("[TransformatorObject] Creation of ExtrinsicObject failed.");

    /* 
     * Identifier
     */
    String eid = JaxrIdentity.getInstance().getPrefixUID(FncConstants.TRANSFORMATOR_PRE);

    eo.setLid(eid);
    eo.getKey().setId(eid);

    /* 
     * Home url
     */
    String home = jaxrHandle.getEndpoint().replace("/saml", "");
    eo.setHome(home);

    /* 
     * The transformator is actually transient and managed by the xslt processor;
     * to register the respective xslt file, we have to invoke the transient
     * cache and get the file
     */

    XslCacheManager cacheManager = XslCacheManager.getInstance();

    String key = jForm.getString(JsonConstants.J_KEY);
    XslTransformator transformator = (XslTransformator) cacheManager.getFromCache(key);

    if (transformator == null)
        throw new Exception("[TransformatorObject] XSL Transformator with id <" + key + "> not found.");

    /*
     * Name & description
     */
    String name = jForm.has(RIM_NAME) ? jForm.getString(RIM_NAME) : null;
    String desc = jForm.has(RIM_DESC) ? jForm.getString(RIM_DESC) : null;

    name = (name == null) ? transformator.getName() : name;

    int pos = name.lastIndexOf(".");
    if (pos != -1)
        name = name.substring(0, pos);

    eo.setName(jaxrLCM.createInternationalString(name));

    desc = (desc == null) ? FncMessages.NO_DESCRIPTION_DESC : desc;
    eo.setDescription(jaxrLCM.createInternationalString(desc));

    /*
     * Classifications
     */
    JSONArray jClases = jForm.has(RIM_CLAS) ? new JSONArray(jForm.getString(RIM_CLAS)) : null;
    if (jClases != null) {

        List<ClassificationImpl> classifications = createClassifications(jClases);
        /*
         * Set composed object
         */
        eo.addClassifications(classifications);

    }

    /*
     * Mimetype & repository item
     */
    String mimetype = transformator.getMimetype();
    DataHandler handler = new DataHandler(
            FileUtil.createByteArrayDataSource(transformator.getBytes(), mimetype));

    eo.setMimeType(mimetype);
    eo.setRepositoryItem(handler);

    /*
     * Indicate as created
     */
    this.created = true;

    return eo;

}