Search in sources :

Example 41 with MessageContext

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

the class MinConcurrencyTest method runTest.

@Override
protected void runTest() throws Throwable {
    int endpointCount = channels.length;
    int expectedConcurrency = endpointCount * messages;
    final MessageReceiver messageReceiver = new MessageReceiver() {

        public void receive(MessageContext msgContext) throws AxisFault {
            synchronized (concurrencyReachedLock) {
                concurrencyReached++;
                concurrencyReachedLock.notifyAll();
            }
            try {
                synchronized (shutdownAwaitLock) {
                    shutdownAwaitLock.wait();
                }
            } catch (InterruptedException ex) {
            }
        }
    };
    TestResourceSet[] clientResourceSets = new TestResourceSet[endpointCount];
    TestResourceSet[] endpointResourceSets = new TestResourceSet[endpointCount];
    try {
        for (int i = 0; i < endpointCount; i++) {
            TestResourceSet clientResourceSet = new TestResourceSet(getResourceSet());
            AsyncChannel channel = channels[i];
            clientResourceSet.addResource(channel);
            AxisAsyncTestClient client = new AxisAsyncTestClient(false);
            clientResourceSet.addResource(client);
            clientResourceSet.setUp();
            clientResourceSets[i] = clientResourceSet;
            TestResourceSet endpointResourceSet = new TestResourceSet(clientResourceSet);
            endpointResourceSet.addResource(new AxisTestEndpoint() {

                @Override
                protected AxisOperation createOperation() {
                    AxisOperation operation = new InOnlyAxisOperation(new QName("in"));
                    operation.setMessageReceiver(messageReceiver);
                    return operation;
                }

                @Override
                protected void onTransportError(Throwable ex) {
                // TODO Auto-generated method stub
                }
            });
            if (!preloadMessages) {
                endpointResourceSet.setUp();
                endpointResourceSets[i] = endpointResourceSet;
            }
            for (int j = 0; j < messages; j++) {
                ClientOptions options = new ClientOptions(client, new ContentType(SOAP11Constants.SOAP_11_CONTENT_TYPE), "UTF-8");
                AxisMessage message = new AxisMessage();
                message.setMessageType(SOAP11Constants.SOAP_11_CONTENT_TYPE);
                SOAPFactory factory = OMAbstractFactory.getSOAP11Factory();
                SOAPEnvelope envelope = factory.getDefaultEnvelope();
                message.setEnvelope(envelope);
                client.sendMessage(options, new ContentType(message.getMessageType()), message);
            }
            if (preloadMessages) {
                endpointResourceSet.setUp();
                endpointResourceSets[i] = endpointResourceSet;
            }
        }
        long startTime = System.currentTimeMillis();
        while (concurrencyReached < expectedConcurrency && System.currentTimeMillis() < (startTime + 5000)) {
            synchronized (concurrencyReachedLock) {
                concurrencyReachedLock.wait(5000);
            }
        }
        synchronized (shutdownAwaitLock) {
            shutdownAwaitLock.notifyAll();
        }
        if (concurrencyReached < expectedConcurrency) {
            fail("Concurrency reached is " + concurrencyReached + ", but expected " + expectedConcurrency);
        }
    } finally {
        for (int i = 0; i < endpointCount; i++) {
            if (endpointResourceSets[i] != null) {
                endpointResourceSets[i].tearDown();
            }
            if (clientResourceSets[i] != null) {
                clientResourceSets[i].tearDown();
            }
        }
    }
}
Also used : ClientOptions(org.apache.axis2.transport.testkit.client.ClientOptions) InOnlyAxisOperation(org.apache.axis2.description.InOnlyAxisOperation) AxisOperation(org.apache.axis2.description.AxisOperation) ContentType(javax.mail.internet.ContentType) QName(javax.xml.namespace.QName) AsyncChannel(org.apache.axis2.transport.testkit.channel.AsyncChannel) SOAPEnvelope(org.apache.axiom.soap.SOAPEnvelope) AxisTestEndpoint(org.apache.axis2.transport.testkit.axis2.endpoint.AxisTestEndpoint) SOAPFactory(org.apache.axiom.soap.SOAPFactory) InOnlyAxisOperation(org.apache.axis2.description.InOnlyAxisOperation) MessageReceiver(org.apache.axis2.engine.MessageReceiver) AxisTestEndpoint(org.apache.axis2.transport.testkit.axis2.endpoint.AxisTestEndpoint) AxisAsyncTestClient(org.apache.axis2.transport.testkit.axis2.client.AxisAsyncTestClient) MessageContext(org.apache.axis2.context.MessageContext) TestResourceSet(org.apache.axis2.transport.testkit.tests.TestResourceSet) AxisMessage(org.apache.axis2.transport.testkit.message.AxisMessage)

Example 42 with MessageContext

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

the class XMPPPacketListener method buildSOAPEnvelope.

/**
 * builds SOAP envelop using message contained in packet
 * @param packet
 * @param msgContext
 * @throws AxisFault
 */
private void buildSOAPEnvelope(Packet packet, MessageContext msgContext) throws AxisFault {
    Message message = (Message) packet;
    String logMsg = "Trying to create " + "message content using XMPP message received :" + packet.toXML();
    String messageBody = StringEscapeUtils.unescapeXml(message.getBody());
    if (msgContext.isServerSide()) {
        log.debug("Received Envelope : " + messageBody);
    }
    InputStream inputStream = new ByteArrayInputStream(messageBody.getBytes());
    SOAPEnvelope envelope = null;
    try {
        Object obj = message.getProperty(XMPPConstants.CONTAINS_SOAP_ENVELOPE);
        if (obj != null && ((Boolean) obj).booleanValue()) {
            String contentType = (String) message.getProperty(XMPPConstants.CONTENT_TYPE);
            if (contentType == null) {
                throw new AxisFault("Can not Find Content type Property in the XMPP Message");
            }
            envelope = TransportUtils.createSOAPMessage(msgContext, inputStream, contentType);
            msgContext.setProperty(XMPPConstants.CONTAINS_SOAP_ENVELOPE, new Boolean(true));
        } else {
            // This message could either be a service call or a help command
            if (!(messageContainsCommandsFromChat(messageBody, msgContext))) {
                envelope = createSOAPEnvelopeForRawMessage(msgContext, messageBody);
            }
        }
        if (envelope != null) {
            msgContext.setEnvelope(envelope);
        }
    } catch (OMException e) {
        log.error(logMsg, e);
        throw new AxisFault(logMsg);
    } catch (XMLStreamException e) {
        log.error(logMsg, e);
        throw new AxisFault(logMsg);
    } catch (FactoryConfigurationError e) {
        log.error(logMsg, e);
        throw new AxisFault(logMsg);
    } catch (AxisFault e) {
        log.error(logMsg, e);
        throw new AxisFault(logMsg);
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) Message(org.jivesoftware.smack.packet.Message) XMLStreamException(javax.xml.stream.XMLStreamException) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) SOAPEnvelope(org.apache.axiom.soap.SOAPEnvelope) OMException(org.apache.axiom.om.OMException) FactoryConfigurationError(javax.xml.parsers.FactoryConfigurationError)

Example 43 with MessageContext

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

the class ProcessPacketTask method run.

public void run() {
    MetricsCollector metrics = endpoint.getMetrics();
    try {
        InputStream inputStream = new ByteArrayInputStream(data, 0, length);
        MessageContext msgContext = endpoint.createMessageContext();
        SOAPEnvelope envelope = TransportUtils.createSOAPMessage(msgContext, inputStream, endpoint.getContentType());
        msgContext.setEnvelope(envelope);
        if (outInfo != null) {
            if (outInfo.getContentType() == null) {
                outInfo.setContentType(endpoint.getContentType());
            }
            msgContext.setProperty(Constants.OUT_TRANSPORT_INFO, outInfo);
        }
        AxisEngine.receive(msgContext);
        metrics.incrementMessagesReceived();
        metrics.incrementBytesReceived(length);
    } catch (Exception ex) {
        metrics.incrementFaultsReceiving();
        StringBuilder buffer = new StringBuilder("Error during processing of datagram:\n");
        Utils.hexDump(buffer, data, length);
        log.error(buffer.toString(), ex);
    }
}
Also used : MetricsCollector(org.apache.axis2.transport.base.MetricsCollector) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) MessageContext(org.apache.axis2.context.MessageContext) SOAPEnvelope(org.apache.axiom.soap.SOAPEnvelope)

Example 44 with MessageContext

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

the class JMSSender method createJMSMessage.

/**
 * Create a JMS Message from the given MessageContext and using the given
 * session
 *
 * @param msgContext the MessageContext
 * @param session    the JMS session
 * @param contentTypeProperty the message property to be used to store the
 *                            content type
 * @return a JMS message from the context and session
 * @throws JMSException on exception
 * @throws AxisFault on exception
 */
private Message createJMSMessage(MessageContext msgContext, Session session, String contentTypeProperty) throws JMSException, AxisFault {
    Message message = null;
    String msgType = getProperty(msgContext, JMSConstants.JMS_MESSAGE_TYPE);
    // check the first element of the SOAP body, do we have content wrapped using the
    // default wrapper elements for binary (BaseConstants.DEFAULT_BINARY_WRAPPER) or
    // text (BaseConstants.DEFAULT_TEXT_WRAPPER) ? If so, do not create SOAP messages
    // for JMS but just get the payload in its native format
    String jmsPayloadType = guessMessageType(msgContext);
    if (jmsPayloadType == null) {
        OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext);
        MessageFormatter messageFormatter = null;
        try {
            messageFormatter = MessageProcessorSelector.getMessageFormatter(msgContext);
        } catch (AxisFault axisFault) {
            throw new JMSException("Unable to get the message formatter to use");
        }
        String contentType = messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction());
        boolean useBytesMessage = msgType != null && JMSConstants.JMS_BYTE_MESSAGE.equals(msgType) || contentType.indexOf(HTTPConstants.HEADER_ACCEPT_MULTIPART_RELATED) > -1;
        OutputStream out;
        StringWriter sw;
        if (useBytesMessage) {
            BytesMessage bytesMsg = session.createBytesMessage();
            sw = null;
            out = new BytesMessageOutputStream(bytesMsg);
            message = bytesMsg;
        } else {
            sw = new StringWriter();
            try {
                out = new WriterOutputStream(sw, format.getCharSetEncoding());
            } catch (UnsupportedCharsetException ex) {
                handleException("Unsupported encoding " + format.getCharSetEncoding(), ex);
                return null;
            }
        }
        try {
            messageFormatter.writeTo(msgContext, format, out, true);
            out.close();
        } catch (IOException e) {
            Transaction transaction = null;
            try {
                transaction = ((TransactionManager) msgContext.getProperty(JMSConstants.JMS_XA_TRANSACTION_MANAGER)).getTransaction();
                rollbackXATransaction(transaction);
            } catch (SystemException e1) {
                handleException("Error occurred during obtaining  transaction", e1);
            }
            handleException("IO Error while creating BytesMessage", e);
        }
        if (!useBytesMessage) {
            TextMessage txtMsg = session.createTextMessage();
            txtMsg.setText(sw.toString());
            message = txtMsg;
        }
        if (contentTypeProperty != null) {
            message.setStringProperty(contentTypeProperty, contentType);
        }
    } else if (JMSConstants.JMS_BYTE_MESSAGE.equals(jmsPayloadType)) {
        message = session.createBytesMessage();
        BytesMessage bytesMsg = (BytesMessage) message;
        OMElement wrapper = msgContext.getEnvelope().getBody().getFirstChildWithName(BaseConstants.DEFAULT_BINARY_WRAPPER);
        OMNode omNode = wrapper.getFirstOMChild();
        if (omNode != null && omNode instanceof OMText) {
            Object dh = ((OMText) omNode).getDataHandler();
            if (dh != null && dh instanceof DataHandler) {
                try {
                    ((DataHandler) dh).writeTo(new BytesMessageOutputStream(bytesMsg));
                } catch (IOException e) {
                    Transaction transaction = null;
                    try {
                        transaction = ((TransactionManager) msgContext.getProperty(JMSConstants.JMS_XA_TRANSACTION_MANAGER)).getTransaction();
                        rollbackXATransaction(transaction);
                    } catch (SystemException e1) {
                        handleException("Error occurred during obtaining  transaction", e1);
                    }
                    handleException("Error serializing binary content of element : " + BaseConstants.DEFAULT_BINARY_WRAPPER, e);
                }
            }
        }
    } else if (JMSConstants.JMS_TEXT_MESSAGE.equals(jmsPayloadType)) {
        message = session.createTextMessage();
        TextMessage txtMsg = (TextMessage) message;
        txtMsg.setText(msgContext.getEnvelope().getBody().getFirstChildWithName(BaseConstants.DEFAULT_TEXT_WRAPPER).getText());
    } else if (JMSConstants.JMS_MAP_MESSAGE.equalsIgnoreCase(jmsPayloadType)) {
        message = session.createMapMessage();
        JMSUtils.convertXMLtoJMSMap(msgContext.getEnvelope().getBody().getFirstChildWithName(JMSConstants.JMS_MAP_QNAME), (MapMessage) message);
    }
    // set the JMS correlation ID if specified
    String correlationId = getProperty(msgContext, JMSConstants.JMS_COORELATION_ID);
    if (correlationId == null && msgContext.getRelatesTo() != null) {
        correlationId = msgContext.getRelatesTo().getValue();
    }
    if (correlationId != null) {
        message.setJMSCorrelationID(correlationId);
    }
    if (msgContext.isServerSide()) {
        // set SOAP Action as a property on the JMS message
        setProperty(message, msgContext, BaseConstants.SOAPACTION);
    } else {
        String action = msgContext.getOptions().getAction();
        if (action != null) {
            message.setStringProperty(BaseConstants.SOAPACTION, action);
        }
    }
    JMSUtils.setTransportHeaders(msgContext, message);
    return message;
}
Also used : AxisFault(org.apache.axis2.AxisFault) BytesMessageOutputStream(org.apache.axis2.transport.jms.iowrappers.BytesMessageOutputStream) OutputStream(java.io.OutputStream) WriterOutputStream(org.apache.commons.io.output.WriterOutputStream) BytesMessageOutputStream(org.apache.axis2.transport.jms.iowrappers.BytesMessageOutputStream) OMElement(org.apache.axiom.om.OMElement) MessageFormatter(org.apache.axis2.transport.MessageFormatter) IOException(java.io.IOException) DataHandler(javax.activation.DataHandler) WriterOutputStream(org.apache.commons.io.output.WriterOutputStream) OMNode(org.apache.axiom.om.OMNode) StringWriter(java.io.StringWriter) Transaction(javax.transaction.Transaction) SystemException(javax.transaction.SystemException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) TransactionManager(javax.transaction.TransactionManager) OMText(org.apache.axiom.om.OMText) OMOutputFormat(org.apache.axiom.om.OMOutputFormat)

Example 45 with MessageContext

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

the class JMSSenderTestCase method testTransactionCommandParameter.

/**
 * Test case for EI-1244.
 * test transport.jms.TransactionCommand parameter in transport url when sending the message.
 * This will verify the fixes which prevent possible OOM issue when publishing messages to a broker using jms.
 *
 * @throws Exception
 */
public void testTransactionCommandParameter() throws Exception {
    JMSSender jmsSender = PowerMockito.spy(new JMSSender());
    JMSOutTransportInfo jmsOutTransportInfo = Mockito.mock(JMSOutTransportInfo.class);
    JMSMessageSender jmsMessageSender = Mockito.mock(JMSMessageSender.class);
    Session session = Mockito.mock(Session.class);
    Mockito.doReturn(session).when(jmsMessageSender).getSession();
    PowerMockito.whenNew(JMSOutTransportInfo.class).withArguments(any(String.class)).thenReturn(jmsOutTransportInfo);
    Mockito.doReturn(jmsMessageSender).when(jmsOutTransportInfo).createJMSSender(any(MessageContext.class));
    PowerMockito.doNothing().when(jmsSender, "sendOverJMS", ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any());
    jmsSender.init(new ConfigurationContext(new AxisConfiguration()), new TransportOutDescription("jms"));
    MessageContext messageContext = new MessageContext();
    // append the transport.jms.TransactionCommand
    String targetAddress = "jms:/SimpleStockQuoteService?transport.jms.ConnectionFactoryJNDIName=" + "QueueConnectionFactory&transport.jms.TransactionCommand=begin" + "&java.naming.factory.initial=org.apache.activemq.jndi.ActiveMQInitialContextFactory";
    Transaction transaction = new TestJMSTransaction();
    messageContext.setProperty(JMSConstants.JMS_XA_TRANSACTION, transaction);
    jmsSender.sendMessage(messageContext, targetAddress, null);
    Map<Transaction, ArrayList<JMSMessageSender>> jmsMessageSenderMap = Whitebox.getInternalState(JMSSender.class, "jmsMessageSenderMap");
    Assert.assertEquals("Transaction not added to map", 1, jmsMessageSenderMap.size());
    List senderList = jmsMessageSenderMap.get(transaction);
    Assert.assertNotNull("List is null", senderList);
    Assert.assertEquals("List is empty", 1, senderList.size());
}
Also used : ConfigurationContext(org.apache.axis2.context.ConfigurationContext) AxisConfiguration(org.apache.axis2.engine.AxisConfiguration) ArrayList(java.util.ArrayList) Transaction(javax.transaction.Transaction) ArrayList(java.util.ArrayList) List(java.util.List) MessageContext(org.apache.axis2.context.MessageContext) Session(javax.jms.Session) TransportOutDescription(org.apache.axis2.description.TransportOutDescription)

Aggregations

MessageContext (org.apache.axis2.context.MessageContext)35 AxisFault (org.apache.axis2.AxisFault)25 OMElement (org.apache.axiom.om.OMElement)13 SOAPEnvelope (org.apache.axiom.soap.SOAPEnvelope)12 IOException (java.io.IOException)11 OMOutputFormat (org.apache.axiom.om.OMOutputFormat)11 XMLStreamException (javax.xml.stream.XMLStreamException)9 QName (javax.xml.namespace.QName)8 MessageFormatter (org.apache.axis2.transport.MessageFormatter)8 AxisOperation (org.apache.axis2.description.AxisOperation)7 ByteArrayInputStream (java.io.ByteArrayInputStream)6 InputStream (java.io.InputStream)5 UnsupportedCharsetException (java.nio.charset.UnsupportedCharsetException)5 SOAPFactory (org.apache.axiom.soap.SOAPFactory)5 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 OMFactory (org.apache.axiom.om.OMFactory)4 Options (org.apache.axis2.client.Options)4 Message (org.jivesoftware.smack.packet.Message)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 OutputStream (java.io.OutputStream)3