Search in sources :

Example 96 with MessageContext

use of org.apache.axis2.context.MessageContext in project wso2-synapse by wso2.

the class ResponseMessageBuilderTest method testUnsubscriptionResponse.

public void testUnsubscriptionResponse() {
    String id = UIDGenerator.generateURNString();
    String addressUrl = "http://synapse.test.com/eventing/sunscriptions";
    SynapseSubscription sub = new SynapseSubscription();
    sub.setId(id);
    sub.setSubManUrl(addressUrl);
    String expected = "<wse:UnsubscribeResponse xmlns:wse=\"http://schemas.xmlsoap.org/ws/2004/08/eventing\"/>";
    try {
        MessageContext msgCtx = TestUtils.getAxis2MessageContext("<empty/>", null).getAxis2MessageContext();
        ResponseMessageBuilder builder = new ResponseMessageBuilder(msgCtx);
        SOAPEnvelope env = builder.genUnSubscribeResponse(sub);
        OMElement resultOm = env.getBody().getFirstElement();
        OMElement expectedOm = AXIOMUtil.stringToOM(expected);
        assertTrue(compare(expectedOm, resultOm));
    } catch (Exception e) {
        fail("Error while constructing the test message context: " + e.getMessage());
    }
}
Also used : SynapseSubscription(org.apache.synapse.eventing.SynapseSubscription) OMElement(org.apache.axiom.om.OMElement) MessageContext(org.apache.axis2.context.MessageContext) SOAPEnvelope(org.apache.axiom.soap.SOAPEnvelope)

Example 97 with MessageContext

use of org.apache.axis2.context.MessageContext in project wso2-synapse by wso2.

the class ResponseMessageBuilderTest method testSubscriptionResponse.

public void testSubscriptionResponse() {
    String id = UIDGenerator.generateURNString();
    String addressUrl = "http://synapse.test.com/eventing/sunscriptions";
    SynapseSubscription sub = new SynapseSubscription();
    sub.setId(id);
    sub.setSubManUrl(addressUrl);
    String expected = "<wse:SubscribeResponse xmlns:wse=\"http://schemas.xmlsoap.org/ws/2004/08/eventing\">" + "<wse:SubscriptionManager>" + "<wsa:Address xmlns:wsa=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\">" + addressUrl + "</wsa:Address>" + "<wsa:ReferenceParameters xmlns:wsa=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\">" + "<wse:Identifier>" + id + "</wse:Identifier>" + "</wsa:ReferenceParameters>" + "</wse:SubscriptionManager>" + "</wse:SubscribeResponse>";
    try {
        MessageContext msgCtx = TestUtils.getAxis2MessageContext("<empty/>", null).getAxis2MessageContext();
        ResponseMessageBuilder builder = new ResponseMessageBuilder(msgCtx);
        SOAPEnvelope env = builder.genSubscriptionResponse(sub);
        OMElement resultOm = env.getBody().getFirstElement();
        OMElement expectedOm = AXIOMUtil.stringToOM(expected);
        assertTrue(compare(expectedOm, resultOm));
    } catch (Exception e) {
        fail("Error while constructing the test message context: " + e.getMessage());
    }
}
Also used : SynapseSubscription(org.apache.synapse.eventing.SynapseSubscription) OMElement(org.apache.axiom.om.OMElement) MessageContext(org.apache.axis2.context.MessageContext) SOAPEnvelope(org.apache.axiom.soap.SOAPEnvelope)

Example 98 with MessageContext

use of org.apache.axis2.context.MessageContext in project wso2-synapse by wso2.

the class EventFilterTest method testTopicBasedEventFilter.

public void testTopicBasedEventFilter() {
    String status = "snow";
    try {
        MessageContext msgCtx = TestUtils.getAxis2MessageContext("<weatherCondition>" + status + "</weatherCondition>", null).getAxis2MessageContext();
        Event<MessageContext> event = new Event<MessageContext>();
        event.setMessage(msgCtx);
        TopicBasedEventFilter filter = new TopicBasedEventFilter();
        filter.setResultValue(status);
        filter.setSourceXpath(new SynapseXPath("//weatherCondition"));
        assertTrue(filter.match(event));
        filter.setResultValue("rain");
        assertFalse(filter.match(event));
    } catch (Exception e) {
        fail("Error while constructing the test message context: " + e.getMessage());
    }
}
Also used : SynapseXPath(org.apache.synapse.util.xpath.SynapseXPath) Event(org.wso2.eventing.Event) MessageContext(org.apache.axis2.context.MessageContext)

Example 99 with MessageContext

use of org.apache.axis2.context.MessageContext in project wso2-synapse by wso2.

the class JsonUtil method getNewJsonPayload.

/**
 * Builds and returns a new JSON payload for a message context with a stream of JSON content. <br/>
 * This is the recommended way to build a JSON payload into an Axis2 message context.<br/>
 * A JSON payload built into a message context with this method can only be removed by calling
 * {@link #removeJsonPayload(org.apache.axis2.context.MessageContext)} method.
 *
 * @param messageContext     Axis2 Message context to which the new JSON payload must be saved (if instructed with <tt>addAsNewFirstChild</tt>).
 * @param inputStream        JSON content as an input stream.
 * @param removeChildren     Whether to remove existing child nodes of the existing payload of the message context
 * @param addAsNewFirstChild Whether to add the new JSON payload as the first child of this message context *after* removing the existing first child element.<br/>
 *                           Setting this argument to <tt>true</tt> will have no effect if the value of the argument <tt>removeChildren</tt> is already <tt>false</tt>.
 * @return Payload object that stores the input JSON content as a Sourced object (See {@link org.apache.axiom.om.OMSourcedElement}) that can build the XML tree for contained JSON payload on demand.
 */
public static OMElement getNewJsonPayload(MessageContext messageContext, InputStream inputStream, boolean removeChildren, boolean addAsNewFirstChild) throws AxisFault {
    if (messageContext == null) {
        logger.error("#getNewJsonPayload. Could not save JSON stream. Message context is null.");
        return null;
    }
    boolean isObject = false;
    boolean isArray = false;
    boolean isValue = false;
    if (inputStream != null) {
        InputStream json = setJsonStream(messageContext, inputStream);
        // read ahead few characters to see if the stream is valid...
        boolean isEmptyPayload = true;
        boolean valid = false;
        try {
            /*
                * Checks for all empty or all whitespace streams and if found  sets isEmptyPayload to false. The while
                * loop exits if one of the valid literals is found. If no valid literal is found the it will loop to
                * the end of the stream and the next if statement after the loop makes sure that valid will remain false
                * */
            int character = json.read();
            while (character != -1 && character != '{' && character != '[' && character != '"' && character != 't' && character != 'n' && character != 'f' && character != '-' && character != '0' && character != '1' && character != '2' && character != '3' && character != '4' && character != '5' && character != '6' && character != '7' && character != '8' && character != '9') {
                if (character != 32) {
                    isEmptyPayload = false;
                }
                character = json.read();
            }
            if (character != -1) {
                valid = true;
            }
            /*
                * A valid JSON can be an object, array or a value (http://json.org/). The following conditions check
                * the beginning char to see if the json stream could fall into one of this category
                * */
            if (character == '{') {
                isObject = true;
                isArray = false;
                isValue = false;
            } else if (character == '[') {
                isArray = true;
                isObject = false;
                isValue = false;
            } else if (character == '"' || character == 't' || character == 'n' || character == 'f' || character == '-' || character == '0' || character == '1' || character == '2' || character == '3' || character == '4' || character == '5' || character == '6' || character == '7' || character == '8' || character == '9') {
                // a value can be a quoted string (") true (t),
                // false (f), null (n) or a number (- or any digit and cannot start with a +)
                isArray = false;
                isObject = false;
                isValue = true;
            }
            json.reset();
        } catch (IOException e) {
            logger.error("#getNewJsonPayload. Could not determine availability of the JSON input stream. MessageID: " + messageContext.getMessageID() + ". Error>>> " + e.getLocalizedMessage());
            return null;
        }
        if (!valid) {
            if (isEmptyPayload) {
                // This is a empty payload so return null without doing further processing.
                if (logger.isDebugEnabled()) {
                    logger.debug("#emptyJsonPayload found.MessageID: " + messageContext.getMessageID());
                }
                logger.debug("#emptyJsonPayload found.MessageID: " + messageContext.getMessageID());
                return null;
            } else {
                /*
                     * This method required to introduce due the GET request failure with query parameter and
                     * contenttype=application/json. Because of the logic implemented with '=' sign below,
                     * it expects a valid JSON string as the query parameter value (string after '=' sign) for GET
                     * requests with application/json content type. Therefore it fails for requests like
                     * https://localhost:8243/services/customer?format=xml and throws axis fault. With this fix,
                     * HTTP method is checked and avoid throwing axis2 fault for GET requests.
                     * https://wso2.org/jira/browse/ESBJAVA-4270
                     */
                if (isValidPayloadRequired(messageContext)) {
                    throw new AxisFault("#getNewJsonPayload. Could not save JSON payload. Invalid input stream found. Payload" + " is not a JSON string.");
                } else {
                    return null;
                }
            }
        }
        QName jsonElement = null;
        if (isObject) {
            jsonElement = JSON_OBJECT;
            messageContext.setProperty(ORG_APACHE_SYNAPSE_COMMONS_JSON_IS_JSON_OBJECT, true);
        }
        if (isValue) {
            String jsonString = "";
            try {
                jsonString = IOUtils.toString(json, "UTF-8");
                messageContext.setProperty(ORG_APACHE_SYNAPSE_COMMONS_JSON_IS_JSON_OBJECT, false);
                if (jsonString.startsWith("\"") && jsonString.endsWith("\"") || jsonString.equals("true") || jsonString.equals("false") || jsonString.equals("null") || jsonString.matches("-?\\d+(\\.\\d+)?")) {
                    jsonElement = JSON_VALUE;
                } else {
                    throw new AxisFault("#getNewJsonPayload. Could not save JSON payload. Invalid input stream found. Payload" + " is not a JSON string.");
                }
                OMElement element = OMAbstractFactory.getOMFactory().createOMElement(jsonElement, null);
                element.addChild(OMAbstractFactory.getOMFactory().createOMText(jsonString));
                if (removeChildren) {
                    removeChildrenFromPayloadBody(messageContext);
                    if (addAsNewFirstChild) {
                        addPayloadBody(messageContext, element);
                    }
                }
                return element;
            } catch (IOException e) {
                throw new AxisFault("#Can not parse stream. MessageID: " + messageContext.getMessageID() + ". Error>>> " + e.getLocalizedMessage(), e);
            }
        }
        if (isArray) {
            jsonElement = JSON_ARRAY;
            messageContext.setProperty(ORG_APACHE_SYNAPSE_COMMONS_JSON_IS_JSON_OBJECT, false);
        }
        OMElement elem = new OMSourcedElementImpl(jsonElement, OMAbstractFactory.getOMFactory(), new JsonDataSource((InputStream) messageContext.getProperty(Constants.ORG_APACHE_SYNAPSE_COMMONS_JSON_JSON_INPUT_STREAM)));
        if (!removeChildren) {
            if (logger.isTraceEnabled()) {
                logger.trace("#getNewJsonPayload. Not removing child elements from exiting message. Returning result. MessageID: " + messageContext.getMessageID());
            }
            return elem;
        } else {
            removeChildrenFromPayloadBody(messageContext);
            if (addAsNewFirstChild) {
                addPayloadBody(messageContext, elem);
            }
        }
        return elem;
    }
    return null;
}
Also used : AxisFault(org.apache.axis2.AxisFault) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) QName(javax.xml.namespace.QName) OMElement(org.apache.axiom.om.OMElement) IOException(java.io.IOException) OMSourcedElementImpl(org.apache.axiom.om.impl.llom.OMSourcedElementImpl)

Example 100 with MessageContext

use of org.apache.axis2.context.MessageContext in project wso2-synapse by wso2.

the class TemporaryDataTest method testGetNewJsonForMalformedPayload.

@Test
public void testGetNewJsonForMalformedPayload() throws AxisFault {
    String malformedJson = "{\n" + " \"categoryCode\": \"RejectedClaim\",\n" + " \"messageCode\": \"JBUPRENORP\",\n" + " \"messageText\": \"DOCUMENT ID OR \"X\" NUMBER ON\"\n" + " }";
    String json = "{\"menu\": {\n" + "  \"id\": \"file\",\n" + "  \"value\": \"File\",\n" + "  \"popup\": {\n" + "    \"menuItem\": [\n" + "      {\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"},\n" + "      {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"},\n" + "      {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}\n" + "    ]\n" + "  }\n" + "}}";
    InputStream malformedInputStream = new ByteArrayInputStream(malformedJson.getBytes());
    InputStream inputStream = new ByteArrayInputStream(json.getBytes());
    MessageContext messageContext = Util.newMessageContext();
    try {
        JsonUtil.getNewJsonPayload(messageContext, malformedInputStream, true, true);
        JsonUtil.getNewJsonPayload(messageContext, inputStream, true, false);
    } catch (SynapseCommonsException exp) {
        Assert.assertThat("Required SynapseCommonsException not thrown, Fault sequence will not be invoked", exp.getMessage(), is("Existing json payload is malformed. MessageID : " + messageContext.getMessageID()));
    }
}
Also used : SynapseCommonsException(org.apache.synapse.commons.SynapseCommonsException) ByteArrayInputStream(java.io.ByteArrayInputStream) DataInputStream(java.io.DataInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) MessageContext(org.apache.axis2.context.MessageContext) Test(org.junit.Test)

Aggregations

MessageContext (org.apache.axis2.context.MessageContext)218 AxisFault (org.apache.axis2.AxisFault)126 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)84 EndpointReference (org.apache.axis2.addressing.EndpointReference)79 OMElement (org.apache.axiom.om.OMElement)75 MessageContext (org.apache.synapse.MessageContext)71 ConfigurationContext (org.apache.axis2.context.ConfigurationContext)62 SOAPEnvelope (org.apache.axiom.soap.SOAPEnvelope)56 IOException (java.io.IOException)55 Map (java.util.Map)52 Test (org.junit.Test)45 AxisConfiguration (org.apache.axis2.engine.AxisConfiguration)44 SynapseConfiguration (org.apache.synapse.config.SynapseConfiguration)36 MessageFormatter (org.apache.axis2.transport.MessageFormatter)35 OMOutputFormat (org.apache.axiom.om.OMOutputFormat)34 Options (org.apache.axis2.client.Options)30 HashMap (java.util.HashMap)29 AxisService (org.apache.axis2.description.AxisService)29 QName (javax.xml.namespace.QName)28 Axis2SynapseEnvironment (org.apache.synapse.core.axis2.Axis2SynapseEnvironment)28