@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(); }
/** * 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); } }
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(); }
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); } }
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); } } }
/** * * @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); } }
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; }
/** * 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; }
@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); } }
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); } }
@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)); }
@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; }
@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"); }
public static JMSException newJMSException(Throwable t) { if (t instanceof JMSException) { return (JMSException) t; } JMSException se = new JMSException(t.getMessage()); return (JMSException) se.initCause(t); }
@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); }
@Override public ConnectionConsumer createSharedDurableConnectionConsumer( final Topic topic, final String subscriptionName, final String messageSelector, final ServerSessionPool sessionPool, final int maxMessages ) throws JMSException { return null; }
@Override public int getIntProperty(String name) { try { return convertPropertyTo(name, messageProperties.get(name), Integer.class); } catch (JMSException jmse) { throw Utils.convertToRuntimeException(jmse); } }
@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(); }
@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)); }
/** * 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(); } }
@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)); }
/** * 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); } }
@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()); }
@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); }
@Override public void send( final Message message, final CompletionListener completionListener ) throws JMSException { send(message, 0, 0, 0, completionListener); }
@Override public void setClientID(String clientID) { try { connection.setClientID(clientID); } catch (JMSException jmse) { throw Utils.convertToRuntimeException(jmse); } }
@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); } }
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); }
@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); }
@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); } }
@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()); } }
@Override public void send(Destination destination, Message message, CompletionListener completionListener) throws JMSException { Span span = TracingMessageUtils.buildAndInjectSpan(destination, message, tracer); messageProducer .send(destination, message, new TracingCompletionListener(span, completionListener)); }
@Override public QueueReceiver createSubscriber() throws JMSException { QueueReceiver recv = ((QueueSession) session).createReceiver((Queue) topic, messageSelector); log.debug("Created non-durable subscriber"); return recv; }
@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); }
@Override public void start() { try { connection.start(); } catch (JMSException jmse) { throw JMSExceptionSupport.createRuntimeException(jmse); } }
MockJMSConnection initialize() throws JMSException { if (explicitClientID) { ensureConnected(); } return this; }
@Override public void sendMessage(MessageDto payload) throws JMSException { Message message = MessageConvertUtils.toMessage(messageConverter, session, payload); dupMessageDetectStrategy.setId(message, payload); messageProducer.send(message); }
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; }
@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(); }
@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); } }