Search in sources :

Example 81 with OMException

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

the class ClientWorker method run.

/**
 * Process the received response through Axis2
 */
public void run() {
    CustomLogSetter.getInstance().clearThreadLocalContent();
    setServerContextAttribute(NhttpConstants.CLIENT_WORKER_START_TIME, System.currentTimeMillis(), outMsgCtx);
    // response and populate it with the soap envelope
    if (responseMsgCtx == null) {
        return;
    }
    try {
        if (in != null) {
            Header cType = response.getFirstHeader(HTTP.CONTENT_TYPE);
            String contentType;
            if (cType != null) {
                // This is the most common case - Most of the time servers send the Content-Type
                contentType = cType.getValue();
            } else {
                // Server hasn't sent the header - Try to infer the content type
                contentType = inferContentType();
            }
            String charSetEnc = BuilderUtil.getCharSetEncoding(contentType);
            if (charSetEnc == null) {
                charSetEnc = MessageContext.DEFAULT_CHAR_SET_ENCODING;
            }
            responseMsgCtx.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc);
            // workaround for Axis2 TransportUtils.createSOAPMessage() issue, where a response
            // of content type "text/xml" is thought to be REST if !MC.isServerSide(). This
            // question is still under debate and due to the timelines, I am commiting this
            // workaround as Axis2 1.2 is about to be released and Synapse 1.0
            responseMsgCtx.setServerSide(false);
            SOAPEnvelope envelope;
            try {
                envelope = TransportUtils.createSOAPMessage(responseMsgCtx, HTTPTransportUtils.handleGZip(responseMsgCtx, in), contentType);
            } catch (OMException e) {
                // handle non SOAP and POX/REST payloads (probably text/html)
                String errorMessage = "Unexpected response received. HTTP response code : " + this.response.getStatusLine().getStatusCode() + " HTTP status : " + this.response.getStatusLine().getReasonPhrase() + " exception : " + e.getMessage();
                log.warn(errorMessage);
                if (log.isDebugEnabled()) {
                    log.debug(errorMessage, e);
                    log.debug("Creating the SOAPFault to be injected...");
                }
                SOAPFactory factory = new SOAP11Factory();
                envelope = factory.getDefaultFaultEnvelope();
                SOAPFaultDetail detail = factory.createSOAPFaultDetail();
                detail.setText(errorMessage);
                envelope.getBody().getFault().setDetail(detail);
                SOAPFaultReason reason = factory.createSOAPFaultReason();
                reason.setText(errorMessage);
                envelope.getBody().getFault().setReason(reason);
                SOAPFaultCode code = factory.createSOAPFaultCode();
                code.setText(Integer.toString(this.response.getStatusLine().getStatusCode()));
                envelope.getBody().getFault().setCode(code);
            }
            responseMsgCtx.setServerSide(true);
            responseMsgCtx.setEnvelope(envelope);
        } else {
            // there is no response entity-body
            responseMsgCtx.setProperty(NhttpConstants.NO_ENTITY_BODY, Boolean.TRUE);
            responseMsgCtx.setEnvelope(new SOAP11Factory().getDefaultEnvelope());
        }
        // copy the HTTP status code as a message context property with the key HTTP_SC to be
        // used at the sender to set the propper status code when passing the message
        int statusCode = this.response.getStatusLine().getStatusCode();
        responseMsgCtx.setProperty(NhttpConstants.HTTP_SC, statusCode);
        if (statusCode >= 400) {
            responseMsgCtx.setProperty(NhttpConstants.FAULT_MESSAGE, NhttpConstants.TRUE);
        }
        responseMsgCtx.setProperty(NhttpConstants.NON_BLOCKING_TRANSPORT, true);
        if (endpointURLPrefix != null) {
            responseMsgCtx.setProperty(NhttpConstants.ENDPOINT_PREFIX, endpointURLPrefix);
        }
        // process response received
        try {
            AxisEngine.receive(responseMsgCtx);
        } catch (AxisFault af) {
            // This will be reached if an exception is thrown within an Axis2 handler
            String errorMessage = "Fault processing response message through Axis2: " + af.getMessage();
            log.warn(errorMessage);
            if (log.isDebugEnabled()) {
                log.debug(errorMessage, af);
                log.debug("Directly invoking SynapseCallbackReceiver after setting " + "error properties");
            }
            responseMsgCtx.setProperty(NhttpConstants.SENDING_FAULT, Boolean.TRUE);
            responseMsgCtx.setProperty(NhttpConstants.ERROR_CODE, NhttpConstants.RESPONSE_PROCESSING_FAILURE);
            responseMsgCtx.setProperty(NhttpConstants.ERROR_MESSAGE, errorMessage.split("\n")[0]);
            responseMsgCtx.setProperty(NhttpConstants.ERROR_DETAIL, JavaUtils.stackToString(af));
            responseMsgCtx.setProperty(NhttpConstants.ERROR_EXCEPTION, af);
            responseMsgCtx.getAxisOperation().getMessageReceiver().receive(responseMsgCtx);
        }
    } catch (AxisFault af) {
        log.error("Fault creating response SOAP envelope", af);
        return;
    } catch (XMLStreamException e) {
        log.error("Error creating response SOAP envelope", e);
    } catch (IOException e) {
        log.error("Error closing input stream from which message was read", e);
    } finally {
        // to read the response back from the server.
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException ignore) {
        }
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) IOException(java.io.IOException) Header(org.apache.http.Header) XMLStreamException(javax.xml.stream.XMLStreamException) SOAP11Factory(org.apache.axiom.soap.impl.llom.soap11.SOAP11Factory) OMException(org.apache.axiom.om.OMException)

Example 82 with OMException

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

the class JsonDataSource method serialize.

public void serialize(XMLStreamWriter xmlWriter) throws XMLStreamException {
    XMLStreamReader reader = getReader();
    xmlWriter.writeStartDocument();
    while (reader.hasNext()) {
        int x = reader.next();
        switch(x) {
            case XMLStreamConstants.START_ELEMENT:
                xmlWriter.writeStartElement(reader.getPrefix(), reader.getLocalName(), reader.getNamespaceURI());
                int namespaceCount = reader.getNamespaceCount();
                for (int i = namespaceCount - 1; i >= 0; i--) {
                    xmlWriter.writeNamespace(reader.getNamespacePrefix(i), reader.getNamespaceURI(i));
                }
                int attributeCount = reader.getAttributeCount();
                for (int i = 0; i < attributeCount; i++) {
                    xmlWriter.writeAttribute(reader.getAttributePrefix(i), reader.getAttributeNamespace(i), reader.getAttributeLocalName(i), reader.getAttributeValue(i));
                }
                break;
            case XMLStreamConstants.START_DOCUMENT:
                break;
            case XMLStreamConstants.CHARACTERS:
                xmlWriter.writeCharacters(reader.getText());
                break;
            case XMLStreamConstants.CDATA:
                xmlWriter.writeCData(reader.getText());
                break;
            case XMLStreamConstants.END_ELEMENT:
                xmlWriter.writeEndElement();
                break;
            case XMLStreamConstants.END_DOCUMENT:
                xmlWriter.writeEndDocument();
                break;
            case XMLStreamConstants.SPACE:
                break;
            case XMLStreamConstants.COMMENT:
                xmlWriter.writeComment(reader.getText());
                break;
            case XMLStreamConstants.DTD:
                xmlWriter.writeDTD(reader.getText());
                break;
            case XMLStreamConstants.PROCESSING_INSTRUCTION:
                xmlWriter.writeProcessingInstruction(reader.getPITarget(), reader.getPIData());
                break;
            case XMLStreamConstants.ENTITY_REFERENCE:
                xmlWriter.writeEntityRef(reader.getLocalName());
                break;
            default:
                throw new OMException();
        }
    }
    xmlWriter.writeEndDocument();
    xmlWriter.flush();
    xmlWriter.close();
}
Also used : XMLStreamReader(javax.xml.stream.XMLStreamReader) OMException(org.apache.axiom.om.OMException)

Example 83 with OMException

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

the class JsonDataSource method serialize.

public void serialize(Writer writer, OMOutputFormat format) throws XMLStreamException {
    try {
        if (format != null && format.getContentType() != null) {
            if (format.getContentType().contains("xml")) {
                // reuse the stream
                inputStream.reset();
                JsonUtil.toXml(inputStream, false).serialize(writer, format);
                return;
            }
        }
        inputStream.reset();
        IOUtils.copy(inputStream, writer);
    } catch (IOException e) {
        logger.error("#serialize:Writer. Could not serialize JSON payload. Error>>> " + e.getLocalizedMessage());
        throw new OMException("Could not serialize JSON payload.", e);
    }
}
Also used : OMException(org.apache.axiom.om.OMException)

Example 84 with OMException

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

the class AbstractSynapseArtifactDeployer method deploy.

/**
 * This method is called by the axis2 deployment framework and it performs a synapse artifact
 * specific yet common across all the artifacts, set of tasks and delegate the actual deployment
 * to the respective artifact deployers.
 *
 * @param deploymentFileData file to be used for the deployment
 * @throws org.apache.axis2.deployment.DeploymentException in-case of an error in deploying the file
 *
 * @see org.apache.synapse.deployers.AbstractSynapseArtifactDeployer#deploySynapseArtifact(org.apache.axiom.om.OMElement,
 * String,java.util.Properties)
 */
public void deploy(DeploymentFileData deploymentFileData) throws DeploymentException {
    if (getServerContextInformation().getServerState() != ServerState.STARTED) {
        // synapse server has not yet being started
        if (log.isDebugEnabled()) {
            log.debug("Skipped the artifact deployment (since the Synapse " + "server doesn't seem to be started yet), from file : " + deploymentFileData.getAbsolutePath());
        }
        return;
    }
    // CustomLogSetter.getInstance().setLogAppender(customLogContent);
    if (!isHotDeploymentEnabled()) {
        if (log.isDebugEnabled()) {
            log.debug("Hot deployment has been suspended - Ignoring");
        }
        return;
    }
    String filename = SynapseArtifactDeploymentStore.getNormalizedAbsolutePath(deploymentFileData.getAbsolutePath());
    if (log.isDebugEnabled()) {
        log.debug("Deployment of the synapse artifact from file : " + filename + " : STARTED");
    }
    SynapseArtifactDeploymentStore deploymentStore = getSynapseConfiguration().getArtifactDeploymentStore();
    // deploy it again
    if (deploymentStore.isRestoredFile(filename)) {
        if (log.isDebugEnabled()) {
            log.debug("Restored artifact detected with filename : " + filename);
        }
        // only one deployment trigger can happen after a restore and hence remove it from
        // restoredFiles at the first hit, allowing the further deployments/updates to take
        // place as usual
        deploymentStore.removeRestoredFile(filename);
        return;
    }
    try {
        InputStream in = FileUtils.openInputStream(new File(filename));
        try {
            // construct the xml element from the file, it has to be XML,
            // since all synapse artifacts are XML based
            OMElement element = new StAXOMBuilder(StAXUtils.createXMLStreamReader(in)).getDocumentElement();
            Properties properties = new Properties();
            properties.put(SynapseConstants.CLASS_MEDIATOR_LOADERS, deploymentStore.getClassMediatorClassLoaders());
            properties.put(SynapseConstants.RESOLVE_ROOT, getSynapseEnvironment().getServerContextInformation().getServerConfigurationInformation().getResolveRoot());
            properties.put(SynapseConstants.SYNAPSE_CONFIGURATION, getSynapseConfiguration());
            String artifactName = null;
            if (deploymentStore.isUpdatingArtifact(filename)) {
                if (log.isDebugEnabled()) {
                    log.debug("Updating artifact detected with filename : " + filename);
                }
                // this is an hot-update case
                String existingArtifactName = deploymentStore.getUpdatingArtifactWithFileName(filename);
                deploymentStore.removeUpdatingArtifact(filename);
                try {
                    artifactName = updateSynapseArtifact(element, filename, existingArtifactName, properties);
                }/*  Multiple exception types can throw from the libraries like wstx and couldn't catch
                    specific exception type. Hence, generic Exception can use to overcome the issue. */
                 catch (Exception ex) {
                    log.error("Update of the Synapse Artifact from file : " + filename + " : Failed!", ex);
                    log.info("The updated file has been backed up into : " + backupFile(deploymentFileData.getFile()));
                    log.info("Restoring the existing artifact into the file : " + filename);
                    restoreSynapseArtifact(existingArtifactName);
                    deploymentStore.addArtifact(filename, existingArtifactName);
                    artifactName = existingArtifactName;
                    throw new DeploymentException(ex);
                }
            } else {
                // new artifact hot-deployment case
                try {
                    // update the existing sequences.
                    if (filename.matches(".*/main-\\d+\\.\\d+\\.\\d+\\.xml")) {
                        artifactName = updateDefaultSequence(filename, element, properties, deploymentStore.getMainSeqLstUpdatedFile(), deploymentStore);
                        String mainSeqFileName = filename.substring(filename.lastIndexOf(File.separator) + 1);
                        deploymentStore.setMainSeqLstUpdatedFile(mainSeqFileName);
                    } else if (filename.matches(".*/fault-\\d+\\.\\d+\\.\\d+\\.xml")) {
                        artifactName = updateDefaultSequence(filename, element, properties, deploymentStore.getFaultSeqLstUpdatedFile(), deploymentStore);
                        String faultSeqFileName = filename.substring(filename.lastIndexOf(File.separator) + 1);
                        deploymentStore.setFaultSeqLstUpdatedFile(faultSeqFileName);
                    } else {
                        artifactName = deploySynapseArtifact(element, filename, properties);
                    }
                // To avoid deployment of service when NoClassDefFoundError thrown while creating a mediator
                } catch (SynapseArtifactDeploymentException | NoClassDefFoundError e) {
                    log.error("Deployment of the Synapse Artifact from file : " + filename + " : Failed!", e);
                    log.info("The file has been backed up into : " + backupFile(deploymentFileData.getFile()));
                    throw new DeploymentException(e);
                }
            }
            if (artifactName != null) {
                deploymentStore.addArtifact(filename, artifactName);
            }
        } finally {
            in.close();
        }
    } catch (IOException ex) {
        handleDeploymentError("Deployment of synapse artifact failed. Error reading " + filename + " : " + ex.getMessage(), ex, filename);
        throw new DeploymentException(ex);
    } catch (XMLStreamException ex) {
        handleDeploymentError("Deployment of synapse artifact failed. Error parsing " + filename + " : " + ex.getMessage(), ex, filename);
        throw new DeploymentException(ex);
    } catch (OMException ex) {
        handleDeploymentError("Deployment of synapse artifact failed. Error parsing " + filename + " : " + ex.getMessage(), ex, filename);
        throw new DeploymentException(ex);
    }
    if (log.isDebugEnabled()) {
        log.debug("Deployment of the synapse artifact from file : " + filename + " : COMPLETED");
    }
}
Also used : InputStream(java.io.InputStream) OMElement(org.apache.axiom.om.OMElement) IOException(java.io.IOException) Properties(java.util.Properties) XMLStreamException(javax.xml.stream.XMLStreamException) DeploymentException(org.apache.axis2.deployment.DeploymentException) IOException(java.io.IOException) OMException(org.apache.axiom.om.OMException) XMLStreamException(javax.xml.stream.XMLStreamException) StAXOMBuilder(org.apache.axiom.om.impl.builder.StAXOMBuilder) DeploymentException(org.apache.axis2.deployment.DeploymentException) File(java.io.File) OMException(org.apache.axiom.om.OMException)

Example 85 with OMException

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

the class CalloutMediator method setSoapHeaderBlock.

private void setSoapHeaderBlock(MessageContext synCtx) {
    // Send the SOAP Header Blocks to support WS-Addressing
    if (synCtx.getEnvelope().getHeader() != null) {
        Iterator iHeader = synCtx.getEnvelope().getHeader().getChildren();
        SOAPFactory fac;
        if (SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI.equals(synCtx.getEnvelope().getBody().getNamespace().getNamespaceURI())) {
            fac = OMAbstractFactory.getSOAP11Factory();
        } else {
            fac = OMAbstractFactory.getSOAP12Factory();
        }
        List<OMNode> newHeaderNodes = new ArrayList<OMNode>();
        while (iHeader.hasNext()) {
            try {
                Object element = iHeader.next();
                /* Convert only OMElements. Skip SOAPHeaderBlock elements*/
                if (!(element instanceof SOAPHeaderBlock)) {
                    if (element instanceof OMElement) {
                        newHeaderNodes.add(ElementHelper.toSOAPHeaderBlock((OMElement) element, fac).cloneOMElement());
                    }
                    iHeader.remove();
                }
            } catch (OMException e) {
                log.error("Unable to convert to SoapHeader Block", e);
            } catch (Exception e) {
                log.error("Unable to convert to SoapHeader Block", e);
            }
        }
        for (OMNode newHeaderNode : newHeaderNodes) {
            synCtx.getEnvelope().getHeader().addChild(newHeaderNode);
        }
    }
}
Also used : OMNode(org.apache.axiom.om.OMNode) SOAPHeaderBlock(org.apache.axiom.soap.SOAPHeaderBlock) OMElement(org.apache.axiom.om.OMElement) OMException(org.apache.axiom.om.OMException) SOAPFactory(org.apache.axiom.soap.SOAPFactory) JaxenException(org.jaxen.JaxenException) NamingException(javax.naming.NamingException) SynapseException(org.apache.synapse.SynapseException) OMException(org.apache.axiom.om.OMException)

Aggregations

OMException (org.apache.axiom.om.OMException)89 OMElement (org.apache.axiom.om.OMElement)35 XMLStreamException (javax.xml.stream.XMLStreamException)31 IOException (java.io.IOException)30 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)21 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)18 InputStream (java.io.InputStream)16 QName (javax.xml.namespace.QName)13 OMFactory (org.apache.axiom.om.OMFactory)12 ArrayList (java.util.ArrayList)11 MalformedURLException (java.net.MalformedURLException)10 Test (org.junit.Test)10 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)10 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)9 ParseException (org.json.simple.parser.ParseException)9 APIMgtResourceAlreadyExistsException (org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException)9 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)9 FaultGatewaysException (org.wso2.carbon.apimgt.api.FaultGatewaysException)9 MonetizationException (org.wso2.carbon.apimgt.api.MonetizationException)9 UnsupportedPolicyTypeException (org.wso2.carbon.apimgt.api.UnsupportedPolicyTypeException)9