Search in sources :

Example 16 with MapMessage

use of javax.jms.MapMessage in project qpid by apache.

the class Console method cancelSubscription.

// end of refreshSubscription()
/**
     * Terminates the given subscription.
     *
     * @param subscriptionId the ID of the subscription to be cancelled
     */
public void cancelSubscription(final String subscriptionId) throws QmfException {
    if (subscriptionId == null) {
        throw new QmfException("Called cancelSubscription() with null subscriptionId");
    }
    SubscriptionManager subscription = _subscriptionById.get(subscriptionId);
    if (subscription == null) {
        throw new QmfException("Called cancelSubscription() with invalid subscriptionId");
    }
    String consoleHandle = subscription.getConsoleHandle();
    Agent agent = subscription.getAgent();
    if (!agent.isActive()) {
        throw new QmfException("Called cancelSubscription() with inactive agent");
    }
    String agentName = agent.getName();
    try {
        MapMessage request = _syncSession.createMapMessage();
        request.setStringProperty("x-amqp-0-10.app-id", "qmf2");
        request.setStringProperty("method", "request");
        request.setStringProperty("qmf.opcode", "_subscribe_cancel_indication");
        request.setStringProperty("qpid.subject", agentName);
        request.setObject("_subscription_id", subscriptionId);
        synchronized (this) {
            if (!_subscriptionEmulationEnabled || !agentName.equals(_brokerAgentName)) {
                _requester.send(request);
            }
        }
        subscription.cancel();
    } catch (JMSException jmse) {
        _log.info("JMSException {} caught in cancelSubscription()", jmse.getMessage());
    }
}
Also used : MapMessage(javax.jms.MapMessage) JMSException(javax.jms.JMSException) QmfException(org.apache.qpid.qmf2.common.QmfException)

Example 17 with MapMessage

use of javax.jms.MapMessage in project qpid by apache.

the class Console method getObjects.

/**
     * Perform a query for QmfConsoleData objects. Returns a list (possibly empty) of matching objects.
     * If replyHandle is null this method will block until the agent replies, or the timeout expires.
     * Once the timeout expires, all data retrieved to date is returned. If replyHandle is non-null an
     * asynchronous request is performed
     * 
     * @param agent the Agent being queried
     * @param query the ObjectId or SchemaClassId being queried for.
     * @param replyHandle the correlation handle used to tie asynchronous method requests with responses
     * @param timeout the time to wait for a reply from the Agent, a value of -1 means use the default timeout
     * @return a List of QMF Objects describing that class
     */
private List<QmfConsoleData> getObjects(final Agent agent, final QmfData query, final String replyHandle, int timeout) {
    String agentName = agent.getName();
    timeout = (timeout < 1) ? _replyTimeout : timeout;
    List<QmfConsoleData> results = Collections.emptyList();
    try {
        Destination destination = (replyHandle == null) ? _replyAddress : _asyncReplyAddress;
        MapMessage request = _syncSession.createMapMessage();
        request.setJMSReplyTo(destination);
        request.setJMSCorrelationID(replyHandle);
        request.setStringProperty("x-amqp-0-10.app-id", "qmf2");
        request.setStringProperty("method", "request");
        request.setStringProperty("qmf.opcode", "_query_request");
        request.setStringProperty("qpid.subject", agentName);
        // Create a QMF Query for an "OBJECT" target using either a schema ID or object ID
        String queryType = (query instanceof SchemaClassId) ? "_schema_id" : "_object_id";
        request.setObject("_what", "OBJECT");
        request.setObject(queryType, query.mapEncode());
        // it would be somewhat unfortunate if their response got interleaved with ours!!
        synchronized (this) {
            _requester.send(request);
            if (replyHandle == null) {
                boolean lastResult = true;
                ArrayList<QmfConsoleData> partials = new ArrayList<QmfConsoleData>();
                do {
                    // Wrap in a do/while loop to cater for the case where the Agent may send partial results.
                    Message response = _responder.receive(timeout * 1000);
                    if (response == null) {
                        _log.info("No response received in getObjects()");
                        return partials;
                    }
                    lastResult = !response.propertyExists("partial");
                    if (AMQPMessage.isAMQPList(response)) {
                        List<Map> mapResults = AMQPMessage.getList(response);
                        partials.ensureCapacity(partials.size() + mapResults.size());
                        for (Map content : mapResults) {
                            partials.add(new QmfConsoleData(content, agent));
                        }
                    } else if (AMQPMessage.isAMQPMap(response)) {
                    // Error responses are returned as MapMessages, though they are being ignored here.
                    //QmfData exception = new QmfData(AMQPMessage.getMap(response));
                    //System.out.println(agentName + " " + exception.getStringValue("error_text"));
                    } else {
                        _log.info("getObjects() Received response message in incorrect format");
                    }
                } while (!lastResult);
                results = partials;
            }
        }
    } catch (JMSException jmse) {
        _log.info("JMSException {} caught in getObjects()", jmse.getMessage());
    }
    return results;
}
Also used : Destination(javax.jms.Destination) AMQPMessage(org.apache.qpid.qmf2.common.AMQPMessage) MapMessage(javax.jms.MapMessage) Message(javax.jms.Message) MapMessage(javax.jms.MapMessage) ArrayList(java.util.ArrayList) JMSException(javax.jms.JMSException) SchemaClassId(org.apache.qpid.qmf2.common.SchemaClassId) HashMap(java.util.HashMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 18 with MapMessage

use of javax.jms.MapMessage in project qpid by apache.

the class Console method refreshSubscription.

/**
     * Renews a subscription identified by SubscriptionId.
     * <p>
     * The Console may request a new subscription duration by providing a requested lifetime. This method may be called 
     * asynchronously by providing a replyHandle argument.
     * <p>
     * When called asynchronously, the result of this method call is returned in a SUBSCRIBE_RESPONSE WorkItem.
     * <p>
     * Timeout can be used to override the console's default reply timeout.
     * <p>  
     * When called synchronously, this method returns a class SubscribeParams object containing the result of the       
     * subscription request.
     *
     * @param subscriptionId the ID of the subscription to be refreshed
     * @param options a String representation of a Map containing the options in the form
     *        <pre>"{lifetime:&lt;value&gt;, replyHandle:&lt;value&gt;, timeout:&lt;value&gt;}"</pre>
     *        they are optional and may appear in any order.
     * <pre>
     *        <b>lifetime</b> requests a new subscription duration.
     *        <b>replyHandle</b> the correlation handle used to tie asynchronous method requests with responses.
     *        <b>timeout</b> the time to wait for a reply from the Agent.
     * </pre>
     */
public SubscribeParams refreshSubscription(String subscriptionId, final String options) throws QmfException {
    if (subscriptionId == null) {
        throw new QmfException("Called refreshSubscription() with null subscriptionId");
    }
    SubscriptionManager subscription = _subscriptionById.get(subscriptionId);
    if (subscription == null) {
        throw new QmfException("Called refreshSubscription() with invalid subscriptionId");
    }
    String consoleHandle = subscription.getConsoleHandle();
    Agent agent = subscription.getAgent();
    if (!agent.isActive()) {
        throw new QmfException("Called refreshSubscription() with inactive agent");
    }
    String agentName = agent.getName();
    // Initialise optional values to defaults;
    long lifetime = 0;
    long timeout = _replyTimeout;
    String replyHandle = null;
    if (options != null) {
        // We wrap the Map in a QmfData object to avoid potential class cast issues with the parsed options
        QmfData optMap = new QmfData(new AddressParser(options).map());
        if (optMap.hasValue("lifetime")) {
            lifetime = optMap.getLongValue("lifetime");
        }
        if (optMap.hasValue("timeout")) {
            timeout = optMap.getLongValue("timeout");
        }
        if (optMap.hasValue("replyHandle")) {
            replyHandle = optMap.getStringValue("replyHandle");
        }
    }
    try {
        Destination destination = (replyHandle == null) ? _replyAddress : _asyncReplyAddress;
        MapMessage request = _syncSession.createMapMessage();
        request.setJMSReplyTo(destination);
        request.setJMSCorrelationID(replyHandle);
        request.setStringProperty("x-amqp-0-10.app-id", "qmf2");
        request.setStringProperty("method", "request");
        request.setStringProperty("qmf.opcode", "_subscribe_refresh_indication");
        request.setStringProperty("qpid.subject", agentName);
        request.setObject("_subscription_id", subscriptionId);
        if (lifetime > 0) {
            request.setObject("_duration", lifetime);
        }
        // it would be somewhat unfortunate if their response got interleaved with ours!!
        synchronized (this) {
            if (_subscriptionEmulationEnabled && agentName.equals(_brokerAgentName)) {
                // If the Agent is the broker Agent we emulate the Subscription on the Console
                subscription.refresh();
                final SubscribeParams params = new SubscribeParams(consoleHandle, subscription.mapEncode());
                if (replyHandle == null) {
                    return params;
                } else {
                    final String handle = replyHandle;
                    Thread thread = new Thread() {

                        public void run() {
                            _eventListener.onEvent(new SubscribeResponseWorkItem(new Handle(handle), params));
                        }
                    };
                    thread.start();
                }
                return null;
            }
            _requester.send(request);
            if (replyHandle == null) {
                // If this is an synchronous request get the response
                Message response = _responder.receive(timeout * 1000);
                if (response == null) {
                    subscription.cancel();
                    _log.info("No response received in refreshSubscription()");
                    throw new QmfException("No response received for Console.refreshSubscription()");
                }
                SubscribeParams result = new SubscribeParams(consoleHandle, AMQPMessage.getMap(response));
                subscriptionId = result.getSubscriptionId();
                if (subscriptionId == null) {
                    subscription.cancel();
                } else {
                    subscription.setDuration(result.getLifetime());
                    subscription.refresh();
                }
                return result;
            }
        }
        // If this is an asynchronous request return without waiting for a response
        return null;
    } catch (JMSException jmse) {
        _log.info("JMSException {} caught in refreshSubscription()", jmse.getMessage());
        throw new QmfException(jmse.getMessage());
    }
}
Also used : Destination(javax.jms.Destination) QmfData(org.apache.qpid.qmf2.common.QmfData) AddressParser(org.apache.qpid.messaging.util.AddressParser) AMQPMessage(org.apache.qpid.qmf2.common.AMQPMessage) MapMessage(javax.jms.MapMessage) Message(javax.jms.Message) MapMessage(javax.jms.MapMessage) JMSException(javax.jms.JMSException) Handle(org.apache.qpid.qmf2.common.Handle) QmfException(org.apache.qpid.qmf2.common.QmfException)

Example 19 with MapMessage

use of javax.jms.MapMessage in project camel by apache.

the class ConsumeJmsMapMessageTest method testConsumeMapMessage.

@Test
public void testConsumeMapMessage() throws Exception {
    endpoint.expectedMessageCount(1);
    jmsTemplate.setPubSubDomain(false);
    jmsTemplate.send("test.map", new MessageCreator() {

        public Message createMessage(Session session) throws JMSException {
            MapMessage mapMessage = session.createMapMessage();
            mapMessage.setString("foo", "abc");
            mapMessage.setString("bar", "xyz");
            return mapMessage;
        }
    });
    endpoint.assertIsSatisfied();
    assertCorrectMapReceived();
}
Also used : MapMessage(javax.jms.MapMessage) Message(javax.jms.Message) MapMessage(javax.jms.MapMessage) JMSException(javax.jms.JMSException) MessageCreator(org.springframework.jms.core.MessageCreator) Session(javax.jms.Session) Test(org.junit.Test)

Example 20 with MapMessage

use of javax.jms.MapMessage in project camel by apache.

the class JmsBinding method createJmsMessageForType.

/**
     *
     * Create the {@link Message}
     *
     * @return jmsMessage or null if the mapping was not successfully
     */
protected Message createJmsMessageForType(Exchange exchange, Object body, Map<String, Object> headers, Session session, CamelContext context, JmsMessageType type) throws JMSException {
    switch(type) {
        case Text:
            {
                TextMessage message = session.createTextMessage();
                if (body != null) {
                    String payload = context.getTypeConverter().convertTo(String.class, exchange, body);
                    message.setText(payload);
                }
                return message;
            }
        case Bytes:
            {
                BytesMessage message = session.createBytesMessage();
                if (body != null) {
                    byte[] payload = context.getTypeConverter().convertTo(byte[].class, exchange, body);
                    message.writeBytes(payload);
                }
                return message;
            }
        case Map:
            {
                MapMessage message = session.createMapMessage();
                if (body != null) {
                    Map<?, ?> payload = context.getTypeConverter().convertTo(Map.class, exchange, body);
                    populateMapMessage(message, payload, context);
                }
                return message;
            }
        case Object:
            ObjectMessage message = session.createObjectMessage();
            if (body != null) {
                try {
                    Serializable payload = context.getTypeConverter().mandatoryConvertTo(Serializable.class, exchange, body);
                    message.setObject(payload);
                } catch (NoTypeConversionAvailableException e) {
                    // cannot convert to serializable then thrown an exception to avoid sending a null message
                    JMSException cause = new MessageFormatException(e.getMessage());
                    cause.initCause(e);
                    throw cause;
                }
            }
            return message;
        default:
            break;
    }
    return null;
}
Also used : MessageFormatException(javax.jms.MessageFormatException) Serializable(java.io.Serializable) NoTypeConversionAvailableException(org.apache.camel.NoTypeConversionAvailableException) ObjectMessage(javax.jms.ObjectMessage) MapMessage(javax.jms.MapMessage) BytesMessage(javax.jms.BytesMessage) JMSException(javax.jms.JMSException) HashMap(java.util.HashMap) Map(java.util.Map) TextMessage(javax.jms.TextMessage)

Aggregations

MapMessage (javax.jms.MapMessage)30 JMSException (javax.jms.JMSException)23 HashMap (java.util.HashMap)12 Map (java.util.Map)9 TextMessage (javax.jms.TextMessage)9 BytesMessage (javax.jms.BytesMessage)8 Message (javax.jms.Message)8 Session (javax.jms.Session)8 Destination (javax.jms.Destination)7 ObjectMessage (javax.jms.ObjectMessage)7 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)6 Test (org.junit.Test)6 AMQPMessage (org.apache.qpid.qmf2.common.AMQPMessage)5 Connection (javax.jms.Connection)4 MessageProducer (javax.jms.MessageProducer)4 QmfException (org.apache.qpid.qmf2.common.QmfException)4 MessageFormatException (javax.jms.MessageFormatException)3 StreamMessage (javax.jms.StreamMessage)3 QmfData (org.apache.qpid.qmf2.common.QmfData)3 SimpleMessageConverter (org.springframework.jms.support.converter.SimpleMessageConverter)3