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.synapse.samples.framework.clients.MTOMSwASampleClient.java

public SampleClientResult sendUsingMTOM(String fileName, String targetEPR) {
    clientResult = new SampleClientResult();
    try {/*  ww w .  ja v a  2s. c om*/
        OMFactory factory = OMAbstractFactory.getOMFactory();
        OMNamespace ns = factory.createOMNamespace("http://services.samples", "m0");
        payload = factory.createOMElement("uploadFileUsingMTOM", ns);
        OMElement request = factory.createOMElement("request", ns);
        OMElement image = factory.createOMElement("image", ns);

        log.info("Sending file : " + fileName + " as MTOM");
        FileDataSource fileDataSource = new FileDataSource(new File(fileName));
        DataHandler dataHandler = new DataHandler(fileDataSource);
        OMText textData = factory.createOMText(dataHandler, true);
        image.addChild(textData);
        request.addChild(image);
        payload.addChild(request);

        ConfigurationContext configContext = ConfigurationContextFactory
                .createConfigurationContextFromFileSystem(configuration.getClientRepo(),
                        configuration.getAxis2Xml());

        serviceClient = new ServiceClient(configContext, null);

        Options options = new Options();
        options.setTo(new EndpointReference(targetEPR));
        options.setAction("urn:uploadFileUsingMTOM");
        options.setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_TRUE);

        serviceClient.setOptions(options);
        OMElement response = serviceClient.sendReceive(payload);

        OMText binaryNode = (OMText) response
                .getFirstChildWithName(new QName("http://services.samples", "response"))
                .getFirstChildWithName(new QName("http://services.samples", "image")).getFirstOMChild();
        dataHandler = (DataHandler) binaryNode.getDataHandler();
        InputStream is = dataHandler.getInputStream();
        log.info("temp.dir: " + System.getProperty("java.io.tmpdir"));
        File tempFile = File.createTempFile("mtom-", ".gif");
        FileOutputStream fos = new FileOutputStream(tempFile);
        BufferedOutputStream dest = new BufferedOutputStream(fos, 2048);

        byte data[] = new byte[2048];
        int count;
        while ((count = is.read(data, 0, 2048)) != -1) {
            dest.write(data, 0, count);
        }

        dest.flush();
        dest.close();
        log.info("Saved response to file : " + tempFile.getAbsolutePath());
        clientResult.incrementResponseCount();
    } catch (Exception e) {
        log.error("Error invoking service", e);
        clientResult.setException(e);
    }

    return clientResult;

}

From source file:se.inera.axel.shs.camel.LargeShsMessageTypeConverterTest.java

@DirtiesContext
@Test/*from w  w w.  j  a v a  2  s . com*/
public void testLargeFileRoundtrip() throws Exception {
    Assert.assertNotNull(testShsMessage);

    InputStream largeInput = new NullInputStream(100_000_000);

    testShsMessage.getDataParts().remove(0);
    DataPart dataPart = new DataPart(
            new DataHandler(new InputStreamDataSource(largeInput, "application/x-iso9660-image")));
    dataPart.setContentType("application/x-iso9660-image");
    dataPart.setFileName("largefile");
    dataPart.setTransferEncoding("base64");
    dataPart.setDataPartType("iso");

    testShsMessage.getDataParts().add(dataPart);

    resultEndpoint.expectedMessageCount(1);
    template.sendBody("direct:convertRoundtrip", 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);
}

From source file:com.adaptris.core.MimeEncoderImpl.java

protected MimeBodyPart asMimePart(Exception e) throws Exception {
    MimeBodyPart p = new MimeBodyPart();
    try (ByteArrayOutputStream out = new ByteArrayOutputStream();
            PrintStream printer = new PrintStream(out, true)) {
        e.printStackTrace(printer);/*from  w w  w .  j a v  a 2  s . com*/
        p.setDataHandler(new DataHandler(new ByteArrayDataSource(out.toByteArray())));
    }
    return p;
}

From source file:org.apache.axis2.jaxws.utility.DataSourceFormatter.java

public void writeTo(org.apache.axis2.context.MessageContext messageContext, OMOutputFormat format,
        OutputStream outputStream, boolean preserve) throws AxisFault {
    AttachmentsAdapter attachments = (AttachmentsAdapter) messageContext
            .getProperty(MessageContext.OUTBOUND_MESSAGE_ATTACHMENTS);
    try {/* ww  w  .  jav  a 2  s .  c o m*/
        if (log.isDebugEnabled()) {
            log.debug("start writeTo()");
        }
        if (attachments != null && !attachments.isEmpty()) {
            OMElement omElement = messageContext.getEnvelope().getBody().getFirstElement();
            DataSource busObject;
            try {
                busObject = (DataSource) ((DataSourceBlock) ((OMSourcedElement) omElement).getDataSource())
                        .getBusinessObject(true);
            } catch (XMLStreamException e) {
                throw AxisFault.makeFault(e);
            }
            MIMEOutputUtils.writeDataHandlerWithAttachmentsMessage(new DataHandler(busObject), contentType,
                    outputStream, attachments, format);
        } else {
            OMElement omElement = messageContext.getEnvelope().getBody().getFirstElement();
            if (omElement != null) {
                try {
                    if (preserve) {
                        omElement.serialize(outputStream, format);
                    } else {
                        omElement.serializeAndConsume(outputStream, format);
                    }
                } catch (XMLStreamException e) {
                    throw AxisFault.makeFault(e);
                }
            }
            try {
                outputStream.flush();
            } catch (IOException e) {
                throw AxisFault.makeFault(e);
            }
        }
    } finally {
        if (log.isDebugEnabled()) {
            log.debug("end writeTo()");
        }
    }
}

From source file:org.mule.DefaultMuleMessageSerializationTestCase.java

@Test
@Ignore("see MULE-2964")
public void testAttachments() throws Exception {
    String attachmentName = "the-attachment";

    MuleMessage message = new DefaultMuleMessage(TEST_MESSAGE, muleContext);
    DataHandler dataHandler = new DataHandler(new StringDataSource("attachment content"));
    message.addAttachment(attachmentName, dataHandler);

    MuleMessage deserializedMessage = serializationRoundtrip(message);

    assertEquals(1, deserializedMessage.getAttachmentNames().size());
    assertTrue(deserializedMessage.getAttachmentNames().contains(attachmentName));
}

From source file:cz.zcu.kiv.eegdatabase.webservices.semantic.SemanticServiceImpl.java

/**
 * Generates an ontology document from POJO objects.
 * This method gives the Jena's output./*from ww  w.java 2  s.  c o m*/
 *
 * @return
 * @throws WebServiceException
 * @throws IOException
 */
public DataHandler getOntology() throws SOAPException {
    InputStream is = null;
    byte[] bytes = null;
    ByteArrayDataSource rdf = null;
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        int i;
        is = simpleSemanticFactory.getOntology(null);
        while ((i = is.read()) > -1) {
            os.write(i);
        }
    } catch (IOException e) {
        log.error(e);
        throw new SOAPException(e);
    }
    rdf = new ByteArrayDataSource(os.toByteArray(), "fileBinaryStream");
    return new DataHandler(rdf);
}

From source file:org.bimserver.client.DirectChannel.java

@Override
public long checkin(String baseAddress, String token, long poid, String comment, long deserializerOid,
        boolean merge, boolean sync, long fileSize, String filename, InputStream inputStream)
        throws ServerException, UserException {
    try {/*from   ww w  .j  a  v a  2s .c  om*/
        return get(ServiceInterface.class).checkin(poid, comment, deserializerOid, fileSize, filename,
                new DataHandler(new InputStreamDataSource(inputStream)), merge, sync);
    } catch (PublicInterfaceNotFoundException e) {
        LOGGER.error("", e);
        return -1;
    }
}

From source file:org.wso2.appserver.integration.tests.carbonappservice.CarbonAppTestCase.java

@Test(groups = "wso2.as", description = "upload car file and verify deployment")
public void carApplicationUpload() throws Exception {
    CarbonAppUploaderClient carbonAppClient = new CarbonAppUploaderClient(backendURL, sessionCookie);

    URL url = new URL("file://" + FrameworkPathUtil.getSystemResourceLocation() + "artifacts" + File.separator
            + "AS" + File.separator + "car" + File.separator + "AxisCApp-1.0.0.car");

    DataHandler dh = new DataHandler(url);
    carbonAppClient.uploadCarbonAppArtifact("AxisCApp-1.0.0.car", dh);
    AxisServiceClientUtils.waitForServiceDeployment(asServer.getContextUrls().getServiceUrl() + "/Calculator");
    log.info("AxisCApp-1.0.0.car uploaded successfully");
}

From source file:com.intuit.tank.mail.TankMailer.java

/**
 * @{inheritDoc/*w  ww  .  jav a 2  s  .co m*/
 */
@Override
public void sendMail(MailMessage message, String... emailAddresses) {
    MailConfig mailConfig = new TankConfig().getMailConfig();
    Properties props = new Properties();
    props.put("mail.smtp.host", mailConfig.getSmtpHost());
    props.put("mail.smtp.port", mailConfig.getSmtpPort());

    Session mailSession = Session.getDefaultInstance(props);
    Message simpleMessage = new MimeMessage(mailSession);

    InternetAddress fromAddress = null;
    InternetAddress toAddress = null;
    try {
        fromAddress = new InternetAddress(mailConfig.getMailFrom());
        simpleMessage.setFrom(fromAddress);
        for (String email : emailAddresses) {
            try {
                toAddress = new InternetAddress(email);
                simpleMessage.addRecipient(RecipientType.TO, toAddress);
            } catch (AddressException e) {
                LOG.warn("Error with recipient " + email + ": " + e.toString());
            }
        }

        simpleMessage.setSubject(message.getSubject());
        final MimeBodyPart textPart = new MimeBodyPart();
        textPart.setContent(message.getPlainTextBody(), "text/plain");
        textPart.setHeader("MIME-Version", "1.0");
        textPart.setHeader("Content-Type", textPart.getContentType());
        // HTML version
        final MimeBodyPart htmlPart = new MimeBodyPart();
        // htmlPart.setContent(message.getHtmlBody(), "text/html");
        htmlPart.setDataHandler(new DataHandler(new HTMLDataSource(message.getHtmlBody())));
        htmlPart.setHeader("MIME-Version", "1.0");
        htmlPart.setHeader("Content-Type", "text/html");
        // Create the Multipart. Add BodyParts to it.
        final Multipart mp = new MimeMultipart("alternative");
        mp.addBodyPart(textPart);
        mp.addBodyPart(htmlPart);
        // Set Multipart as the message's content
        simpleMessage.setContent(mp);
        simpleMessage.setHeader("MIME-Version", "1.0");
        simpleMessage.setHeader("Content-Type", mp.getContentType());
        logMsg(mailConfig.getSmtpHost(), simpleMessage);
        if (simpleMessage.getRecipients(RecipientType.TO) != null
                && simpleMessage.getRecipients(RecipientType.TO).length > 0) {
            Transport.send(simpleMessage);
        }
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:es.pode.modificador.presentacion.importar.ImportarModificacionControllerImpl.java

/**
 * @see es.pode.modificador.presentacion.importar.ImportarModificacionController#importar(org.apache.struts.action.ActionMapping, es.pode.modificador.presentacion.importar.ImportarForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *///from w  w  w .  java  2  s. c o m
public final void importar(ActionMapping mapping, es.pode.modificador.presentacion.importar.ImportarForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    FormFile xml = form.getFichero();
    if (xml == null || xml.getFileSize() == 0) {
        throw new ValidatorException("{importarModificacion.error}");
    }
    //       convierto el FormFile en un DataHandler
    InternetHeaders ih = new InternetHeaders();
    MimeBodyPart mbp = null;
    DataSource source = null;
    DataHandler dFichero = null;
    mbp = new MimeBodyPart(ih, xml.getFileData());
    source = new MimePartDataSource(mbp);
    dFichero = new DataHandler(source);

    // Llamo al servicio para parsear el fichero XML
    ConfiguracionTarea configuracion;
    try {
        configuracion = this.getSrvHerramientaModificacion().importarModificacion(dFichero);
    } catch (Exception e) {
        throw new ValidatorException("{importarModificacion.error}");
    }

    // Creo el objeto de sesion para editar la tarea
    this.getConfigurarModificacionSession(request).setConfiguracion(configuracion);
}