Search in sources :

Example 1 with URL

use of org.apache.axis2.util.URL in project wso2-axis2-transports by wso2.

the class RabbitMQMessageSender method publish.

/**
 * Perform the creation of exchange/queue and the Outputstream
 *
 * @param message    the RabbitMQ AMQP message
 * @param msgContext the Axis2 MessageContext
 */
public void publish(RabbitMQMessage message, MessageContext msgContext) throws AxisRabbitMQException, IOException {
    String exchangeName = null;
    AMQP.BasicProperties basicProperties = null;
    byte[] messageBody = null;
    if (rmqChannel.isOpen()) {
        String queueName = properties.get(RabbitMQConstants.QUEUE_NAME);
        String routeKey = properties.get(RabbitMQConstants.QUEUE_ROUTING_KEY);
        exchangeName = properties.get(RabbitMQConstants.EXCHANGE_NAME);
        String exchangeType = properties.get(RabbitMQConstants.EXCHANGE_TYPE);
        String replyTo = properties.get(RabbitMQConstants.REPLY_TO_NAME);
        String correlationID = properties.get(RabbitMQConstants.CORRELATION_ID);
        String queueAutoDeclareStr = properties.get(RabbitMQConstants.QUEUE_AUTODECLARE);
        String exchangeAutoDeclareStr = properties.get(RabbitMQConstants.EXCHANGE_AUTODECLARE);
        boolean queueAutoDeclare = true;
        boolean exchangeAutoDeclare = true;
        if (!StringUtils.isEmpty(queueAutoDeclareStr)) {
            queueAutoDeclare = Boolean.parseBoolean(queueAutoDeclareStr);
        }
        if (!StringUtils.isEmpty(exchangeAutoDeclareStr)) {
            exchangeAutoDeclare = Boolean.parseBoolean(exchangeAutoDeclareStr);
        }
        message.setReplyTo(replyTo);
        if (StringUtils.isEmpty(correlationID)) {
            // if reply-to is enabled a correlationID must be available. If not specified, use messageID
            correlationID = message.getMessageId();
        }
        if (!StringUtils.isEmpty(correlationID)) {
            message.setCorrelationId(correlationID);
        }
        if (queueName == null || queueName.equals("")) {
            log.debug("No queue name is specified");
        }
        if (routeKey == null && !"x-consistent-hash".equals(exchangeType)) {
            if (queueName == null || queueName.equals("")) {
                log.debug("Routing key is not specified");
            } else {
                log.debug("Routing key is not specified. Using queue name as the routing key.");
                routeKey = queueName;
            }
        }
        // read publish properties corr id and route key from message context
        Object prRouteKey = msgContext.getProperty(RabbitMQConstants.QUEUE_ROUTING_KEY);
        Object prCorrId = msgContext.getProperty(RabbitMQConstants.CORRELATION_ID).toString();
        if (prRouteKey != null) {
            routeKey = prRouteKey.toString();
            log.debug("Specifying routing key from axis2 properties");
        }
        if (prCorrId != null) {
            message.setCorrelationId(prCorrId.toString());
            log.debug("Specifying correlation id from axis2 properties");
        }
        // Declaring the queue
        if (queueAutoDeclare && queueName != null && !queueName.equals("")) {
            RabbitMQUtils.declareQueue(rmqChannel, queueName, properties);
        }
        // Declaring the exchange
        if (exchangeAutoDeclare && exchangeName != null && !exchangeName.equals("")) {
            RabbitMQUtils.declareExchange(rmqChannel, exchangeName, properties);
            if (queueName != null && !"x-consistent-hash".equals(exchangeType)) {
                // Create bind between the queue and exchange with the routeKey
                try {
                    rmqChannel.getChannel().queueBind(queueName, exchangeName, routeKey);
                } catch (IOException e) {
                    handleException("Error occurred while creating the bind between the queue: " + queueName + " & exchange: " + exchangeName + " with route-key " + routeKey, e);
                }
            }
        }
        AMQP.BasicProperties.Builder builder = buildBasicProperties(message);
        String deliveryModeString = properties.get(RabbitMQConstants.QUEUE_DELIVERY_MODE);
        int deliveryMode = RabbitMQConstants.DEFAULT_DELIVERY_MODE;
        if (deliveryModeString != null) {
            deliveryMode = Integer.parseInt(deliveryModeString);
        }
        builder.deliveryMode(deliveryMode);
        if (!StringUtils.isEmpty(replyTo)) {
            builder.replyTo(replyTo);
        }
        basicProperties = builder.build();
        OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext);
        MessageFormatter messageFormatter = null;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            messageFormatter = MessageProcessorSelector.getMessageFormatter(msgContext);
        } catch (AxisFault axisFault) {
            throw new AxisRabbitMQException("Unable to get the message formatter to use", axisFault);
        }
        // given. Queue/exchange creation, bindings should be done at the broker
        try {
            // x-consistent-hash type
            if (exchangeType != null && exchangeType.equals("x-consistent-hash")) {
                routeKey = UUID.randomUUID().toString();
            }
        } catch (UnsupportedCharsetException ex) {
            handleException("Unsupported encoding " + format.getCharSetEncoding(), ex);
        }
        try {
            messageFormatter.writeTo(msgContext, format, out, false);
            messageBody = out.toByteArray();
        } catch (IOException e) {
            handleException("IO Error while creating BytesMessage", e);
        } finally {
            if (out != null) {
                out.close();
            }
        }
        try {
            /**
             * Check for parameter on confirmed delivery in RabbitMq to ensure reliable delivery.
             * Can be enabled by setting the parameter "rabbitmq.confirm.delivery" to "true" in broker URL.
             */
            boolean isConfirmedDeliveryEnabled = Boolean.parseBoolean(properties.get(RabbitMQConstants.CONFIRMED_DELIVERY));
            if (isConfirmedDeliveryEnabled) {
                rmqChannel.getChannel().confirmSelect();
            }
            if (exchangeName != null && exchangeName != "") {
                rmqChannel.getChannel().basicPublish(exchangeName, routeKey, basicProperties, messageBody);
            } else {
                rmqChannel.getChannel().basicPublish("", routeKey, basicProperties, messageBody);
            }
            if (isConfirmedDeliveryEnabled) {
                rmqChannel.getChannel().waitForConfirmsOrDie();
            }
        } catch (IOException e) {
            handleException("Error while publishing the message", e);
        } catch (InterruptedException e) {
            handleException("InterruptedException while waiting for AMQP message confirm :", e);
        }
    } else {
        handleException("Channel cannot be created");
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) AxisRabbitMQException(org.apache.axis2.transport.rabbitmq.utils.AxisRabbitMQException) IOException(java.io.IOException) MessageFormatter(org.apache.axis2.transport.MessageFormatter) ByteArrayOutputStream(java.io.ByteArrayOutputStream) AMQP(com.rabbitmq.client.AMQP) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) OMOutputFormat(org.apache.axiom.om.OMOutputFormat)

Example 2 with URL

use of org.apache.axis2.util.URL in project wso2-synapse by wso2.

the class XFormURLEncodedFormatterTest method testGetBytes.

public void testGetBytes() throws AxisFault, XMLStreamException {
    XFormURLEncodedFormatter formatter = new XFormURLEncodedFormatter();
    MessageContext messageContext = Util.newMessageContext("<test><test>123</test></test>");
    byte[] bytes = formatter.getBytes(messageContext, new OMOutputFormat());
    assertEquals("Invalid X-form URL Encoded string", "test=123", new String(bytes));
}
Also used : MessageContext(org.apache.axis2.context.MessageContext) OMOutputFormat(org.apache.axiom.om.OMOutputFormat)

Example 3 with URL

use of org.apache.axis2.util.URL in project wso2-synapse by wso2.

the class DynamicLoadbalanceEndpoint method sendToApplicationMember.

protected void sendToApplicationMember(MessageContext synCtx, Member currentMember, DynamicLoadbalanceFaultHandler faultHandler, boolean newSession) {
    // Rewriting the URL
    org.apache.axis2.context.MessageContext axis2MsgCtx = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
    // Removing the REST_URL_POSTFIX - this is a hack.
    // In this loadbalance endpoint we create an endpoint per request by setting the complete url as the adress.
    // If a REST message comes Axis2FlexibleMEPClient append the REST_URL_POSTFIX to the adress. Hence endpoint fails
    // do send the request. e.g.  http://localhost:8080/example/index.html/example/index.html
    axis2MsgCtx.removeProperty(NhttpConstants.REST_URL_POSTFIX);
    String transport = axis2MsgCtx.getTransportIn().getName();
    String address = synCtx.getTo().getAddress();
    int incomingPort = extractPort(synCtx, transport);
    EndpointReference to = getEndpointReferenceAfterURLRewrite(currentMember, transport, address, incomingPort);
    synCtx.setTo(to);
    faultHandler.setTo(to);
    faultHandler.setCurrentMember(currentMember);
    synCtx.pushFaultHandler(faultHandler);
    if (isFailover()) {
        synCtx.getEnvelope().build();
    }
    Endpoint endpoint = getEndpoint(to, currentMember, synCtx);
    faultHandler.setCurrentEp(endpoint);
    if (isSessionAffinityBasedLB()) {
        synCtx.setProperty(SynapseConstants.PROP_SAL_ENDPOINT_DEFAULT_SESSION_TIMEOUT, getSessionTimeout());
        synCtx.setProperty(SynapseConstants.PROP_SAL_ENDPOINT_CURRENT_DISPATCHER, dispatcher);
        prepareEndPointSequence(synCtx, endpoint);
        if (newSession) {
            synCtx.setProperty(SynapseConstants.PROP_SAL_ENDPOINT_CURRENT_MEMBER, currentMember);
            // we should also indicate that this is the first message in the session. so that
            // onFault(...) method can resend only the failed attempts for the first message.
            synCtx.setProperty(SynapseConstants.PROP_SAL_ENDPOINT_FIRST_MESSAGE_IN_SESSION, Boolean.TRUE);
        }
    }
    Map<String, String> memberHosts;
    if ((memberHosts = (Map<String, String>) currentMember.getProperties().get(HttpSessionDispatcher.HOSTS)) == null) {
        currentMember.getProperties().put(HttpSessionDispatcher.HOSTS, memberHosts = new HashMap<String, String>());
    }
    memberHosts.put(extractHost(synCtx), "true");
    setupTransportHeaders(synCtx);
    try {
        endpoint.send(synCtx);
    } catch (Exception e) {
        if (e.getMessage().toLowerCase().contains("io reactor shutdown")) {
            log.fatal("System cannot continue normal operation. Restarting", e);
            // restart
            System.exit(121);
        } else {
            throw new SynapseException(e);
        }
    }
}
Also used : SynapseException(org.apache.synapse.SynapseException) MalformedURLException(java.net.MalformedURLException) SynapseException(org.apache.synapse.SynapseException) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) EndpointReference(org.apache.axis2.addressing.EndpointReference)

Example 4 with URL

use of org.apache.axis2.util.URL in project wso2-synapse by wso2.

the class AxisOperationClient method send.

/**
 * @param trpUrl Transport url
 * @param addUrl WS-Addressing EPR url
 * @param payload Request payload
 * @param action Soap Action
 * @return  Soap envelope
 * @throws AxisFault
 */
public OMElement send(String trpUrl, String addUrl, OMElement payload, String action) throws AxisFault {
    init();
    operationClient = serviceClient.createClient(ServiceClient.ANON_OUT_IN_OP);
    setMessageContext(addUrl, trpUrl, action);
    outMsgCtx.setEnvelope(createSOAPEnvelope(payload));
    operationClient.addMessageContext(outMsgCtx);
    operationClient.execute(true);
    MessageContext inMsgtCtx = operationClient.getMessageContext("In");
    SOAPEnvelope response = inMsgtCtx.getEnvelope();
    return response;
}
Also used : MessageContext(org.apache.axis2.context.MessageContext) SOAPEnvelope(org.apache.axiom.soap.SOAPEnvelope)

Example 5 with URL

use of org.apache.axis2.util.URL in project wso2-synapse by wso2.

the class AxisOperationClient method setMessageContext.

/**
 * Creating the message context of the soap message     *
 * @param addUrl WS-Addressing EPR url
 * @param trpUrl Transport url
 * @param action Soap action
 */
private void setMessageContext(String addUrl, String trpUrl, String action) {
    outMsgCtx = new MessageContext();
    // assigning message context&rsquo;s option object into instance variable
    Options options = outMsgCtx.getOptions();
    // setting properties into option
    if (trpUrl != null && !"null".equals(trpUrl)) {
        options.setProperty(Constants.Configuration.TRANSPORT_URL, trpUrl);
    }
    if (addUrl != null && !"null".equals(addUrl)) {
        options.setTo(new EndpointReference(addUrl));
    }
    if (action != null && !"null".equals(action)) {
        options.setAction(action);
    }
}
Also used : Options(org.apache.axis2.client.Options) MessageContext(org.apache.axis2.context.MessageContext) EndpointReference(org.apache.axis2.addressing.EndpointReference)

Aggregations

IOException (java.io.IOException)31 EndpointReference (org.apache.axis2.addressing.EndpointReference)29 AxisFault (org.apache.axis2.AxisFault)27 URL (java.net.URL)21 ConfigurationContext (org.apache.axis2.context.ConfigurationContext)19 URL (org.apache.axis2.util.URL)19 HttpClient (org.apache.http.client.HttpClient)19 Options (org.apache.axis2.client.Options)18 MalformedURLException (java.net.MalformedURLException)17 OMElement (org.apache.axiom.om.OMElement)17 MessageContext (org.apache.axis2.context.MessageContext)16 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)16 ServiceClient (org.apache.axis2.client.ServiceClient)13 SynapseException (org.apache.synapse.SynapseException)13 AxisConfiguration (org.apache.axis2.engine.AxisConfiguration)12 AxisService (org.apache.axis2.description.AxisService)10 StringEntity (org.apache.http.entity.StringEntity)9 SynapseConfiguration (org.apache.synapse.config.SynapseConfiguration)9 Map (java.util.Map)7 JSONObject (org.json.JSONObject)7