Java Code Examples for org.springframework.jms.support.converter.MessageConversionException

The following examples show how to use org.springframework.jms.support.converter.MessageConversionException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * Build a JMS message to be sent as response based on the given result object.
 * @param session the JMS Session to operate on
 * @param result the content of the message, as returned from the listener method
 * @return the JMS {@code Message} (never {@code null})
 * @throws JMSException if thrown by JMS API methods
 * @see #setMessageConverter
 */
protected Message buildMessage(Session session, Object result) throws JMSException {
	Object content = preProcessResponse(result instanceof JmsResponse
			? ((JmsResponse<?>) result).getResponse() : result);

	MessageConverter converter = getMessageConverter();
	if (converter != null) {
		if (content instanceof org.springframework.messaging.Message) {
			return this.messagingMessageConverter.toMessage(content, session);
		}
		else {
			return converter.toMessage(content, session);
		}
	}

	if (!(content instanceof Message)) {
		throw new MessageConversionException(
				"No MessageConverter specified - cannot handle message [" + content + "]");
	}
	return (Message) content;
}
 
Example 2
Source Project: spring-analysis-note   Source File: MessageListenerAdapterTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testWithResponsiveMessageDelegateWhenReturnTypeIsNotAJMSMessageAndNoMessageConverterIsSupplied() throws Exception {
	final TextMessage sentTextMessage = mock(TextMessage.class);
	final Session session = mock(Session.class);
	ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class);
	given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT);

	final MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) {
		@Override
		protected Object extractMessage(Message message) {
			return message;
		}
	};
	adapter.setMessageConverter(null);
	try {
		adapter.onMessage(sentTextMessage, session);
		fail("expected CouldNotSendReplyException with MessageConversionException");
	}
	catch (ReplyFailureException ex) {
		assertEquals(MessageConversionException.class, ex.getCause().getClass());
	}
}
 
Example 3
Source Project: spring-analysis-note   Source File: SimpleMessageConverterTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testMapConversionWhereMapHasNonStringTypesForKeys() throws JMSException {
	MapMessage message = mock(MapMessage.class);
	Session session = mock(Session.class);
	given(session.createMapMessage()).willReturn(message);

	Map<Integer, String> content = new HashMap<>(1);
	content.put(1, "value1");

	SimpleMessageConverter converter = new SimpleMessageConverter();
	try {
		converter.toMessage(content, session);
		fail("expected MessageConversionException");
	}
	catch (MessageConversionException ex) { /* expected */ }
}
 
Example 4
Source Project: spring-analysis-note   Source File: SimpleMessageConverterTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testMapConversionWhereMapHasNNullForKey() throws JMSException {
	MapMessage message = mock(MapMessage.class);
	Session session = mock(Session.class);
	given(session.createMapMessage()).willReturn(message);

	Map<Object, String> content = new HashMap<>(1);
	content.put(null, "value1");

	SimpleMessageConverter converter = new SimpleMessageConverter();
	try {
		converter.toMessage(content, session);
		fail("expected MessageConversionException");
	}
	catch (MessageConversionException ex) { /* expected */ }
}
 
Example 5
/**
 * Build a JMS message to be sent as response based on the given result object.
 * @param session the JMS Session to operate on
 * @param result the content of the message, as returned from the listener method
 * @return the JMS {@code Message} (never {@code null})
 * @throws JMSException if thrown by JMS API methods
 * @see #setMessageConverter
 */
protected Message buildMessage(Session session, Object result) throws JMSException {
	Object content = preProcessResponse(result instanceof JmsResponse
			? ((JmsResponse<?>) result).getResponse() : result);

	MessageConverter converter = getMessageConverter();
	if (converter != null) {
		if (content instanceof org.springframework.messaging.Message) {
			return this.messagingMessageConverter.toMessage(content, session);
		}
		else {
			return converter.toMessage(content, session);
		}
	}

	if (!(content instanceof Message)) {
		throw new MessageConversionException(
				"No MessageConverter specified - cannot handle message [" + content + "]");
	}
	return (Message) content;
}
 
Example 6
@Test
public void testWithResponsiveMessageDelegateWhenReturnTypeIsNotAJMSMessageAndNoMessageConverterIsSupplied() throws Exception {
	final TextMessage sentTextMessage = mock(TextMessage.class);
	final Session session = mock(Session.class);
	ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class);
	given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT);

	final MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) {
		@Override
		protected Object extractMessage(Message message) {
			return message;
		}
	};
	adapter.setMessageConverter(null);
	try {
		adapter.onMessage(sentTextMessage, session);
		fail("expected CouldNotSendReplyException with MessageConversionException");
	}
	catch (ReplyFailureException ex) {
		assertEquals(MessageConversionException.class, ex.getCause().getClass());
	}
}
 
Example 7
@Test
public void testMapConversionWhereMapHasNonStringTypesForKeys() throws JMSException {
	MapMessage message = mock(MapMessage.class);
	Session session = mock(Session.class);
	given(session.createMapMessage()).willReturn(message);

	Map<Integer, String> content = new HashMap<>(1);
	content.put(1, "value1");

	SimpleMessageConverter converter = new SimpleMessageConverter();
	try {
		converter.toMessage(content, session);
		fail("expected MessageConversionException");
	}
	catch (MessageConversionException ex) { /* expected */ }
}
 
Example 8
@Test
public void testMapConversionWhereMapHasNNullForKey() throws JMSException {
	MapMessage message = mock(MapMessage.class);
	Session session = mock(Session.class);
	given(session.createMapMessage()).willReturn(message);

	Map<Object, String> content = new HashMap<>(1);
	content.put(null, "value1");

	SimpleMessageConverter converter = new SimpleMessageConverter();
	try {
		converter.toMessage(content, session);
		fail("expected MessageConversionException");
	}
	catch (MessageConversionException ex) { /* expected */ }
}
 
Example 9
/**
 * Build a JMS message to be sent as response based on the given result object.
 * @param session the JMS Session to operate on
 * @param result the content of the message, as returned from the listener method
 * @return the JMS {@code Message} (never {@code null})
 * @throws JMSException if thrown by JMS API methods
 * @see #setMessageConverter
 */
protected Message buildMessage(Session session, Object result) throws JMSException {
	Object content = (result instanceof JmsResponse ? ((JmsResponse<?>) result).getResponse() : result);
	if (content instanceof org.springframework.messaging.Message) {
		return this.messagingMessageConverter.toMessage(content, session);
	}

	MessageConverter converter = getMessageConverter();
	if (converter != null) {
		return converter.toMessage(content, session);
	}

	if (!(content instanceof Message)) {
		throw new MessageConversionException(
				"No MessageConverter specified - cannot handle message [" + content + "]");
	}
	return (Message) content;
}
 
Example 10
@Test
public void testWithResponsiveMessageDelegateWhenReturnTypeIsNotAJMSMessageAndNoMessageConverterIsSupplied() throws Exception {
	final TextMessage sentTextMessage = mock(TextMessage.class);
	final Session session = mock(Session.class);
	ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class);
	given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT);

	final MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) {
		@Override
		protected Object extractMessage(Message message) {
			return message;
		}
	};
	adapter.setMessageConverter(null);
	try {
		adapter.onMessage(sentTextMessage, session);
		fail("expected CouldNotSendReplyException with MessageConversionException");
	} catch(ReplyFailureException ex) {
		assertEquals(MessageConversionException.class, ex.getCause().getClass());
	}
}
 
Example 11
@Test
public void testMapConversionWhereMapHasNonStringTypesForKeys() throws JMSException {

	MapMessage message = mock(MapMessage.class);
	final Session session = mock(Session.class);
	given(session.createMapMessage()).willReturn(message);

	final Map<Integer, String> content = new HashMap<Integer, String>(1);
	content.put(1, "value1");

	final SimpleMessageConverter converter = new SimpleMessageConverter();
	try {
		converter.toMessage(content, session);
		fail("expected MessageConversionException");
	} catch (MessageConversionException ex) { /* expected */ }
}
 
Example 12
@Test
public void testMapConversionWhereMapHasNNullForKey() throws JMSException {

	MapMessage message = mock(MapMessage.class);
	final Session session = mock(Session.class);
	given(session.createMapMessage()).willReturn(message);

	final Map<Object, String> content = new HashMap<Object, String>(1);
	content.put(null, "value1");

	final SimpleMessageConverter converter = new SimpleMessageConverter();
	try {
		converter.toMessage(content, session);
		fail("expected MessageConversionException");
	} catch (MessageConversionException ex) { /* expected */ }
}
 
Example 13
/**
 * Converts an incoming tag update into a {@link DataTagValueUpdate} object.
 *
 * @param message the incoming tag update
 *
 * @throws JMSException if an error occurs converting the message
 */
@Override
public Object fromMessage(final Message message) throws JMSException {

  if (message == null) {
    throw new MessageConversionException("Message must not be null!");
  }

  if (!(message instanceof TextMessage)) {
    throw new MessageConversionException("Message must be an instance of TextMessage!");
  }

  try {
    String json = ((TextMessage) message).getText();
    log.trace("Update received from DAQ:\n" + json);

    return mapper.readValue(json, DataTagValueUpdate.class);
  } catch (IOException | RuntimeException e) {
    log.error("Exception caught while parsing incoming update", e);
    throw new MessageConversionException("Exception caught while parsing incoming update: " + ((TextMessage) message).getText(), e);
  }
}
 
Example 14
/**
 * Converts the top level DOM element of an XML document to
 * a ConfigurationRequest object.
 * @param domElement the top-level XML element ("ConfigurationRequest")
 * @return the request object
 */
private static ConfigurationRequest fromXML(final Element domElement) {
  ConfigurationRequest result = null;

  if (domElement.getNodeName().equals(CONFIGURATION_XML_ROOT)) {
    String idStr = domElement.getAttribute(CONFIGURATION_ID_ATTRIBUTE);
    if (idStr == null || idStr.length() == 0) {
      throw new RuntimeException("Unable to read configuration request id: " + idStr);
    } else {
      result = new ConfigurationRequest(new Integer(idStr));
    }
    return result;
  } else {
    throw new MessageConversionException("Called the fromXML message on the wrong XML doc Element! - check your code as this should be checked first");
  }
}
 
Example 15
@Override
public void onMessage(final Message message, final Session session) throws JMSException {
  try {
    DataTagValueUpdate update = (DataTagValueUpdate) converter.fromMessage(message);

    // We do the process PIK checking in order to accept or not the update
    if(this.checkProcessPIK(update)) {
      processUpdates(update);
    }
    else {
      log.warn("Received update(s) for Process #" + update.getProcessId()
          + " with wrong PIK: Ignoring " + update.getValues().size() + " updates");
    }
  } catch (MessageConversionException ex) {
    String errorMessage = "Error processing incoming update from DAQ: message is being discarded!";
    log.error(errorMessage, ex);
    if (System.currentTimeMillis() - lastEmailLog > EMAIL_FREQUENCY_MILLIS) {
      EMAILLOGGER.error(errorMessage, ex);
      lastEmailLog = System.currentTimeMillis();
    }
  }
}
 
Example 16
Source Project: Thunder   Source File: MQBytesMessageConverter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException {
    if (!(object instanceof Serializable)) {
        LOG.error("Object should be instance of Serializable");

        return null;
    }

    Serializable serializable = (Serializable) object;

    byte[] bytes = SerializerExecutor.serialize(serializable);
    BytesMessage bytesMessage = session.createBytesMessage();
    bytesMessage.writeBytes(bytes);

    return bytesMessage;
}
 
Example 17
protected Message<?> toMessagingMessage(javax.jms.Message jmsMessage) {
	try {
		return (Message<?>) getMessagingMessageConverter().fromMessage(jmsMessage);
	}
	catch (JMSException ex) {
		throw new MessageConversionException("Could not convert JMS message", ex);
	}
}
 
Example 18
/**
 * Extract the message body from the given JMS message.
 * @param message the JMS {@code Message}
 * @return the content of the message, to be passed into the listener method
 * as an argument
 * @throws MessageConversionException if the message could not be extracted
 */
protected Object extractMessage(Message message)  {
	try {
		MessageConverter converter = getMessageConverter();
		if (converter != null) {
			return converter.fromMessage(message);
		}
		return message;
	}
	catch (JMSException ex) {
		throw new MessageConversionException("Could not convert JMS message", ex);
	}
}
 
Example 19
@Override
public Object getPayload() {
	if (this.payload == null) {
		try {
			this.payload = unwrapPayload();
		}
		catch (JMSException ex) {
			throw new MessageConversionException(
					"Failed to extract payload from [" + this.message + "]", ex);
		}
	}
	return this.payload;
}
 
Example 20
protected Message<?> toMessagingMessage(javax.jms.Message jmsMessage) {
	try {
		return (Message<?>) getMessagingMessageConverter().fromMessage(jmsMessage);
	}
	catch (JMSException ex) {
		throw new MessageConversionException("Could not convert JMS message", ex);
	}
}
 
Example 21
/**
 * Extract the message body from the given JMS message.
 * @param message the JMS {@code Message}
 * @return the content of the message, to be passed into the listener method
 * as an argument
 * @throws MessageConversionException if the message could not be extracted
 */
protected Object extractMessage(Message message)  {
	try {
		MessageConverter converter = getMessageConverter();
		if (converter != null) {
			return converter.fromMessage(message);
		}
		return message;
	}
	catch (JMSException ex) {
		throw new MessageConversionException("Could not convert JMS message", ex);
	}
}
 
Example 22
@Override
public Object getPayload() {
	if (this.payload == null) {
		try {
			this.payload = unwrapPayload();
		}
		catch (JMSException ex) {
			throw new MessageConversionException(
					"Failed to extract payload from [" + this.message + "]", ex);
		}
	}
	return this.payload;
}
 
Example 23
public Message toMessage(Object obj, Session session) throws JMSException,
			MessageConversionException {

		if (obj instanceof InvokeMessage) {
			ActiveMQObjectMessage objMsg = (ActiveMQObjectMessage) session
					.createObjectMessage();
			long delay=5*1000;
        	System.out.println("延时:"+delay/1000+"秒");
        	System.out.println("msgId:"+objMsg.getJMSMessageID());
        	objMsg.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, delay);
//        	objMsg.setExpiration(2000);
        	
			Map<String, byte[]> map = new HashMap<String, byte[]>();
			try {
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				ObjectOutputStream oos = new ObjectOutputStream(bos);
				oos.writeObject(obj);
				map.put("InvokeMessage", bos.toByteArray());
			} catch (IOException e) {
				e.printStackTrace();
			}
			objMsg.setObjectProperty("Map", map);
			return objMsg;
		} else {
			throw new JMSException("Object:[" + obj + "] is not InvokeMessage");
		}
	}
 
Example 24
protected Message<?> toMessagingMessage(javax.jms.Message jmsMessage) {
	try {
		return (Message<?>) getMessagingMessageConverter().fromMessage(jmsMessage);
	}
	catch (JMSException ex) {
		throw new MessageConversionException("Could not convert JMS message", ex);
	}
}
 
Example 25
/**
 * Extract the message body from the given JMS message.
 * @param message the JMS {@code Message}
 * @return the content of the message, to be passed into the listener method
 * as an argument
 * @throws MessageConversionException if the message could not be extracted
 */
protected Object extractMessage(Message message)  {
	try {
		MessageConverter converter = getMessageConverter();
		if (converter != null) {
			return converter.fromMessage(message);
		}
		return message;
	}
	catch (JMSException ex) {
		throw new MessageConversionException("Could not convert JMS message", ex);
	}
}
 
Example 26
/**
 * Converts a {@link DataTagValueUpdate} to a JMS {@link Message}
 *
 * @param tag     the tag to convert
 * @param session the session in which the message must be created
 *
 * @return the resulting message
 * @throws JMSException if an error occurs in creating the message
 */
@Override
public Message toMessage(final Object tag, final Session session) throws JMSException {
  try {
    String json = mapper.writeValueAsString(tag);
    return session.createTextMessage(json);

  } catch (JsonProcessingException e) {
    log.error("Exception caught on update reception", e.getMessage());
    throw new MessageConversionException("Exception caught in converting dataTagValueUpdate to a json String:"
        + e.getMessage());
  }
}
 
Example 27
Source Project: c2mon   Source File: XMLConverter.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Static method for creating a Process object
 * from a XML String by making use of the simpleframework XML library.
 * @param xml The XML to parse
 * @return Document Document created from the given XML String
 * @throws Exception In case of a parsing error or a wrong XML definition
 */
public final Object fromXml(final String xml) throws Exception {
  try {
    Document doc = this.parser.parse(xml);
    // Getting the XML doc name to make call the proper class
    String docName = doc.getDocumentElement().getNodeName();
    
    LOGGER.trace("fromXml() - Message received from " + docName + ": " + xml);
    
    if(docName.equals(ProcessMessageType.CONNECT_REQUEST.getName())) {
      return fromXml(xml, ProcessMessageType.CONNECT_REQUEST);
    } else if(docName.equals(ProcessMessageType.CONNECT_RESPONSE.getName())) {
      return fromXml(xml, ProcessMessageType.CONNECT_RESPONSE); 
    } else if(docName.equals(ProcessMessageType.CONFIG_REQUEST.getName())) {
      return fromXml(xml, ProcessMessageType.CONFIG_REQUEST); 
    } else if(docName.equals(ProcessMessageType.CONFIG_RESPONSE.getName())) {
      return fromXml(xml, ProcessMessageType.CONFIG_RESPONSE); 
    } else if(docName.equals(ProcessMessageType.DISCONNETION_REQUEST.getName())) {
      return fromXml(xml, ProcessMessageType.DISCONNETION_REQUEST); 
    } else {
      LOGGER.error("fromXml() : Cannot deserialize XML message since the message type could not be determined" + xml);
      throw new MessageFormatException("XML TAG Node Name not found: " + xml);  
    }
  } catch (ParserException ex) {        
    LOGGER.error("Exception caught in DOM parsing of incoming message: ", ex);
    LOGGER.error("Message was: " + xml);          
    throw new MessageConversionException("Exception caught in DOM parsing on process request message");
  }
}
 
Example 28
@Override
public Object fromMessage(final Message message) throws JMSException, MessageConversionException {
  if (TextMessage.class.isAssignableFrom(message.getClass())) {
    try {
      Document doc = parser.parse(((TextMessage) message).getText());
      String docName = doc.getDocumentElement().getNodeName();
      if (docName.equals(CONFIGURATION_XML_ROOT)) {
        if (log.isDebugEnabled()) {
          log.debug("fromMessage() : Reconfiguration request received.");
        }
        return fromXML(doc.getDocumentElement());
      } else {
       log.error("Unrecognized XML message received on the reconfiguration request topic - is being ignored");
       log.error("  (unrecognized document root element is " + docName + ")");
       throw new MessageConversionException("Unrecognized XML message received.");
      }
    } catch (ParserException ex) {
      log.error("Exception caught in DOM parsing of incoming message: ", ex);
      //TODO may need to adjust encoding in next line (UTF-8 or whatever used by ActiveMQ)?
      log.error("Message was: " + ((TextMessage) message).getText());
      throw new MessageConversionException("Exception caught in DOM parsing on reconfiguration request message");
    }
  } else {
    StringBuffer str = new StringBuffer("fromMessage() : Unsupported message type(");
    str.append(message.getClass().getName());
    str.append(") : Message discarded.");
    log.error(str.toString());
    throw new MessageConversionException("Unsupported JMS message type received on configuration request connection.");
  }
}
 
Example 29
@Override
  public Message toMessage(Object obj, Session session) throws JMSException,
          MessageConversionException {

      logger.debug("Method : toMessage");

      if (!(obj instanceof MessageBeanImpl)) {

          throw new MessageConversionException("Obj is not MessageBeanImpl.");
      }

/* Jms字节类型消息 */
      BytesMessage bytesMessage = session.createBytesMessage();

      MessageBeanImpl messageBean = (MessageBeanImpl) obj;

      bytesMessage.setStringProperty("MessageType",
              messageBean.getMessageType());
      bytesMessage.setStringProperty("MessageAckNo",
              messageBean.getMessageAckNo());
      bytesMessage.setStringProperty("MessageNo", messageBean.getMessageNo());
      bytesMessage.setLongProperty("MessageDate",
              messageBean.getMessageDate());

      bytesMessage.writeBytes(messageBean.getMessageContent());

      logger.debug("Convert Success, The Send Message No is "
              + messageBean.getMessageNo());

      return bytesMessage;
  }
 
Example 30
Source Project: Thunder   Source File: MQBytesMessageConverter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object fromMessage(Message message) throws JMSException, MessageConversionException {
    if (!(message instanceof BytesMessage)) {
        LOG.error("Message should be instance of BytesMessage");

        return null;
    }

    BytesMessage bytesMessage = (BytesMessage) message;
    int length = (int) bytesMessage.getBodyLength();
    byte[] bytes = new byte[length];
    bytesMessage.readBytes(bytes);

    return SerializerExecutor.deserialize(bytes);
}