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:com.vmware.vchs.publicapi.samples.GatewayRuleSample.java

/**
 * This method is to configure NAT and Firewall Rules to the EdgeGateway
 * /*from   www.j a  v  a2s  .co m*/
 * @param networkHref
 *            the href to the network on which nat rules to be applied
 * @param serviceConfHref
 *            the href to the service configure action of gateway
 * @return
 */
private void configureRules(String networkHref, String serviceConfHref) {
    // NAT Rules
    NatServiceType natService = new NatServiceType();

    // To Enable the service using this flag
    natService.setIsEnabled(Boolean.TRUE);

    // Configuring Destination nat
    NatRuleType dnatRule = new NatRuleType();

    // Setting Rule type Destination Nat DNAT
    dnatRule.setRuleType("DNAT");
    dnatRule.setIsEnabled(Boolean.TRUE);
    GatewayNatRuleType dgatewayNat = new GatewayNatRuleType();
    ReferenceType refd = new ReferenceType();
    refd.setHref(networkHref);

    // Network on which nat rules to be applied
    dgatewayNat.setInterface(refd);

    // Setting Original IP
    dgatewayNat.setOriginalIp(options.externalIp);
    dgatewayNat.setOriginalPort("any");

    dgatewayNat.setTranslatedIp(options.internalIp);

    // To allow all ports and all protocols
    // dgatewayNat.setTranslatedPort("any");
    // dgatewayNat.setProtocol("Any");

    // To allow only https use Port 443 and TCP protocol
    dgatewayNat.setTranslatedPort("any");
    dgatewayNat.setProtocol("TCP");

    // To allow only ssh use Port 22 and TCP protocol
    // dgatewayNat.setTranslatedPort("22");
    // dgatewayNat.setProtocol("TCP");
    // Setting Destination IP
    dnatRule.setGatewayNatRule(dgatewayNat);
    natService.getNatRule().add(dnatRule);

    // Configuring Source nat
    NatRuleType snatRule = new NatRuleType();

    // Setting Rule type Source Nat SNAT
    snatRule.setRuleType("SNAT");
    snatRule.setIsEnabled(Boolean.TRUE);
    GatewayNatRuleType sgatewayNat = new GatewayNatRuleType();
    //ReferenceType refd = new ReferenceType();
    //refd.setHref(networkHref);

    // Network on which nat rules to be applied
    sgatewayNat.setInterface(refd);

    // Setting Original IP
    sgatewayNat.setOriginalIp(options.internalIp);
    //sgatewayNat.setOriginalPort("any");

    sgatewayNat.setTranslatedIp(options.externalIp);

    // Setting Source IP
    snatRule.setGatewayNatRule(sgatewayNat);
    natService.getNatRule().add(snatRule);

    // Firewall Rules
    FirewallServiceType firewallService = new FirewallServiceType();

    // Enable or disable the service using this flag
    firewallService.setIsEnabled(Boolean.TRUE);

    // Default action of the firewall set to drop
    firewallService.setDefaultAction("drop");

    // Flag to enable logging for default action
    firewallService.setLogDefaultAction(Boolean.FALSE);

    // Firewall Rule settings
    FirewallRuleType firewallInRule = new FirewallRuleType();
    firewallInRule.setIsEnabled(Boolean.TRUE);
    firewallInRule.setMatchOnTranslate(Boolean.FALSE);
    firewallInRule.setDescription("Allow incoming https access");
    firewallInRule.setPolicy("allow");
    FirewallRuleProtocols firewallProtocol = new FirewallRuleProtocols();
    firewallProtocol.setAny(Boolean.TRUE);
    firewallInRule.setProtocols(firewallProtocol);
    firewallInRule.setDestinationPortRange("any");
    firewallInRule.setDestinationIp(options.externalIp);
    firewallInRule.setSourcePortRange("Any");
    firewallInRule.setSourceIp("external");
    firewallInRule.setEnableLogging(Boolean.FALSE);
    firewallService.getFirewallRule().add(firewallInRule);

    // To create the HttpPost request Body
    ObjectFactory objectFactory = new ObjectFactory();
    GatewayFeaturesType gatewayFeatures = new GatewayFeaturesType();
    JAXBElement<NetworkServiceType> serviceType = objectFactory.createNetworkService(natService);
    JAXBElement<NetworkServiceType> firewallserviceType = objectFactory.createNetworkService(firewallService);
    gatewayFeatures.getNetworkService().add(serviceType);
    gatewayFeatures.getNetworkService().add(firewallserviceType);
    JAXBContext jaxbContexts = null;

    try {
        jaxbContexts = JAXBContext.newInstance(GatewayFeaturesType.class);
    } catch (JAXBException ex) {
        ex.printStackTrace();
    }

    OutputStream os = null;
    JAXBElement<GatewayFeaturesType> gateway_Features = objectFactory
            .createEdgeGatewayServiceConfiguration(gatewayFeatures);

    try {
        javax.xml.bind.Marshaller marshaller = jaxbContexts.createMarshaller();
        marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        os = new ByteArrayOutputStream();

        // Marshal the JAXB class to XML
        marshaller.marshal(gateway_Features, os);
    } catch (JAXBException e) {
        e.printStackTrace();
    }

    HttpPost httpPost = vcd.post(serviceConfHref, options);
    ContentType contentType = ContentType.create(SampleConstants.CONTENT_TYPE_EDGE_GATEWAY, "ISO-8859-1");
    StringEntity rules = new StringEntity(os.toString(), contentType);
    httpPost.setEntity(rules);
    InputStream is = null;

    // Invoking api to add rules to gateway
    HttpResponse response = HttpUtils.httpInvoke(httpPost);

    // Make sure the response code is 202 ACCEPTED
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_ACCEPTED) {
        // System.out.println("ResponseCode : " + response.getStatusLine().getStatusCode());
        System.out.println("\nRequest To update Gateway initiated sucessfully");
        System.out.print("\nUpdating EdgeGateways to add NAT and Firewall Rules...");
        taskStatus(response);
    }
}

From source file:org.wso2.carbon.bpmn.rest.service.base.BaseExecutionService.java

protected RestVariable createBinaryExecutionVariable(Execution execution, int responseVariableType,
        UriInfo uriInfo, boolean isNew, MultipartBody multipartBody) {

    boolean debugEnabled = log.isDebugEnabled();
    Response.ResponseBuilder responseBuilder = Response.ok();

    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");
    }/*w w  w  .ja v a  2  s. co 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 ("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 description = outputStream.toString();
                    attachmentDataHolder.setScope(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" + ".");
    }
    String variableScope = attachmentDataHolder.getScope();
    String variableName = attachmentDataHolder.getName();
    String variableType = attachmentDataHolder.getType();

    if (log.isDebugEnabled()) {
        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 (RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE.equals(variableType)) {
            // 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);
            }
        }

        if (responseVariableType == RestResponseFactory.VARIABLE_PROCESS) {
            return new RestResponseFactory().createBinaryRestVariable(variableName, scope, variableType, null,
                    null, execution.getId(), uriInfo.getBaseUri().toString());
        } else {
            return new 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 nog found: "
                        + ioe.getMessage());
    }

}

From source file:org.apache.ofbiz.shipment.thirdparty.usps.UspsServices.java

private static Document sendUspsRequest(String requestType, Document requestDocument, Delegator delegator,
        String shipmentGatewayConfigId, String resource, Locale locale) throws UspsRequestException {
    String conUrl = null;/*from w w w .j ava 2s.  com*/
    List<String> labelRequestTypes = UtilMisc.toList("PriorityMailIntl", "PriorityMailIntlCertify");
    if (labelRequestTypes.contains(requestType)) {
        conUrl = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "connectUrlLabels", resource,
                "shipment.usps.connect.url.labels");
    } else {
        conUrl = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "connectUrl", resource,
                "shipment.usps.connect.url");
    }
    if (UtilValidate.isEmpty(conUrl)) {
        throw new UspsRequestException(
                UtilProperties.getMessage(resourceError, "FacilityShipmentUspsConnectUrlIncomplete", locale));
    }

    OutputStream os = new ByteArrayOutputStream();

    try {
        UtilXml.writeXmlDocument(requestDocument, os, "UTF-8", true, false, 0);
    } catch (TransformerException e) {
        throw new UspsRequestException(UtilProperties.getMessage(resourceError,
                "FacilityShipmentUspsSerializingError", UtilMisc.toMap("errorString", e.getMessage()), locale));
    }

    String xmlString = os.toString();

    Debug.logInfo("USPS XML request string: " + xmlString, module);

    String timeOutStr = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "connectTimeout",
            resource, "shipment.usps.connect.timeout", "60");
    int timeout = 60;
    try {
        timeout = Integer.parseInt(timeOutStr);
    } catch (NumberFormatException e) {
        Debug.logError(e, "Unable to set timeout to " + timeOutStr + " using default " + timeout);
    }

    HttpClient http = new HttpClient(conUrl);
    http.setTimeout(timeout * 1000);
    http.setParameter("API", requestType);
    http.setParameter("XML", xmlString);

    String responseString = null;
    try {
        responseString = http.get();
    } catch (HttpClientException e) {
        throw new UspsRequestException(UtilProperties.getMessage(resourceError,
                "FacilityShipmentUspsConnectionProblem", UtilMisc.toMap("errorString", e), locale));
    }

    Debug.logInfo("USPS response: " + responseString, module);

    if (UtilValidate.isEmpty(responseString)) {
        return null;
    }

    Document responseDocument = null;
    try {
        responseDocument = UtilXml.readXmlDocument(responseString, false);
    } catch (Exception e) {
        throw new UspsRequestException(UtilProperties.getMessage(resourceError,
                "FacilityShipmentUspsResponseError", UtilMisc.toMap("errorString", e.getMessage()), locale));
    }

    // If a top-level error document is returned, throw exception
    // Other request-level errors should be handled by the caller
    Element responseElement = responseDocument.getDocumentElement();
    if ("Error".equals(responseElement.getNodeName())) {
        throw new UspsRequestException(UtilXml.childElementValue(responseElement, "Description"));
    }

    return responseDocument;
}

From source file:com.couchbase.spring.core.convert.MappingCouchbaseConverter.java

protected void writeInternal(final Object source, ConvertedCouchbaseDocument target, TypeInformation<?> type)
        throws IOException {
    CouchbasePersistentEntity<?> entity = mappingContext.getPersistentEntity(source.getClass());

    if (entity == null) {
        throw new MappingException(
                "No mapping metadata found for entity of type " + source.getClass().getName());
    }/*from  w  w w  .j  a  v  a 2 s . c o  m*/

    final CouchbasePersistentProperty idProperty = entity.getIdProperty();
    if (idProperty == null) {
        throw new MappingException("ID property required for entity of type " + source.getClass().getName());
    }

    final BeanWrapper<CouchbasePersistentEntity<Object>, Object> wrapper = BeanWrapper.create(source,
            conversionService);

    String id = wrapper.getProperty(idProperty, String.class, false);
    target.setId(id);
    target.setExpiry(entity.getExpiry());

    JsonFactory jsonFactory = new JsonFactory();
    OutputStream jsonStream = new ByteArrayOutputStream();
    final JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(jsonStream, JsonEncoding.UTF8);
    jsonGenerator.setCodec(new ObjectMapper());

    jsonGenerator.writeStartObject();
    entity.doWithProperties(new PropertyHandler<CouchbasePersistentProperty>() {
        @Override
        public void doWithPersistentProperty(CouchbasePersistentProperty prop) {
            if (prop.equals(idProperty)) {
                return;
            }

            Object propertyValue = wrapper.getProperty(prop, prop.getType(), false);
            if (propertyValue != null) {
                try {
                    jsonGenerator.writeFieldName(prop.getFieldName());
                    jsonGenerator.writeObject(propertyValue);
                } catch (IOException ex) {
                    throw new MappingException(
                            "Could not translate to JSON while converting " + source.getClass().getName());
                }
            }

        }
    });
    jsonGenerator.writeEndObject();
    jsonGenerator.close();

    target.setRawValue(jsonStream.toString());
}

From source file:org.wso2.carbon.bpmn.rest.service.base.BaseTaskService.java

protected RestVariable setBinaryVariable(MultipartBody multipartBody, Task task, boolean isNew, UriInfo uriInfo)
        throws IOException {

    boolean debugEnabled = log.isDebugEnabled();

    if (debugEnabled) {
        log.debug("Processing Binary variables");
    }//from   w w  w  .j a va  2s .com

    Object result = null;

    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");
    }
    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("Binary Variable 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("\"Binary Variable 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(
                            "Binary Variable scopeDescription Reading error " + "occured", e);
                }

                if (outputStream != null) {
                    String scope = outputStream.toString();
                    attachmentDataHolder.setScope(scope);
                }
            }

            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 BinaryV variable Body Failed.", e);
                        }
                        attachmentDataHolder.setAttachmentArray(attachmentArray);
                    }
                }
            }
        }
    }

    attachmentDataHolder.printDebug();

    String variableScope = attachmentDataHolder.getScope();
    String variableName = attachmentDataHolder.getName();
    String variableType = attachmentDataHolder.getType();
    byte[] attachmentArray = attachmentDataHolder.getAttachmentArray();

    try {
        if (variableName == null) {
            throw new ActivitiIllegalArgumentException("No variable name was found in request body.");
        }

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

        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 {
            attachmentDataHolder.setType(RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE);
        }

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

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

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

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

        }

        return new RestResponseFactory().createBinaryRestVariable(variableName, scope, variableType,
                task.getId(), null, null, uriInfo.getBaseUri().toString());

    } catch (IOException ioe) {
        throw new ActivitiIllegalArgumentException("Error getting binary variable", ioe);
    } catch (ClassNotFoundException ioe) {
        throw new BPMNContentNotSupportedException(
                "The provided body contains a serialized object for which the class is nog found: "
                        + ioe.getMessage());
    }
}

From source file:org.lockss.repository.TestRepositoryNodeImpl.java

public static String getRNCContent(RepositoryNode.RepositoryNodeContents rnc) throws IOException {
    InputStream is = rnc.getInputStream();
    OutputStream baos = new ByteArrayOutputStream(20);
    StreamUtil.copy(is, baos);/*  w  w w  . java  2s . co  m*/
    is.close();
    String resultStr = baos.toString();
    baos.close();
    return resultStr;
}

From source file:org.pentaho.platform.engine.services.SoapHelper.java

public static void generateSoapResponse(final IRuntimeContext context, final SimpleOutputHandler outputHandler,
        final OutputStream contentStream, final StringBuffer messageBuffer, final List messages) {
    // we need to generate a soap package for this
    // the outputs of the action need to be put into the package

    /*//w  w w . j a  va 2 s  . c  om
     * This is the format of the response message package
     * 
     * 
     * <SOAP-ENV:Envelope
     * xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
     * SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
     * <SOAP-ENV:Body> <m:ExecuteActivityResponse
     * xmlns:m="http://pentaho.org"> <result>...</result> <result>...</result>
     * <result>...</result> </m:ExecuteActivityResponse> </SOAP-ENV:Body>
     * </SOAP-ENV:Envelope>
     * 
     */

    if ((context == null) || (context.getStatus() != IRuntimeContext.RUNTIME_STATUS_SUCCESS)) {
        SoapHelper.generateSoapError(messageBuffer, messages);
    } else {

        messageBuffer.append(SoapHelper.openSoapResponse());

        IContentItem contentItem = outputHandler.getFeedbackContentItem();

        // hmm do we need this to be ordered?
        Set outputNames = context.getOutputNames();

        Iterator outputNameIterator = outputNames.iterator();
        while (outputNameIterator.hasNext()) {
            String outputName = (String) outputNameIterator.next();
            contentItem = outputHandler.getOutputContentItem(IOutputHandler.RESPONSE, IOutputHandler.CONTENT,
                    context.getSolutionName(), context.getInstanceId(), "text/xml"); //$NON-NLS-1$
            if ((outputNames.size() == 1) && (contentItem != null)) {
                String mimeType = contentItem.getMimeType();
                if ((mimeType != null) && mimeType.startsWith("text/")) { //$NON-NLS-1$
                    if (mimeType.equals("text/xml")) { //$NON-NLS-1$
                        // this should be ok to embed directly, any CDATA
                        // sections in the XML will be ok
                        messageBuffer.append("<").append(outputName).append(">") //$NON-NLS-1$//$NON-NLS-2$
                                .append(contentStream.toString()).append("</").append(outputName).append(">"); //$NON-NLS-1$ //$NON-NLS-2$
                    } else if (mimeType.startsWith("text/")) { //$NON-NLS-1$
                        // put this is a CDATA section and hope it does not
                        // contain the string ']]>'
                        messageBuffer.append("<").append(outputName).append("><![CDATA[") //$NON-NLS-1$ //$NON-NLS-2$
                                .append(contentStream.toString()).append("]]></").append(outputName) //$NON-NLS-1$
                                .append(">"); //$NON-NLS-1$
                    }
                } else {
                    Object value = context.getOutputParameter(outputName).getValue();
                    if (value == null) {
                        value = ""; //$NON-NLS-1$
                    }
                    messageBuffer.append(SoapHelper.toSOAP(outputName, value));
                }
            } else {
                Object value = context.getOutputParameter(outputName).getValue();
                if (value == null) {
                    value = ""; //$NON-NLS-1$
                }
                messageBuffer.append(SoapHelper.toSOAP(outputName, value));
            }
        }
        messageBuffer.append(SoapHelper.closeSoapResponse());
    }
}

From source file:com.adobe.share.api.ShareAPI.java

/**
 * Parses the response from the Share service.
 *
 * @param method the method/*from w ww .ja v  a2  s  .  c  o  m*/
 *
 * @return the jSON object
 *
 * @throws HttpException the http exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws ShareAPIException the share api exception
 */
protected final JSONObject parseResponse(final HttpMethod method)
        throws HttpException, IOException, ShareAPIException {
    JSONObject json = null;
    String content = null;

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("URL: " + method.getURI().toString());
        LOGGER.debug("Proxy: " + httpClient.getHostConfiguration().getProxyHost());
        LOGGER.debug("Proxy Port: " + httpClient.getHostConfiguration().getProxyPort());
    }

    try {
        int status = httpClient.executeMethod(method);

        final int bufferSize = 4096;
        byte[] buffer = new byte[bufferSize];

        OutputStream outputStream = new ByteArrayOutputStream();
        InputStream inputStream = method.getResponseBodyAsStream();

        while (true) {
            int read = inputStream.read(buffer);

            if (read == -1) {
                break;
            }
            outputStream.write(buffer, 0, read);
        }

        outputStream.close();
        inputStream.close();

        content = outputStream.toString();

        if (method.getResponseHeader("Content-Type") != null) {
            String contentType = method.getResponseHeader("Content-Type").getValue();
            if (method.getStatusCode() == STATUS_OK) {
                if (contentType.contains("application/xml")) {
                    json = XML.toJSONObject(content);
                }
            }
        }

        if (status >= STATUS_BAD_REQUEST) {
            if (json != null) {
                throw new ShareAPIException(method.getStatusCode(),
                        json.getJSONObject("response").getString("message"));
            } else {
                throw new ShareAPIException(method.getStatusCode(), content);
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
        throw new ShareAPIException(method.getStatusCode(), content);
    }

    return json;
}

From source file:com.netspective.sparx.form.DialogContext.java

public String getAsXml() throws ParserConfigurationException, ClassNotFoundException, NoSuchMethodException,
        InstantiationException, IllegalAccessException, InvocationTargetException {
    Document doc = getAsXmlDocument();

    // we use reflection so that org.apache.xml.serialize.* is not a package requirement
    // TODO: when DOM Level 3 is finalized, switch it over to Load/Save methods in that DOM3 spec

    Class serializerCls = Class.forName("org.apache.xml.serialize.XMLSerializer");
    Class outputFormatCls = Class.forName("org.apache.xml.serialize.OutputFormat");

    Constructor serialCons = serializerCls
            .getDeclaredConstructor(new Class[] { OutputStream.class, outputFormatCls });
    Constructor outputCons = outputFormatCls.getDeclaredConstructor(new Class[] { Document.class });

    OutputStream os = new java.io.ByteArrayOutputStream();

    Object outputFormat = outputCons.newInstance(new Object[] { doc });
    Method indenting = outputFormatCls.getMethod("setIndenting", new Class[] { boolean.class });
    indenting.invoke(outputFormat, new Object[] { new Boolean(true) });
    Method omitXmlDecl = outputFormatCls.getMethod("setOmitXMLDeclaration", new Class[] { boolean.class });
    omitXmlDecl.invoke(outputFormat, new Object[] { new Boolean(true) });

    Object serializer = serialCons.newInstance(new Object[] { os, outputFormat });
    Method serialize = serializerCls.getMethod("serialize", new Class[] { Document.class });
    serialize.invoke(serializer, new Object[] { doc });

    return os.toString();
}

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

private void submitReplaceEmbedHTML(Map response) throws XFormsException {
    // check for targetid
    String targetid = getXFormsAttribute(TARGETID_ATTRIBUTE);
    String evaluatedTarget = evalAttributeValueTemplates(targetid, this.element);
    String resource = getResource();
    Map eventInfo = new HashMap();
    String error = null;//from w w  w.j a va  2 s . c om

    if (evaluatedTarget == null) {
        error = "evaluatedTarget";
    } 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);
    }

    // Map eventInfo = constructEventInfo(response);

    OutputStream outputStream = new ByteArrayOutputStream();
    try {
        DOMUtil.prettyPrintDOM(embedElement, outputStream);
    } catch (TransformerException e) {
        throw new XFormsException(e);
    }

    eventInfo.put(EMBEDNODE, outputStream.toString());
    eventInfo.put("embedTarget", evaluatedTarget);

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

}