Search in sources :

Example 11 with Builder

use of org.apache.axis2.builder.Builder in project wso2-synapse by wso2.

the class JsonStreamingBuilderTest method testProcessDocumentInputStreamNull.

public void testProcessDocumentInputStreamNull() {
    try {
        MessageContext messageContext = Util.newMessageContext();
        Builder jsonBuilder = Util.newJsonStreamBuilder();
        jsonBuilder.processDocument(null, "application/json", messageContext);
        Assert.fail("AxisFault expected");
    } catch (AxisFault axisFault) {
        assertEquals("Cannot build payload without a valid EPR.", axisFault.getMessage());
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) Builder(org.apache.axis2.builder.Builder) MessageContext(org.apache.axis2.context.MessageContext)

Example 12 with Builder

use of org.apache.axis2.builder.Builder in project wso2-synapse by wso2.

the class ProxyService method buildAxisService.

/**
 * Build the underlying Axis2 service from the Proxy service definition
 *
 * @param synCfg  the Synapse configuration
 * @param axisCfg the Axis2 configuration
 * @return the Axis2 service for the Proxy
 */
public AxisService buildAxisService(SynapseConfiguration synCfg, AxisConfiguration axisCfg) {
    Parameter synapseEnv = axisCfg.getParameter(SynapseConstants.SYNAPSE_ENV);
    if (synapseEnv != null) {
        synapseEnvironment = (SynapseEnvironment) synapseEnv.getValue();
    }
    auditInfo("Building Axis service for Proxy service : " + name);
    if (pinnedServers != null && !pinnedServers.isEmpty()) {
        Parameter param = axisCfg.getParameter(SynapseConstants.SYNAPSE_ENV);
        if (param != null && param.getValue() instanceof SynapseEnvironment) {
            SynapseEnvironment synEnv = (SynapseEnvironment) param.getValue();
            String serverName = synEnv != null ? synEnv.getServerContextInformation().getServerConfigurationInformation().getServerName() : "localhost";
            if (!pinnedServers.contains(serverName)) {
                log.info("Server name " + serverName + " not in pinned servers list. " + "Not deploying Proxy service : " + name);
                return null;
            }
        }
    }
    // get the wsdlElement as an OMElement
    if (trace()) {
        trace.info("Loading the WSDL : " + (publishWSDLEndpoint != null ? " endpoint = " + publishWSDLEndpoint : (wsdlKey != null ? " key = " + wsdlKey : (wsdlURI != null ? " URI = " + wsdlURI : " <Inlined>"))));
    }
    InputStream wsdlInputStream = null;
    OMElement wsdlElement = null;
    boolean wsdlFound = false;
    String publishWSDL = null;
    SynapseEnvironment synEnv = SynapseConfigUtils.getSynapseEnvironment(axisCfg);
    String synapseHome = synEnv != null ? synEnv.getServerContextInformation().getServerConfigurationInformation().getSynapseHome() : "";
    if (wsdlKey != null) {
        synCfg.getEntryDefinition(wsdlKey);
        Object keyObject = synCfg.getEntry(wsdlKey);
        // start of fix for ESBJAVA-2641
        if (keyObject == null) {
            synCfg.removeEntry(wsdlKey);
        }
        // end of fix for ESBJAVA-2641
        if (keyObject instanceof OMElement) {
            wsdlElement = (OMElement) keyObject;
        }
        wsdlFound = true;
    } else if (inLineWSDL != null) {
        wsdlElement = (OMElement) inLineWSDL;
        wsdlFound = true;
    } else if (wsdlURI != null) {
        try {
            URL url = wsdlURI.toURL();
            publishWSDL = url.toString();
            OMNode node = SynapseConfigUtils.getOMElementFromURL(publishWSDL, synapseHome);
            if (node instanceof OMElement) {
                wsdlElement = (OMElement) node;
            }
            wsdlFound = true;
        } catch (MalformedURLException e) {
            handleException("Malformed URI for wsdl", e);
        } catch (IOException e) {
            // handleException("Error reading from wsdl URI", e);
            boolean enablePublishWSDLSafeMode = false;
            Map proxyParameters = this.getParameterMap();
            if (!proxyParameters.isEmpty()) {
                if (proxyParameters.containsKey("enablePublishWSDLSafeMode")) {
                    enablePublishWSDLSafeMode = Boolean.parseBoolean(proxyParameters.get("enablePublishWSDLSafeMode").toString().toLowerCase());
                } else {
                    if (trace()) {
                        trace.info("WSDL was unable to load for: " + publishWSDL);
                        trace.info("Please add <syn:parameter name=\"enableURISafeMode\">true" + "</syn:parameter> to proxy service.");
                    }
                    handleException("Error reading from wsdl URI", e);
                }
            }
            if (enablePublishWSDLSafeMode) {
                // !!!Need to add a reload function... And display that the wsdl/service is offline!!!
                if (trace()) {
                    trace.info("WSDL was unable to load for: " + publishWSDL);
                    trace.info("enableURISafeMode: true");
                }
                log.warn("Unable to load the WSDL for : " + name, e);
                return null;
            } else {
                if (trace()) {
                    trace.info("WSDL was unable to load for: " + publishWSDL);
                    trace.info("enableURISafeMode: false");
                }
                handleException("Error reading from wsdl URI", e);
            }
        }
    } else if (publishWSDLEndpoint != null) {
        try {
            URL url = null;
            Endpoint ep = synCfg.getEndpoint(publishWSDLEndpoint);
            if (ep == null) {
                handleException("Unable to resolve WSDL url. " + publishWSDLEndpoint + " is null");
            }
            if (ep instanceof AddressEndpoint) {
                url = new URL(((AddressEndpoint) (ep)).getDefinition().getAddress() + "?wsdl");
            } else if (ep instanceof WSDLEndpoint) {
                url = new URL(((WSDLEndpoint) (ep)).getWsdlURI());
            } else {
                handleException("Unable to resolve WSDL url. " + publishWSDLEndpoint + " is not a AddressEndpoint or WSDLEndpoint");
            }
            publishWSDL = url.toString();
            OMNode node = SynapseConfigUtils.getOMElementFromURL(publishWSDL, synapseHome);
            if (node instanceof OMElement) {
                wsdlElement = (OMElement) node;
            }
            wsdlFound = true;
        } catch (MalformedURLException e) {
            handleException("Malformed URI for wsdl", e);
        } catch (IOException e) {
            // handleException("Error reading from wsdl URI", e);
            boolean enablePublishWSDLSafeMode = false;
            Map proxyParameters = this.getParameterMap();
            if (!proxyParameters.isEmpty()) {
                if (proxyParameters.containsKey("enablePublishWSDLSafeMode")) {
                    enablePublishWSDLSafeMode = Boolean.parseBoolean(proxyParameters.get("enablePublishWSDLSafeMode").toString().toLowerCase());
                } else {
                    if (trace()) {
                        trace.info("WSDL was unable to load for: " + publishWSDL);
                        trace.info("Please add <syn:parameter name=\"enableURISafeMode\">true" + "</syn:parameter> to proxy service.");
                    }
                    handleException("Error reading from wsdl URI " + publishWSDL, e);
                }
            }
            if (enablePublishWSDLSafeMode) {
                // !!!Need to add a reload function... And display that the wsdl/service is offline!!!
                if (trace()) {
                    trace.info("WSDL was unable to load for: " + publishWSDL);
                    trace.info("enableURISafeMode: true");
                }
                log.warn("Unable to load the WSDL for : " + name, e);
                return null;
            } else {
                if (trace()) {
                    trace.info("WSDL was unable to load for: " + publishWSDL);
                    trace.info("enableURISafeMode: false");
                }
                handleException("Error reading from wsdl URI " + publishWSDL, e);
            }
        }
    } else {
        // our SynapseDispatcher will properly dispatch to
        if (trace())
            trace.info("Did not find a WSDL. Assuming a POX or Legacy service");
        axisService = new AxisService();
        AxisOperation mediateOperation = new InOutAxisOperation(SynapseConstants.SYNAPSE_OPERATION_NAME);
        // Set the names of the two messages so that Axis2 is able to produce a WSDL (see SYNAPSE-366):
        mediateOperation.getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE).setName("in");
        mediateOperation.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE).setName("out");
        axisService.addOperation(mediateOperation);
    }
    // if a WSDL was found
    if (wsdlElement != null) {
        OMNamespace wsdlNamespace = wsdlElement.getNamespace();
        // if preservePolicy is set to 'false', remove the security policy content of publish wsdl
        if (preservePolicy != null && preservePolicy.equals("false")) {
            if (org.apache.axis2.namespace.Constants.NS_URI_WSDL11.equals(wsdlNamespace.getNamespaceURI())) {
                removePolicyOfWSDL(wsdlElement);
            }
        }
        // serialize and create an input stream to read WSDL
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            if (trace())
                trace.info("Serializing wsdlElement found to build an Axis2 service");
            wsdlElement.serialize(baos);
            wsdlInputStream = new ByteArrayInputStream(baos.toByteArray());
        } catch (XMLStreamException e) {
            handleException("Error converting to a StreamSource", e);
        }
        if (wsdlInputStream != null) {
            try {
                // detect version of the WSDL 1.1 or 2.0
                if (trace())
                    trace.info("WSDL Namespace is : " + wsdlNamespace.getNamespaceURI());
                if (wsdlNamespace != null) {
                    WSDLToAxisServiceBuilder wsdlToAxisServiceBuilder = null;
                    if (WSDL2Constants.WSDL_NAMESPACE.equals(wsdlNamespace.getNamespaceURI())) {
                        wsdlToAxisServiceBuilder = new WSDL20ToAxisServiceBuilder(wsdlInputStream, null, null);
                    } else if (org.apache.axis2.namespace.Constants.NS_URI_WSDL11.equals(wsdlNamespace.getNamespaceURI())) {
                        wsdlToAxisServiceBuilder = new WSDL11ToAxisServiceBuilder(wsdlInputStream);
                    } else {
                        handleException("Unknown WSDL format.. not WSDL 1.1 or WSDL 2.0");
                    }
                    if (wsdlToAxisServiceBuilder == null) {
                        throw new SynapseException("Could not get the WSDL to Axis Service Builder");
                    }
                    wsdlToAxisServiceBuilder.setBaseUri(wsdlURI != null ? wsdlURI.toString() : synapseHome);
                    if (trace()) {
                        trace.info("Setting up custom resolvers");
                    }
                    // load the UserDefined WSDLResolver and SchemaURIResolver implementations
                    if (synCfg.getProperty(SynapseConstants.SYNAPSE_WSDL_RESOLVER) != null && synCfg.getProperty(SynapseConstants.SYNAPSE_SCHEMA_RESOLVER) != null) {
                        setUserDefinedResourceResolvers(synCfg, wsdlInputStream, wsdlToAxisServiceBuilder);
                    } else {
                        if (resourceMap != null) {
                            // if the resource map is available use it
                            wsdlToAxisServiceBuilder.setCustomResolver(new CustomXmlSchemaURIResolver(resourceMap, synCfg));
                            // Axis 2 also needs a WSDLLocator for WSDL 1.1 documents
                            if (wsdlToAxisServiceBuilder instanceof WSDL11ToAxisServiceBuilder) {
                                ((WSDL11ToAxisServiceBuilder) wsdlToAxisServiceBuilder).setCustomWSDLResolver(new CustomWSDLLocator(new InputSource(wsdlInputStream), wsdlURI != null ? wsdlURI.toString() : "", resourceMap, synCfg));
                            }
                        } else {
                            // if the resource map isn't available ,
                            // then each import URIs will be resolved using base URI
                            wsdlToAxisServiceBuilder.setCustomResolver(new CustomXmlSchemaURIResolver());
                            // Axis 2 also needs a WSDLLocator for WSDL 1.1 documents
                            if (wsdlToAxisServiceBuilder instanceof WSDL11ToAxisServiceBuilder) {
                                ((WSDL11ToAxisServiceBuilder) wsdlToAxisServiceBuilder).setCustomWSDLResolver(new CustomWSDLLocator(new InputSource(wsdlInputStream), wsdlURI != null ? wsdlURI.toString() : ""));
                            }
                        }
                    }
                    if (trace()) {
                        trace.info("Populating Axis2 service using WSDL");
                        if (trace.isTraceEnabled()) {
                            trace.trace("WSDL : " + wsdlElement.toString());
                        }
                    }
                    axisService = wsdlToAxisServiceBuilder.populateService();
                    // this is to clear the bindings and ports already in the WSDL so that the
                    // service will generate the bindings on calling the printWSDL otherwise
                    // the WSDL which will be shown is same as the original WSDL except for the
                    // service name
                    axisService.getEndpoints().clear();
                } else {
                    handleException("Unknown WSDL format.. not WSDL 1.1 or WSDL 2.0");
                }
            } catch (AxisFault af) {
                handleException("Error building service from WSDL", af);
            } catch (IOException ioe) {
                handleException("Error reading WSDL", ioe);
            }
        }
    } else if (wsdlFound) {
        handleException("Couldn't build the proxy service : " + name + ". Unable to locate the specified WSDL to build the service");
    }
    // default Service destination
    if (axisService == null) {
        throw new SynapseException("Could not create a proxy service");
    }
    axisService.setName(name);
    if (description != null) {
        axisService.setDocumentation(description);
    }
    // Setting file path for axis2 service
    if (filePath != null) {
        axisService.setFileName(filePath);
    }
    // destination
    if (transports == null || transports.size() == 0) {
    // default to all transports using service name as destination
    } else {
        if (trace())
            trace.info("Exposing transports : " + transports);
        axisService.setExposedTransports(transports);
    }
    // process parameters
    if (trace() && parameters.size() > 0) {
        trace.info("Setting service parameters : " + parameters);
    }
    for (Object o : parameters.keySet()) {
        String name = (String) o;
        Object value = parameters.get(name);
        Parameter p = new Parameter();
        p.setName(name);
        if (value instanceof String) {
            value = resolve(synapseEnvironment, (String) value);
        }
        p.setValue(value);
        try {
            axisService.addParameter(p);
        } catch (AxisFault af) {
            handleException("Error setting parameter : " + name + "" + "to proxy service as a Parameter", af);
        }
    }
    if (JavaUtils.isTrueExplicitly(axisService.getParameterValue(ABSOLUTE_SCHEMA_URL_PARAM))) {
        axisService.setCustomSchemaNamePrefix("");
    }
    if (JavaUtils.isTrueExplicitly(axisService.getParameterValue(ABSOLUTE_PROXY_SCHEMA_URL_PARAM))) {
        axisService.setCustomSchemaNamePrefix("fullschemaurl");
    }
    if (JavaUtils.isTrueExplicitly(axisService.getParameterValue("disableOperationValidation"))) {
        try {
            AxisOperation defaultOp = processOperationValidation(axisService);
        // proxyServiceGroup.setParent(axisCfg);
        } catch (AxisFault axisFault) {
        // ignore
        }
    }
    boolean isNoSecPolicy = false;
    if (!policies.isEmpty()) {
        for (PolicyInfo pi : policies) {
            String policyKey = pi.getPolicyKey();
            Policy policy = null;
            synCfg.getEntryDefinition(policyKey);
            Object policyEntry = synCfg.getEntry(policyKey);
            if (policyEntry == null) {
                handleException("Security Policy Entry not found for key: " + policyKey + " in Proxy Service: " + name);
            } else {
                policy = PolicyEngine.getPolicy(SynapseConfigUtils.getStreamSource(policyEntry).getInputStream());
            }
            if (policy == null) {
                handleException("Invalid Security Policy found for the key: " + policyKey + " in proxy service: " + name);
            }
            if (NO_SECURITY_POLICY.equals(policy.getId())) {
                isNoSecPolicy = true;
                log.info("NoSecurity Policy found, skipping policy attachment");
                continue;
            }
            if (pi.isServicePolicy()) {
                axisService.getPolicySubject().attachPolicy(policy);
            } else if (pi.isOperationPolicy()) {
                AxisOperation op = axisService.getOperation(pi.getOperation());
                if (op != null) {
                    op.getPolicySubject().attachPolicy(policy);
                } else {
                    handleException("Couldn't find the operation specified " + "by the QName : " + pi.getOperation());
                }
            } else if (pi.isMessagePolicy()) {
                if (pi.getOperation() != null) {
                    AxisOperation op = axisService.getOperation(pi.getOperation());
                    if (op != null) {
                        op.getMessage(pi.getMessageLable()).getPolicySubject().attachPolicy(policy);
                    } else {
                        handleException("Couldn't find the operation " + "specified by the QName : " + pi.getOperation());
                    }
                } else {
                    // operation is not specified and hence apply to all the applicable messages
                    for (Iterator itr = axisService.getOperations(); itr.hasNext(); ) {
                        Object obj = itr.next();
                        if (obj instanceof AxisOperation) {
                            // check whether the policy is applicable
                            if (!((obj instanceof OutOnlyAxisOperation && pi.getType() == PolicyInfo.MESSAGE_TYPE_IN) || (obj instanceof InOnlyAxisOperation && pi.getType() == PolicyInfo.MESSAGE_TYPE_OUT))) {
                                AxisMessage message = ((AxisOperation) obj).getMessage(pi.getMessageLable());
                                message.getPolicySubject().attachPolicy(policy);
                            }
                        }
                    }
                }
            } else {
                handleException("Undefined Policy type");
            }
        }
    }
    // create a custom message receiver for this proxy service
    ProxyServiceMessageReceiver msgRcvr = new ProxyServiceMessageReceiver();
    msgRcvr.setName(name);
    msgRcvr.setProxy(this);
    Iterator iter = axisService.getOperations();
    while (iter.hasNext()) {
        AxisOperation op = (AxisOperation) iter.next();
        op.setMessageReceiver(msgRcvr);
    }
    try {
        axisService.addParameter(SynapseConstants.SERVICE_TYPE_PARAM_NAME, SynapseConstants.PROXY_SERVICE_TYPE);
        if (serviceGroup == null) {
            auditInfo("Adding service " + name + " to the Axis2 configuration");
            axisCfg.addService(axisService);
        } else {
            auditInfo("Adding service " + name + " to the service group " + serviceGroup);
            if (axisCfg.getServiceGroup(serviceGroup) == null) {
                // If the specified group does not exist we should create it
                AxisServiceGroup proxyServiceGroup = new AxisServiceGroup();
                proxyServiceGroup.setServiceGroupName(serviceGroup);
                proxyServiceGroup.setParent(axisCfg);
                // Add  the service to the new group and add the group the AxisConfiguration
                proxyServiceGroup.addService(axisService);
                axisCfg.addServiceGroup(proxyServiceGroup);
            } else {
                // Simply add the service to the existing group
                axisService.setParent(axisCfg.getServiceGroup(serviceGroup));
                axisCfg.addServiceToExistingServiceGroup(axisService, serviceGroup);
            }
        }
        this.setRunning(true);
    } catch (AxisFault axisFault) {
        try {
            if (axisCfg.getService(axisService.getName()) != null) {
                if (trace())
                    trace.info("Removing service " + name + " due to error : " + axisFault.getMessage());
                axisCfg.removeService(axisService.getName());
            }
        } catch (AxisFault ignore) {
        }
        handleException("Error adding Proxy service to the Axis2 engine", axisFault);
    }
    // should Addressing be engaged on this service?
    if (wsAddrEnabled) {
        auditInfo("WS-Addressing is enabled for service : " + name);
        try {
            axisService.engageModule(axisCfg.getModule(SynapseConstants.ADDRESSING_MODULE_NAME), axisCfg);
        } catch (AxisFault axisFault) {
            handleException("Error loading WS Addressing module on proxy service : " + name, axisFault);
        }
    }
    // should Security be engaged on this service?
    boolean secModuleEngaged = false;
    if (wsSecEnabled && !isNoSecPolicy) {
        auditInfo("WS-Security is enabled for service : " + name);
        try {
            axisService.engageModule(axisCfg.getModule(SynapseConstants.SECURITY_MODULE_NAME), axisCfg);
            secModuleEngaged = true;
        } catch (AxisFault axisFault) {
            handleException("Error loading WS Sec module on proxy service : " + name, axisFault);
        }
    } else if (isNoSecPolicy) {
        log.info("NoSecurity Policy found, skipping rampart engagement");
    }
    moduleEngaged = secModuleEngaged || wsAddrEnabled;
    wsdlPublished = wsdlFound;
    // Engaging Axis2 modules
    Object engaged_modules = parameters.get(ENGAGED_MODULES);
    if (engaged_modules != null) {
        String[] moduleNames = getModuleNames((String) engaged_modules);
        if (moduleNames != null) {
            for (String moduleName : moduleNames) {
                try {
                    AxisModule axisModule = axisCfg.getModule(moduleName);
                    if (axisModule != null) {
                        axisService.engageModule(axisModule, axisCfg);
                        moduleEngaged = true;
                    }
                } catch (AxisFault axisFault) {
                    handleException("Error loading " + moduleName + " module on proxy service : " + name, axisFault);
                }
            }
        }
    }
    auditInfo("Successfully created the Axis2 service for Proxy service : " + name);
    return axisService;
}
Also used : AxisFault(org.apache.axis2.AxisFault) Policy(org.apache.neethi.Policy) MalformedURLException(java.net.MalformedURLException) InputSource(org.xml.sax.InputSource) SynapseException(org.apache.synapse.SynapseException) SynapseEnvironment(org.apache.synapse.core.SynapseEnvironment) OMElement(org.apache.axiom.om.OMElement) URL(java.net.URL) Endpoint(org.apache.synapse.endpoints.Endpoint) WSDLEndpoint(org.apache.synapse.endpoints.WSDLEndpoint) AddressEndpoint(org.apache.synapse.endpoints.AddressEndpoint) WSDLEndpoint(org.apache.synapse.endpoints.WSDLEndpoint) CustomXmlSchemaURIResolver(org.apache.synapse.util.resolver.CustomXmlSchemaURIResolver) OMNamespace(org.apache.axiom.om.OMNamespace) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) PolicyInfo(org.apache.synapse.util.PolicyInfo) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OMNode(org.apache.axiom.om.OMNode) AddressEndpoint(org.apache.synapse.endpoints.AddressEndpoint) XMLStreamException(javax.xml.stream.XMLStreamException) ByteArrayInputStream(java.io.ByteArrayInputStream) CustomWSDLLocator(org.apache.synapse.util.resolver.CustomWSDLLocator) ResourceMap(org.apache.synapse.util.resolver.ResourceMap)

Example 13 with Builder

use of org.apache.axis2.builder.Builder in project wso2-synapse by wso2.

the class DeferredMessageBuilder method getDocument.

public OMElement getDocument(MessageContext msgCtx, InputStream in) throws XMLStreamException, IOException {
    /**
     * HTTP Delete requests may contain entity body or not. Hence if the request is a HTTP DELETE, we have to verify
     * that the payload stream is empty or not.
     */
    if (HTTPConstants.HEADER_DELETE.equals(msgCtx.getProperty(Constants.Configuration.HTTP_METHOD)) && RelayUtils.isEmptyPayloadStream(in)) {
        msgCtx.setProperty(PassThroughConstants.NO_ENTITY_BODY, Boolean.TRUE);
        return TransportUtils.createSOAPEnvelope(null);
    }
    String contentType = (String) msgCtx.getProperty(Constants.Configuration.CONTENT_TYPE);
    String _contentType = getContentType(contentType, msgCtx);
    in = HTTPTransportUtils.handleGZip(msgCtx, in);
    AxisConfiguration configuration = msgCtx.getConfigurationContext().getAxisConfiguration();
    Parameter useFallbackParameter = configuration.getParameter(Constants.Configuration.USE_DEFAULT_FALLBACK_BUILDER);
    boolean useFallbackBuilder = false;
    if (useFallbackParameter != null) {
        useFallbackBuilder = JavaUtils.isTrueExplicitly(useFallbackParameter.getValue(), useFallbackBuilder);
    }
    Map transportHeaders = (Map) msgCtx.getProperty(MessageContext.TRANSPORT_HEADERS);
    String contentLength = null;
    String trasferEncoded = null;
    if (transportHeaders != null) {
        contentLength = (String) transportHeaders.get(HTTP.CONTENT_LEN);
        trasferEncoded = (String) transportHeaders.get(HTTP.TRANSFER_ENCODING);
        if (contentType.equals(PassThroughConstants.DEFAULT_CONTENT_TYPE) && (contentLength == null || Integer.valueOf(contentLength) == 0) && trasferEncoded == null) {
            msgCtx.setProperty(PassThroughConstants.NO_ENTITY_BODY, true);
            msgCtx.setProperty(Constants.Configuration.CONTENT_TYPE, "");
            msgCtx.setProperty(PassThroughConstants.RELAY_EARLY_BUILD, true);
            return new SOAP11Factory().getDefaultEnvelope();
        }
    }
    OMElement element = null;
    Builder builder;
    if (contentType != null) {
        // loading builder from externally..
        // builder = configuration.getMessageBuilder(_contentType,useFallbackBuilder);
        builder = MessageProcessorSelector.getMessageBuilder(_contentType, msgCtx);
        if (builder != null) {
            try {
                if (contentLength != null && "0".equals(contentLength) && !msgCtx.isDoingREST()) {
                    element = new org.apache.axiom.soap.impl.llom.soap11.SOAP11Factory().getDefaultEnvelope();
                    // since we are setting an empty envelop to achieve the empty body, we have to set a different
                    // content-type other than text/xml, application/soap+xml or any other content-type which will
                    // invoke the soap builder, otherwise soap builder will get hit and an empty envelope
                    // will be send out
                    msgCtx.setProperty(Constants.Configuration.MESSAGE_TYPE, "application/xml");
                } else {
                    element = builder.processDocument(in, contentType, msgCtx);
                }
            } catch (AxisFault axisFault) {
                log.error("Error building message", axisFault);
                throw axisFault;
            }
        }
    }
    if (element == null) {
        if (msgCtx.isDoingREST()) {
            try {
                element = BuilderUtil.getPOXBuilder(in, null).getDocumentElement();
            } catch (XMLStreamException e) {
                log.error("Error building message using POX Builder", e);
                throw e;
            }
        } else {
            // switch to default
            builder = new SOAPBuilder();
            try {
                if (contentLength != null && "0".equals(contentLength)) {
                    element = new SOAP11Factory().getDefaultEnvelope();
                    // since we are setting an empty envelop to achieve the empty body, we have to set a different
                    // content-type other than text/xml, application/soap+xml or any other content-type which will
                    // invoke the soap builder, otherwise soap builder will get hit and an empty envelope
                    // will be send out
                    msgCtx.setProperty(Constants.Configuration.MESSAGE_TYPE, "application/xml");
                } else {
                    element = builder.processDocument(in, contentType, msgCtx);
                }
            } catch (AxisFault axisFault) {
                log.error("Error building message using SOAP builder");
                throw axisFault;
            }
        }
    }
    // build the soap headers and body
    if (element instanceof SOAPEnvelope) {
        SOAPEnvelope env = (SOAPEnvelope) element;
        env.hasFault();
    }
    // setting up original contentType (resetting the content type)
    if (contentType != null && !contentType.isEmpty()) {
        msgCtx.setProperty(Constants.Configuration.CONTENT_TYPE, contentType);
    }
    return element;
}
Also used : AxisFault(org.apache.axis2.AxisFault) AxisConfiguration(org.apache.axis2.engine.AxisConfiguration) OMElement(org.apache.axiom.om.OMElement) SOAPEnvelope(org.apache.axiom.soap.SOAPEnvelope) XMLStreamException(javax.xml.stream.XMLStreamException) SOAP11Factory(org.apache.axiom.soap.impl.dom.soap11.SOAP11Factory) Parameter(org.apache.axis2.description.Parameter) HashMap(java.util.HashMap) Map(java.util.Map)

Example 14 with Builder

use of org.apache.axis2.builder.Builder in project wso2-synapse by wso2.

the class FIXMessageBuilderTest method testProcessDocument.

public void testProcessDocument() {
    String input = "8=FIX.4.0\u00019=105\u000135=D\u000134=2\u000149=BANZAI\u000152=20080711-06:42:26\u000156=SYNAPSE\u0001" + "11=1215758546278\u000121=1\u000138=90000000\u000140=1\u000154=1\u000155=DEL\u000159=0\u000110=121\u0001";
    MessageContext msgCtx = new MessageContext();
    FIXMessageBuilder builder = new FIXMessageBuilder();
    try {
        OMElement element = builder.processDocument(new ByteArrayInputStream(input.getBytes()), "fix/j", msgCtx);
        Assert.assertNotNull(element);
    } catch (AxisFault e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) ByteArrayInputStream(java.io.ByteArrayInputStream) OMElement(org.apache.axiom.om.OMElement) MessageContext(org.apache.axis2.context.MessageContext)

Example 15 with Builder

use of org.apache.axis2.builder.Builder in project wso2-synapse by wso2.

the class VFSTransportListener method processFile.

/**
 * Process a single file through Axis2
 * @param entry the PollTableEntry for the file (or its parent directory or archive)
 * @param file the file that contains the actual message pumped into Axis2
 * @throws AxisFault on error
 */
private void processFile(PollTableEntry entry, FileObject file) throws AxisFault {
    try {
        FileContent content = file.getContent();
        String fileName = file.getName().getBaseName();
        String filePath = file.getName().getPath();
        String fileURI = file.getName().getURI();
        metrics.incrementBytesReceived(content.getSize());
        Map<String, Object> transportHeaders = new HashMap<String, Object>();
        transportHeaders.put(VFSConstants.FILE_PATH, filePath);
        transportHeaders.put(VFSConstants.FILE_NAME, fileName);
        transportHeaders.put(VFSConstants.FILE_URI, fileURI);
        try {
            transportHeaders.put(VFSConstants.FILE_LENGTH, content.getSize());
            transportHeaders.put(VFSConstants.LAST_MODIFIED, content.getLastModifiedTime());
        } catch (FileSystemException ignore) {
        }
        MessageContext msgContext = entry.createMessageContext();
        String contentType = entry.getContentType();
        if (BaseUtils.isBlank(contentType)) {
            if (file.getName().getExtension().toLowerCase().endsWith(".xml")) {
                contentType = "text/xml";
            } else if (file.getName().getExtension().toLowerCase().endsWith(".txt")) {
                contentType = "text/plain";
            }
        } else {
            // Extract the charset encoding from the configured content type and
            // set the CHARACTER_SET_ENCODING property as e.g. SOAPBuilder relies on this.
            String charSetEnc = null;
            try {
                if (contentType != null) {
                    charSetEnc = new ContentType(contentType).getParameter("charset");
                }
            } catch (ParseException ex) {
            // ignore
            }
            msgContext.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc);
        }
        // if the content type was not found, but the service defined it.. use it
        if (contentType == null) {
            if (entry.getContentType() != null) {
                contentType = entry.getContentType();
            } else if (VFSUtils.getProperty(content, BaseConstants.CONTENT_TYPE) != null) {
                contentType = VFSUtils.getProperty(content, BaseConstants.CONTENT_TYPE);
            }
        }
        // does the service specify a default reply file URI ?
        String replyFileURI = entry.getReplyFileURI();
        if (replyFileURI != null) {
            msgContext.setProperty(Constants.OUT_TRANSPORT_INFO, new VFSOutTransportInfo(replyFileURI, entry.isFileLockingEnabled()));
        }
        // Determine the message builder to use
        Builder builder;
        if (contentType == null) {
            if (log.isDebugEnabled()) {
                log.debug("No content type specified. Using SOAP builder.");
            }
            builder = new SOAPBuilder();
        } else {
            int index = contentType.indexOf(';');
            String type = index > 0 ? contentType.substring(0, index) : contentType;
            builder = BuilderUtil.getBuilderFromSelector(type, msgContext);
            if (builder == null) {
                if (log.isDebugEnabled()) {
                    log.debug("No message builder found for type '" + type + "'. Falling back to SOAP.");
                }
                builder = new SOAPBuilder();
            }
        }
        // set the message payload to the message context
        InputStream in;
        ManagedDataSource dataSource;
        if (builder instanceof DataSourceMessageBuilder && entry.isStreaming()) {
            in = null;
            dataSource = ManagedDataSourceFactory.create(new FileObjectDataSource(file, contentType));
        } else {
            in = new AutoCloseInputStream(content.getInputStream());
            dataSource = null;
        }
        try {
            OMElement documentElement;
            if (in != null) {
                documentElement = builder.processDocument(in, contentType, msgContext);
            } else {
                documentElement = ((DataSourceMessageBuilder) builder).processDocument(dataSource, contentType, msgContext);
            }
            msgContext.setEnvelope(TransportUtils.createSOAPEnvelope(documentElement));
            handleIncomingMessage(msgContext, transportHeaders, // * SOAP Action - not applicable *//
            null, contentType);
        } finally {
            if (dataSource != null) {
                dataSource.destroy();
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("Processed file : " + VFSUtils.maskURLPassword(file.toString()) + " of Content-type : " + contentType);
        }
    } catch (FileSystemException e) {
        handleException("Error reading file content or attributes : " + VFSUtils.maskURLPassword(file.toString()), e);
    } finally {
        try {
            if (file != null) {
                if (fsManager != null && file.getName() != null && file.getName().getScheme() != null && file.getName().getScheme().startsWith("file")) {
                    fsManager.closeFileSystem(file.getParent().getFileSystem());
                }
                file.close();
            }
        } catch (FileSystemException warn) {
        // ignore the warning,  since we handed over the stream close job to
        // AutocloseInputstream..
        }
    }
}
Also used : ContentType(javax.mail.internet.ContentType) HashMap(java.util.HashMap) AutoCloseInputStream(org.apache.commons.io.input.AutoCloseInputStream) InputStream(java.io.InputStream) DataSourceMessageBuilder(org.apache.axis2.format.DataSourceMessageBuilder) Builder(org.apache.axis2.builder.Builder) SOAPBuilder(org.apache.axis2.builder.SOAPBuilder) OMElement(org.apache.axiom.om.OMElement) FileContent(org.apache.commons.vfs2.FileContent) FileSystemException(org.apache.commons.vfs2.FileSystemException) FileObject(org.apache.commons.vfs2.FileObject) SOAPBuilder(org.apache.axis2.builder.SOAPBuilder) FileObjectDataSource(org.apache.synapse.commons.vfs.FileObjectDataSource) MessageContext(org.apache.axis2.context.MessageContext) ParseException(javax.mail.internet.ParseException) VFSOutTransportInfo(org.apache.synapse.commons.vfs.VFSOutTransportInfo) AutoCloseInputStream(org.apache.commons.io.input.AutoCloseInputStream) ManagedDataSource(org.apache.axis2.format.ManagedDataSource) DataSourceMessageBuilder(org.apache.axis2.format.DataSourceMessageBuilder)

Aggregations

OMElement (org.apache.axiom.om.OMElement)24 MessageContext (org.apache.axis2.context.MessageContext)15 Builder (org.apache.axis2.builder.Builder)13 AxisFault (org.apache.axis2.AxisFault)11 SOAPEnvelope (org.apache.axiom.soap.SOAPEnvelope)9 ByteArrayInputStream (java.io.ByteArrayInputStream)8 SOAPBuilder (org.apache.axis2.builder.SOAPBuilder)8 InputStream (java.io.InputStream)7 HashMap (java.util.HashMap)7 ByteArrayOutputStream (java.io.ByteArrayOutputStream)5 EndpointReference (org.apache.axis2.addressing.EndpointReference)5 ContentType (javax.mail.internet.ContentType)4 ParseException (javax.mail.internet.ParseException)4 XMLStreamException (javax.xml.stream.XMLStreamException)4 Parameter (org.apache.axis2.description.Parameter)4 AxisConfiguration (org.apache.axis2.engine.AxisConfiguration)4 MessageFormatter (org.apache.axis2.transport.MessageFormatter)4 ManagedTestSuite (org.apache.axis2.transport.testkit.ManagedTestSuite)4 TransportTestSuiteBuilder (org.apache.axis2.transport.testkit.TransportTestSuiteBuilder)4 AxisAsyncTestClient (org.apache.axis2.transport.testkit.axis2.client.AxisAsyncTestClient)4