Example usage for java.io OutputStream toString

List of usage examples for java.io OutputStream toString

Introduction

In this page you can find the example usage for java.io OutputStream toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:de.betterform.xml.xforms.model.submission.Submission.java

private void submitReplaceNew(Map response) throws XFormsException {
    Document result = getResponseAsDocument(response);
    Node embedElement = result.getDocumentElement();

    OutputStream outputStream = new ByteArrayOutputStream();
    try {/*from  w  w  w.ja  v  a 2s.co m*/
        DOMUtil.prettyPrintDOM(embedElement, outputStream);
    } catch (TransformerException e) {
        throw new XFormsException(e);
    }
    Map eventInfo = new HashMap();
    eventInfo.put(DOCUMENT, outputStream.toString());

    // dispatch xforms-submit-done
    this.container.dispatch(this.target, XFormsEventNames.SUBMIT_DONE, eventInfo);

}

From source file:ee.ria.xroad.opmonitordaemon.QueryRequestHandlerTest.java

/**
 * Ensure that an operational data response contains the required attachment
 * that is correctly referenced from within the SOAP body.
 *///from w w  w  .  j  a v a 2s  .co  m
@Test
public void handleOperationalDataRequest() throws Exception {
    InputStream is = new FileInputStream(OPERATIONAL_DATA_REQUEST);
    SoapParser parser = new SoapParserImpl();
    SoapMessageImpl request = (SoapMessageImpl) parser.parse(MimeTypes.TEXT_XML_UTF8, is);

    QueryRequestHandler handler = new OperationalDataRequestHandler() {
        @Override
        protected OperationalDataRecords getOperationalDataRecords(ClientId filterByClient, long recordsFrom,
                long recordsTo, ClientId filterByServiceProvider, Set<String> outputFields) {
            return new OperationalDataRecords(Collections.emptyList());
        }

        @Override
        protected ClientId getClientForFilter(ClientId clientId, SecurityServerId serverId) throws Exception {
            return null;
        }
    };

    OutputStream out = new ByteArrayOutputStream();

    handler.handle(request, out, ct -> testContentType = ct);

    String baseContentType = MimeUtils.getBaseContentType(testContentType);
    assertEquals(MimeTypes.MULTIPART_RELATED, baseContentType);

    SoapMessageDecoder decoder = new SoapMessageDecoder(testContentType, new SoapMessageDecoder.Callback() {
        @Override
        public void soap(SoapMessage message, Map<String, String> headers) throws Exception {
            assertEquals("cid:" + OperationalDataRequestHandler.CID, findRecordsContentId(message));
        }

        @Override
        public void attachment(String contentType, InputStream content, Map<String, String> additionalHeaders)
                throws Exception {
            String expectedCid = "<" + OperationalDataRequestHandler.CID + ">";
            assertEquals(expectedCid, additionalHeaders.get("content-id"));
        }

        @Override
        public void onCompleted() {
            // Do nothing.
        }

        @Override
        public void onError(Exception t) throws Exception {
            throw t;
        }

        @Override
        public void fault(SoapFault fault) throws Exception {
            throw fault.toCodedException();
        }
    });

    decoder.parse(IOUtils.toInputStream(out.toString()));
}

From source file:com.vmware.vchs.publicapi.samples.VMCreateSample.java

/**
 * This method will initialize and deploy a vApp using the instantiationHref, vappTemplateHref,
 * vmNetworkName and vdc provided.//from  ww  w.  j  av  a2 s  .co  m
 * 
 * @param instantiateHref
 *            the href to instantiatevApp action
 * @param vappTempalteHref
 *            the href to the vApp Template to be used to create vApp
 * @param vmNetworkName
 *            the network name for VM
 * @param VdcType
 *            the vdc
 * @return VappType if the initialize vapp succeeds, null otherwise
 */
private VAppType createVApp(final String instantiateHref, final String vappTempalteHref, VdcType vdc) {
    System.out.print("Attempting to create vApp...");
    ReferenceType vappReference = new ReferenceType();
    vappReference.setHref(vappTempalteHref);

    // Create an InstantiateVAppTemplateParamsType object and initialize it
    InstantiateVAppTemplateParamsType instvApp = new InstantiateVAppTemplateParamsType();

    // Set the name of vApp using the options.vappname (command line option --targetvappname)
    instvApp.setName(options.vappName);

    // do not deploy this vApp.. we still need to update network info which requires the
    // vApp to be undeployed and not powered on.
    instvApp.setDeploy(Boolean.FALSE);
    instvApp.setPowerOn(Boolean.FALSE);

    // vApp reference to be used
    instvApp.setSource(vappReference);
    instvApp.setDescription("VM creation using VMCreateSample");
    instvApp.setAllEULAsAccepted(Boolean.TRUE);

    InstantiationParamsType instParams = new InstantiationParamsType();

    instvApp.setInstantiationParams(instParams);

    JAXBContext jaxbContexts = null;
    try {
        jaxbContexts = JAXBContext.newInstance(InstantiateVAppTemplateParamsType.class);
    } catch (JAXBException ex) {
        throw new RuntimeException("Problem creating JAXB Context: ", ex);
    }

    // Create HttpPost request to perform InstantiatevApp action
    HttpPost instantiateVAppPost = vcd.post(instantiateHref, options);
    com.vmware.vcloud.api.rest.schema.ObjectFactory obj = new com.vmware.vcloud.api.rest.schema.ObjectFactory();
    JAXBElement<InstantiateVAppTemplateParamsType> instvAppTemplate = obj
            .createInstantiateVAppTemplateParams(instvApp);
    OutputStream os = null;

    try {
        javax.xml.bind.Marshaller marshaller = jaxbContexts.createMarshaller();
        marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        os = new ByteArrayOutputStream();
        // Marshal the object via JAXB to XML
        marshaller.marshal(instvAppTemplate, os);
    } catch (JAXBException e) {
        throw new RuntimeException("Problem marshalling instantiation vApp template", e);
    }

    // Set the Content-Type header for the VM vApp template parameters
    ContentType contentType = ContentType
            .create("application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml", "ISO-8859-1");
    StringEntity vapp = new StringEntity(os.toString(), contentType);
    instantiateVAppPost.setEntity(vapp);

    // Invoke the HttoPost to initiate the VM creation process
    HttpResponse response = HttpUtils.httpInvoke(instantiateVAppPost);

    VAppType vApp = null;

    // Make sure response status is 201 Created
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
        vApp = HttpUtils.unmarshal(response.getEntity(), VAppType.class);
    }

    if (null == vApp) {
        throw new RuntimeException("Could not instatiate or deploy the vApp.");
    }

    return vApp;
}

From source file:de.betterform.xml.xforms.model.submission.Submission.java

private void submitReplaceEmbedXForms(Map response) throws XFormsException {
    // check for targetid
    String targetid = getXFormsAttribute(TARGETID_ATTRIBUTE);
    String resource = getResource();
    Map eventInfo = new HashMap();
    String error = null;/*from  w w w.j  a v  a 2 s . co  m*/
    if (targetid == null) {
        error = "targetId";
    } else if (resource == null) {
        error = "resource";
    }

    if (error != null && error.length() > 0) {
        eventInfo.put(XFormsConstants.ERROR_TYPE, "no " + error + "defined for submission resource");
        this.container.dispatch(this.target, XFormsEventNames.SUBMIT_ERROR, eventInfo);
        return;
    }

    Document result = getResponseAsDocument(response);
    Node embedElement = result.getDocumentElement();

    if (resource.indexOf("#") != -1) {
        // detected a fragment so extract that from our result Document

        String fragmentid = resource.substring(resource.indexOf("#") + 1);
        if (fragmentid.indexOf("?") != -1) {
            fragmentid = fragmentid.substring(0, fragmentid.indexOf("?"));
        }
        embedElement = DOMUtil.getById(result, fragmentid);
    }

    Element embeddedNode = null;
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("get target element for id: " + targetid);
    }
    Element targetElem = this.container.getElementById(targetid);
    DOMResult domResult = new DOMResult();
    //Test if targetElem exist.
    if (targetElem != null) {
        // destroy existing embedded form within targetNode
        if (targetElem.hasChildNodes()) {
            // destroyembeddedModels(targetElem);
            Initializer.disposeUIElements(targetElem);
        }
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("destroyed any existing ui elements for target elem");
        }

        // import referenced embedded form into host document
        embeddedNode = (Element) this.container.getDocument().importNode(embedElement, true);

        //import namespaces
        NamespaceResolver.applyNamespaces(targetElem.getOwnerDocument().getDocumentElement(),
                (Element) embeddedNode);

        // keep original targetElem id within hostdoc
        embeddedNode.setAttributeNS(null, "id", targetElem.getAttributeNS(null, "id"));
        //copy all Attributes that might have been on original mountPoint to embedded node
        DOMUtil.copyAttributes(targetElem, embeddedNode, null);
        targetElem.getParentNode().replaceChild(embeddedNode, targetElem);
        //create model for it
        Initializer.initializeUIElements(model, embeddedNode, null, null);

        try {
            CachingTransformerService transformerService = new CachingTransformerService(
                    new ClasspathResourceResolver("unused"));
            // TODO: MUST BE GENERIFIED USING USERAGENT MECHANISM
            //TODO: check exploded mode!!!
            String path = getClass().getResource("/META-INF/resources/xslt/xhtml.xsl").getPath();

            //String xslFilePath = "file:" + path;
            transformerService.getTransformer(new URI(path));
            XSLTGenerator generator = new XSLTGenerator();
            generator.setTransformerService(transformerService);
            generator.setStylesheetURI(new URI(path));
            generator.setInput(embeddedNode);
            generator.setOutput(domResult);
            generator.generate();
        } catch (TransformerException e) {
            throw new XFormsException(
                    "Transformation error while executing 'Submission.submitReplaceEmbedXForms'", e);
        } catch (URISyntaxException e) {
            throw new XFormsException(
                    "Malformed URI throwed URISyntaxException in 'Submission.submitReplaceEmbedXForms'", e);
        }
    }

    // Map eventInfo = constructEventInfo(response);
    OutputStream outputStream = new ByteArrayOutputStream();
    try {
        DOMUtil.prettyPrintDOM(domResult.getNode(), outputStream);
    } catch (TransformerException e) {
        throw new XFormsException(e);
    }

    eventInfo.put(EMBEDNODE, outputStream.toString());
    eventInfo.put("embedTarget", targetid);
    eventInfo.put("embedXForms", true);

    // dispatch xforms-submit-done
    this.container.dispatch(this.target, XFormsEventNames.SUBMIT_DONE, eventInfo);

}

From source file:com.groupon.odo.Proxy.java

/**
 * Execute a request through Odo processing
 *
 * @param httpMethodProxyRequest//from   ww w.jav a2s  .co m
 * @param httpServletRequest
 * @param httpServletResponse
 * @param history
 */
private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse, History history) {
    try {
        RequestInformation requestInfo = requestInformation.get();

        // Execute the request
        // removing accept headers so that the server doesn't encode anything
        // TODO: make this handle things like gzip encoding
        httpMethodProxyRequest.removeRequestHeader(Constants.HEADER_ACCEPT_ENCODING);
        httpMethodProxyRequest.removeRequestHeader(Constants.HEADER_ACCEPT);

        // set virtual host so the server knows how to direct the request
        // If the host header exists then this uses that value
        // Otherwise the hostname from the URL is used
        processVirtualHostName(httpMethodProxyRequest, httpServletRequest);
        cullDisabledPaths();

        // define output stream
        OutputStream outStream = new ByteArrayOutputStream();
        requestInfo.hasCustomResponse = hasCustomResponse();

        if (!requestInfo.hasCustomResponse) {
            logger.info("Sending request to server");

            history.setModified(requestInfo.modified);

            executeRequest(httpMethodProxyRequest, httpServletRequest, httpServletResponse, history, outStream);
        }
        if (requestInfo.selectedResponsePaths.size() > 0) {
            requestInfo.outputString = outStream.toString();
        }
        logOriginalResponseHistory(httpServletResponse, history, outStream);
        String jsonpCallback = stripJSONPToOutstr(httpServletRequest);
        applyResponseOverrides(httpServletResponse, httpServletRequest, history);
        writeResponseOutput(httpServletResponse, outStream, jsonpCallback);
        // store history
        history.setModified(requestInfo.modified);
        logRequestHistory(httpMethodProxyRequest, httpServletResponse, history);
    } catch (Exception e) {
        e.printStackTrace();
        return;
    }
}

From source file:com.groupon.odo.Proxy.java

/**
 * Log original response/*from w ww.  j a  v  a 2 s  .c  om*/
 *
 * @param httpServletResponse
 * @param history
 * @throws URIException
 */
private void logOriginalResponseHistory(HttpServletResponse httpServletResponse, History history,
        OutputStream outStream) throws URIException {
    RequestInformation requestInfo = requestInformation.get();
    if (requestInfo.handle && requestInfo.client.getIsActive()) {
        logger.info("Storing original response history");
        history.setOriginalResponseHeaders(HttpUtilities.getHeaders(httpServletResponse));
        history.setOriginalResponseCode(Integer.toString(httpServletResponse.getStatus()));
        history.setOriginalResponseContentType(httpServletResponse.getContentType());
        history.setOriginalResponseData(outStream.toString());
        logger.info("Done storing");
    }
}

From source file:com.vmware.vchs.publicapi.samples.VMCreateSample.java

/**
 * This will use the passed in vm  to find the VirtualHardwareSection and modify it to attach
 * the Vm network to the vApp network the Vm is a child of. The first step is to search the
 * Vm section types for VirtualHardwareSection. If found, look in the attributes of the section
 * to find the VirtualHardwareSection Href value. The VirtualHardwareSection found in the Vm
 * has a number of extra LinkType links that can not be part of the request body when the PUT
 * call to update the network settings is made. Therefore, the Href is used to first GET the
 * VirtualHardwareSection again which responds without the links so it can be used to PUT back
 * to the same Href to update the Vm network settings. With the newly acquired 
 * VirtualHardwareSection, a search through the items is done to find the network item. This
 * is denoted by a resource type value of "10". If found the command line options.networkName
 * is set as the value of the connection, and the value POOL is assigned to the ipAddressingMode
 * attribute. With those values set, the updated VirtualHardwareSection is then sent via a PUT
 * request to change the Vm network settings.
 * //from   w  ww .ja v  a 2  s  .c o m
 * @param vm the Vm to change network settings on
 */
private TaskType updateVMWithNetworkDetails(VmType vm) {
    // the Href to use for GET and PUT calls for the VirtualHardwareSection
    String hardwareHref = null;
    // With the VDC network details, we can now update the Vm network section to connect the Vm to the vApp network
    for (JAXBElement<? extends SectionType> st : vm.getSection()) {
        if (st.getName().toString().contains("VirtualHardwareSection")) {
            VirtualHardwareSectionType hardware = (VirtualHardwareSectionType) st.getValue();

            // Try to find the Href attribute which is used for GET and PUT
            Map<QName, String> map = hardware.getOtherAttributes();
            Set<QName> keys = map.keySet();
            for (QName key : keys) {
                if (key.toString().endsWith("href")) {
                    hardwareHref = map.get(key);
                    break;
                }
            }

            // Make sure VirtualHardwareSection href was found. This is used for the GET below
            // and PUT to later update the network settings of the Vm.
            if (null != hardwareHref) {
                // It's necessary to GET the VirtualHardwareSection again because the current
                // hardware variables from the Vm contains links that can not be sent as part
                // of the PUT body. This GET call will only get the details without the links
                // that the Vm section provides.
                HttpResponse response = HttpUtils.httpInvoke(vcd.get(hardwareHref, options));
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    hardware = HttpUtils.unmarshal(response.getEntity(), VirtualHardwareSectionType.class);

                    // Find the RASDType that has a ResourceType of 10, which indicates the
                    // VMs network info
                    for (RASDType rasType : hardware.getItem()) {
                        if (rasType.getResourceType().getValue().equals("10")) {
                            CimBoolean c = new CimBoolean();
                            c.setValue(true);

                            rasType.setAutomaticAllocation(c);
                            // Get the first CimString
                            CimString cs = rasType.getConnection().get(0);

                            // Set the network name
                            cs.setValue(options.networkName);

                            // Look in the list of attributes for the ip addressing mode
                            map = cs.getOtherAttributes();
                            keys = map.keySet();
                            for (QName key : keys) {
                                if (key.toString().endsWith("ipAddressingMode")) {
                                    // Set it to POOL
                                    map.put(key, "POOL");
                                    break;
                                }
                            }

                            break;
                        }
                    }
                }

                // Now do a PUT with update data
                com.vmware.vcloud.api.rest.schema.ovf.ObjectFactory objectFactory = new com.vmware.vcloud.api.rest.schema.ovf.ObjectFactory();
                JAXBElement<VirtualHardwareSectionType> hardwareSection = objectFactory
                        .createVirtualHardwareSection(hardware);

                JAXBContext jaxbContexts = null;
                try {
                    jaxbContexts = JAXBContext.newInstance(VirtualHardwareSectionType.class);
                } catch (JAXBException ex) {
                    throw new RuntimeException("Problem creating JAXB Context: ", ex);
                }

                // Create HttpPut request to update the VirtualHardwareSection
                HttpPut updateVmNetwork = vcd.put(hardwareHref, options);
                OutputStream os = null;

                try {
                    javax.xml.bind.Marshaller marshaller = jaxbContexts.createMarshaller();
                    marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
                    os = new ByteArrayOutputStream();
                    // Marshal the object via JAXB to XML
                    marshaller.marshal(hardwareSection, os);
                } catch (JAXBException e) {
                    throw new RuntimeException("Problem marshalling VirtualHardwareSection", e);
                }

                // Set the Content-Type header for VirtualHardwareSection
                ContentType contentType = ContentType
                        .create("application/vnd.vmware.vcloud.virtualHardwareSection+xml", "ISO-8859-1");
                StringEntity update = new StringEntity(os.toString(), contentType);
                updateVmNetwork.setEntity(update);

                // Invoke the HttoPut to update the VirtualHardwareSection of the Vm
                response = HttpUtils.httpInvoke(updateVmNetwork);

                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_ACCEPTED) {
                    // Update was good, return the TaskType
                    TaskType taskType = HttpUtils.unmarshal(response.getEntity(), TaskType.class);
                    return taskType;
                }

                break;
            }
        }
    }

    throw new RuntimeException("Could not update Vm VirtualHardwareSection");
}

From source file:org.ebayopensource.turmeric.eclipse.buildsystem.utils.ProjectPropertiesFileUtil.java

/**
 * Creates the consumer project properties file. The name of the file is
 * "service_consumer_project.properties". This file has information about
 * the base consumer source directory if there is one.
 *
 * @param soaConsumerProject the soa consumer project
 * @param monitor the monitor/*from   w w w.j a v  a2  s. com*/
 * @return the i file
 * @throws Exception the exception
 */
public static IFile createPropsFile(SOAConsumerProject soaConsumerProject, IProgressMonitor monitor)
        throws Exception {
    IFile file = soaConsumerProject.getEclipseMetadata().getProject()
            .getFile(SOAProjectConstants.PROPS_FILE_SERVICE_CONSUMER);
    OutputStream output = null;
    try {
        final SOAConsumerMetadata metadata = soaConsumerProject.getMetadata();
        output = new ByteArrayOutputStream();
        Properties properties = new Properties();
        properties.setProperty(SOAProjectConstants.PROPS_KEY_CLIENT_NAME, metadata.getClientName());
        String consumerID = metadata.getConsumerId() != null ? metadata.getConsumerId() : "";
        properties.setProperty(SOAProjectConstants.PROPS_KEY_CONSUMER_ID, consumerID);
        ISOAConfigurationRegistry configReg = GlobalRepositorySystem.instanceOf().getActiveRepositorySystem()
                .getConfigurationRegistry();
        if (configReg != null && StringUtils.isNotBlank(configReg.getEnvironmentMapperImpl())) {
            properties.setProperty(SOAProjectConstants.PROPS_ENV_MAPPER, configReg.getEnvironmentMapperImpl());
        }
        properties.setProperty(SOAProjectConstants.PROPS_KEY_SCPP_VERSION,
                SOAProjectConstants.PROPS_DEFAULT_SCPP_VERSION);

        final Collection<String> services = new ArrayList<String>();
        final ISOAAssetRegistry assetRegistry = GlobalRepositorySystem.instanceOf().getActiveRepositorySystem()
                .getAssetRegistry();

        for (String serviceName : metadata.getServiceNames()) {
            final String assetLocation = assetRegistry.getAssetLocation(serviceName);
            if (StringUtils.isNotBlank(assetLocation)) {
                final Version version = SOAIntfUtil.getServiceMetadataVersion(serviceName, assetLocation);
                if (version.compareTo(SOAProjectConstants.DEFAULT_PROPERTY_VERSION) >= 0) {
                    //the project is post 2.4
                    services.add(serviceName);
                }
            } else {
                SOALogger.getLogger().warning(
                        "Could not find the service in the underlying system, so generate the base cosumer:",
                        serviceName);
                //services.add(serviceName);
            }
        }
        properties.setProperty(SOAProjectConstants.PROPS_NOT_GENERATE_BASE_CONSUMER,
                StringUtils.join(services, SOAProjectConstants.DELIMITER_COMMA));
        properties.setProperty(SOAProjectConstants.PROPS_SUPPORT_ZERO_CONFIG,
                Boolean.toString(metadata.isZeroConfig()));

        properties.store(output, SOAProjectConstants.PROPS_COMMENTS);
        WorkspaceUtil.writeToFile(output.toString(), file, monitor);
    } finally {
        IOUtils.closeQuietly(output);
    }
    return file;
}

From source file:org.wso2.carbon.bpmn.rest.service.runtime.WorkflowTaskService.java

@POST
@Path("/{taskId}/attachments")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response createAttachmentForBinary(@PathParam("taskId") String taskId, MultipartBody multipartBody,
        @Context HttpServletRequest httpServletRequest) {

    boolean debugEnabled = log.isDebugEnabled();
    List<org.apache.cxf.jaxrs.ext.multipart.Attachment> attachments = multipartBody.getAllAttachments();

    int attachmentSize = attachments.size();

    if (attachmentSize <= 0) {
        throw new ActivitiIllegalArgumentException("No Attachments found with the request body");
    }/*from  ww  w .  j av a2  s . c o  m*/
    AttachmentDataHolder attachmentDataHolder = new AttachmentDataHolder();

    for (int i = 0; i < attachmentSize; i++) {
        org.apache.cxf.jaxrs.ext.multipart.Attachment attachment = attachments.get(i);

        String contentDispositionHeaderValue = attachment.getHeader("Content-Disposition");
        String contentType = attachment.getHeader("Content-Type");

        if (debugEnabled) {
            log.debug("Going to iterate:" + i);
            log.debug("contentDisposition:" + contentDispositionHeaderValue);
        }

        if (contentDispositionHeaderValue != null) {
            contentDispositionHeaderValue = contentDispositionHeaderValue.trim();

            Map<String, String> contentDispositionHeaderValueMap = Utils
                    .processContentDispositionHeader(contentDispositionHeaderValue);
            String dispositionName = contentDispositionHeaderValueMap.get("name");
            DataHandler dataHandler = attachment.getDataHandler();

            OutputStream outputStream = null;

            if ("name".equals(dispositionName)) {
                try {
                    outputStream = Utils.getAttachmentStream(dataHandler.getInputStream());
                } catch (IOException e) {
                    throw new ActivitiIllegalArgumentException("Attachment Name Reading error occured", e);
                }

                if (outputStream != null) {
                    String fileName = outputStream.toString();
                    attachmentDataHolder.setName(fileName);
                }

            } else if ("type".equals(dispositionName)) {
                try {
                    outputStream = Utils.getAttachmentStream(dataHandler.getInputStream());
                } catch (IOException e) {
                    throw new ActivitiIllegalArgumentException("Attachment Type Reading error occured", e);
                }

                if (outputStream != null) {
                    String typeName = outputStream.toString();
                    attachmentDataHolder.setType(typeName);
                }

            } else if ("description".equals(dispositionName)) {
                try {
                    outputStream = Utils.getAttachmentStream(dataHandler.getInputStream());
                } catch (IOException e) {
                    throw new ActivitiIllegalArgumentException("Attachment Description Reading error occured",
                            e);
                }

                if (outputStream != null) {
                    String description = outputStream.toString();
                    attachmentDataHolder.setDescription(description);
                }
            }

            if (contentType != null) {
                if ("file".equals(dispositionName)) {

                    InputStream inputStream = null;
                    try {
                        inputStream = dataHandler.getInputStream();
                    } catch (IOException e) {
                        throw new ActivitiIllegalArgumentException(
                                "Error Occured During processing empty body.", e);
                    }

                    if (inputStream != null) {
                        attachmentDataHolder.setContentType(contentType);
                        byte[] attachmentArray = new byte[0];
                        try {
                            attachmentArray = IOUtils.toByteArray(inputStream);
                        } catch (IOException e) {
                            throw new ActivitiIllegalArgumentException("Processing Attachment Body Failed.", e);
                        }
                        attachmentDataHolder.setAttachmentArray(attachmentArray);
                    }
                }
            }
        }
    }

    attachmentDataHolder.printDebug();

    if (attachmentDataHolder.getName() == null) {
        throw new ActivitiIllegalArgumentException("Attachment name is required.");
    }

    if (attachmentDataHolder.getAttachmentArray() == null) {
        throw new ActivitiIllegalArgumentException(
                "Empty attachment body was found in request body after " + "decoding the request" + ".");
    }

    TaskService taskService = BPMNOSGIService.getTaskService();
    Task task = getTaskFromRequest(taskId);
    Response.ResponseBuilder responseBuilder = Response.ok();

    AttachmentResponse result = null;
    try {

        InputStream inputStream = new ByteArrayInputStream(attachmentDataHolder.getAttachmentArray());
        Attachment createdAttachment = taskService.createAttachment(attachmentDataHolder.getContentType(),
                task.getId(), task.getProcessInstanceId(), attachmentDataHolder.getName(),
                attachmentDataHolder.getDescription(), inputStream);

        responseBuilder.status(Response.Status.CREATED);
        result = new RestResponseFactory().createAttachmentResponse(createdAttachment,
                uriInfo.getBaseUri().toString());
    } catch (Exception e) {
        throw new ActivitiException("Error creating attachment response", e);
    }

    return responseBuilder.status(Response.Status.CREATED).entity(result).build();
}

From source file:org.wso2.carbon.bpmn.rest.service.runtime.ProcessInstanceService.java

protected RestVariable setBinaryVariable(MultipartBody multipartBody, Execution execution,
        int responseVariableType, boolean isNew) throws IOException, ServletException {

    boolean debugEnabled = log.isDebugEnabled();
    List<org.apache.cxf.jaxrs.ext.multipart.Attachment> attachments = multipartBody.getAllAttachments();

    int attachmentSize = attachments.size();

    if (attachmentSize <= 0) {
        throw new ActivitiIllegalArgumentException("No Attachments found with the request body");
    }/*from www.j a va 2s.c  om*/
    AttachmentDataHolder attachmentDataHolder = new AttachmentDataHolder();

    for (int i = 0; i < attachmentSize; i++) {
        org.apache.cxf.jaxrs.ext.multipart.Attachment attachment = attachments.get(i);

        String contentDispositionHeaderValue = attachment.getHeader("Content-Disposition");
        String contentType = attachment.getHeader("Content-Type");

        if (debugEnabled) {
            log.debug("Going to iterate:" + i);
            log.debug("contentDisposition:" + contentDispositionHeaderValue);
        }

        if (contentDispositionHeaderValue != null) {
            contentDispositionHeaderValue = contentDispositionHeaderValue.trim();

            Map<String, String> contentDispositionHeaderValueMap = Utils
                    .processContentDispositionHeader(contentDispositionHeaderValue);
            String dispositionName = contentDispositionHeaderValueMap.get("name");
            DataHandler dataHandler = attachment.getDataHandler();

            OutputStream outputStream;

            if ("name".equals(dispositionName)) {
                try {
                    outputStream = Utils.getAttachmentStream(dataHandler.getInputStream());
                } catch (IOException e) {
                    throw new ActivitiIllegalArgumentException("Attachment Name Reading error occured", e);
                }

                if (outputStream != null) {
                    String fileName = outputStream.toString();
                    attachmentDataHolder.setName(fileName);
                }

            } else if ("type".equals(dispositionName)) {
                try {
                    outputStream = Utils.getAttachmentStream(dataHandler.getInputStream());
                } catch (IOException e) {
                    throw new ActivitiIllegalArgumentException("Attachment Type Reading error occured", e);
                }

                if (outputStream != null) {
                    String typeName = outputStream.toString();
                    attachmentDataHolder.setType(typeName);
                }

            } else if ("scope".equals(dispositionName)) {
                try {
                    outputStream = Utils.getAttachmentStream(dataHandler.getInputStream());
                } catch (IOException e) {
                    throw new ActivitiIllegalArgumentException("Attachment Description Reading error occured",
                            e);
                }

                if (outputStream != null) {
                    String scope = outputStream.toString();
                    attachmentDataHolder.setScope(scope);
                }
            }
            if (contentType != null) {
                if ("file".equals(dispositionName)) {

                    InputStream inputStream;
                    try {
                        inputStream = dataHandler.getInputStream();
                    } catch (IOException e) {
                        throw new ActivitiIllegalArgumentException(
                                "Error Occured During processing empty body.", e);
                    }

                    if (inputStream != null) {
                        attachmentDataHolder.setContentType(contentType);
                        byte[] attachmentArray = new byte[0];
                        try {
                            attachmentArray = IOUtils.toByteArray(inputStream);
                        } catch (IOException e) {
                            throw new ActivitiIllegalArgumentException("Processing Attachment Body Failed.", e);
                        }
                        attachmentDataHolder.setAttachmentArray(attachmentArray);
                    }
                }
            }
        }
    }

    attachmentDataHolder.printDebug();

    String variableScope = attachmentDataHolder.getScope();
    String variableName = attachmentDataHolder.getName();
    String variableType = attachmentDataHolder.getType();

    if (attachmentDataHolder.getName() == null) {
        throw new ActivitiIllegalArgumentException("Attachment name is required.");
    }

    if (attachmentDataHolder.getAttachmentArray() == null) {
        throw new ActivitiIllegalArgumentException(
                "Empty attachment body was found in request body after " + "decoding the request" + ".");
    }

    if (debugEnabled) {
        log.debug("variableScope:" + variableScope + " variableName:" + variableName + " variableType:"
                + variableType);
    }

    try {

        // Validate input and set defaults
        if (variableName == null) {
            throw new ActivitiIllegalArgumentException("No variable name was found in request body.");
        }

        if (variableType != null) {
            if (!RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE.equals(variableType)
                    && !RestResponseFactory.SERIALIZABLE_VARIABLE_TYPE.equals(variableType)) {
                throw new ActivitiIllegalArgumentException(
                        "Only 'binary' and 'serializable' are supported as variable type.");
            }
        } else {
            variableType = RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE;
        }

        RestVariable.RestVariableScope scope = RestVariable.RestVariableScope.LOCAL;
        if (variableScope != null) {
            scope = RestVariable.getScopeFromString(variableScope);
        }

        if (variableType.equals(RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE)) {
            // Use raw bytes as variable value
            setVariable(execution, variableName, attachmentDataHolder.getAttachmentArray(), scope, isNew);

        } else {
            // Try deserializing the object
            try (InputStream inputStream = new ByteArrayInputStream(attachmentDataHolder.getAttachmentArray());
                    ObjectInputStream stream = new ObjectInputStream(inputStream);) {
                Object value = stream.readObject();
                setVariable(execution, variableName, value, scope, isNew);
            }

        }

        RestResponseFactory restResponseFactory = new RestResponseFactory();
        if (responseVariableType == RestResponseFactory.VARIABLE_PROCESS) {

            return new RestResponseFactory().createBinaryRestVariable(variableName, scope, variableType, null,
                    null, execution.getId(), uriInfo.getBaseUri().toString());
        } else {
            return restResponseFactory.createBinaryRestVariable(variableName, scope, variableType, null,
                    execution.getId(), null, uriInfo.getBaseUri().toString());
        }

    } catch (IOException ioe) {
        throw new ActivitiIllegalArgumentException("Could not process multipart content", ioe);
    } catch (ClassNotFoundException ioe) {
        throw new BPMNContentNotSupportedException(
                "The provided body contains a serialized object for which the " + "class is not found: "
                        + ioe.getMessage());
    }

}