Example usage for javax.jms TextMessage getText

List of usage examples for javax.jms TextMessage getText

Introduction

In this page you can find the example usage for javax.jms TextMessage getText.

Prototype


String getText() throws JMSException;

Source Link

Document

Gets the string containing this message's data.

Usage

From source file:nl.nn.adapterframework.extensions.tibco.SendTibcoMessage.java

public String doPipeWithTimeoutGuarded(Object input, IPipeLineSession session) throws PipeRunException {
    Connection connection = null;
    Session jSession = null;//  ww w  .  j  a  v a2  s. co  m
    MessageProducer msgProducer = null;
    Destination destination = null;

    String url_work;
    String authAlias_work;
    String userName_work;
    String password_work;
    String queueName_work;
    String messageProtocol_work;
    int replyTimeout_work;
    String soapAction_work;

    String result = null;

    ParameterValueList pvl = null;
    if (getParameterList() != null) {
        ParameterResolutionContext prc = new ParameterResolutionContext((String) input, session);
        try {
            pvl = prc.getValues(getParameterList());
        } catch (ParameterException e) {
            throw new PipeRunException(this, getLogPrefix(session) + "exception on extracting parameters", e);
        }
    }

    url_work = getParameterValue(pvl, "url");
    if (url_work == null) {
        url_work = getUrl();
    }
    authAlias_work = getParameterValue(pvl, "authAlias");
    if (authAlias_work == null) {
        authAlias_work = getAuthAlias();
    }
    userName_work = getParameterValue(pvl, "userName");
    if (userName_work == null) {
        userName_work = getUserName();
    }
    password_work = getParameterValue(pvl, "password");
    if (password_work == null) {
        password_work = getPassword();
    }
    queueName_work = getParameterValue(pvl, "queueName");
    if (queueName_work == null) {
        queueName_work = getQueueName();
    }
    messageProtocol_work = getParameterValue(pvl, "messageProtocol");
    if (messageProtocol_work == null) {
        messageProtocol_work = getMessageProtocol();
    }
    String replyTimeout_work_str = getParameterValue(pvl, "replyTimeout");
    if (replyTimeout_work_str == null) {
        replyTimeout_work = getReplyTimeout();
    } else {
        replyTimeout_work = Integer.parseInt(replyTimeout_work_str);
    }
    soapAction_work = getParameterValue(pvl, "soapAction");
    if (soapAction_work == null)
        soapAction_work = getSoapAction();

    if (StringUtils.isEmpty(soapAction_work) && !StringUtils.isEmpty(queueName_work)) {
        String[] q = queueName_work.split("\\.");
        if (q.length > 0) {
            if (q[0].equalsIgnoreCase("P2P") && q.length >= 4) {
                soapAction_work = q[3];
            } else if (q[0].equalsIgnoreCase("ESB") && q.length == 8) {
                soapAction_work = q[5] + "_" + q[6];
            } else if (q[0].equalsIgnoreCase("ESB") && q.length > 8) {
                soapAction_work = q[6] + "_" + q[7];
            }
        }
    }

    if (StringUtils.isEmpty(soapAction_work)) {
        log.debug(getLogPrefix(session) + "deriving default soapAction");
        try {
            URL resource = ClassUtils.getResourceURL(this, "/xml/xsl/esb/soapAction.xsl");
            TransformerPool tp = new TransformerPool(resource, true);
            soapAction_work = tp.transform(input.toString(), null);
        } catch (Exception e) {
            log.error(getLogPrefix(session) + "failed to execute soapAction.xsl");
        }
    }

    if (messageProtocol_work == null) {
        throw new PipeRunException(this, getLogPrefix(session) + "messageProtocol must be set");
    }
    if (!messageProtocol_work.equalsIgnoreCase(REQUEST_REPLY)
            && !messageProtocol_work.equalsIgnoreCase(FIRE_AND_FORGET)) {
        throw new PipeRunException(this, getLogPrefix(session) + "illegal value for messageProtocol ["
                + messageProtocol_work + "], must be '" + REQUEST_REPLY + "' or '" + FIRE_AND_FORGET + "'");
    }

    CredentialFactory cf = new CredentialFactory(authAlias_work, userName_work, password_work);
    try {
        TibjmsAdmin admin;
        try {
            admin = TibcoUtils.getActiveServerAdmin(url_work, cf);
        } catch (TibjmsAdminException e) {
            log.debug(getLogPrefix(session) + "caught exception", e);
            admin = null;
        }
        if (admin != null) {
            QueueInfo queueInfo;
            try {
                queueInfo = admin.getQueue(queueName_work);
            } catch (Exception e) {
                throw new PipeRunException(this, getLogPrefix(session) + " exception on getting queue info", e);
            }
            if (queueInfo == null) {
                throw new PipeRunException(this,
                        getLogPrefix(session) + " queue [" + queueName_work + "] does not exist");
            }

            try {
                admin.close();
            } catch (TibjmsAdminException e) {
                log.warn(getLogPrefix(session) + "exception on closing Tibjms Admin", e);
            }
        }

        ConnectionFactory factory = new com.tibco.tibjms.TibjmsConnectionFactory(url_work);
        connection = factory.createConnection(cf.getUsername(), cf.getPassword());
        jSession = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
        destination = jSession.createQueue(queueName_work);

        msgProducer = jSession.createProducer(destination);
        TextMessage msg = jSession.createTextMessage();
        msg.setText(input.toString());
        Destination replyQueue = null;
        if (messageProtocol_work.equalsIgnoreCase(REQUEST_REPLY)) {
            replyQueue = jSession.createTemporaryQueue();
            msg.setJMSReplyTo(replyQueue);
            msg.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT);
            msgProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
            msgProducer.setTimeToLive(replyTimeout_work);
        } else {
            msg.setJMSDeliveryMode(DeliveryMode.PERSISTENT);
            msgProducer.setDeliveryMode(DeliveryMode.PERSISTENT);
        }
        if (StringUtils.isNotEmpty(soapAction_work)) {
            log.debug(
                    getLogPrefix(session) + "setting [SoapAction] property to value [" + soapAction_work + "]");
            msg.setStringProperty("SoapAction", soapAction_work);
        }
        msgProducer.send(msg);
        if (log.isDebugEnabled()) {
            log.debug(getLogPrefix(session) + "sent message [" + msg.getText() + "] " + "to ["
                    + msgProducer.getDestination() + "] " + "msgID [" + msg.getJMSMessageID() + "] "
                    + "correlationID [" + msg.getJMSCorrelationID() + "] " + "replyTo [" + msg.getJMSReplyTo()
                    + "]");
        } else {
            if (log.isInfoEnabled()) {
                log.info(getLogPrefix(session) + "sent message to [" + msgProducer.getDestination() + "] "
                        + "msgID [" + msg.getJMSMessageID() + "] " + "correlationID ["
                        + msg.getJMSCorrelationID() + "] " + "replyTo [" + msg.getJMSReplyTo() + "]");
            }
        }
        if (messageProtocol_work.equalsIgnoreCase(REQUEST_REPLY)) {
            String replyCorrelationId = msg.getJMSMessageID();
            MessageConsumer msgConsumer = jSession.createConsumer(replyQueue,
                    "JMSCorrelationID='" + replyCorrelationId + "'");
            log.debug(getLogPrefix(session) + "] start waiting for reply on [" + replyQueue + "] selector ["
                    + replyCorrelationId + "] for [" + replyTimeout_work + "] ms");
            try {
                connection.start();
                Message rawReplyMsg = msgConsumer.receive(replyTimeout_work);
                if (rawReplyMsg == null) {
                    throw new PipeRunException(this,
                            getLogPrefix(session) + "did not receive reply on [" + replyQueue
                                    + "] replyCorrelationId [" + replyCorrelationId + "] within ["
                                    + replyTimeout_work + "] ms");
                }
                TextMessage replyMsg = (TextMessage) rawReplyMsg;
                result = replyMsg.getText();
            } finally {
            }

        } else {
            result = msg.getJMSMessageID();
        }
    } catch (JMSException e) {
        throw new PipeRunException(this, getLogPrefix(session) + " exception on sending message to Tibco queue",
                e);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                log.warn(getLogPrefix(session) + "exception on closing connection", e);
            }
        }
    }
    return result;
}

From source file:com.tremolosecurity.provisioning.core.ProvisioningEngineImpl.java

@Override
public void onMessage(javax.jms.Message msg) {
    TextMessage fromq = (TextMessage) msg;

    try {//from   ww w  . j a  v  a2 s  .co m

        Gson gson = new Gson();
        SmtpMessage email = gson.fromJson(fromq.getText(), SmtpMessage.class);

        this.sendEmail(email);
        fromq.acknowledge();
        //session.commit();
    } catch (MessagingException | JMSException e) {
        logger.error("Could not send email", e);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintWriter baout = new PrintWriter(baos);
        e.printStackTrace(baout);
        baout.flush();
        baout.close();
        StringBuffer b = new StringBuffer();
        b.append("Could not send email\n").append(new String(baos.toByteArray()));
        throw new RuntimeException(b.toString(), e);

    }

}

From source file:org.openengsb.ports.jms.JMSIncomingPort.java

public void start() {
    simpleMessageListenerContainer = createListenerContainer(receive, new MessageListener() {
        @Override/*from ww w.  j a  v  a  2  s  .c o  m*/
        public void onMessage(Message message) {
            LOGGER.trace("JMS-message recieved. Checking if the type is supported");
            if (!(message instanceof TextMessage)) {
                LOGGER.debug("Received JMS-message is not type of text message.");
                return;
            }
            LOGGER.trace("Received a text message and start parsing");
            TextMessage textMessage = (TextMessage) message;
            String textContent = extractTextFromMessage(textMessage);
            HashMap<String, Object> metadata = new HashMap<String, Object>();
            String result = null;
            try {
                LOGGER.debug("starting filterchain for incoming message");
                result = (String) getFilterChainToUse().filter(textContent, metadata);
            } catch (Exception e) {
                LOGGER.error("an error occured when processing the filterchain", e);
                result = ExceptionUtils.getStackTrace(e);
            }
            Destination replyQueue;
            final String correlationID;
            try {
                if (message.getJMSCorrelationID() == null) {
                    correlationID = message.getJMSMessageID();
                } else {
                    correlationID = message.getJMSCorrelationID();
                }
                replyQueue = message.getJMSReplyTo();
            } catch (JMSException e) {
                LOGGER.warn("error when getting destination queue or correlationid from client message: {}", e);
                return;
            }
            if (replyQueue == null) {
                LOGGER.warn("no replyTo destination specifyed could not send response");
                return;
            }

            new JmsTemplate(connectionFactory).convertAndSend(replyQueue, result, new MessagePostProcessor() {
                @Override
                public Message postProcessMessage(Message message) throws JMSException {
                    message.setJMSCorrelationID(correlationID);
                    return message;
                }
            });
        }

        private String extractTextFromMessage(TextMessage textMessage) {
            try {
                return textMessage.getText();
            } catch (JMSException e) {
                throw new IllegalStateException("Couldn't extract text from jms message", e);
            }
        }

    });
    simpleMessageListenerContainer.start();
}

From source file:org.openanzo.combus.CombusConnection.java

/**
 * Send a request to a destination and wait for a response
 * //from w w  w  .j  a  v a  2  s.c  om
 * @param context
 *            context for this operational call
 * @param destinationName
 *            destination queue for this request
 * @param request
 *            request message
 * @param timeout
 *            timeout for waiting for a response
 * @return response message
 * @throws AnzoException
 *             if there was an exception sending request, or a timeout waiting for a response
 */
public TextMessage requestResponse(IOperationContext context, String destinationName, Message request,
        long timeout) throws AnzoException {
    Destination destination = null;

    if (context.getAttribute(OPTIONS.DATASOURCE) != null) {
        URI datasourceUri = (URI) context.getAttribute(OPTIONS.DATASOURCE);
        Queue defaultDestination = (Queue) destinations.get(destinationName);
        if (datasourceUri.toString().equals("http://openanzo.org/datasource/systemDatasource")) {
            destination = defaultDestination;
        } else {
            String queueNamePrefix = UriGenerator.generateEncapsulatedString("", datasourceUri.toString())
                    + "/";
            try {
                String[] parts = StringUtils.split(defaultDestination.getQueueName(), '/');
                String queue = "services/" + queueNamePrefix + parts[1];
                destination = destinations.get(queue);
                if (destination == null) {
                    destination = session.createQueue(queue);
                    destinations.put(queue, destination);
                }
            } catch (JMSException e) {
                throw new AnzoException(ExceptionConstants.COMBUS.NO_SUCH_DESTINATION, destinationName);
            }
        }
    } else {
        destination = destinations.get(destinationName);
        if (destination == null) {
            throw new AnzoException(ExceptionConstants.COMBUS.NO_SUCH_DESTINATION, destinationName);
        }
    }

    if (context.getAttribute(COMBUS.TIMEOUT) != null) {
        timeout = (Long) context.getAttribute(COMBUS.TIMEOUT);
    }

    String correlationId = context.getOperationId();
    if (correlationId == null) {
        correlationId = UUID.randomUUID().toString();
    }

    try {
        request.setJMSCorrelationID(correlationId);
        request.setJMSReplyTo(tempQueue);
        request.setIntProperty(SerializationConstants.protocolVersion, Constants.VERSION);
        if (context.getOperationPrincipal() != null
                && !context.getOperationPrincipal().getName().equals(this.userName)) {
            request.setStringProperty(SerializationConstants.runAsUser,
                    context.getOperationPrincipal().getName());
        }
        if (context.getAttribute(OPTIONS.PRIORITY) != null) {
            Integer priority = (Integer) context.getAttribute(OPTIONS.PRIORITY);
            request.setJMSPriority(priority);
            messageProducer.setPriority(priority);
        } else {
            messageProducer.setPriority(4);
        }
        if (context.getAttribute(OPTIONS.SKIPCACHE) != null) {
            request.setBooleanProperty(OPTIONS.SKIPCACHE,
                    context.getAttribute(OPTIONS.SKIPCACHE, Boolean.class));
        }
        if (log.isTraceEnabled()) {
            log.trace(LogUtils.COMBUS_MARKER,
                    MessageUtils.prettyPrint(request, "Sending Request: (destination=" + destination + ")"));
        }
        messageProducer.send(destination, request);
    } catch (JMSException jmsex) {
        performDisconnect(true);
        throw new AnzoException(ExceptionConstants.COMBUS.COULD_NOT_PUBLISH, jmsex);
    }
    lock.lock();
    try {
        Collection<TextMessage> messageSet = correlationIdToMessage.remove(correlationId);
        long start = System.currentTimeMillis();
        while (messageSet == null) {
            if (timeout <= 0) {
                try {
                    newMessage.await(2, TimeUnit.SECONDS);
                } catch (InterruptedException ie) {
                    throw new AnzoException(ExceptionConstants.COMBUS.INTERRUPTED, correlationId);
                }
                if (closed || closing) {
                    throw new AnzoException(ExceptionConstants.COMBUS.INTERRUPTED, correlationId);
                }
                messageSet = correlationIdToMessage.remove(correlationId);
            } else {
                try {
                    newMessage.await(timeout, TimeUnit.MILLISECONDS);
                } catch (InterruptedException ie) {
                    throw new AnzoException(ExceptionConstants.COMBUS.INTERRUPTED, correlationId);
                }
                if (closed || closing) {
                    throw new AnzoException(ExceptionConstants.COMBUS.INTERRUPTED, correlationId);
                }
                messageSet = correlationIdToMessage.remove(correlationId);
                if (!connected) {
                    log.error(LogUtils.COMBUS_MARKER, "Request Response failed because connection was closed");
                    throw new AnzoException(ExceptionConstants.COMBUS.JMS_NOT_CONNECTED, correlationId);
                }
                if (messageSet == null && ((timeout > 0) && ((System.currentTimeMillis() - start) > timeout))) {
                    throw new AnzoException(ExceptionConstants.COMBUS.NO_SERVER_RESPONSE, correlationId);
                }
            }
        }
        try {
            TextMessage message = messageSet.iterator().next();
            if (log.isTraceEnabled()) {
                log.trace(LogUtils.COMBUS_MARKER, MessageUtils.prettyPrint(message, "Received Response:"));
            }

            if (message.getBooleanProperty(SerializationConstants.operationFailed)) {
                long errorCodes = message.propertyExists(SerializationConstants.errorTags)
                        ? message.getLongProperty(SerializationConstants.errorCode)
                        : ExceptionConstants.COMBUS.JMS_SERVICE_EXCEPTION;

                // if available, use enumerated args, since these can be reconstruct an AnzoException correctly.
                List<String> args = new ArrayList<String>();
                for (int i = 0; true; i++) {
                    String errorArg = message.getStringProperty(SerializationConstants.errorMessageArg + i);
                    if (errorArg == null) {
                        break;
                    }
                    args.add(errorArg);
                }

                // NOTE: This doesn't really make any sense, but it was here before and it's better to be too verbose than not verbose enough
                // when it comes to error messages, so it stays.  For now at least. -jpbetz
                if (args.isEmpty()) {
                    args.add(message.getText());
                }
                throw new AnzoException(errorCodes, args.toArray(new String[0]));
            }
            /*Object prp = context.getAttribute("populateResponseProperties");
            if (prp != null && ((Boolean) prp)) {
            HashMap<String, Object> props = new HashMap<String, Object>();
            Enumeration<String> keys = message.getPropertyNames();
            while (keys.hasMoreElements()) {
                String key = keys.nextElement();
                props.put(key, message.getObjectProperty(key));
            }
            context.setAttribute("responseProperties", props);
            }*/
            return message;
        } catch (JMSException jmsex) {
            log.debug(LogUtils.COMBUS_MARKER, Messages.formatString(
                    ExceptionConstants.COMBUS.ERROR_PROCESSING_MESSGE, "request response"), jmsex);
        }
        return null;
    } finally {
        lock.unlock();
    }
}

From source file:org.wso2.carbon.appfactory.eventing.jms.AFMessageListener.java

@Override
public void onMessage(Message message) {
    if (log.isDebugEnabled()) {
        if (message instanceof MapMessage) {
            try {
                String messageBody = ((MapMessage) message).getString(TopicPublisher.MESSAGE_BODY);
                log.debug("Received a message:" + messageBody);
            } catch (JMSException e) {
                log.error("Error while getting message content.", e);
            }/* ww w  . j  a va  2s . c  o m*/
        }
    }
    MapMessage mapMessage;
    if (message instanceof MapMessage) {
        mapMessage = (MapMessage) message;
        MessageStore.getInstance().addMessage(this.subscriptionId, mapMessage);
    } else if (message instanceof TextMessage) {
        //Todo:remove this. we only support mapMessages initially and below code is only for testing purpose.
        final TextMessage textMessage = (TextMessage) message;
        mapMessage = new MapMessage() {
            @Override
            public boolean getBoolean(String s) throws JMSException {
                return false; //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public byte getByte(String s) throws JMSException {
                return 0; //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public short getShort(String s) throws JMSException {
                return 0; //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public char getChar(String s) throws JMSException {
                return 0; //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public int getInt(String s) throws JMSException {
                return 0; //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public long getLong(String s) throws JMSException {
                return 0; //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public float getFloat(String s) throws JMSException {
                return 0; //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public double getDouble(String s) throws JMSException {
                return 0; //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public String getString(String s) throws JMSException {
                return textMessage.getText();
            }

            @Override
            public byte[] getBytes(String s) throws JMSException {
                return new byte[0]; //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public Object getObject(String s) throws JMSException {
                return null; //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public Enumeration getMapNames() throws JMSException {
                return null; //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public void setBoolean(String s, boolean b) throws JMSException {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public void setByte(String s, byte b) throws JMSException {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public void setShort(String s, short i) throws JMSException {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public void setChar(String s, char c) throws JMSException {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public void setInt(String s, int i) throws JMSException {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public void setLong(String s, long l) throws JMSException {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public void setFloat(String s, float v) throws JMSException {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public void setDouble(String s, double v) throws JMSException {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public void setString(String s, String s2) throws JMSException {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public void setBytes(String s, byte[] bytes) throws JMSException {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public void setBytes(String s, byte[] bytes, int i, int i2) throws JMSException {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public void setObject(String s, Object o) throws JMSException {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public boolean itemExists(String s) throws JMSException {
                return false; //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public String getJMSMessageID() throws JMSException {
                return textMessage.getJMSMessageID();
            }

            @Override
            public void setJMSMessageID(String s) throws JMSException {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public long getJMSTimestamp() throws JMSException {
                return textMessage.getJMSTimestamp();
            }

            @Override
            public void setJMSTimestamp(long l) throws JMSException {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public byte[] getJMSCorrelationIDAsBytes() throws JMSException {
                return new byte[0]; //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public void setJMSCorrelationIDAsBytes(byte[] bytes) throws JMSException {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public void setJMSCorrelationID(String s) throws JMSException {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public String getJMSCorrelationID() throws JMSException {
                return textMessage.getJMSCorrelationID();
            }

            @Override
            public Destination getJMSReplyTo() throws JMSException {
                return null; //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public void setJMSReplyTo(Destination destination) throws JMSException {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public Destination getJMSDestination() throws JMSException {
                return textMessage.getJMSDestination();
            }

            @Override
            public void setJMSDestination(Destination destination) throws JMSException {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public int getJMSDeliveryMode() throws JMSException {
                return textMessage.getJMSDeliveryMode();
            }

            @Override
            public void setJMSDeliveryMode(int i) throws JMSException {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public boolean getJMSRedelivered() throws JMSException {
                return textMessage.getJMSRedelivered();
            }

            @Override
            public void setJMSRedelivered(boolean b) throws JMSException {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public String getJMSType() throws JMSException {
                return textMessage.getJMSType();
            }

            @Override
            public void setJMSType(String s) throws JMSException {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public long getJMSExpiration() throws JMSException {
                return textMessage.getJMSExpiration();
            }

            @Override
            public void setJMSExpiration(long l) throws JMSException {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public int getJMSPriority() throws JMSException {
                return textMessage.getJMSPriority();
            }

            @Override
            public void setJMSPriority(int i) throws JMSException {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public void clearProperties() throws JMSException {
                textMessage.clearProperties();
            }

            @Override
            public boolean propertyExists(String s) throws JMSException {
                return textMessage.propertyExists(s);
            }

            @Override
            public boolean getBooleanProperty(String s) throws JMSException {
                return false; //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public byte getByteProperty(String s) throws JMSException {
                return 0; //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public short getShortProperty(String s) throws JMSException {
                return 0; //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public int getIntProperty(String s) throws JMSException {
                return 0; //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public long getLongProperty(String s) throws JMSException {
                return 0; //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public float getFloatProperty(String s) throws JMSException {
                return 0; //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public double getDoubleProperty(String s) throws JMSException {
                return 0; //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public String getStringProperty(String s) throws JMSException {
                return null; //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public Object getObjectProperty(String s) throws JMSException {
                return null; //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public Enumeration getPropertyNames() throws JMSException {
                return null; //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public void setBooleanProperty(String s, boolean b) throws JMSException {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public void setByteProperty(String s, byte b) throws JMSException {
                textMessage.setByteProperty(s, b);
            }

            @Override
            public void setShortProperty(String s, short i) throws JMSException {
                textMessage.setShortProperty(s, i);
            }

            @Override
            public void setIntProperty(String s, int i) throws JMSException {
                textMessage.setIntProperty(s, i);
            }

            @Override
            public void setLongProperty(String s, long l) throws JMSException {
                textMessage.setLongProperty(s, l);
            }

            @Override
            public void setFloatProperty(String s, float v) throws JMSException {
                textMessage.setFloatProperty(s, v);
            }

            @Override
            public void setDoubleProperty(String s, double v) throws JMSException {
                textMessage.setDoubleProperty(s, v);
            }

            @Override
            public void setStringProperty(String s, String s2) throws JMSException {
                textMessage.setStringProperty(s, s2);
            }

            @Override
            public void setObjectProperty(String s, Object o) throws JMSException {
                textMessage.setObjectProperty(s, o);
            }

            @Override
            public void acknowledge() throws JMSException {
                textMessage.acknowledge();
            }

            @Override
            public void clearBody() throws JMSException {
                textMessage.clearBody();
            }
        };
        MessageStore.getInstance().addMessage(this.subscriptionId, mapMessage);
    }

}

From source file:prodandes.Prodandes.java

public String receive() throws JMSException {
    TextMessage msg = (TextMessage) mc.receive();
    return msg.getText();
}

From source file:prodandes.Prodandes.java

public void onMessage(Message message) {
    try {//  w w  w  . j  ava2 s  . com
        TextMessage text = (TextMessage) message;
        String respuesta = text.getText();
        String txt = respuesta;
        System.out.println("El mensaje de Jose fue: " + respuesta);
        System.out.println("onMessage");
        System.out.println(respuesta.startsWith("jp-pe"));
        System.out.println(respuesta.equals("jp-pe"));
        if (txt.startsWith("RF18-")) {

            String[] params = txt.split("-");
            String[] fecha = params[1].split("/");
            Calendar c = new GregorianCalendar(Integer.parseInt(fecha[2]), Integer.parseInt(fecha[0]),
                    Integer.parseInt(fecha[1]));

            JSONObject jp = new JSONObject();

            jp.put("fechaEsperada",
                    fecha[2] + "-" + ((fecha[0].length() == 1) ? ("0" + fecha[0]) : fecha[0]) + "-" + fecha[1]);
            jp.put("nombre", params[2]);
            jp.put("cantidad", params[3]);
            jp.put("id_cliente", params[4]);

            JSONObject jO = registrarPedido2(jp);

            Send env = new Send();
            env.enviar("RF18R-" + jO.get("id_pedido") + "-" + jO.get("Respuesta"));
            env.close();
        } else if (txt.startsWith("RF18R-")) {

            buzon.add(txt);
        } else if (txt.equals("jp-pe")) {
            System.out.println("Entro a jp-pe");
            Send env = new Send();
            env.enviar(darEtapasCuentaJose());
            env.close();
        } else if (txt.startsWith("jp-agr")) {
            System.out.println("Entro a agregar de Jose a Pacho");
            String[] arreglo = txt.split(":");
            insertarRegEtapaEstacionJose(arreglo[2], Integer.parseInt(arreglo[1]));
        } else if (txt.startsWith("jp-del")) {
            System.out.println("Entro a eliminar de Jose a Pacho");
            String[] arreglo = txt.split(":");
            borrarRegEtapaEstacionJose(arreglo[2], Integer.parseInt(arreglo[1]));
        } else if (txt.startsWith("jp-x")) {
            System.out.println("Entro a jp-x");
            buzon.add(txt);
            System.out.println("Se anade al buzon: " + txt);
            System.out.println("Tamano buzon");
            System.out.println(buzon.size());
        } else if (txt.startsWith("jp-r")) {
            System.out.println("Entro a jp-r");
            buzon.add(txt);
            System.out.println("Se anade al buzon: " + txt);
            System.out.println("Tamano buzon");
            System.out.println(buzon.size());
        } else if (txt.startsWith("jp-ret")) {
            System.out.println("Entro a jp-ret");
            buzon.add(txt);
            System.out.println("Se anade al buzon: " + txt);
            System.out.println("Tamano buzon");
            System.out.println(buzon.size());
        } else if (txt.startsWith("RFC12R$")) {
            System.out.println("Entro a RFC12R$");
            buzon.add(txt);
        } else if (txt.startsWith("RC12-")) {
            System.out.println("Entro a RC12-");
            //RC12-solicitud-id-fechaInicial-FechaFinal
            String s[] = txt.split("-");
            String criterio = s[1];
            String valor = s[2];
            String fecha[] = s[3].split("/");
            Calendar c = new GregorianCalendar(Integer.parseInt(fecha[2]), Integer.parseInt(fecha[0]),
                    Integer.parseInt(fecha[1]));
            Date fechaI = c.getTime();
            fecha = s[4].split("/");
            c = new GregorianCalendar(Integer.parseInt(fecha[2]), Integer.parseInt(fecha[0]),
                    Integer.parseInt(fecha[1]));
            Date fechaF = c.getTime();

            JSONObject jParam = new JSONObject();
            jParam.put("criterio", criterio);
            jParam.put("valor", valor);
            jParam.put("fecha1", fechaI);
            jParam.put("fecha2", fechaF);
            String mensaje = consultarEtapasRangoFechaRFC8y9AEnviar(jParam);
            System.out.println("Respuesta a enviar RFC12: " + mensaje);
            //Enviar mis etapas
            Send send = new Send();
            send.enviar("RFC12$" + mensaje);
            send.close();

        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.openanzo.combus.CombusConnection.java

/**
 * Send a request to a destination and wait for a response
 * /* ww w .  j  a v a2s. c om*/
 * @param context
 *            context for this operational call
 * @param destinationName
 *            destination queue for this request
 * @param request
 *            request message
 * @param timeout
 *            timeout for waiting for a response
 * @param messageHandler
 *            the handler of multiple messages
 * @throws AnzoException
 *             if there was an exception sending request, or a timeout waiting for a response
 */
public void requestMultipleResponse(IOperationContext context, String destinationName, Message request,
        long timeout, IMessageHandler messageHandler) throws AnzoException {
    Destination destination = null;
    if (context.getAttribute(OPTIONS.DATASOURCE) != null) {
        URI datasourceUri = (URI) context.getAttribute(OPTIONS.DATASOURCE);
        Queue defaultDestination = (Queue) destinations.get(destinationName);
        if (datasourceUri.toString().equals("http://openanzo.org/datasource/systemDatasource")) {
            destination = defaultDestination;
        } else {
            String queueNamePrefix = UriGenerator.generateEncapsulatedString("", datasourceUri.toString())
                    + "/";
            try {
                String[] parts = StringUtils.split(defaultDestination.getQueueName(), '/');
                String queue = "services/" + queueNamePrefix + parts[1];
                destination = destinations.get(queue);
                if (destination == null) {
                    destination = session.createQueue(queue);
                    destinations.put(queue, destination);
                }
            } catch (JMSException e) {
                throw new AnzoException(ExceptionConstants.COMBUS.NO_SUCH_DESTINATION, destinationName);
            }
        }
    } else {
        destination = destinations.get(destinationName);
        if (destination == null) {
            throw new AnzoException(ExceptionConstants.COMBUS.NO_SUCH_DESTINATION, destinationName);
        }
    }
    String correlationId = context.getOperationId();
    if (correlationId == null) {
        correlationId = UUID.randomUUID().toString();
    }

    try {
        request.setJMSCorrelationID(correlationId);
        request.setJMSReplyTo(tempQueue);
        request.setIntProperty(SerializationConstants.protocolVersion, Constants.VERSION);
        if (context.getOperationPrincipal() != null
                && !context.getOperationPrincipal().getName().equals(this.userName)) {
            request.setStringProperty(SerializationConstants.runAsUser,
                    context.getOperationPrincipal().getName());
        }
        if (context.getAttribute(OPTIONS.PRIORITY) != null) {
            Integer priority = (Integer) context.getAttribute(OPTIONS.PRIORITY);
            request.setJMSPriority(priority);
            messageProducer.setPriority(priority);
        } else {
            messageProducer.setPriority(4);
        }
        if (context.getAttribute(OPTIONS.SKIPCACHE) != null) {
            request.setBooleanProperty(OPTIONS.SKIPCACHE,
                    context.getAttribute(OPTIONS.SKIPCACHE, Boolean.class));
        }
        if (context.getAttribute(OPTIONS.INCLUDEMETADATAGRAPHS) != null) {
            request.setBooleanProperty(OPTIONS.INCLUDEMETADATAGRAPHS,
                    context.getAttribute(OPTIONS.INCLUDEMETADATAGRAPHS, Boolean.class));
        }
        if (log.isTraceEnabled()) {
            log.trace(LogUtils.COMBUS_MARKER,
                    MessageUtils.prettyPrint(request, "Sending Request: (destination=" + destination + ")"));
        }
        messageProducer.send(destination, request);
    } catch (JMSException jmsex) {
        performDisconnect(true);
        throw new AnzoException(ExceptionConstants.COMBUS.COULD_NOT_PUBLISH, jmsex);
    }
    lock.lock();
    try {
        long start = System.currentTimeMillis();
        boolean done = false;
        int seq = 0;
        while (!done) {
            Collection<TextMessage> messageSet = correlationIdToMessage.remove(correlationId);
            while (messageSet == null) {
                if (timeout <= 0) {
                    try {
                        newMessage.await(2, TimeUnit.SECONDS);
                    } catch (InterruptedException ie) {
                        throw new AnzoException(ExceptionConstants.COMBUS.INTERRUPTED, correlationId);
                    }
                    if (closed || closing) {
                        throw new AnzoException(ExceptionConstants.COMBUS.INTERRUPTED, correlationId);
                    }
                    messageSet = correlationIdToMessage.remove(correlationId);
                } else {
                    try {
                        newMessage.await(timeout, TimeUnit.MILLISECONDS);
                    } catch (InterruptedException ie) {
                        throw new AnzoException(ExceptionConstants.COMBUS.INTERRUPTED, correlationId);
                    }
                    if (closed || closing) {
                        throw new AnzoException(ExceptionConstants.COMBUS.INTERRUPTED, correlationId);
                    }
                    messageSet = correlationIdToMessage.remove(correlationId);
                    if (!connected) {
                        log.error(LogUtils.COMBUS_MARKER, Messages.formatString(
                                ExceptionConstants.COMBUS.ERROR_PROCESSING_MESSGE, "connection closed"));
                        throw new AnzoException(ExceptionConstants.COMBUS.JMS_NOT_CONNECTED, correlationId);
                    }
                    if (messageSet == null
                            && ((timeout > -1) && ((System.currentTimeMillis() - start) > timeout))) {
                        throw new AnzoException(ExceptionConstants.COMBUS.NO_SERVER_RESPONSE, correlationId);
                    }
                }

            }
            try {
                for (TextMessage message : messageSet) {
                    if (log.isTraceEnabled()) {
                        log.trace(LogUtils.COMBUS_MARKER,
                                MessageUtils.prettyPrint(message, "Recieved Response:"));
                    }
                    if (message.propertyExists("done")) {
                        done = message.getBooleanProperty("done");
                    } else {
                        done = true;
                    }
                    if (message.propertyExists("sequence")) {
                        int sequence = message.getIntProperty("sequence");
                        if (sequence != seq) {
                            throw new AnzoException(ExceptionConstants.COMBUS.NO_SERVER_RESPONSE,
                                    correlationId);
                        } else {
                            seq++;
                        }
                    }

                    int totalSize = 0;
                    if (message.propertyExists(SerializationConstants.totalSolutions)) {
                        totalSize = message.getIntProperty(SerializationConstants.totalSolutions);
                    }
                    if (message.getBooleanProperty(SerializationConstants.operationFailed)) {
                        long errorCodes = message.propertyExists(SerializationConstants.errorTags)
                                ? message.getLongProperty(SerializationConstants.errorCode)
                                : ExceptionConstants.COMBUS.JMS_SERVICE_EXCEPTION;

                        // if available, use enumerated args, since these can be reconstruct an AnzoException correctly.
                        List<String> args = new ArrayList<String>();
                        for (int i = 0; true; i++) {
                            String errorArg = message
                                    .getStringProperty(SerializationConstants.errorMessageArg + i);
                            if (errorArg == null) {
                                break;
                            }
                            args.add(errorArg);
                        }

                        // NOTE: This doesn't really make any sense, but it was here before and it's better to be too verbose than not verbose enough
                        // when it comes to error messages, so it stays.  For now at least. -jpbetz
                        if (args.isEmpty()) {
                            args.add(message.getText());
                        }
                        throw new AnzoException(errorCodes, args.toArray(new String[0]));
                    } else {
                        messageHandler.handleMessage(message, seq, done, totalSize);
                    }
                }
            } catch (JMSException jmsex) {
                log.debug(LogUtils.COMBUS_MARKER, Messages.formatString(
                        ExceptionConstants.COMBUS.ERROR_PROCESSING_MESSGE, "request multiple response"), jmsex);
            }
        }
    } finally {
        lock.unlock();
    }
}