Example usage for javax.activation DataHandler getContentType

List of usage examples for javax.activation DataHandler getContentType

Introduction

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

Prototype

public String getContentType() 

Source Link

Document

Return the MIME type of this object as retrieved from the source object.

Usage

From source file:org.hubiquitus.hubotsdk.adapters.HHttpAdapterInbox.java

@Override
public void process(Exchange exchange) throws Exception {
    Message in = exchange.getIn();/*from   w  ww. ja  v  a  2 s  . c  o m*/

    HttpServletRequest request = exchange.getIn().getBody(HttpServletRequest.class);

    //Gather data to send through an hmessage
    byte[] rawBody = (byte[]) in.getBody(byte[].class);
    Map<String, Object> headers = in.getHeaders();
    Map<String, DataHandler> attachments = in.getAttachments();

    String method = request.getMethod().toLowerCase();
    String queryArgs = request.getQueryString();
    String queryPath = request.getRequestURI();
    String serverName = request.getServerName();
    Integer serverPort = request.getServerPort();

    //create message to send
    HMessage message = new HMessage();
    message.setAuthor(this.actor);
    if (headers != null) {
        JSONObject jsonHeaders = new JSONObject();
        for (String key : headers.keySet()) {
            Object header = headers.get(key);
            String value = null;
            if (header != null) {
                value = header.toString();
            }
            jsonHeaders.put(key, value);
        }
    }

    message.setPublished(new DateTime());

    message.setType("hHttpData");
    //create payload
    HHttpData httpData = new HHttpData();
    httpData.setMethod(method);
    httpData.setQueryArgs(queryArgs);
    httpData.setQueryPath(queryPath);
    httpData.setServerName(serverName);
    httpData.setServerPort(serverPort);
    httpData.setRawBody(rawBody);

    //create attachements
    JSONObject hattachements = new JSONObject();
    for (String key : attachments.keySet()) {
        DataHandler attachement = attachments.get(key);
        if (attachement != null) {
            HHttpAttachement hattachement = new HHttpAttachement();
            hattachement.setContentType(attachement.getContentType());
            hattachement.setName(attachement.getName());

            //read attachement
            byte[] buffer = new byte[8 * 1024];
            InputStream input = attachement.getInputStream();

            ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
            int bytesRead;
            while ((bytesRead = input.read(buffer)) != -1) {
                byteOutputStream.write(buffer, 0, bytesRead);
            }
            hattachement.setData(byteOutputStream.toByteArray());
            try {
                hattachements.put(key, hattachement);
            } catch (JSONException e) {
                logger.debug(e.toString());
            }
        } else {
            //if attachment is null, do not put the key in hattachments.
        }
    }

    httpData.setAttachments(hattachements);
    message.setPayload(httpData);

    //finally send message to actor
    this.put(message);
}

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

@DirtiesContext
@Test//from  w  ww  .ja v a2  s  . c o  m
public void convertCamelMessageToDataPartWithoutFilename() throws Exception {

    resultEndpoint.expectedMessageCount(1);

    String message = DEFAULT_TEST_BODY;

    Map<String, Object> headers = new HashMap<String, Object>();
    headers.put(ShsHeaders.DATAPART_TRANSFERENCODING, DEFAULT_TEST_DATAPART_TRANSFERENCODING);
    headers.put(ShsHeaders.DATAPART_CONTENTTYPE, DEFAULT_TEST_DATAPART_CONTENTTYPE);
    headers.put(ShsHeaders.DATAPART_CONTENTLENGTH, message.length());
    headers.put(ShsHeaders.DATAPART_TYPE, DEFAULT_TEST_DATAPART_TYPE);

    template.sendBodyAndHeaders("direct:camelToShsConverter", message, headers);

    resultEndpoint.assertIsSatisfied();
    List<Exchange> exchanges = resultEndpoint.getExchanges();
    Exchange exchange = exchanges.get(0);
    Message in = exchange.getIn();
    DataPart datapart = in.getMandatoryBody(DataPart.class);
    assertNotNull(datapart);

    assertEquals((long) datapart.getContentLength(), message.length());
    assertEquals(datapart.getContentType(), DEFAULT_TEST_DATAPART_CONTENTTYPE);
    assertEquals(datapart.getDataPartType(), DEFAULT_TEST_DATAPART_TYPE);
    assertNull(datapart.getFileName());
    assertEquals(datapart.getTransferEncoding(), DEFAULT_TEST_DATAPART_TRANSFERENCODING);
    assertNotNull(datapart.getDataHandler());

    DataHandler dataHandler = datapart.getDataHandler();
    assertEquals(dataHandler.getContentType(), DEFAULT_TEST_DATAPART_CONTENTTYPE);
    assertNull(dataHandler.getName());
    assertEquals(dataHandler.getContent(), DEFAULT_TEST_BODY);
}

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

@DirtiesContext
@Test//from   w  ww .  j  a  v a 2s .c o m
public void convertCamelMessageToDataPart() throws Exception {

    resultEndpoint.expectedMessageCount(1);

    String message = DEFAULT_TEST_BODY;

    Map<String, Object> headers = new HashMap<String, Object>();
    headers.put(ShsHeaders.DATAPART_TRANSFERENCODING, DEFAULT_TEST_DATAPART_TRANSFERENCODING);
    headers.put(ShsHeaders.DATAPART_CONTENTTYPE, DEFAULT_TEST_DATAPART_CONTENTTYPE);
    headers.put(ShsHeaders.DATAPART_FILENAME, DEFAULT_TEST_DATAPART_FILENAME);
    headers.put(ShsHeaders.DATAPART_CONTENTLENGTH, message.length());
    headers.put(ShsHeaders.DATAPART_TYPE, DEFAULT_TEST_DATAPART_TYPE);

    template.sendBodyAndHeaders("direct:camelToShsConverter", message, headers);

    resultEndpoint.assertIsSatisfied();
    List<Exchange> exchanges = resultEndpoint.getExchanges();
    Exchange exchange = exchanges.get(0);
    Message in = exchange.getIn();
    DataPart datapart = in.getMandatoryBody(DataPart.class);
    assertNotNull(datapart);

    assertEquals((long) datapart.getContentLength(), message.length());
    assertEquals(datapart.getContentType(), DEFAULT_TEST_DATAPART_CONTENTTYPE);
    assertEquals(datapart.getDataPartType(), DEFAULT_TEST_DATAPART_TYPE);
    assertEquals(datapart.getFileName(), DEFAULT_TEST_DATAPART_FILENAME);
    assertEquals(datapart.getTransferEncoding(), DEFAULT_TEST_DATAPART_TRANSFERENCODING);
    assertNotNull(datapart.getDataHandler());

    DataHandler dataHandler = datapart.getDataHandler();
    assertEquals(dataHandler.getContentType(), DEFAULT_TEST_DATAPART_CONTENTTYPE);
    assertEquals(dataHandler.getName(), DEFAULT_TEST_DATAPART_FILENAME);
    assertEquals(dataHandler.getContent(), DEFAULT_TEST_BODY);
}

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

@DirtiesContext
@Test//  www .  java 2  s  . c o m
public void convertCamelMessageToDataPartWithBase64() throws Exception {

    resultEndpoint.expectedMessageCount(1);

    String message = DEFAULT_TEST_BODY;

    Map<String, Object> headers = new HashMap<String, Object>();
    headers.put(ShsHeaders.DATAPART_TRANSFERENCODING, "base64");
    headers.put(ShsHeaders.DATAPART_CONTENTTYPE, DEFAULT_TEST_DATAPART_CONTENTTYPE);
    headers.put(ShsHeaders.DATAPART_FILENAME, DEFAULT_TEST_DATAPART_FILENAME);
    headers.put(ShsHeaders.DATAPART_CONTENTLENGTH, message.length());
    headers.put(ShsHeaders.DATAPART_TYPE, DEFAULT_TEST_DATAPART_TYPE);

    template.sendBodyAndHeaders("direct:camelToShsConverter", message, headers);

    resultEndpoint.assertIsSatisfied();
    List<Exchange> exchanges = resultEndpoint.getExchanges();
    Exchange exchange = exchanges.get(0);
    Message in = exchange.getIn();
    DataPart datapart = in.getMandatoryBody(DataPart.class);
    assertNotNull(datapart);

    assertEquals((long) datapart.getContentLength(), message.length());
    assertEquals(datapart.getContentType(), DEFAULT_TEST_DATAPART_CONTENTTYPE);
    assertEquals(datapart.getDataPartType(), DEFAULT_TEST_DATAPART_TYPE);
    assertEquals(datapart.getFileName(), DEFAULT_TEST_DATAPART_FILENAME);
    assertEquals(datapart.getTransferEncoding(), "base64");

    assertNotNull(datapart.getDataHandler());
    DataHandler dataHandler = datapart.getDataHandler();
    assertEquals(dataHandler.getContentType(), DEFAULT_TEST_DATAPART_CONTENTTYPE);
    assertEquals(dataHandler.getName(), DEFAULT_TEST_DATAPART_FILENAME);
    assertEquals(dataHandler.getContent(), DEFAULT_TEST_BODY);
}

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

@DirtiesContext
@Test/*w w  w  .j  av a  2s .  c  om*/
public void convertCamelMessageToDataPartWithFilenameInContentType() throws Exception {

    resultEndpoint.expectedMessageCount(1);

    String message = DEFAULT_TEST_BODY;

    Map<String, Object> headers = new HashMap<String, Object>();
    headers.put(ShsHeaders.DATAPART_TRANSFERENCODING, DEFAULT_TEST_DATAPART_TRANSFERENCODING);
    headers.put(ShsHeaders.DATAPART_CONTENTTYPE,
            DEFAULT_TEST_DATAPART_CONTENTTYPE + ";name=" + DEFAULT_TEST_DATAPART_FILENAME);
    headers.put(ShsHeaders.DATAPART_CONTENTLENGTH, message.length());
    headers.put(ShsHeaders.DATAPART_TYPE, DEFAULT_TEST_DATAPART_TYPE);

    template.sendBodyAndHeaders("direct:camelToShsConverter", message, headers);

    resultEndpoint.assertIsSatisfied();
    List<Exchange> exchanges = resultEndpoint.getExchanges();
    Exchange exchange = exchanges.get(0);
    Message in = exchange.getIn();
    DataPart datapart = in.getMandatoryBody(DataPart.class);
    assertNotNull(datapart);

    assertEquals((long) datapart.getContentLength(), message.length());
    assertEquals(datapart.getContentType(),
            DEFAULT_TEST_DATAPART_CONTENTTYPE + ";name=" + DEFAULT_TEST_DATAPART_FILENAME);
    assertEquals(datapart.getDataPartType(), DEFAULT_TEST_DATAPART_TYPE);
    assertEquals(datapart.getFileName(), DEFAULT_TEST_DATAPART_FILENAME);
    assertEquals(datapart.getTransferEncoding(), DEFAULT_TEST_DATAPART_TRANSFERENCODING);

    assertNotNull(datapart.getDataHandler());
    DataHandler dataHandler = datapart.getDataHandler();
    assertEquals(dataHandler.getContentType(),
            DEFAULT_TEST_DATAPART_CONTENTTYPE + ";name=" + DEFAULT_TEST_DATAPART_FILENAME);
    assertEquals(dataHandler.getName(), DEFAULT_TEST_DATAPART_FILENAME);
    assertEquals(dataHandler.getContent(), DEFAULT_TEST_BODY);

}

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

@DirtiesContext
@Test(expectedExceptions = IllegalDatapartContentException.class)
public void convertCamelMessageToDataPartWithNoDataPartTypeShouldThrow() throws Throwable {

    resultEndpoint.expectedMessageCount(1);

    String message = DEFAULT_TEST_BODY;

    Map<String, Object> headers = new HashMap<String, Object>();
    headers.put(ShsHeaders.DATAPART_TRANSFERENCODING, "base64");
    headers.put(ShsHeaders.DATAPART_CONTENTTYPE, DEFAULT_TEST_DATAPART_CONTENTTYPE);
    headers.put(ShsHeaders.DATAPART_FILENAME, DEFAULT_TEST_DATAPART_FILENAME);
    headers.put(ShsHeaders.DATAPART_CONTENTLENGTH, message.length());

    try {// ww w .ja v  a 2  s.  c o m
        template.sendBodyAndHeaders("direct:camelToShsConverter", message, headers);
    } catch (CamelExecutionException e) {
        throw e.getCause();
    }

    resultEndpoint.assertIsSatisfied();
    List<Exchange> exchanges = resultEndpoint.getExchanges();
    Exchange exchange = exchanges.get(0);
    Message in = exchange.getIn();
    DataPart datapart = in.getMandatoryBody(DataPart.class);
    assertNotNull(datapart);

    assertEquals((long) datapart.getContentLength(), message.length());
    assertEquals(datapart.getContentType(), DEFAULT_TEST_DATAPART_CONTENTTYPE);
    assertEquals(datapart.getDataPartType(), DEFAULT_TEST_DATAPART_TYPE);
    assertEquals(datapart.getFileName(), DEFAULT_TEST_DATAPART_FILENAME);
    assertEquals(datapart.getTransferEncoding(), "base64");

    assertNotNull(datapart.getDataHandler());
    DataHandler dataHandler = datapart.getDataHandler();
    assertEquals(dataHandler.getContentType(), DEFAULT_TEST_DATAPART_CONTENTTYPE);
    assertEquals(dataHandler.getName(), DEFAULT_TEST_DATAPART_FILENAME);
    assertEquals(dataHandler.getContent(), DEFAULT_TEST_BODY);
}

From source file:com.vangent.hieos.xutil.soap.Mtom.java

public void decode(OMElement document) throws XdsIOException, IOException {
    this.document = document;
    OMText binaryNode = (OMText) document.getFirstOMChild();
    //System.out.println("isOptimized: " + binaryNode.isOptimized());

    xop = binaryNode.isOptimized();//from   www .  j a  va2  s.c  om

    if (xop) {
        javax.activation.DataHandler datahandler = (javax.activation.DataHandler) binaryNode.getDataHandler();
        InputStream is = null;
        try {
            is = datahandler.getInputStream();
            contents = Io.getBytesFromInputStream(is);
        } catch (IOException e) {
            throw new XdsIOException("Error accessing XOP encoded document content from message");
        }
        this.content_type = datahandler.getContentType();
    } else {
        String base64 = binaryNode.getText();
        contents = Base64.decodeBase64(base64.getBytes());
        /* BHT: REMOVED (and replaced with above line).
        BASE64Decoder d  = new BASE6decoded.toString();4Decoder();
        contents = d.decodeBuffer(base64);
         */
        this.content_type = null;
    }
}

From source file:org.apache.camel.component.cxf.jaxrs.simplebinding.CxfRsConsumerSimpleBindingTest.java

protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        public void configure() {
            from(CXF_RS_ENDPOINT_URI).recipientList(simple("direct:${header.operationName}"));

            from("direct:getCustomer").process(new Processor() {
                public void process(Exchange exchange) throws Exception {
                    assertNotNull(exchange.getIn().getHeader("id"));
                    long id = exchange.getIn().getHeader("id", Long.class);
                    if (id == 123) {
                        assertEquals("123", exchange.getIn().getHeader("id"));
                        assertEquals(MessageContentsList.class, exchange.getIn().getBody().getClass());
                        exchange.getOut().setBody(new Customer(123, "Raul"));
                        exchange.getOut().setHeader(Exchange.HTTP_RESPONSE_CODE, 200);
                    } else if (id == 456) {
                        exchange.getOut().setHeader(Exchange.HTTP_RESPONSE_CODE, 404);
                    } else {
                        fail();/*from w  w w . j a v  a 2  s. co m*/
                    }
                }
            });

            from("direct:updateCustomer").process(new Processor() {
                public void process(Exchange exchange) throws Exception {
                    assertEquals("123", exchange.getIn().getHeader("id"));
                    Customer c = exchange.getIn().getBody(Customer.class);
                    assertEquals(123, c.getId());
                    assertNotNull(c);
                }
            });

            from("direct:newCustomer").process(new Processor() {
                public void process(Exchange exchange) throws Exception {
                    Customer c = exchange.getIn().getBody(Customer.class);
                    assertNotNull(c);
                    assertEquals(123, c.getId());
                }
            });

            from("direct:listVipCustomers").process(new Processor() {
                public void process(Exchange exchange) throws Exception {
                    assertEquals("gold", exchange.getIn().getHeader("status", String.class));
                    assertEquals(MessageContentsList.class, exchange.getIn().getBody().getClass());
                    assertEquals(0, exchange.getIn().getBody(MessageContentsList.class).size());
                    CustomerList response = new CustomerList();
                    List<Customer> list = new ArrayList<Customer>(2);
                    list.add(new Customer(123, "Raul"));
                    list.add(new Customer(456, "Raul2"));
                    response.setCustomers(list);
                    exchange.getOut().setBody(response);
                }
            });

            from("direct:updateVipCustomer").process(new Processor() {
                public void process(Exchange exchange) throws Exception {
                    assertEquals("gold", exchange.getIn().getHeader("status", String.class));
                    assertEquals("123", exchange.getIn().getHeader("id"));
                    Customer c = exchange.getIn().getBody(Customer.class);
                    assertEquals(123, c.getId());
                    assertNotNull(c);
                }
            });

            from("direct:deleteVipCustomer").process(new Processor() {
                public void process(Exchange exchange) throws Exception {
                    assertEquals("gold", exchange.getIn().getHeader("status", String.class));
                    assertEquals("123", exchange.getIn().getHeader("id"));
                }
            });

            from("direct:uploadImageInputStream").process(new Processor() {
                public void process(Exchange exchange) throws Exception {
                    assertEquals("123", exchange.getIn().getHeader("id"));
                    assertEquals("image/jpeg", exchange.getIn().getHeader("Content-Type"));
                    assertTrue(InputStream.class.isAssignableFrom(exchange.getIn().getBody().getClass()));
                    InputStream is = exchange.getIn().getBody(InputStream.class);
                    is.close();
                    exchange.getOut().setBody(null);
                }
            });

            from("direct:uploadImageDataHandler").process(new Processor() {
                public void process(Exchange exchange) throws Exception {
                    assertEquals("123", exchange.getIn().getHeader("id"));
                    assertEquals("image/jpeg", exchange.getIn().getHeader("Content-Type"));
                    assertTrue(DataHandler.class.isAssignableFrom(exchange.getIn().getBody().getClass()));
                    DataHandler dh = exchange.getIn().getBody(DataHandler.class);
                    assertEquals("image/jpeg", dh.getContentType());
                    dh.getInputStream().close();
                    exchange.getOut().setBody(null);
                }
            });

            from("direct:multipartPostWithParametersAndPayload").process(new Processor() {
                public void process(Exchange exchange) throws Exception {
                    assertEquals("abcd", exchange.getIn().getHeader("query"));
                    assertEquals("123", exchange.getIn().getHeader("id"));
                    assertNotNull(exchange.getIn().getAttachment("part1"));
                    assertNotNull(exchange.getIn().getAttachment("part2"));
                    assertNull(exchange.getIn().getHeader("part1"));
                    assertNull(exchange.getIn().getHeader("part2"));
                    assertEquals(Customer.class, exchange.getIn().getHeader("body").getClass());
                    exchange.getOut().setBody(null);
                }
            });

            from("direct:multipartPostWithoutParameters").process(new Processor() {
                public void process(Exchange exchange) throws Exception {
                    assertNotNull(exchange.getIn().getAttachment("part1"));
                    assertNotNull(exchange.getIn().getAttachment("part2"));
                    assertNull(exchange.getIn().getHeader("part1"));
                    assertNull(exchange.getIn().getHeader("part2"));
                    assertEquals(Customer.class, exchange.getIn().getHeader("body").getClass());
                    exchange.getOut().setBody(null);
                }
            });
        }
    };
}

From source file:se.inera.axel.shs.processor.ShsMessageMarshaller.java

public ShsMessage unmarshal(InputStream stream) throws IllegalMessageStructureException {
    log.trace("unmarshal(InputStream)");

    try {//from w  ww . j  av  a 2 s .  com
        stream = SharedDeferredStream.toSharedInputStream(stream);
        MimeMessage mimeMessage = new MimeMessage(session, stream);
        Object msgContent = mimeMessage.getContent();

        if (!(msgContent instanceof MimeMultipart)) {
            throw new IllegalMessageStructureException(
                    "Expected a multipart mime message, got " + msgContent.getClass());
        }

        MimeMultipart multipart = (MimeMultipart) msgContent;

        if (multipart.getCount() < 2) {
            throw new IllegalMessageStructureException("SHS message must contain at least two mime bodyparts");
        }

        ShsMessage shsMessage = new ShsMessage();

        BodyPart labelPart = multipart.getBodyPart(0);
        if (!labelPart.isMimeType("text/xml") && !labelPart.isMimeType("text/plain")) {
            throw new IllegalMessageStructureException(
                    "First bodypart is not text/xml nor text/plain but was " + labelPart.getContentType());
        }

        ShsLabel label = shsLabelMarshaller.unmarshal((String) labelPart.getContent());

        shsMessage.setLabel(label);

        Content content = label.getContent();
        if (content == null) {
            throw new IllegalMessageStructureException("Label contains no content elements");
        }

        // this reads only as many mime body parts as there are content/data elements in the label
        int i = 1;
        for (Object o : content.getDataOrCompound()) {
            MimeBodyPart dp = (MimeBodyPart) multipart.getBodyPart(i);
            DataHandler dh = dp.getDataHandler();
            DataPart dataPart = new DataPart();
            dataPart.setDataHandler(new DataHandler(
                    new InputStreamDataSource(dh.getDataSource().getInputStream(), dh.getContentType())));

            dataPart.setContentType(dh.getContentType());

            String encoding = dp.getEncoding();
            if (encoding != null) {
                dataPart.setTransferEncoding(encoding);
            }

            dataPart.setFileName(dp.getFileName());

            if (o instanceof Data) {
                Data data = (Data) o;
                dataPart.setDataPartType(data.getDatapartType());
            } else if (o instanceof Compound) {
                continue;
            }
            shsMessage.addDataPart(dataPart);
            i++;
        }

        return shsMessage;

    } catch (Exception e) {
        if (e instanceof IllegalMessageStructureException) {
            throw (IllegalMessageStructureException) e;
        }

        throw new IllegalMessageStructureException(e);
    }
}

From source file:org.wso2.carbon.attachment.mgt.core.dao.impl.jpa.openjpa.entity.AttachmentDAOImpl.java

@Override
public void setContent(DataHandler content) throws AttachmentMgtException {
    try {/*  www  .j  ava  2 s . co  m*/
        //Here we are giving priority to setContentType() and setName(). If those values are already assigned,
        // then name and contentType in the content DataHandler will be ignored.
        if (this.name == null) {
            setName(content.getName());
        }
        if (this.contentType == null) {
            setContentType(content.getContentType());
        }

        this.content = IOUtils.toByteArray(content.getInputStream());
    } catch (IOException e) {
        log.error(e.getLocalizedMessage(), e);
        throw new AttachmentMgtException(e.getLocalizedMessage(), e);
    }
}