Search in sources :

Example 31 with OMOutputFormat

use of org.apache.axiom.om.OMOutputFormat in project wso2-synapse by wso2.

the class TargetRequest method processChunking.

/**
 * Handles the chuking messages in Passthough context, create a temporary buffer and calculate the message
 * size before writing to the external buffer, which is required the context of handling DISABLED chunking
 * messages
 *
 * @param conn
 * @param requestMsgCtx
 * @throws IOException
 * @throws AxisFault
 */
private void processChunking(NHttpClientConnection conn, MessageContext requestMsgCtx) throws IOException, AxisFault {
    String disableChunking = (String) requestMsgCtx.getProperty(PassThroughConstants.DISABLE_CHUNKING);
    String forceHttp10 = (String) requestMsgCtx.getProperty(PassThroughConstants.FORCE_HTTP_1_0);
    if ("true".equals(disableChunking) || "true".equals(forceHttp10)) {
        if (requestMsgCtx.getEnvelope().getBody().getFirstElement() == null) {
            BasicHttpEntity entity = (BasicHttpEntity) ((BasicHttpEntityEnclosingRequest) request).getEntity();
            try {
                RelayUtils.buildMessage(requestMsgCtx);
                this.hasEntityBody = true;
                Pipe pipe = (Pipe) requestMsgCtx.getProperty(PassThroughConstants.PASS_THROUGH_PIPE);
                if (pipe != null) {
                    pipe.attachConsumer(conn);
                    this.connect(pipe);
                    if (Boolean.TRUE.equals(requestMsgCtx.getProperty(PassThroughConstants.MESSAGE_BUILDER_INVOKED))) {
                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        MessageFormatter formatter = MessageProcessorSelector.getMessageFormatter(requestMsgCtx);
                        OMOutputFormat format = PassThroughTransportUtils.getOMOutputFormat(requestMsgCtx);
                        formatter.writeTo(requestMsgCtx, format, out, false);
                        OutputStream _out = pipe.getOutputStream();
                        IOUtils.write(out.toByteArray(), _out);
                        entity.setContentLength(new Long(out.toByteArray().length));
                        entity.setChunked(false);
                    }
                }
            // pipe.setSerializationComplete(true);
            } catch (XMLStreamException e) {
                e.printStackTrace();
            }
        }
    }
}
Also used : XMLStreamException(javax.xml.stream.XMLStreamException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) BasicHttpEntity(org.apache.http.entity.BasicHttpEntity) ByteArrayOutputStream(java.io.ByteArrayOutputStream) MessageFormatter(org.apache.axis2.transport.MessageFormatter) OMOutputFormat(org.apache.axiom.om.OMOutputFormat)

Example 32 with OMOutputFormat

use of org.apache.axiom.om.OMOutputFormat in project wso2-synapse by wso2.

the class SourceResponseFactory method create.

public static SourceResponse create(MessageContext msgContext, SourceRequest sourceRequest, SourceConfiguration sourceConfiguration) {
    // determine the status code to be sent
    int statusCode = PassThroughTransportUtils.determineHttpStatusCode(msgContext);
    SourceResponse sourceResponse;
    String statusLine = PassThroughTransportUtils.determineHttpStatusLine(msgContext);
    if (msgContext.getProperty(PassThroughConstants.ORIGINAL_HTTP_SC) != null && statusCode == ((Integer) msgContext.getProperty(PassThroughConstants.ORIGINAL_HTTP_SC))) {
        sourceResponse = new SourceResponse(sourceConfiguration, statusCode, statusLine, sourceRequest);
    } else {
        if (msgContext.getProperty(PassThroughConstants.ORIGINAL_HTTP_REASON_PHRASE) != null && (statusLine.equals(msgContext.getProperty(PassThroughConstants.ORIGINAL_HTTP_REASON_PHRASE)))) {
            sourceResponse = new SourceResponse(sourceConfiguration, statusCode, sourceRequest);
        } else {
            sourceResponse = new SourceResponse(sourceConfiguration, statusCode, statusLine, sourceRequest);
        }
    }
    // set any transport headers
    Map transportHeaders = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);
    boolean forceContentLength = msgContext.isPropertyTrue(NhttpConstants.FORCE_HTTP_CONTENT_LENGTH);
    boolean forceContentLengthCopy = msgContext.isPropertyTrue(PassThroughConstants.COPY_CONTENT_LENGTH_FROM_INCOMING);
    if (forceContentLength && forceContentLengthCopy && msgContext.getProperty(PassThroughConstants.ORGINAL_CONTEN_LENGTH) != null && !sourceConfiguration.isPreserveHttpHeader(HTTP.CONTENT_LEN)) {
        sourceResponse.addHeader(HTTP.CONTENT_LEN, (String) msgContext.getProperty(PassThroughConstants.ORGINAL_CONTEN_LENGTH));
    }
    // set to sourceResponse.
    if (sourceRequest != null && PassThroughConstants.HTTP_HEAD.equalsIgnoreCase(sourceRequest.getRequest().getRequestLine().getMethod()) && msgContext.getProperty(PassThroughConstants.ORGINAL_CONTEN_LENGTH) != null && !sourceConfiguration.isPreserveHttpHeader(PassThroughConstants.ORGINAL_CONTEN_LENGTH)) {
        sourceResponse.addHeader(PassThroughConstants.ORGINAL_CONTEN_LENGTH, (String) msgContext.getProperty(PassThroughConstants.ORGINAL_CONTEN_LENGTH));
    }
    if (transportHeaders != null && msgContext.getProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE) != null) {
        if (msgContext.getProperty(org.apache.axis2.Constants.Configuration.CONTENT_TYPE) != null && msgContext.getProperty(org.apache.axis2.Constants.Configuration.CONTENT_TYPE).toString().contains(PassThroughConstants.CONTENT_TYPE_MULTIPART_RELATED) && !sourceConfiguration.isPreserveHttpHeader(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE)) {
            transportHeaders.put(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE, PassThroughConstants.CONTENT_TYPE_MULTIPART_RELATED);
        } else {
            Pipe pipe = (Pipe) msgContext.getProperty(PassThroughConstants.PASS_THROUGH_PIPE);
            if (pipe != null && !Boolean.TRUE.equals(msgContext.getProperty(PassThroughConstants.MESSAGE_BUILDER_INVOKED)) && !sourceConfiguration.isPreserveHttpHeader(HTTP.CONTENT_TYPE)) {
                transportHeaders.put(HTTP.CONTENT_TYPE, msgContext.getProperty(org.apache.axis2.Constants.Configuration.CONTENT_TYPE));
            }
        }
    }
    if (transportHeaders != null) {
        addResponseHeader(sourceResponse, transportHeaders);
    } else {
        Boolean noEntityBody = (Boolean) msgContext.getProperty(NhttpConstants.NO_ENTITY_BODY);
        if (noEntityBody == null || Boolean.FALSE == noEntityBody) {
            OMOutputFormat format = NhttpUtil.getOMOutputFormat(msgContext);
            transportHeaders = new HashMap();
            MessageFormatter messageFormatter = MessageFormatterDecoratorFactory.createMessageFormatterDecorator(msgContext);
            if (msgContext.getProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE) == null && !sourceConfiguration.isPreserveHttpHeader(HTTP.CONTENT_TYPE)) {
                transportHeaders.put(HTTP.CONTENT_TYPE, messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction()));
            }
            addResponseHeader(sourceResponse, transportHeaders);
        }
    }
    // Add excess response header.
    String excessProp = NhttpConstants.EXCESS_TRANSPORT_HEADERS;
    Map excessHeaders = (Map) msgContext.getProperty(excessProp);
    if (excessHeaders != null) {
        for (Iterator iterator = excessHeaders.keySet().iterator(); iterator.hasNext(); ) {
            String key = (String) iterator.next();
            for (String excessVal : (Collection<String>) excessHeaders.get(key)) {
                sourceResponse.addHeader(key, (String) excessVal);
            }
        }
    }
    // keep alive
    String noKeepAlive = (String) msgContext.getProperty(PassThroughConstants.NO_KEEPALIVE);
    if ("true".equals(noKeepAlive) || PassThroughConfiguration.getInstance().isKeepAliveDisabled()) {
        sourceResponse.setKeepAlive(false);
    } else {
        // that, disable keep-alive to avoid re-using the existing connection by client for the next request.
        if (sourceRequest != null) {
            String requestMethod = sourceRequest.getRequest().getRequestLine().getMethod();
            if (requestMethod != null && isPayloadOptionalMethod(requestMethod.toUpperCase()) && (sourceRequest.getHeaders().containsKey(HTTP.CONTENT_LEN) || sourceRequest.getHeaders().containsKey(HTTP.TRANSFER_ENCODING))) {
                if (log.isDebugEnabled()) {
                    log.debug("Disable keep-alive in the client connection : Content-length/Transfer-encoding" + " headers present for GET/HEAD/DELETE request");
                }
                sourceResponse.setKeepAlive(false);
            }
        }
    }
    return sourceResponse;
}
Also used : SourceResponse(org.apache.synapse.transport.passthru.SourceResponse) HashMap(java.util.HashMap) Iterator(java.util.Iterator) Collection(java.util.Collection) Pipe(org.apache.synapse.transport.passthru.Pipe) MessageFormatter(org.apache.axis2.transport.MessageFormatter) OMOutputFormat(org.apache.axiom.om.OMOutputFormat) HashMap(java.util.HashMap) Map(java.util.Map)

Example 33 with OMOutputFormat

use of org.apache.axiom.om.OMOutputFormat in project wso2-synapse by wso2.

the class TargetRequestHandler method getOutboundReqPath.

private static String getOutboundReqPath(URL url, MessageContext msgCtx) throws IOException {
    if (HttpUtils.isGETRequest(msgCtx) || (RelayUtils.isDeleteRequestWithoutPayload(msgCtx))) {
        MessageFormatter formatter = MessageProcessorSelector.getMessageFormatter(msgCtx);
        OMOutputFormat format = PassThroughTransportUtils.getOMOutputFormat(msgCtx);
        if (formatter != null) {
            URL targetURL = formatter.getTargetAddress(msgCtx, format, url);
            if (targetURL != null && !targetURL.toString().isEmpty()) {
                if (msgCtx.isPropertyTrue(BridgeConstants.POST_TO_URI)) {
                    return targetURL.toString();
                } else {
                    return targetURL.getPath() + ((targetURL.getQuery() != null && !targetURL.getQuery().isEmpty()) ? ("?" + targetURL.getQuery()) : "");
                }
            }
        }
    }
    if (msgCtx.isPropertyTrue(BridgeConstants.POST_TO_URI)) {
        return url.toString();
    }
    // TODO: need to check "(route.getProxyHost() != null && !route.isTunnelled())" as well
    return msgCtx.isPropertyTrue(BridgeConstants.FULL_URI) ? url.toString() : url.getPath() + (url.getQuery() != null ? "?" + url.getQuery() : "");
}
Also used : MessageFormatter(org.apache.axis2.transport.MessageFormatter) SOAPMessageFormatter(org.apache.axis2.transport.http.SOAPMessageFormatter) OMOutputFormat(org.apache.axiom.om.OMOutputFormat) URL(java.net.URL)

Example 34 with OMOutputFormat

use of org.apache.axiom.om.OMOutputFormat in project wso2-synapse by wso2.

the class SourceResponseHandler method getContentTypeForOutboundResponse.

public static String getContentTypeForOutboundResponse(MessageContext msgContext) throws AxisFault {
    // when there is no SOAPAction.
    if (msgContext.isPropertyTrue(Constants.Configuration.ENABLE_MTOM) || msgContext.isPropertyTrue(Constants.Configuration.ENABLE_SWA)) {
        Object contentType = msgContext.getProperty(Constants.Configuration.CONTENT_TYPE);
        // issue of response dropping the MIME boundary.
        if (Objects.isNull(contentType) || !((String) contentType).trim().startsWith(HTTPConstants.MEDIA_TYPE_MULTIPART_RELATED)) {
            msgContext.setProperty(Constants.Configuration.CONTENT_TYPE, HTTPConstants.MEDIA_TYPE_MULTIPART_RELATED);
        }
        msgContext.setProperty(Constants.Configuration.MESSAGE_TYPE, HTTPConstants.MEDIA_TYPE_MULTIPART_RELATED);
    }
    Object contentTypeInMsgCtx = msgContext.getProperty(Constants.Configuration.CONTENT_TYPE);
    OMOutputFormat format = PassThroughTransportUtils.getOMOutputFormat(msgContext);
    // If ContentType header is set in the axis2 message context, use it.
    if (contentTypeInMsgCtx != null) {
        String contentTypeValueInMsgCtx = contentTypeInMsgCtx.toString();
        // Skip multipart/related as it should be taken from formatter.
        if (!(contentTypeValueInMsgCtx.contains(HTTPConstants.MEDIA_TYPE_MULTIPART_RELATED) || contentTypeValueInMsgCtx.contains(HTTPConstants.MEDIA_TYPE_MULTIPART_FORM_DATA))) {
            // adding charset only if charset is not available,
            if (!contentTypeValueInMsgCtx.contains(HTTPConstants.CHAR_SET_ENCODING) && msgContext.isPropertyTrue(BridgeConstants.SET_CHARACTER_ENCODING, true)) {
                String encoding = format.getCharSetEncoding();
                if (encoding != null) {
                    contentTypeValueInMsgCtx += "; charset=" + encoding;
                }
            }
            return contentTypeValueInMsgCtx;
        }
    }
    // If ContentType is not set from msg context, get the formatter ContentType
    MessageFormatter formatter = null;
    try {
        formatter = MessageProcessorSelector.getMessageFormatter(msgContext);
    } catch (AxisFault e) {
        RequestResponseUtils.handleException("Cannot find a suitable MessageFormatter.", e);
    }
    return formatter.getContentType(msgContext, format, msgContext.getSoapAction());
}
Also used : AxisFault(org.apache.axis2.AxisFault) MessageFormatter(org.apache.axis2.transport.MessageFormatter) OMOutputFormat(org.apache.axiom.om.OMOutputFormat)

Example 35 with OMOutputFormat

use of org.apache.axiom.om.OMOutputFormat in project wso2-synapse by wso2.

the class VFSTransportSender method populateResponseFile.

private void populateResponseFile(FileObject responseFile, MessageContext msgContext, boolean append, boolean lockingEnabled, FileSystemOptions fso) throws AxisFault {
    MessageFormatter messageFormatter = getMessageFormatter(msgContext);
    OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext);
    try {
        CountingOutputStream os = new CountingOutputStream(responseFile.getContent().getOutputStream(append));
        try {
            messageFormatter.writeTo(msgContext, format, os, false);
        } finally {
            os.close();
        }
        // setting last modified
        Long lastModified = VFSUtils.getLastModified(msgContext);
        String updateLastModifiedParam = UriParser.extractQueryParams(responseFile.getName().getURI()).get(VFSConstants.UPDATE_LAST_MODIFIED);
        responseFile.setUpdateLastModified(Boolean.parseBoolean(updateLastModifiedParam));
        if (lastModified != null && responseFile.getUpdateLastModified()) {
            try {
                if (log.isDebugEnabled()) {
                    log.debug("Set last modified to " + lastModified);
                }
                responseFile.getContent().setLastModifiedTime(lastModified);
            } catch (Exception e) {
                log.warn("Could not set last modified.", e);
            }
        }
        // update metrics
        metrics.incrementMessagesSent(msgContext);
        metrics.incrementBytesSent(msgContext, os.getByteCount());
    } catch (FileSystemException e) {
        if (lockingEnabled) {
            VFSUtils.releaseLock(fsManager, responseFile, fso);
        }
        metrics.incrementFaultsSending();
        handleException("IO Error while creating response file : " + VFSUtils.maskURLPassword(responseFile.getName().getURI()), e);
    } catch (IOException e) {
        if (lockingEnabled) {
            VFSUtils.releaseLock(fsManager, responseFile, fso);
        }
        metrics.incrementFaultsSending();
        handleException("IO Error while creating response file : " + VFSUtils.maskURLPassword(responseFile.getName().getURI()), e);
    }
}
Also used : CountingOutputStream(org.apache.commons.io.output.CountingOutputStream) MessageFormatter(org.apache.axis2.transport.MessageFormatter) IOException(java.io.IOException) OMOutputFormat(org.apache.axiom.om.OMOutputFormat) IOException(java.io.IOException)

Aggregations

OMOutputFormat (org.apache.axiom.om.OMOutputFormat)64 MessageFormatter (org.apache.axis2.transport.MessageFormatter)24 ByteArrayOutputStream (java.io.ByteArrayOutputStream)21 OutputStream (java.io.OutputStream)18 IOException (java.io.IOException)16 AxisFault (org.apache.axis2.AxisFault)13 MessageContext (org.apache.axis2.context.MessageContext)12 OMElement (org.apache.axiom.om.OMElement)11 DataHandler (javax.activation.DataHandler)7 ByteArrayInputStream (java.io.ByteArrayInputStream)6 InputStream (java.io.InputStream)6 StringWriter (java.io.StringWriter)6 XMLStreamException (javax.xml.stream.XMLStreamException)6 SOAPEnvelope (org.apache.axiom.soap.SOAPEnvelope)6 UnsupportedCharsetException (java.nio.charset.UnsupportedCharsetException)5 OMText (org.apache.axiom.om.OMText)5 Map (java.util.Map)4 MultipartBody (org.apache.axiom.mime.MultipartBody)4 SOAPFactory (org.apache.axiom.soap.SOAPFactory)4 Collection (java.util.Collection)3