Example usage for javax.activation DataHandler getInputStream

List of usage examples for javax.activation DataHandler getInputStream

Introduction

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

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Get the InputStream for this object.

Usage

From source file:com.utest.webservice.impl.v2.ProductWebServiceImpl.java

@Override
@Secured(Permission.TEST_CASE_EDIT)
@POST/*from   www.j  a  va  2 s  .  co m*/
@Path("/{id}/import_singlestep_testcases/")
public Boolean importSingleStepTestCasesFromCsv(MultipartBody body_, @PathParam("id") final Integer productId_)
        throws Exception {
    List<org.apache.cxf.jaxrs.ext.multipart.Attachment> attachments = body_.getAllAttachments();
    javax.activation.DataHandler dataHandler = attachments.get(0).getDataHandler();
    InputStream inputStream = dataHandler.getInputStream();
    OutputStream outputStream = new ByteArrayOutputStream();
    IOUtils.copy(inputStream, outputStream);
    inputStream.close();
    outputStream.close();
    testCaseService.importSingleStepTestCasesFromCsv(outputStream.toString(), productId_);
    return Boolean.TRUE;
}

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. c  o  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:it.cnr.icar.eric.service.catalogingTest.cppaCataloging.CPPACataloging.java

public SOAPElement catalogContent(SOAPElement partCatalogContentRequest) throws RemoteException {
    try {/*from   w  w  w.  j  av  a 2  s. c  o m*/
        if (log.isDebugEnabled()) {
            printNodeToConsole(partCatalogContentRequest);
        }

        final HashMap<String, DataHandler> repositoryItemDHMap = getRepositoryItemDHMap();

        if (log.isDebugEnabled()) {
            log.debug("Attachments: " + repositoryItemDHMap.size());
        }

        Object requestObj = getBindingObjectFromNode(partCatalogContentRequest);

        if (!(requestObj instanceof CatalogContentRequest)) {
            throw new Exception(
                    "Wrong response received from validation service.  Expected CatalogContentRequest, got: "
                            + partCatalogContentRequest.getElementName().getQualifiedName());
        }

        ccReq = (CatalogContentRequest) requestObj;

        IdentifiableType originalContentIT = ccReq.getOriginalContent().getIdentifiable().get(0).getValue();
        IdentifiableType invocationControlIT = ccReq.getInvocationControlFile().get(0);

        DataHandler invocationControlDH = repositoryItemDHMap.get(invocationControlIT.getId());

        if (log.isDebugEnabled()) {
            log.debug("originalContentIT id: " + originalContentIT.getId());
            log.debug("invocationControlIT id: " + invocationControlIT.getId());
        }

        StreamSource invocationControlSrc = new StreamSource(invocationControlDH.getInputStream());

        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer(invocationControlSrc);

        transformer.setURIResolver(new URIResolver() {
            public Source resolve(String href, String base) throws TransformerException {
                Source source = null;
                try {
                    // Should this check that href is UUID URN first?
                    source = new StreamSource((repositoryItemDHMap.get(href)).getInputStream());
                } catch (Exception e) {
                    source = null;
                }

                return source;
            }
        });
        transformer.setErrorListener(new ErrorListener() {
            public void error(TransformerException exception) throws TransformerException {
                log.info(exception);
            }

            public void fatalError(TransformerException exception) throws TransformerException {
                log.error(exception);
                throw exception;
            }

            public void warning(TransformerException exception) throws TransformerException {
                log.info(exception);
            }
        });

        //Set respository item as parameter
        transformer.setParameter("repositoryItem", originalContentIT.getId());

        StringWriter sw = new StringWriter();
        transformer.transform(new JAXBSource(jaxbContext, originalContentIT), new StreamResult(sw));

        ccResp = cmsFac.createCatalogContentResponse();

        RegistryObjectListType catalogedMetadata = (RegistryObjectListType) getUnmarshaller()
                .unmarshal(new StreamSource(new StringReader(sw.toString())));
        RegistryObjectListType roList = rimFac.createRegistryObjectListType();
        ccResp.setCatalogedContent(roList);
        // FIXME: Setting catalogedMetadata as CatalogedContent results in incorrect serialization.
        roList.getIdentifiable().addAll(catalogedMetadata.getIdentifiable());

        ccResp.setStatus(CANONICAL_RESPONSE_STATUS_TYPE_ID_Success);

        ccRespElement = getSOAPElementFromBindingObject(ccResp);

        // Copy request's attachments to response to exercise attachment-processing code on client.
        MessageContext mc = servletEndpointContext.getMessageContext();
        mc.setProperty(com.sun.xml.rpc.server.ServerPropertyConstants.SET_ATTACHMENT_PROPERTY,
                (Collection<?>) mc
                        .getProperty(com.sun.xml.rpc.server.ServerPropertyConstants.GET_ATTACHMENT_PROPERTY));

    } catch (Exception e) {
        throw new RemoteException("Could not create response.", e);
    }

    return ccRespElement;
}

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

@Override
public void process(Exchange exchange) throws Exception {
    Message in = exchange.getIn();//ww w . j  a  va2  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:org.wso2.am.admin.clients.proxy.admin.ProxyServiceAdminClient.java

/**
 * Adding proxy service// w  ww  .j a  va2  s .com
 *
 * @param dh Data Handler
 * @throws ProxyServiceAdminProxyAdminException Proxy service admin exception
 * @throws java.rmi.RemoteException             Remote exception
 * @throws javax.xml.stream.XMLStreamException  Exception
 */
public void addProxyService(DataHandler dh)
        throws ProxyServiceAdminProxyAdminException, IOException, XMLStreamException {

    XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream());
    //create the builder
    StAXOMBuilder builder = new StAXOMBuilder(parser);
    //get the root element (in this case the envelope)
    OMElement documentElement = builder.getDocumentElement();

    ProxyData proxyData = getProxyData(documentElement.toString());

    log.info("Proxy Added");
}

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 {//from  w w w.  j av a2 s.c o  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);
    }
}

From source file:com.collabnet.ccf.teamforge.TFAttachmentHandler.java

/**
 * Retrieves the attachment data for a given file id.
 * //w ww.java2 s.c om
 * @param sessionId
 * @param fileId
 * @param size
 * @param folderId
 * @param shouldShipAttachmentsWithArtifact
 * @return
 * @throws RemoteException
 */
public byte[] getAttachmentData(Connection connection, String fileId, long size, String folderId,
        boolean shouldShipAttachmentsWithArtifact, GenericArtifact ga) throws RemoteException {
    boolean retryCall = true;
    byte[] data = null;
    while (retryCall) {
        retryCall = false;
        DataHandler dataHandler = connection.getFileStorageClient().downloadFileDirect(folderId, fileId);
        BufferedInputStream is = null;
        try {
            is = new BufferedInputStream(dataHandler.getInputStream());
            if (shouldShipAttachmentsWithArtifact) {
                // TODO not a safe cast here...
                data = new byte[(int) size];
                int readLength = is.read(data);
                if (readLength == size) {
                    // Good that we read all the data
                } else {
                    // FIXME What if the attachment's size has been changed
                    // in
                    // the mean time?
                    log.error(
                            "While reading data from the attachment stream, less data than expected was returned.");
                }
            } else {
                File tempFile = null;
                data = new byte[1024 * 3];
                tempFile = File.createTempFile("CSFE_Attachment", "file");

                String attachmentDataFile = tempFile.getAbsolutePath();
                int readBytes = 0;
                FileOutputStream fos = new FileOutputStream(tempFile);
                while ((readBytes = is.read(data)) != -1) {
                    fos.write(data, 0, readBytes);
                }
                fos.close();
                GenericArtifactField attachmentDataFileField = ga.addNewField(
                        AttachmentMetaData.ATTACHMENT_DATA_FILE,
                        GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD);
                attachmentDataFileField.setFieldValueType(GenericArtifactField.FieldValueTypeValue.STRING);
                attachmentDataFileField.setFieldValue(attachmentDataFile);
                attachmentDataFileField.setFieldAction(GenericArtifactField.FieldActionValue.REPLACE);
                data = null;
            }
        } catch (IOException e) {
            if (connectionManager.isEnableRetryAfterNetworkTimeout()
                    && (!connectionManager.isUseStandardTimeoutHandlingCode())) {
                log.warn("An IO-Error while reading the attachment stream occured, trying again: ", e);
                retryCall = true;
            } else {
                throw new RuntimeException(e);
            }

        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    log.error("By closing the attachment stream, an error occured: " + e.getMessage());
                }
            }
        }
    }
    return data;
}

From source file:org.apache.axis2.rpc.complex.ComplexDataTypesComplexDataTypesSOAP11Test.java

/**
 * Auto generated test method//from   w  ww  . ja v a 2s  .  co  m
 */
public void testretByteArray() throws java.lang.Exception {

    byte[] input = new byte[] { (byte) 0xDE, (byte) 0xAD, (byte) 0xBE, (byte) 0xEF };
    DataHandler ret = stub.retByteArray(new DataHandler(new ByteArrayDataSource(input)));
    byte[] bytes = IOUtils.toByteArray(ret.getInputStream());
    assertTrue(Arrays.equals(bytes, input));
}

From source file:com.collabnet.ccf.pi.sfee.v44.SFEEAttachmentHandler.java

/**
 * Retrieves the attachment data for a given file id.
 * //  ww w . java2s. c o m
 * @param sessionId
 * @param fileId
 * @param size
 * @param folderId
 * @param shouldShipAttachmentsWithArtifact
 * @return
 * @throws RemoteException
 */
public byte[] getAttachmentData(String sessionId, String fileId, long size, String folderId,
        boolean shouldShipAttachmentsWithArtifact, GenericArtifact ga) throws RemoteException {
    boolean retryCall = true;
    byte[] data = null;
    while (retryCall) {
        retryCall = false;
        DataHandler dataHandler = fileStorageSoapApp.downloadFileDirect(sessionId, folderId, fileId);
        BufferedInputStream is = null;
        try {
            is = new BufferedInputStream(dataHandler.getInputStream());
            if (shouldShipAttachmentsWithArtifact) {
                // TODO not a safe cast here...
                data = new byte[(int) size];
                int readLength = is.read(data);
                if (readLength == size) {
                    // Good that we read all the data
                } else {
                    // FIXME What if the attachment's size has been changed
                    // in
                    // the mean time?
                    log.error(
                            "While reading data from the attachment stream, less data than expected was returned.");
                }
            } else {
                File tempFile = null;
                data = new byte[1024 * 3];
                tempFile = File.createTempFile("CSFE_Attachment", "file");

                String attachmentDataFile = tempFile.getAbsolutePath();
                int readBytes = 0;
                FileOutputStream fos = new FileOutputStream(tempFile);
                while ((readBytes = is.read(data)) != -1) {
                    fos.write(data, 0, readBytes);
                }
                fos.close();
                GenericArtifactField attachmentDataFileField = ga.addNewField(
                        AttachmentMetaData.ATTACHMENT_DATA_FILE,
                        GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD);
                attachmentDataFileField.setFieldValueType(GenericArtifactField.FieldValueTypeValue.STRING);
                attachmentDataFileField.setFieldValue(attachmentDataFile);
                attachmentDataFileField.setFieldAction(GenericArtifactField.FieldActionValue.REPLACE);
                data = null;
            }
        } catch (IOException e) {
            if (connectionManager.isEnableRetryAfterNetworkTimeout()
                    && (!connectionManager.isUseStandardTimeoutHandlingCode())) {
                log.warn("An IO-Error while reading the attachment stream occured, trying again: ", e);
                retryCall = true;
            } else {
                throw new RuntimeException(e);
            }

        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    log.error("By closing the attachment stream, an error occured: " + e.getMessage());
                }
            }
        }
    }
    return data;
}

From source file:org.apache.axis.attachments.DimeBodyPart.java

void send(java.io.OutputStream os, byte position, DataHandler dh, final long maxchunk)
        throws java.io.IOException {
    java.io.InputStream in = null;
    try {//www.j  ava 2  s .  co  m
        long dataSize = getDataSize();
        in = dh.getInputStream();
        byte[] readbuf = new byte[64 * 1024];
        int bytesread;

        sendHeader(os, position, dataSize, (byte) 0);
        long totalsent = 0;

        do {
            bytesread = in.read(readbuf);
            if (bytesread > 0) {
                os.write(readbuf, 0, bytesread);
                totalsent += bytesread;
            }
        } while (bytesread > -1);
        os.write(pad, 0, dimePadding(totalsent));
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
}