Example usage for javax.jms JMSException getMessage

List of usage examples for javax.jms JMSException getMessage

Introduction

In this page you can find the example usage for javax.jms JMSException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.sakaiproject.nakamura.email.outgoing.LiteOutgoingEmailMessageListener.java

@Activate
@Modified//from ww  w  . ja  v  a2  s .  com
protected void activate(ComponentContext ctx) {
    @SuppressWarnings("rawtypes")
    Dictionary props = ctx.getProperties();

    Integer _maxRetries = PropertiesUtil.toInteger(props.get(MAX_RETRIES), -1);
    if (_maxRetries > -1) {
        if (diff(maxRetries, _maxRetries)) {
            maxRetries = _maxRetries;
        }
    } else {
        LOGGER.error("Maximum times to retry messages not set.");
    }

    Integer _retryInterval = PropertiesUtil.toInteger(props.get(RETRY_INTERVAL), -1);
    if (_retryInterval > -1) {
        if (diff(_retryInterval, retryInterval)) {
            retryInterval = _retryInterval;
        }
    } else {
        LOGGER.error("SMTP retry interval not set.");
    }

    if (maxRetries * retryInterval < 4320 /* minutes in 3 days */) {
        LOGGER.warn("SMTP retry window is very short.");
    }

    Integer _smtpPort = PropertiesUtil.toInteger(props.get(SMTP_PORT), -1);
    boolean validPort = _smtpPort != null && _smtpPort >= 0 && _smtpPort <= 65535;
    if (validPort) {
        if (diff(smtpPort, _smtpPort)) {
            smtpPort = _smtpPort;
        }
    } else {
        LOGGER.error("Invalid port set for SMTP");
    }

    String _smtpServer = PropertiesUtil.toString(props.get(SMTP_SERVER), "");
    if (!StringUtils.isBlank(_smtpServer)) {
        if (diff(smtpServer, _smtpServer)) {
            smtpServer = _smtpServer;
        }
    } else {
        LOGGER.error("No SMTP server set");
    }

    String _replyAsAddress = PropertiesUtil.toString(props.get(REPLY_AS_ADDRESS), "");
    if (!StringUtils.isBlank(_replyAsAddress)) {
        if (diff(replyAsAddress, _replyAsAddress)) {
            replyAsAddress = _replyAsAddress;
        }
    } else {
        LOGGER.error("No reply-as email address set");
    }

    String _replyAsName = PropertiesUtil.toString(props.get(REPLY_AS_NAME), "");
    if (!StringUtils.isBlank(_replyAsName)) {
        if (diff(replyAsName, _replyAsName)) {
            replyAsName = _replyAsName;
        }
    } else {
        LOGGER.error("No reply-as email name set");
    }

    useTls = PropertiesUtil.toBoolean(props.get(SMTP_USE_TLS), false);
    useSsl = PropertiesUtil.toBoolean(props.get(SMTP_USE_SSL), false);
    authUser = PropertiesUtil.toString(props.get(SMTP_AUTH_USER), "");
    authPass = PropertiesUtil.toString(props.get(SMTP_AUTH_PASS), "");

    try {
        connection = connFactoryService.getDefaultConnectionFactory().createConnection();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue dest = session.createQueue(QUEUE_NAME);
        MessageConsumer consumer = session.createConsumer(dest);
        consumer.setMessageListener(this);
        connection.start();
    } catch (JMSException e) {
        LOGGER.error(e.getMessage(), e);
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e1) {
            }
        }
    }
}

From source file:com.googlecode.fascinator.common.PythonUtils.java

/*****
 * Try to closing any objects that require closure
 * /* ww w  . ja  va2 s  .com*/
 */
public void shutdown() {
    if (connection != null) {
        try {
            connection.close();
        } catch (JMSException jmse) {
            log.warn("Failed to close connection: {}", jmse.getMessage());
        }
    }
    if (session != null) {
        try {
            session.close();
        } catch (JMSException jmse) {
            log.warn("Failed to close session: {}", jmse.getMessage());
        }
    }
    if (producer != null) {
        try {
            producer.close();
        } catch (JMSException jmse) {
            log.warn("Failed to close producer: {}", jmse.getMessage());
        }
    }
    if (access != null) {
        try {
            access.shutdown();
        } catch (PluginException ex) {
            log.warn("Failed shutting down access control manager:", ex);
        }
    }
}

From source file:net.timewalker.ffmq4.local.FFMQEngine.java

public void deploy() throws JMSException {
    try {/*from  w  ww  .  j  av  a2s  . co  m*/
        synchronized (deployedEngines) {
            if (deployed)
                throw new FFMQException("Local engine is already deployed.", "ENGINE_ALREADY_DEPLOYED");

            log.info("Deploying local engine '" + name + "'");
            this.destinationDefinitionProvider.loadExistingDefinitions();
            this.destinationTemplateProvider.loadExistingTemplates();
            this.templateMappingProvider.loadMappings();

            // AsyncTaskManager - Notification
            this.notificationAsyncTaskManager = new AsyncTaskManager("AsyncTaskManager-notification-" + name,
                    setup.getNotificationAsyncTaskManagerThreadPoolMinSize(),
                    setup.getNotificationAsyncTaskManagerThreadPoolMaxIdle(),
                    setup.getNotificationAsyncTaskManagerThreadPoolMaxSize());

            // AsyncTaskManager - Delivery
            this.deliveryAsyncTaskManager = new AsyncTaskManager("AsyncTaskManager-delivery-" + name,
                    setup.getDeliveryAsyncTaskManagerThreadPoolMinSize(),
                    setup.getDeliveryAsyncTaskManagerThreadPoolMaxIdle(),
                    setup.getDeliveryAsyncTaskManagerThreadPoolMaxSize());

            // AsyncTaskManager - Disk I/O
            this.diskIOAsyncTaskManager = new AsyncTaskManager("AsyncTaskManager-diskIO-" + name,
                    setup.getDiskIOAsyncTaskManagerThreadPoolMinSize(),
                    setup.getDiskIOAsyncTaskManagerThreadPoolMaxIdle(),
                    setup.getDiskIOAsyncTaskManagerThreadPoolMaxSize());

            // Delete old temporary destinations
            deleteTemporaryDestinations();

            // Deploy existing destinations
            if (setup.doDeployQueuesOnStartup())
                deployExistingQueues();
            if (setup.doDeployTopicsOnStartup())
                deployExistingTopics();

            deployedEngines.put(name, this);
            deployed = true;
            log.info("Engine deployed (vm://" + name + ")");
        }

        if (listener != null)
            listener.engineDeployed();
    } catch (JMSException e) {
        log.error("Cannot deploy engine : " + e.getMessage());
        throw e;
    }
}

From source file:tld.yourname.jms.server.JMSServer.java

/**
 *
 * @param aArgs/*from  w  w  w  .ja va 2  s  .  co  m*/
 * @return
 */
public JWSEndPoint start(String[] aArgs) {
    // set up log4j logging
    // later this should be read from a shared log4j properties or xml file!
    Properties lProps = new Properties();
    lProps.setProperty("log4j.rootLogger", "INFO, console");
    lProps.setProperty("log4j.logger.org.apache.activemq", "WARN");
    lProps.setProperty("log4j.logger.org.springframework", "WARN");
    lProps.setProperty("log4j.logger.org.apache.xbean", "WARN");
    lProps.setProperty("log4j.logger.org.apache.camel", "INFO");
    lProps.setProperty("log4j.logger.org.eclipse.jetty", "WARN");
    lProps.setProperty("log4j.appender.console", "org.apache.log4j.ConsoleAppender");
    lProps.setProperty("log4j.appender.console.layout", "org.apache.log4j.PatternLayout");
    lProps.setProperty("log4j.appender.console.layout.ConversionPattern",
            // "%p: %m%n"
            "%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p - %C{1}: %m%n");
    // set here the jWebSocket log level:
    lProps.setProperty("log4j.logger.org.jwebsocket", "DEBUG");
    lProps.setProperty("log4j.appender.console.threshold", "DEBUG");
    PropertyConfigurator.configure(lProps);

    final JWSAutoSelectAuthenticator lAuthenticator = new JWSAutoSelectAuthenticator();
    final JWSOAuthAuthenticator lOAuthAuthenticator = new JWSOAuthAuthenticator();
    final JWSLDAPAuthenticator lLDAPAuthenticator = new JWSLDAPAuthenticator();

    mLog.info("jWebSocket JMS Gateway Server Endpoint");
    Configuration lConfig = null;
    boolean lConfigLoaded;
    try {
        // try to load properties files from local folder or jar
        String lPath = "JMSServer.properties";
        mLog.debug("Trying to read properties from: " + lPath);
        lConfig = new PropertiesConfiguration(lPath);
    } catch (ConfigurationException ex) {
    }
    if (null == lConfig) {
        try {
            // try to load properties files from JWEBSOCKET_HOME/conf/JMSPlugIn
            String lPath = Tools.expandEnvVarsAndProps("/private/JMSServer.properties");
            // String lPath = Tools.expandEnvVarsAndProps("${JWEBSOCKET_HOME}conf/JMSPlugIn/JMSServer.properties");
            mLog.debug("Tring to read properties from: " + lPath);
            lConfig = new PropertiesConfiguration(lPath);
        } catch (ConfigurationException ex) {
        }
    }
    if (null == lConfig) {
        mLog.error("Configuration file could not be opened.");
        return null;
    }

    // the URL of the message broker
    String lBrokerURL = lConfig.getString("BrokerURL", "tcp://127.0.0.1:61616");
    // "failover:(tcp://0.0.0.0:61616,tcp://127.0.0.1:61616)?initialReconnectDelay=100&randomize=false";
    // the name of the JMS Gateway topic
    String lGatewayTopic = lConfig.getString("GatewayTopic", "org.jwebsocket.jms.gateway");
    // endpoint id of JMS Gateway
    String lGatewayId = lConfig.getString("GatewayId", "org.jwebsocket.jms.gateway");
    String lEndPointId = lConfig.getString("EndPointId", UUID.randomUUID().toString());

    // get authentication information against jWebSocket
    final String lJWSUsername = lConfig.getString("JWSUsername");
    final String lJWSPassword = lConfig.getString("JWSPassword");
    final boolean lFullTextLogging = lConfig.getBoolean("FullTextLogging", false);

    // set up OAuth Authenticator
    boolean lUseOAuth = lConfig.getBoolean("UseOAuth", false);

    String lOAuthHost = lConfig.getString("OAuthHost");
    String lOAuthAppId = lConfig.getString("OAuthAppId");
    String lOAuthAppSecret = lConfig.getString("OAuthAppSecret");
    String lOAuthUsername = lConfig.getString("OAuthUsername");
    String lOAuthPassword = lConfig.getString("OAuthPassword");
    long lOAuthTimeout = lConfig.getLong("OAuthTimeout", 5000);

    lUseOAuth = lUseOAuth && null != lOAuthHost && null != lOAuthAppId && null != lOAuthAppSecret
            && null != lOAuthUsername && null != lOAuthPassword;

    if (lUseOAuth) {
        lOAuthAuthenticator.init(lOAuthHost, lOAuthAppId, lOAuthAppSecret, lOAuthTimeout);
        lAuthenticator.addAuthenticator(lOAuthAuthenticator);
    }

    // set up LDAP Authenticator
    boolean lUseLDAP = lConfig.getBoolean("UseLDAP", false);

    String lLDAPURL = lConfig.getString("LDAPURL");
    String lBaseDNGroups = lConfig.getString("BaseDNGroups");
    String lBaseDNUsers = lConfig.getString("BaseDNUsers");

    if (lUseLDAP) {
        lLDAPAuthenticator.init(lLDAPURL, lBaseDNGroups, lBaseDNUsers);
        lAuthenticator.addAuthenticator(lLDAPAuthenticator);
    }

    // TODO: Validate config data here!
    lConfigLoaded = true;

    if (!lConfigLoaded) {
        mLog.error("Config not loaded.");
        System.exit(1);
    }

    mLog.info("Using: " + lBrokerURL + ", " + "topic: " + lGatewayTopic + ", " + "gateway-id: " + lGatewayId
            + ", " + "endpoint-id: " + lEndPointId);

    // todo: Comment that for production purposes
    JMSLogging.setFullTextLogging(lFullTextLogging);

    // instantiate a new jWebSocket JMS Gateway Client
    try {
        lJWSEndPoint = JWSEndPoint.getInstance(lBrokerURL, lGatewayTopic, // gateway topic
                lGatewayId, // gateway endpoint id
                lEndPointId, // unique node id
                5, // thread pool size, messages being processed concurrently
                JMSEndPoint.TEMPORARY // durable (for servers) or temporary (for clients)
        );
    } catch (JMSException lEx) {
        mLog.fatal("JMSEndpoint could not be instantiated: " + lEx.getMessage());
        System.exit(0);
    }

    lJWSEndPoint.addRequestListener("org.jwebsocket.jms.gateway", "welcome",
            new JWSMessageListener(lJWSEndPoint) {
                @Override
                public void processToken(String aSourceId, Token aToken) {
                    mLog.info("Received 'welcome', authenticating against jWebSocket...");
                    Token lToken = TokenFactory.createToken("org.jwebsocket.plugins.system", "login");
                    lToken.setString("username", lJWSUsername);
                    lToken.setString("password", lJWSPassword);
                    sendToken(aSourceId, lToken);
                }
            });

    // on response of the login...
    lJWSEndPoint.addResponseListener("org.jwebsocket.plugins.system", "login",
            new JWSMessageListener(lJWSEndPoint) {
                @Override
                public void processToken(String aSourceId, Token aToken) {
                    int lCode = aToken.getInteger("code", -1);
                    if (0 == lCode) {
                        if (mLog.isInfoEnabled()) {
                            mLog.info("Authentication against jWebSocket successful.");
                        }
                    } else {
                        mLog.error("Authentication against jWebSocket failed!");
                    }
                }
            });

    // on response of the login...
    lJWSEndPoint.addRequestListener("org.jwebsocket.jms.demo", "getUser", new JWSMessageListener(lJWSEndPoint) {
        @Override
        public void processToken(String aSourceId, Token aToken) {
            String lPayload = aToken.getString("payload");
            if (mLog.isInfoEnabled()) {
                mLog.info("Processing 'getUser'...");
            }
        }
    });

    // on response of the login...
    lJWSEndPoint.addRequestListener("org.jwebsocket.jms.demo", "echo", new JWSMessageListener(lJWSEndPoint) {
        @Override
        public void processToken(String aSourceId, Token aToken) {
            String lPayload = aToken.getString("payload");
            if (mLog.isInfoEnabled()) {
                mLog.info("Processing 'demo1 with Payload '" + lPayload + "'");
            }
            Map<String, Object> lAdditionalResults = new FastMap<String, Object>();
            lAdditionalResults.putAll(aToken.getMap());
            // lAdditionalResults.remove("sourceId");
            lAdditionalResults.remove("payload");
            lJWSEndPoint.respondPayload(aToken, 0, // return code
                    "Ok", // return message
                    lAdditionalResults, aToken.getString("payload"));
        }
    });

    // on response of the login...
    lJWSEndPoint.addRequestListener("org.jwebsocket.jms.demo", "testProgress",
            new JWSMessageListener(lJWSEndPoint) {
                @Override
                @SuppressWarnings("SleepWhileInLoop")
                public void processToken(String aSourceId, Token aToken) {
                    int lMax = 10;
                    for (int lIdx = 0; lIdx < lMax; lIdx++) {
                        mLog.debug("Progress iteration " + lIdx + "...");
                        try {
                            Thread.sleep(333);
                        } catch (InterruptedException lEx) {
                        }
                        lJWSEndPoint.sendProgress(aToken, ((lIdx + 1.0) / lMax) * 100, 0, "Iteration #" + lIdx,
                                null);
                    }
                    lJWSEndPoint.respondPayload(aToken, 0, // return code
                            "Ok", // return message
                            null, aToken.getString("payload"));
                }
            });

    // ...
    lJWSEndPoint.addRequestListener("org.jwebsocket.jms.demo", "testCaughtException",
            new JWSMessageListener(lJWSEndPoint) {
                @Override
                public void processToken(String aSourceId, Token aToken) {
                    mLog.debug("Testing caught exception...");
                    // provoke null pointer exception and DO catch it for test purposes
                    int a = 1;
                    int b = 0;
                    try {
                        int c = a / b;
                        lJWSEndPoint.respondPayload(aToken, 0, // return code
                                "Ok", // return message
                                null, aToken.getString("payload"));
                    } catch (Exception Ex) {
                        lJWSEndPoint.respondPayload(aToken, -1, // return code
                                Ex.getClass().getSimpleName() + ": " + Ex.getMessage(), // return message
                                null, aToken.getString("payload"));
                    }
                }
            });

    // ...
    lJWSEndPoint.addRequestListener("org.jwebsocket.jms.demo", "testUncaughtException",
            new JWSMessageListener(lJWSEndPoint) {
                @Override
                public void processToken(String aSourceId, Token aToken) {
                    mLog.debug("Testing uncaught exception...");
                    // provoke null pointer exception and do NOT catch it for test purposes
                    int a = 1;
                    int b = 0;
                    int c = a / b;

                    lJWSEndPoint.respondPayload(aToken, 0, // return code
                            "Ok", // return message
                            null, aToken.getString("payload"));
                }
            });

    // test for the OAuth interface
    lJWSEndPoint.addRequestListener("org.jwebsocket.jms.demo", "testOAuth",
            new JWSMessageListener(lJWSEndPoint) {
                @Override
                public void processToken(String aSourceId, Token aToken) {

                    Map<String, Object> lArgs = new FastMap<String, Object>();

                    String lUsername;
                    int lCode = 0;
                    String lMessage = "Ok";
                    try {
                        lUsername = lOAuthAuthenticator.authToken(aToken);
                        if (null == lUsername) {
                            lCode = -1;
                            lMessage = "User could not be authenticated!";
                        } else {
                            lArgs.put("username", lUsername);
                        }
                    } catch (JMSEndpointException ex) {
                        lCode = -1;
                        lMessage = ex.getClass().getSimpleName() + " on authentication: " + ex.getMessage();
                    }

                    lJWSEndPoint.respondPayload(aToken, lCode, // return code
                            lMessage, // return message
                            lArgs, // additional result fields
                            null); // payload
                }
            });

    // test for the LDAP interface
    lJWSEndPoint.addRequestListener("org.jwebsocket.jms.demo", "testLDAP",
            new JWSMessageListener(lJWSEndPoint) {
                @Override
                public void processToken(String aSourceId, Token aToken) {

                    Map<String, Object> lArgs = new FastMap<String, Object>();

                    String lUsername;
                    int lCode = 0;
                    String lMessage = "Ok";
                    try {
                        lUsername = lLDAPAuthenticator.authToken(aToken);
                        if (null == lUsername) {
                            lCode = -1;
                            lMessage = "User could not be authenticated!";
                        } else {
                            lArgs.put("username", lUsername);
                        }
                    } catch (JMSEndpointException ex) {
                        lCode = -1;
                        lMessage = ex.getClass().getSimpleName() + " on authentication: " + ex.getMessage();
                    }

                    lJWSEndPoint.respondPayload(aToken, lCode, // return code
                            lMessage, // return message
                            lArgs, // additional result fields
                            null); // payload
                }
            });

    // test for the auto authentication interface
    lJWSEndPoint.addRequestListener("org.jwebsocket.jms.demo", "testAuth",
            new JWSMessageListener(lJWSEndPoint) {
                @Override
                public void processToken(String aSourceId, Token aToken) {

                    mLog.debug("Testing auto authenticator...");
                    Map<String, Object> lArgs = new FastMap<String, Object>();

                    String lUsername;
                    int lCode = 0;
                    String lMessage = "Ok";
                    try {
                        checkADUsername(aToken);
                        lUsername = lAuthenticator.authToken(aToken);
                        if (null == lUsername) {
                            lCode = -1;
                            lMessage = "User could not be authenticated!";
                        } else {
                            lArgs.put("username", lUsername);
                        }
                    } catch (JMSEndpointException lEx) {
                        lCode = -1;
                        lMessage = lEx.getClass().getSimpleName() + " on auto authentication: "
                                + lEx.getMessage();
                    }

                    lJWSEndPoint.respondPayload(aToken, lCode, // return code
                            lMessage, // return message
                            lArgs, // additional result fields
                            null); // payload
                }
            });

    lJWSEndPoint.addRequestListener("tld.yourname.jms", "transferFile", new JWSMessageListener(lJWSEndPoint) {
        @Override
        public void processToken(String aSourceId, Token aToken) {
            // here you can get the additional arguments
            mLog.info("Received 'transferFile' with additional args" + " (arg1=" + aToken.getString("arg1")
                    + " (arg2=" + aToken.getString("arg2") + ")...");
            // here you get the payload from the requester
            String lPayload = aToken.getString("payload");
            // parse the JSON payload into a Token (for simpler processing)
            Token lToken = JSONProcessor.JSONStringToToken(lPayload);
            // extract the base64 and compressed file contents into Strings 
            // (it's a text message)
            // String lBase64Encoded = lToken.getString("fileAsBase64");
            String lBase64Zipped = lToken.getString("fileAsZip");

            // specify the target file
            File lFile = new File("Apache License 2.0 (copy).txt");
            try {
                // take the zipped version of the file... 
                byte[] lBA = Tools.unzip(lBase64Zipped.getBytes("UTF-8"), Boolean.TRUE);
                // and save it to the hard disk
                FileUtils.writeByteArrayToFile(lFile, lBA);
            } catch (Exception lEx) {
                mLog.error("Demo file " + lFile.getAbsolutePath() + " could not be saved!");
            }
        }
    });

    // add a high level listener to listen in coming messages
    lJWSEndPoint.addRequestListener("org.jwebsocket.jms.demo", "helloWorld",
            new JWSMessageListener(lJWSEndPoint) {
                @Override
                public void processToken(String aSourceId, Token aToken) {
                    mLog.info("Received 'helloWorld'...");
                    lJWSEndPoint.respondPayload(aToken.getString("sourceId"), aToken, 0, // return code
                            "Ok", // return message
                            null, // here you can add additional results beside the payload
                            "Hello World!");
                }
            });

    // start the endpoint all all listener have been assigned
    lJWSEndPoint.start();
    return lJWSEndPoint;
}

From source file:hermes.impl.DefaultXMLHelper.java

public Message createMessage(MessageFactory hermes, XMLMessage message)
        throws JMSException, IOException, ClassNotFoundException, DecoderException {
    try {//ww w  . ja v  a2s .c o m
        Message rval = hermes.createMessage();

        if (message instanceof XMLTextMessage) {
            rval = hermes.createTextMessage();

            XMLTextMessage textMessage = (XMLTextMessage) message;
            TextMessage textRval = (TextMessage) rval;

            if (BASE64_CODEC.equals(textMessage.getCodec())) {
                byte[] bytes = base64EncoderTL.get().decode(textMessage.getText().getBytes());
                textRval.setText(new String(bytes, "ASCII"));
            } else {
                textRval.setText(textMessage.getText());
            }
        } else if (message instanceof XMLMapMessage) {
            rval = hermes.createMapMessage();

            XMLMapMessage mapMessage = (XMLMapMessage) message;
            MapMessage mapRval = (MapMessage) rval;

            for (Iterator iter = mapMessage.getBodyProperty().iterator(); iter.hasNext();) {
                final Property property = (Property) iter.next();

                if (property.getValue() == null) {
                    mapRval.setObject(property.getName(), null);
                } else if (property.getType().equals(String.class.getName())) {
                    mapRval.setString(property.getName(), property.getValue());
                } else if (property.getType().equals(Long.class.getName())) {
                    mapRval.setLong(property.getName(), Long.parseLong(property.getValue()));
                } else if (property.getType().equals(Double.class.getName())) {
                    mapRval.setDouble(property.getName(), Double.parseDouble(property.getValue()));
                } else if (property.getType().equals(Boolean.class.getName())) {
                    mapRval.setBoolean(property.getName(), Boolean.getBoolean(property.getValue()));
                } else if (property.getType().equals(Character.class.getName())) {
                    mapRval.setChar(property.getName(), property.getValue().charAt(0));
                } else if (property.getType().equals(Short.class.getName())) {
                    mapRval.setShort(property.getName(), Short.parseShort(property.getValue()));
                } else if (property.getType().equals(Integer.class.getName())) {
                    mapRval.setInt(property.getName(), Integer.parseInt(property.getValue()));
                }
            }
        } else if (message instanceof XMLBytesMessage) {
            rval = hermes.createBytesMessage();

            XMLBytesMessage bytesMessage = (XMLBytesMessage) message;
            BytesMessage bytesRval = (BytesMessage) rval;

            bytesRval.writeBytes(base64EncoderTL.get().decode(bytesMessage.getBytes().getBytes()));
        } else if (message instanceof XMLObjectMessage) {
            rval = hermes.createObjectMessage();

            XMLObjectMessage objectMessage = (XMLObjectMessage) message;
            ObjectMessage objectRval = (ObjectMessage) rval;
            ByteArrayInputStream bistream = new ByteArrayInputStream(
                    base64EncoderTL.get().decode(objectMessage.getObject().getBytes()));

            ObjectInputStream oistream = new ObjectInputStream(bistream);

            objectRval.setObject((Serializable) oistream.readObject());
        }

        //
        // JMS Header properties

        try {
            rval.setJMSDeliveryMode(message.getJMSDeliveryMode());
        } catch (JMSException ex) {
            log.error("unable to set JMSDeliveryMode to " + message.getJMSDeliveryMode() + ": "
                    + ex.getMessage());
        }

        try {
            rval.setJMSMessageID(message.getJMSMessageID());
        } catch (JMSException ex) {
            log.error("unable to set JMSMessageID: " + ex.getMessage(), ex);
        }

        try {
            if (message.getJMSExpiration() != null) {
                rval.setJMSExpiration(message.getJMSExpiration());
            }
        } catch (JMSException ex) {
            log.error("unable to set JMSExpiration: " + ex.getMessage(), ex);
        }

        try {
            if (message.getJMSPriority() != null) {
                rval.setJMSPriority(message.getJMSPriority());
            }
        } catch (JMSException ex) {
            log.error("unable to set JMSPriority: " + ex.getMessage(), ex);
        }

        try {
            if (message.getJMSTimestamp() != null) {
                rval.setJMSTimestamp(message.getJMSTimestamp());
            }
        } catch (JMSException ex) {
            log.error("unable to set JMSTimestamp:" + ex.getMessage(), ex);
        }

        if (message.getJMSCorrelationID() != null) {
            rval.setJMSCorrelationID(message.getJMSCorrelationID());
        }

        if (message.getJMSReplyTo() != null && !message.getJMSReplyTo().equals("null")) {
            rval.setJMSReplyTo(hermes.getDestination(message.getJMSReplyTo(),
                    Domain.getDomain(message.getJMSReplyToDomain())));
        }

        if (message.getJMSType() != null) {
            rval.setJMSType(message.getJMSType());
        }

        if (message.getJMSDestination() != null) {
            if (message.isFromQueue()) {
                rval.setJMSDestination(hermes.getDestination(message.getJMSDestination(), Domain.QUEUE));
            } else {
                rval.setJMSDestination(hermes.getDestination(message.getJMSDestination(), Domain.TOPIC));
            }
        }

        for (Iterator iter = message.getHeaderProperty().iterator(); iter.hasNext();) {
            Property property = (Property) iter.next();

            if (property.getValue() == null) {
                rval.setObjectProperty(property.getName(), null);
            } else if (property.getType().equals(String.class.getName())) {
                rval.setStringProperty(property.getName(), StringEscapeUtils.unescapeXml(property.getValue()));
            } else if (property.getType().equals(Long.class.getName())) {
                rval.setLongProperty(property.getName(), Long.parseLong(property.getValue()));
            } else if (property.getType().equals(Double.class.getName())) {
                rval.setDoubleProperty(property.getName(), Double.parseDouble(property.getValue()));
            } else if (property.getType().equals(Boolean.class.getName())) {
                rval.setBooleanProperty(property.getName(), Boolean.parseBoolean(property.getValue()));
            } else if (property.getType().equals(Short.class.getName())) {
                rval.setShortProperty(property.getName(), Short.parseShort(property.getValue()));
            } else if (property.getType().equals(Integer.class.getName())) {
                rval.setIntProperty(property.getName(), Integer.parseInt(property.getValue()));
            }
        }

        return rval;
    } catch (NamingException e) {
        throw new HermesException(e);
    }

}

From source file:org.mule.transport.jms.integration.AbstractJmsFunctionalTestCase.java

public Message receive(Scenario scenario) throws Exception {
    assertNotNull("scenario is null!", scenario);
    Connection connection = null;
    try {//  www . j a v a2  s  . c  o  m
        connection = getConnection(false, false);
        connection.start();
        Session session = null;
        try {
            session = connection.createSession(scenario.isTransacted(), scenario.getAcknowledge());
            Destination destination = createOutputDestination(session, scenario);
            MessageConsumer consumer = null;
            try {
                consumer = session.createConsumer(destination);
                return scenario.receive(session, consumer);
            } finally {
                if (consumer != null) {
                    consumer.close();
                }
            }
        } finally {
            if (session != null) {
                session.close();
            }
        }
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                logger.warn("Failed to close jms connection: " + e.getMessage());
            }
        }
    }
}

From source file:au.com.redboxresearchdata.fascinator.plugins.JsonHarvestQueueConsumer.java

/**
 * Stop the JSON Harvest Queue Consumer. Including stopping the storage and
 * indexer/*  ww w  .  j  a va2s .  c  om*/
 */
public void stop() throws Exception {
    log.info("Stopping {}...", name);
    if (indexer != null) {
        try {
            indexer.shutdown();
        } catch (PluginException pe) {
            log.error("Failed to shutdown indexer: {}", pe.getMessage());
            throw pe;
        }
    }
    if (storage != null) {
        try {
            storage.shutdown();
        } catch (PluginException pe) {
            log.error("Failed to shutdown storage: {}", pe.getMessage());
            throw pe;
        }
    }
    if (producer != null) {
        try {
            producer.close();
        } catch (JMSException jmse) {
            log.warn("Failed to close producer: {}", jmse);
        }
    }
    if (consumer != null) {
        try {
            consumer.close();
        } catch (JMSException jmse) {
            log.warn("Failed to close consumer: {}", jmse.getMessage());
            throw jmse;
        }
    }
    if (session != null) {
        try {
            session.close();
        } catch (JMSException jmse) {
            log.warn("Failed to close consumer session: {}", jmse);
        }
    }
    if (connection != null) {
        try {
            connection.close();
        } catch (JMSException jmse) {
            log.warn("Failed to close connection: {}", jmse);
        }
    }
    if (messaging != null) {
        messaging.release();
    }
}

From source file:com.adaptris.core.jms.JmsProducerImpl.java

protected void rollback() {
    boolean tryRollback = false;
    try {//  w  ww.  j a v a  2 s  .  co  m
        tryRollback = currentSession().getTransacted();
    } catch (JMSException f) {
        // session is probably broken, can't rollback anyway.
    }
    if (tryRollback) {
        try {
            currentLogger().trace("Attempting to rollback transacted session");
            currentSession().rollback();
        } catch (JMSException f) {
            currentLogger().trace("Error encountered rolling back transaction : {}", f.getMessage());
        }
    }
}

From source file:org.apache.activemq.usecases.RequestReplyToTopicViaThreeNetworkHopsTest.java

protected void sendWithRetryOnDeletedDest(MessageProducer prod, Message msg) throws JMSException {
    try {/* ww w.  j  a  v  a  2 s. c o  m*/
        if (LOG.isDebugEnabled())
            LOG.debug("SENDING REQUEST message " + msg);

        prod.send(msg);
    } catch (JMSException jms_exc) {
        System.out.println("AAA: " + jms_exc.getMessage());
        throw jms_exc;
    }
}

From source file:org.mule.transport.jms.integration.AbstractJmsFunctionalTestCase.java

/**
 * Clear the specified topic/*from  ww  w . ja  v a2 s.c om*/
 */
protected void purgeTopic(String destination, String topic) throws Exception {
    Connection c = null;
    Session s = null;

    try {
        logger.debug("purging topic : " + topic);
        c = getConnection(true, false);
        if (c == null) {
            logger.debug("could not create a connection to topic : " + destination);
        }

        c.start();
        s = ((TopicConnection) c).createTopicSession(true, Session.SESSION_TRANSACTED);

        logger.debug("created topic session");
        Topic dest = s.createTopic(destination);
        logger.debug("created topic destination");

        if (client != null) {
            client.dispose();
        }

        MessageConsumer consumer = null;

        try {
            consumer = s.createDurableSubscriber(dest, topic);
            logger.debug("created consumer");
            while (consumer.receiveNoWait() != null) {
                logger.debug("Topic " + topic + " isn't empty, draining it");
            }
            logger.debug("topic should be empty");
            consumer.close();
            s.unsubscribe(topic);
        } catch (JMSException e) {
            logger.debug("could not unsubscribe : " + topic);
        }
    }

    finally {
        if (c != null) {
            c.stop();
            if (s != null) {
                s.close();
            }
            try {
                c.close();
            } catch (JMSException e) {
                logger.warn("Failed to close jms connection: " + e.getMessage());
            }
        }
    }
    logger.debug("completed draining topic :" + topic);
}