List of usage examples for javax.jms JMSException JMSException
public JMSException(String reason)
From source file:com.cws.esolutions.core.utils.MQUtils.java
/** * Puts an MQ message on a specified queue and returns the associated * correlation ID for retrieval upon request. * * @param connName - The connection name to utilize * @param authData - The authentication data to utilize, if required * @param requestQueue - The request queue name to put the message on * @param targetHost - The target host for the message * @param value - The data to place on the request. MUST be <code>Serialiable</code> * @return <code>String</code> - the JMS correlation ID associated with the message * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing *//*from ww w . j av a 2 s . c om*/ public static final synchronized String sendMqMessage(final String connName, final List<String> authData, final String requestQueue, final String targetHost, final Serializable value) throws UtilityException { final String methodName = MQUtils.CNAME + "sendMqMessage(final String connName, final List<String> authData, final String requestQueue, final String targetHost, final Serializable value) throws UtilityException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", connName); DEBUGGER.debug("Value: {}", requestQueue); DEBUGGER.debug("Value: {}", targetHost); DEBUGGER.debug("Value: {}", value); } Connection conn = null; Session session = null; Context envContext = null; InitialContext initCtx = null; MessageProducer producer = null; ConnectionFactory connFactory = null; final String correlationId = RandomStringUtils.randomAlphanumeric(64); if (DEBUG) { DEBUGGER.debug("correlationId: {}", correlationId); } try { try { initCtx = new InitialContext(); envContext = (Context) initCtx.lookup(MQUtils.INIT_CONTEXT); connFactory = (ConnectionFactory) envContext.lookup(connName); } catch (NamingException nx) { // we're probably not in a container connFactory = new ActiveMQConnectionFactory(connName); } if (DEBUG) { DEBUGGER.debug("ConnectionFactory: {}", connFactory); } if (connFactory == null) { throw new UtilityException("Unable to create connection factory for provided name"); } // Create a Connection conn = connFactory.createConnection(authData.get(0), PasswordUtils.decryptText(authData.get(1), authData.get(2), authData.get(3), Integer.parseInt(authData.get(4)), Integer.parseInt(authData.get(5)), authData.get(6), authData.get(7), authData.get(8))); conn.start(); if (DEBUG) { DEBUGGER.debug("Connection: {}", conn); } // Create a Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); if (DEBUG) { DEBUGGER.debug("Session: {}", session); } // Create a MessageProducer from the Session to the Topic or Queue if (envContext != null) { try { producer = session.createProducer((Destination) envContext.lookup(requestQueue)); } catch (NamingException nx) { throw new UtilityException(nx.getMessage(), nx); } } else { Destination destination = session.createTopic(requestQueue); if (DEBUG) { DEBUGGER.debug("Destination: {}", destination); } producer = session.createProducer(destination); } if (producer == null) { throw new JMSException("Failed to create a producer object"); } producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); if (DEBUG) { DEBUGGER.debug("MessageProducer: {}", producer); } ObjectMessage message = session.createObjectMessage(true); message.setJMSCorrelationID(correlationId); message.setStringProperty("targetHost", targetHost); if (DEBUG) { DEBUGGER.debug("correlationId: {}", correlationId); } message.setObject(value); if (DEBUG) { DEBUGGER.debug("ObjectMessage: {}", message); } producer.send(message); } catch (JMSException jx) { throw new UtilityException(jx.getMessage(), jx); } finally { try { // Clean up if (!(session == null)) { session.close(); } if (!(conn == null)) { conn.close(); conn.stop(); } } catch (JMSException jx) { ERROR_RECORDER.error(jx.getMessage(), jx); } } return correlationId; }
From source file:com.fusesource.example.camel.ingest.FileIngestorRouteBuilderTest.java
@Test @DirtiesContext//from ww w . j av a2 s .co m public void testJmsFailure() throws Exception { RouteDefinition routeDef = context.getRouteDefinition(FileIngestorRouteBuilder.ENQUEUE_RECORD_ROUTE_ID); routeDef.adviceWith(context, new RouteBuilder() { @Override public void configure() throws Exception { interceptSendToEndpoint(builder.getEnqueueRecordsDestinationUri()).choice().when() .xpath("/example:record/example:id[text() = '1']", FileIngestorRouteBuilder.NAMESPACES) .throwException(new JMSException("Simulated JMS Error!")).end(); } }); context.start(); DatatypeFactory dtf = DatatypeFactory.newInstance(); Set<String> expectedIds = new HashSet<String>(); AggregateRecordType agt = new AggregateRecordType(); agt.setDate(dtf.newXMLGregorianCalendar(new GregorianCalendar())); output.setExpectedMessageCount(9); for (int i = 0; i < 10; i++) { RecordType record = new RecordType(); record.setId(String.valueOf(i)); record.setDate(dtf.newXMLGregorianCalendar(new GregorianCalendar())); record.setDescription("Record number: " + i); agt.getRecord().add(record); if (i != 1) { expectedIds.add(String.valueOf(i)); } } createAndMoveFile(agt); output.assertIsSatisfied(); validateFileMove(true); for (Exchange exchange : output.getReceivedExchanges()) { assertTrue(expectedIds.remove(exchange.getIn().getBody(RecordType.class).getId())); } assertTrue(expectedIds.isEmpty()); }
From source file:com.adaptris.core.jms.JmsProducer.java
@Override protected AdaptrisMessage doRequest(AdaptrisMessage msg, ProduceDestination dest, long timeout) throws ProduceException { AdaptrisMessage translatedReply = defaultIfNull(getMessageFactory()).newMessage(); Destination replyTo = null;//from ww w . j a va 2 s . co m MessageConsumer receiver = null; try { setupSession(msg); VendorImplementation vendorImp = retrieveConnection(JmsConnection.class) .configuredVendorImplementation(); String destString = dest.getDestination(msg); MyJmsDestination target = new MyJmsDestination(vendorImp.createDestination(destString, this)); replyTo = createReplyTo(msg, target, true); target.setReplyTo(replyTo); receiver = currentSession().createConsumer(replyTo); produce(msg, target); Message jmsReply = receiver.receive(timeout); if (jmsReply != null) { translatedReply = MessageTypeTranslatorImp.translate(getMessageTranslator(), jmsReply); } else { throw new JMSException("No Reply Received within " + timeout + "ms"); } acknowledge(jmsReply); // BUG#915 commit(); } catch (Exception e) { logLinkedException("", e); rollback(); throw ExceptionHelper.wrapProduceException(e); } finally { JmsUtils.closeQuietly(receiver); JmsUtils.deleteTemporaryDestination(replyTo); } return translatedReply; }
From source file:com.orange.mmp.message.jms.JMSMessageDecorator.java
/** * Inner method used to build the MMP Message from the JMS Message *//*from w w w. ja v a2s .c om*/ @SuppressWarnings("unchecked") protected void buildMessage() throws JMSException { //Object message if (this.jmsMessage instanceof ObjectMessage) { Serializable jmsObject = ((ObjectMessage) jmsMessage).getObject(); if (jmsObject instanceof Message) { this.message = (Message) jmsObject; } else { this.message = new Message(); this.message.setData(jmsObject); } } //Text message else if (this.jmsMessage instanceof TextMessage) { this.message = new Message(); this.message.setData(((TextMessage) jmsMessage).getText()); } //Map Message else if (this.jmsMessage instanceof MapMessage) { HashMap<String, Object> messageMap = new HashMap<String, Object>(); Enumeration<String> messageMapEnum = ((MapMessage) jmsMessage).getMapNames(); while (messageMapEnum.hasMoreElements()) { String key = messageMapEnum.nextElement(); messageMap.put(key, ((MapMessage) jmsMessage).getObject(key)); } this.message = new Message(); this.message.setData(messageMap); } //Byte[] message else if (this.jmsMessage instanceof BytesMessage) { byte[] messageBytes = new byte[(int) ((BytesMessage) jmsMessage).getBodyLength()]; ((BytesMessage) jmsMessage).readBytes(messageBytes); this.message = new Message(); this.message.setData(messageBytes); } else throw new JMSException("Unsupported message type '" + this.jmsMessage.getClass().getName() + "'"); }
From source file:com.mirth.connect.connectors.jms.JmsMessageUtils.java
/** * @param message// w w w.j a v a 2s. c om * the message to receive the bytes from. Note this only works * for TextMessge, ObjectMessage, StreamMessage and BytesMessage. * @return a byte array corresponding with the message payload * @throws JMSException * if the message can't be read or if the message passed is a * MapMessage * @throws java.io.IOException * if a failiare occurs while stream and converting the message * data */ public static byte[] getBytesFromMessage(Message message) throws JMSException, IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024 * 2]; int len; if (message instanceof BytesMessage) { BytesMessage bMsg = (BytesMessage) message; // put message in read-only mode bMsg.reset(); while ((len = bMsg.readBytes(buffer)) != -1) { baos.write(buffer, 0, len); } } else if (message instanceof StreamMessage) { StreamMessage sMsg = (StreamMessage) message; sMsg.reset(); while ((len = sMsg.readBytes(buffer)) != -1) { baos.write(buffer, 0, len); } } else if (message instanceof ObjectMessage) { ObjectMessage oMsg = (ObjectMessage) message; ByteArrayOutputStream bs = new ByteArrayOutputStream(); ObjectOutputStream os = new ObjectOutputStream(bs); os.writeObject(oMsg.getObject()); os.flush(); baos.write(bs.toByteArray()); os.close(); bs.close(); } else if (message instanceof TextMessage) { TextMessage tMsg = (TextMessage) message; baos.write(tMsg.getText().getBytes()); } else { throw new JMSException("Cannot get bytes from Map Message"); } baos.flush(); byte[] bytes = baos.toByteArray(); baos.close(); return bytes; }
From source file:com.oneops.controller.jms.InductorListener.java
private void processResponseMessage(TextMessage msg) throws JMSException { String corelationId = msg.getJMSCorrelationID(); if (corelationId == null) { corelationId = msg.getStringProperty("task_id"); }/* ww w. ja va2 s. c om*/ String[] props = corelationId.split("!"); String processId = props[0]; String executionId = props[1]; //String taskName = props[2]; String woTaskResult = msg.getStringProperty("task_result_code"); logger.debug("Inductor responce >>>>>>" + ((TextMessage) msg).getText()); String type = msg.getStringProperty("type"); Map<String, Object> params = new HashMap<String, Object>(); logger.info("Got inductor response with JMSCorrelationID: " + corelationId + " result " + woTaskResult); CmsWorkOrderSimpleBase wo = null; CmsWorkOrderSimple strippedWo = null; if ("opsprocedure".equalsIgnoreCase(type)) { wo = gson.fromJson(((TextMessage) msg).getText(), CmsActionOrderSimple.class); logger.info("Action ci_id = " + ((CmsActionOrderSimple) wo).getCiId()); } else if ("deploybom".equalsIgnoreCase(type)) { wo = gson.fromJson(((TextMessage) msg).getText(), CmsWorkOrderSimple.class); strippedWo = controllerUtil.stripWO((CmsWorkOrderSimple) wo); if (woTaskResult.equalsIgnoreCase("200")) { try { sensorClient.processMonitors((CmsWorkOrderSimple) wo); } catch (SensorClientException e) { logger.error(e); e.printStackTrace(); } } logger.info("WorkOrder rfc_id = " + ((CmsWorkOrderSimple) wo).getRfcId()); } else { throw new JMSException("the type property of the received msg is uknown - " + type); } if (strippedWo != null) { params.put("wo", strippedWo); } else { params.put("wo", wo); } if (woTaskResult.equalsIgnoreCase("200")) { params.put("wostate", "complete"); } else { params.put("wostate", "failed"); } setWoTimeStamps(wo); String woCorelationId = processId + executionId; wfController.pokeSubProcess(processId, executionId, params); woPublisher.publishMessage(wo, type, woCorelationId); }
From source file:com.amazon.sqs.javamessaging.SQSConnection.java
/** * Creates a <code>Session</code> * /*from w ww . j a v a 2 s . c o m*/ * @param transacted * Only false is supported. * @param acknowledgeMode * Legal values are <code>Session.AUTO_ACKNOWLEDGE</code>, * <code>Session.CLIENT_ACKNOWLEDGE</code>, * <code>Session.DUPS_OK_ACKNOWLEDGE</code>, and * <code>SQSSession.UNORDERED_ACKNOWLEDGE</code> * @return a new session. * @throws JMSException * If the QueueConnection object fails to create a session due * to some internal error or lack of support for the specific * transaction and acknowledge mode. */ @Override public Session createSession(boolean transacted, int acknowledgeMode) throws JMSException { checkClosed(); actionOnConnectionTaken = true; if (transacted || acknowledgeMode == Session.SESSION_TRANSACTED) throw new JMSException("SQSSession does not support transacted"); SQSSession sqsSession; if (acknowledgeMode == Session.AUTO_ACKNOWLEDGE) { sqsSession = new SQSSession(this, AcknowledgeMode.ACK_AUTO.withOriginalAcknowledgeMode(acknowledgeMode)); } else if (acknowledgeMode == Session.CLIENT_ACKNOWLEDGE || acknowledgeMode == Session.DUPS_OK_ACKNOWLEDGE) { sqsSession = new SQSSession(this, AcknowledgeMode.ACK_RANGE.withOriginalAcknowledgeMode(acknowledgeMode)); } else if (acknowledgeMode == SQSSession.UNORDERED_ACKNOWLEDGE) { sqsSession = new SQSSession(this, AcknowledgeMode.ACK_UNORDERED.withOriginalAcknowledgeMode(acknowledgeMode)); } else { LOG.error("Unrecognized acknowledgeMode. Cannot create Session."); throw new JMSException("Unrecognized acknowledgeMode. Cannot create Session."); } synchronized (stateLock) { checkClosing(); sessions.add(sqsSession); /** * Any new sessions created on a started connection should be * started on creation */ if (running) { sqsSession.start(); } } return sqsSession; }
From source file:com.amalto.core.storage.task.staging.ClusteredStagingTaskManagerTestCase.java
@Test(expected = RuntimeException.class) public void testExceptionWhenReadingMessage() throws Exception { TextMessage message = Mockito.mock(TextMessage.class); Mockito.when(message.getText()).thenThrow(new JMSException("")); taskManager.onMessage(message);/* w ww . j av a 2 s. c om*/ Mockito.verifyNoMoreInteractions(this.repository); this.internalListener.assertNoMessageSent(); }
From source file:com.amazon.sqs.javamessaging.SQSSession.java
/** * According to JMS specification, a message can be sent with only headers * without any payload, SQS does not support messages with empty payload. so * this method is not supported/*from w w w .j a v a 2s. co m*/ */ @Override public Message createMessage() throws JMSException { throw new JMSException(SQSMessagingClientConstants.UNSUPPORTED_METHOD); }
From source file:com.amazon.sqs.javamessaging.SQSMessageConsumer.java
/** This method is not supported. */ @Override//from w w w. ja v a2 s. co m public String getMessageSelector() throws JMSException { throw new JMSException(SQSMessagingClientConstants.UNSUPPORTED_METHOD); }