Java Code Examples for javax.jms.JMSException

The following are top voted examples for showing how to use javax.jms.JMSException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: pooled-jms   File: PooledConnectionSecurityExceptionTest.java   View source code 7 votes vote down vote up
@Test
public void testFailedCreateConsumerConnectionStillWorks() throws JMSException {
    Connection connection = pooledConnFact.createConnection("guest", "password");
    connection.start();

    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = session.createQueue(name.getMethodName());

    try {
        session.createConsumer(queue);
        fail("Should fail to create consumer");
    } catch (JMSSecurityException ex) {
        LOG.info("Caught expected security error");
    }

    queue = session.createQueue("GUESTS." + name.getMethodName());

    MessageProducer producer = session.createProducer(queue);
    producer.close();

    connection.close();
}
 
Example 2
Project: jaffa-framework   File: JmsClientHelper.java   View source code 6 votes vote down vote up
/**
 * Add any properties (name/value pairs) to the message as string properties
 * @param message properties will be added here
 * @param props the set of additional properties to be added to message.
 * NOTE: If values other than strings need to be added to Messages this 
 * method can be refactored to support.
 */
private void populateMessageProperties(Message message, Properties props){
    if(props == null || message == null){
        return;
    }

    Set<String> propNames = props.stringPropertyNames();
    try{
        for(String propName : propNames){
            String value = props.getProperty(propName);
            if(value != null){
                message.setStringProperty(propName, value);
            }
        }
    }catch(JMSException jmse){
        log.error("Problem added properties to Message", jmse);
    }
}
 
Example 3
Project: pooled-jms   File: JmsPoolWrappedProducersTest.java   View source code 6 votes vote down vote up
private void doTestCreateMessageProducer(boolean useAnonymousProducers) throws JMSException {
    cf.setUseAnonymousProducers(useAnonymousProducers);

    JmsPoolConnection connection = (JmsPoolConnection) cf.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    Queue queue1 = session.createTemporaryQueue();
    Queue queue2 = session.createTemporaryQueue();

    JmsPoolMessageProducer producer1 = (JmsPoolMessageProducer) session.createProducer(queue1);
    JmsPoolMessageProducer producer2 = (JmsPoolMessageProducer) session.createProducer(queue2);

    if (useAnonymousProducers) {
        assertSame(producer1.getMessageProducer(), producer2.getMessageProducer());
    } else {
        assertNotSame(producer1.getMessageProducer(), producer2.getMessageProducer());
    }

    connection.close();
}
 
Example 4
Project: ats-framework   File: JmsClient.java   View source code 6 votes vote down vote up
private void doSendBinaryMessage( final Session session, final Destination destination,
                                  final byte[] bytes,
                                  final Map<String, ?> properties ) throws JMSException {

    try {
        BytesMessage message = session.createBytesMessage();
        message.writeBytes(bytes);
        if (properties != null) {
            // Note: Setting any properties (including JMS fields) using
            // setObjectProperty might not be supported by all providers
            // Tested with: ActiveMQ
            for (final Entry<String, ?> property : properties.entrySet()) {
                message.setObjectProperty(property.getKey(), property.getValue());
            }
        }
        final MessageProducer producer = session.createProducer(destination);
        producer.send(message);
    } finally {
        releaseSession(false);
    }
}
 
Example 5
Project: xtf   File: JmsClient.java   View source code 6 votes vote down vote up
public MessageConsumer createTopicConsumer(String selector) throws JMSException {
	if (isQueue) {
		throw new IllegalArgumentException("Only for topic, not queue");
	}
	String consumerId = "consumer-" + UUID.randomUUID();
	topicConnection = startConnection(consumerId);
	Session session = topicConnection.createSession(isTransacted, Session.AUTO_ACKNOWLEDGE);
	Topic topic = session.createTopic(destinationName);
	if (isDurable) {
		if (selector != null) {
			return session.createDurableSubscriber(topic, consumerId, selector, true);
		} else {
			return session.createDurableSubscriber(topic, consumerId);
		}
	} else {
		if (selector != null) {
			return session.createConsumer(topic, selector);
		} else {
			return session.createConsumer(topic);
		}
	}
}
 
Example 6
Project: oneops   File: WoPublisher.java   View source code 6 votes vote down vote up
/**
 *
 * @throws JMSException
 */
public void publishMessage(CmsWorkOrderSimpleBase cmsWoSimpleBase, String type, String id)
    throws JMSException {
  if (isPubEnabled) {
    long t1 = System.currentTimeMillis();
    cmsWoSimpleBase = CmsUtil.maskSecuredFields(cmsWoSimpleBase, type);
    String payload = gson.toJson(cmsWoSimpleBase);
    Map<String, String> headers = new HashMap<>(2);
    headers.put("type", getType(type));
    headers.put("msgId", id);
    MessageData data = new MessageData(payload, headers);
    searchPublisher.publish(data);
    if (cmsWoSimpleBase instanceof CmsWorkOrderSimple) {
      logger.info("WO published to search stream queue for RfcId: "
          + ((CmsWorkOrderSimple) cmsWoSimpleBase).getRfcId() + " took " + (
          System.currentTimeMillis() - t1));
    } else if (cmsWoSimpleBase instanceof CmsActionOrderSimple) {
      logger.info("AO published to search stream queue for procedureId/actionId: "
          + ((CmsActionOrderSimple) cmsWoSimpleBase).getProcedureId() + "/"
          + ((CmsActionOrderSimple) cmsWoSimpleBase).getActionId() + " took " + (
          System.currentTimeMillis() - t1));
    }
  } else {
    logger.warn(">>>WOPublisher is disabled<IS_SEARCH_ENABLED>"+ isPubEnabled);
  }
}
 
Example 7
Project: ats-framework   File: JmsClient.java   View source code 6 votes vote down vote up
private ManagedConnection createManagedConnection() {

        final ManagedConnection connection;
        final ConnectionFactory connectionFactory = getConnectionFactory();
        try {
            if (!StringUtils.isNullOrEmpty(this.username)) {
                connection = ManagedConnection.create(connectionFactory.createConnection(this.username,
                                                                                         this.password));
            } else {
                connection = ManagedConnection.create(connectionFactory.createConnection());
            }
        } catch (JMSException e) {
            throw new JmsMessageException("Error creating JMS connection from connection factory '"
                                          + defaultConnectionFactoryName + "'", e);
        }
        return connection;
    }
 
Example 8
Project: xsharing-services-router   File: AbstractSharingListener.java   View source code 6 votes vote down vote up
/**
 * Since we use a request/response communication style with the client,
 * we must ensure that tha appropriate fields are set.
 */
private boolean isValidRequestResponse(Message incoming) {
    try {
        if (incoming.getJMSCorrelationID() == null) {
            getLogger().warn("JMSCorrelationID is not set! Will not process request");
            return false;
        }

        if (incoming.getJMSReplyTo() == null) {
            getLogger().warn("JMSReplyTo is not set! Will not process request");
            return false;
        }
    } catch (JMSException e) {
        getLogger().warn(
                "Failed to read JMSCorrelationID/JMSReplyTo. " +
                "Will not process request. Exception message = {}", e.getMessage());
        return false;
    }

    return true;
}
 
Example 9
Project: org.ops4j.pax.transx   File: JMSContextImpl.java   View source code 5 votes vote down vote up
@Override
public JMSConsumer createConsumer(Destination destination, String selector, boolean noLocal) {
    try {
        return startIfNeeded(new JMSConsumerImpl(this, getSession().createConsumer(destination, selector, noLocal)));
    } catch (JMSException jmse) {
        throw Utils.convertToRuntimeException(jmse);
    }
}
 
Example 10
Project: lemon   File: ProxyConnectionFactory.java   View source code 5 votes vote down vote up
public void sendMessage(MessageContext messageContext,
        Destination destination, Message message) throws JMSException {
    String destinationName = destination.toString();

    if (destination instanceof Topic) {
        messageHandler.sendMessageToTopic(messageContext, destinationName,
                message);
    } else {
        messageHandler.sendMessageToQueue(messageContext, destinationName,
                message);
    }
}
 
Example 11
Project: spring-cloud-ribbon-extensions   File: AbstractPreservesMessagePropertiesTest.java   View source code 5 votes vote down vote up
@Test
public void fail_on_get_property() throws Exception {
    when(message.getPropertyNames()).thenReturn(Collections.enumeration(asList("1", "2", "3")));
    when(message.getStringProperty("1")).thenReturn("1");
    when(message.getStringProperty("2")).thenThrow(JMSException.class);
    propagator.copyFromMessage(message);
    verify(message).getStringProperty(eq("1"));
    verify(message).getStringProperty(eq("2"));
    verify(message, never()).getStringProperty(eq("3"));
    Assert.assertThat(current().containsKey("1"), is(true));
    Assert.assertThat(current().entrySet().size(), is(1));
}
 
Example 12
Project: pooled-jms   File: MockJMSConnection.java   View source code 5 votes vote down vote up
@Override
public QueueSession createQueueSession(boolean transacted, int acknowledgeMode) throws JMSException {
    checkClosedOrFailed();
    ensureConnected();
    int ackMode = getSessionAcknowledgeMode(transacted, acknowledgeMode);
    MockJMSQueueSession result = new MockJMSQueueSession(getNextSessionId(), ackMode, this);
    addSession(result);
    if (started.get()) {
        result.start();
    }
    return result;
}
 
Example 13
Project: oneops   File: ProcedureRunnerImpl.java   View source code 5 votes vote down vote up
@Override
@Transactional
public void convergeIfNeeded(CmsActionOrderSimple ao) throws JMSException {
  long procId = ao.getProcedureId();
  long ciId = ao.getCiId();
  String logPrefix = "procedure " + procId + " ci " + ciId;
  int step = ao.getExecOrder();
  if (canConverge(ao.getProcedureId(), ao.getCiId(), step)) {
    //send a jms message to controller.workflow queue to proceed to next step
    logger.info("procedure " + procId + " ciId " + ciId + ": inductor response converging to next step");
    sendMessageToProceed(PROCEDURE.getName(), procId);
  }
  logger.info(logPrefix + " inductor response processing finished");
}
 
Example 14
Project: org.ops4j.pax.transx   File: Utils.java   View source code 5 votes vote down vote up
public static JMSException newJMSException(Throwable t) {
    if (t instanceof JMSException) {
        return (JMSException) t;
    }
    JMSException se = new JMSException(t.getMessage());
    return (JMSException) se.initCause(t);
}
 
Example 15
Project: pooled-jms   File: MockJMSMapMessage.java   View source code 5 votes vote down vote up
@Override
public void setBytes(String name, byte[] value, int offset, int length) throws JMSException {
    // Fail early to avoid unnecessary array copy.
    checkKeyNameIsValid(name);

    byte[] clone = null;
    if (value != null) {
        clone = new byte[length];
        System.arraycopy(value, offset, clone, 0, length);
    }

    put(name, clone);
}
 
Example 16
Project: testee.fi   File: TestEEfiConnection.java   View source code 5 votes vote down vote up
@Override
public ConnectionConsumer createSharedDurableConnectionConsumer(
        final Topic topic,
        final String subscriptionName,
        final String messageSelector,
        final ServerSessionPool sessionPool,
        final int maxMessages
) throws JMSException {
    return null;
}
 
Example 17
Project: org.ops4j.pax.transx   File: JMSProducerImpl.java   View source code 5 votes vote down vote up
@Override
public int getIntProperty(String name) {
    try {
        return convertPropertyTo(name, messageProperties.get(name), Integer.class);
    } catch (JMSException jmse) {
        throw Utils.convertToRuntimeException(jmse);
    }
}
 
Example 18
Project: flume-release-1.7.0   File: TestJMSMessageConsumer.java   View source code 5 votes vote down vote up
@Test(expected = FlumeException.class)
public void testCreateTopicFails() throws Exception {
  destinationType = JMSDestinationType.TOPIC;
  when(session.createQueue(destinationName)).thenThrow(new AssertionError());
  when(session.createTopic(destinationName)).thenReturn(topic);
  when(session.createTopic(destinationName))
    .thenThrow(new JMSException(""));
  create();
}
 
Example 19
Project: java-jms   File: JmsTextMapInjectAdapterTest.java   View source code 5 votes vote down vote up
@Test
public void propertyWithDash() throws JMSException {
  JmsTextMapInjectAdapter adapter = new JmsTextMapInjectAdapter(message);
  adapter.put("key-1", "value1");
  assertEquals("value1", message.getStringProperty("key" + DASH + "1"));

  adapter.put("-key-1-2-", "value2");
  assertEquals("value2",
      message.getStringProperty(DASH + "key" + DASH + "1" + DASH + "2" + DASH));
}
 
Example 20
Project: cli-java   File: Utils.java   View source code 5 votes vote down vote up
/**
     * Write message binary body to provided file or default one in temp directory.
     *
     * @param filePath file to write data to
     * @param message  to be read and written to provided file
     */
    public static void writeBinaryContentToFile(String filePath, Message message, int msgCounter) {
        byte[] readByteArray;
        try {
            File writeBinaryFile;
            if (filePath == null || filePath.equals("")) {
                writeBinaryFile = File.createTempFile("recv_msg_", Long.toString(System.currentTimeMillis()));
            } else {
                writeBinaryFile = new File(filePath + "_" + msgCounter);
            }

            LOG.debug("Write binary content to file '" + writeBinaryFile.getPath() + "'.");
            if (message instanceof BytesMessage) {
                BytesMessage bm = (BytesMessage) message;
                readByteArray = new byte[(int) bm.getBodyLength()];
                bm.reset(); // added to be able to read message content
                bm.readBytes(readByteArray);
                try (FileOutputStream fos = new FileOutputStream(writeBinaryFile)) {
                    fos.write(readByteArray);
                    fos.close();
                }

            } else if (message instanceof StreamMessage) {
                LOG.debug("Writing StreamMessage to");
                StreamMessage sm = (StreamMessage) message;
//        sm.reset(); TODO haven't tested this one
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(baos);
                oos.writeObject(sm.readObject());
                oos.close();
            }

        } catch (JMSException e) {
            e.printStackTrace();
        } catch (IOException e1) {
            LOG.error("Error while writing to file '" + filePath + "'.");
            e1.printStackTrace();
        }
    }
 
Example 21
Project: bench   File: JMSHelperTest.java   View source code 5 votes vote down vote up
@Test
public void serialize_deserialize_through_bytes_message() throws JMSException {
    String expected = DUMMY;
    byte[] data = convertToBytes(expected);
    BytesMessage bytesMessage = createTestBytesMessage(data);
    String actual = objectFromMsg(bytesMessage);

    assertThat(actual, is(expected));
}
 
Example 22
Project: oneops   File: OpsEventPublisher.java   View source code 5 votes vote down vote up
/**
 * Inits the.
 *
 * @throws JMSException the jMS exception
 */
public void init() throws JMSException {

	connection = connectionFactory.createConnection();
	connection.start();
	
	// Create the session
	session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
	Destination destination = session.createQueue(queue);
	// Create the producer.
	producer = session.createProducer(destination);
	
	if (persistent) {
	    producer.setDeliveryMode(DeliveryMode.PERSISTENT);
	} else {
	    producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
	}
	if (timeToLive != 0) {
	    producer.setTimeToLive(timeToLive);
	}
   }
 
Example 23
Project: pooled-jms   File: JmsPoolJMSContextTest.java   View source code 5 votes vote down vote up
@Test(timeout = 30000)
public void testAutoStartCanBeDisabled() throws JMSException {
    JmsPoolJMSContext context = (JmsPoolJMSContext) cf.createContext();
    context.setAutoStart(false);

    MockJMSConnection connection = (MockJMSConnection) context.getConnection();
    assertFalse(connection.isStarted());

    assertNotNull(context.createConsumer(context.createQueue(getTestName())));
    assertFalse(connection.isStarted());
    assertNotNull(context.createBrowser(context.createQueue(getTestName())));
    assertFalse(connection.isStarted());
}
 
Example 24
Project: pooled-jms   File: MockJMSBytesMessage.java   View source code 5 votes vote down vote up
@Override
protected <T> T doGetBody(Class<T> asType) throws JMSException {
    reset();

    if (content == null || content.length == 0) {
        return null;
    }

    return (T) Arrays.copyOf(content, content.length);
}
 
Example 25
Project: testee.fi   File: TestEEfiMessageProducer.java   View source code 5 votes vote down vote up
@Override
public void send(
        final Message message,
        final CompletionListener completionListener
) throws JMSException {
    send(message, 0, 0, 0, completionListener);
}
 
Example 26
Project: org.ops4j.pax.transx   File: JMSContextImpl.java   View source code 5 votes vote down vote up
@Override
public void setClientID(String clientID) {
    try {
        connection.setClientID(clientID);
    } catch (JMSException jmse) {
        throw Utils.convertToRuntimeException(jmse);
    }
}
 
Example 27
Project: continuous-performance-evaluation   File: CargoHandledConsumer.java   View source code 5 votes vote down vote up
@Override
public void onMessage(Message message) {
    try {
        TextMessage textMessage = (TextMessage) message;
        String trackingIdString = textMessage.getText();

        cargoInspectionService.inspectCargo(new TrackingId(trackingIdString));
    } catch (JMSException e) {
        logger.log(Level.SEVERE, "Error processing JMS message", e);
    }
}
 
Example 28
Project: oneops   File: WorkflowPublisher.java   View source code 5 votes vote down vote up
public void sendWorkflowMessage(String type, long executionId, Map<String, String> headers) throws JMSException {
	WorkflowMessage wfMessage = new WorkflowMessage();
	wfMessage.setType(type);
	wfMessage.setExecutionId(executionId);
	String message = gson.toJson(wfMessage);
	MessageData data = new MessageData();
	data.setPayload(message);
	data.setHeaders(headers);
	publish(data);
}
 
Example 29
Project: pooled-jms   File: MockJMSQueueSession.java   View source code 5 votes vote down vote up
@Override
public MessageConsumer createConsumer(Destination destination, String messageSelector) throws JMSException {
    if (destination instanceof Topic) {
        throw new IllegalStateException("Operation not supported by a QueueSession");
    }
    return super.createConsumer(destination, messageSelector);
}
 
Example 30
Project: org.ops4j.pax.transx   File: JMSContextImpl.java   View source code 5 votes vote down vote up
@Override
public JMSConsumer createSharedConsumer(Topic topic, String name, String selector) {
    try {
        return startIfNeeded(new JMSConsumerImpl(this, getSession().createSharedConsumer(topic, name, selector)));
    } catch (JMSException jmse) {
        throw Utils.convertToRuntimeException(jmse);
    }
}
 
Example 31
Project: pooled-jms   File: MockJMSMapMessage.java   View source code 5 votes vote down vote up
@Override
public byte[] getBytes(String name) throws JMSException {
    Object value = getObject(name);

    if (value == null) {
        return null;
    } else if (value instanceof byte[]) {
        byte[] original = (byte[]) value;
        byte[] clone = new byte[original.length];
        System.arraycopy(original, 0, clone, 0, original.length);
        return clone;
    } else {
        throw new MessageFormatException("Cannot read a byte[] from " + value.getClass().getSimpleName());
    }
}
 
Example 32
Project: jmsclient   File: JMSQueueClient.java   View source code 5 votes vote down vote up
@Override
public QueueReceiver createSubscriber() throws JMSException
{
    QueueReceiver recv = ((QueueSession) session).createReceiver((Queue) topic, messageSelector);
    log.debug("Created non-durable subscriber");
    return recv;
}
 
Example 33
Project: bench   File: JMSAgentMessageListenerTest.java   View source code 5 votes vote down vote up
@Test
public void create_actor_for_wrong_agent_does_nothing() throws IOException, ClassNotFoundException, JMSException {
    ActorCreationRequest creationRequest = new ActorCreationRequest(DUMMY_CONFIG);
    AgentInputMessage toAgent = AgentInputMessage.createActor(new AgentKey("another-agent"), creationRequest);
    BytesMessage testBytesMessage = toBytesMessage(toAgent);

    listener.onMessage(testBytesMessage);

    verifyNoMoreInteractions(agentListener);
}
 
Example 34
Project: pooled-jms   File: JmsPoolJMSContext.java   View source code 5 votes vote down vote up
@Override
public void start() {
    try {
        connection.start();
    } catch (JMSException jmse) {
        throw JMSExceptionSupport.createRuntimeException(jmse);
    }
}
 
Example 35
Project: pooled-jms   File: MockJMSConnection.java   View source code 5 votes vote down vote up
MockJMSConnection initialize() throws JMSException {
    if (explicitClientID) {
        ensureConnected();
    }

    return this;
}
 
Example 36
Project: artemis-disruptor-miaosha   File: SimpleJmsMessageSender.java   View source code 5 votes vote down vote up
@Override
public void sendMessage(MessageDto payload) throws JMSException {

  Message message = MessageConvertUtils.toMessage(messageConverter, session, payload);
  dupMessageDetectStrategy.setId(message, payload);
  messageProducer.send(message);

}
 
Example 37
Project: pooled-jms   File: QpidJmsPoolTestSupport.java   View source code 5 votes vote down vote up
protected BrokerViewMBean getProxyToBroker() throws MalformedObjectNameException, JMSException {
    ObjectName brokerViewMBean = new ObjectName(
        "org.apache.activemq:type=Broker,brokerName=" + brokerService.getBrokerName());
    BrokerViewMBean proxy = (BrokerViewMBean) brokerService.getManagementContext()
            .newProxyInstance(brokerViewMBean, BrokerViewMBean.class, true);
    return proxy;
}
 
Example 38
Project: pooled-jms   File: JmsPoolConnectionSecurityExceptionTest.java   View source code 5 votes vote down vote up
@Test
public void testFailedCreateConsumerConnectionStillWorks() throws JMSException {
    // User can write but not read
    user.setCanConsumeAll(false);

    Connection connection = null;

    try {
        connection = cf.createConnection("admin", "admin");
    } catch (JMSSecurityException jmsse) {
        fail("Should not be able to create connection using bad credentials");
    }

    connection.start();

    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = session.createQueue("test");

    try {
        session.createConsumer(queue);
        fail("Should fail to create consumer");
    } catch (JMSSecurityException ex) {
        LOG.debug("Caught expected security error");
    }

    MessageProducer producer = session.createProducer(queue);
    producer.close();

    connection.close();
}
 
Example 39
Project: OperatieBRP   File: SelectieTaakResultaatQueueMessageListener.java   View source code 5 votes vote down vote up
@Override
public void onMessage(final Message message) {
    BrpNu.set(DatumUtil.nuAlsZonedDateTime());
    try {
        LOGGER.debug("onMessage");
        final TextMessage textMessage = (TextMessage) message;
        final String text = textMessage.getText();
        final SelectieTaakResultaat selectieTaakResultaat = JSON_STRING_SERIALISEERDER.deserialiseerVanuitString(text, SelectieTaakResultaat.class);
        selectieTaakResultaatOntvanger.ontvang(selectieTaakResultaat);
    } catch (JMSException e) {
        LOGGER.error("error on message", e);
    }
}
 
Example 40
Project: DWSurvey   File: InvokeMessageProducer.java   View source code 5 votes vote down vote up
public void send() {
	template.send(this.destination, new MessageCreator() {
		@Override
		public Message createMessage(Session session) throws JMSException {
			TextMessage message=session.createTextMessage();
			System.out.println("发出消息,延时10秒.");
			String msgId=message.getJMSMessageID();
			System.out.println("msgId:"+msgId);
			message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, 20*1000);
			message.setStringProperty("content", "内容content...");
			return message;
		}
	});
}