List of usage examples for javax.jms Message setStringProperty
void setStringProperty(String name, String value) throws JMSException;
From source file:org.apache.axis2.transport.jms.JMSSender.java
/** * Create a JMS Message from the given MessageContext and using the given * session//from w ww . j a v a2 s .c o m * * @param msgContext the MessageContext * @param session the JMS session * @param contentTypeProperty the message property to be used to store the * content type * @return a JMS message from the context and session * @throws JMSException on exception * @throws AxisFault on exception */ private Message createJMSMessage(MessageContext msgContext, Session session, String contentTypeProperty) throws JMSException, AxisFault { Message message = null; String msgType = getProperty(msgContext, JMSConstants.JMS_MESSAGE_TYPE); // check the first element of the SOAP body, do we have content wrapped using the // default wrapper elements for binary (BaseConstants.DEFAULT_BINARY_WRAPPER) or // text (BaseConstants.DEFAULT_TEXT_WRAPPER) ? If so, do not create SOAP messages // for JMS but just get the payload in its native format String jmsPayloadType = guessMessageType(msgContext); if (jmsPayloadType == null) { OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext); MessageFormatter messageFormatter = null; try { messageFormatter = TransportUtils.getMessageFormatter(msgContext); } catch (AxisFault axisFault) { throw new JMSException("Unable to get the message formatter to use"); } String contentType = messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction()); boolean useBytesMessage = msgType != null && JMSConstants.JMS_BYTE_MESSAGE.equals(msgType) || contentType.indexOf(HTTPConstants.HEADER_ACCEPT_MULTIPART_RELATED) > -1; OutputStream out; StringWriter sw; if (useBytesMessage) { BytesMessage bytesMsg = session.createBytesMessage(); sw = null; out = new BytesMessageOutputStream(bytesMsg); message = bytesMsg; } else { sw = new StringWriter(); try { out = new WriterOutputStream(sw, format.getCharSetEncoding()); } catch (UnsupportedCharsetException ex) { handleException("Unsupported encoding " + format.getCharSetEncoding(), ex); return null; } } try { messageFormatter.writeTo(msgContext, format, out, true); out.close(); } catch (IOException e) { handleException("IO Error while creating BytesMessage", e); } if (!useBytesMessage) { TextMessage txtMsg = session.createTextMessage(); txtMsg.setText(sw.toString()); message = txtMsg; } if (contentTypeProperty != null) { message.setStringProperty(contentTypeProperty, contentType); } } else if (JMSConstants.JMS_BYTE_MESSAGE.equals(jmsPayloadType)) { message = session.createBytesMessage(); BytesMessage bytesMsg = (BytesMessage) message; OMElement wrapper = msgContext.getEnvelope().getBody() .getFirstChildWithName(BaseConstants.DEFAULT_BINARY_WRAPPER); OMNode omNode = wrapper.getFirstOMChild(); if (omNode != null && omNode instanceof OMText) { Object dh = ((OMText) omNode).getDataHandler(); if (dh != null && dh instanceof DataHandler) { try { ((DataHandler) dh).writeTo(new BytesMessageOutputStream(bytesMsg)); } catch (IOException e) { handleException("Error serializing binary content of element : " + BaseConstants.DEFAULT_BINARY_WRAPPER, e); } } } } else if (JMSConstants.JMS_TEXT_MESSAGE.equals(jmsPayloadType)) { message = session.createTextMessage(); TextMessage txtMsg = (TextMessage) message; txtMsg.setText(msgContext.getEnvelope().getBody() .getFirstChildWithName(BaseConstants.DEFAULT_TEXT_WRAPPER).getText()); } // set the JMS correlation ID if specified String correlationId = getProperty(msgContext, JMSConstants.JMS_COORELATION_ID); if (correlationId == null && msgContext.getRelatesTo() != null) { correlationId = msgContext.getRelatesTo().getValue(); } if (correlationId != null) { message.setJMSCorrelationID(correlationId); } if (msgContext.isServerSide()) { // set SOAP Action as a property on the JMS message setProperty(message, msgContext, BaseConstants.SOAPACTION); } else { String action = msgContext.getOptions().getAction(); if (action != null) { message.setStringProperty(BaseConstants.SOAPACTION, action); } } JMSUtils.setTransportHeaders(msgContext, message); return message; }
From source file:org.openanzo.combus.CombusConnection.java
/** * Send a request to a destination and wait for a response * // w ww . j a va 2 s . c om * @param context * context for this operational call * @param destinationName * destination queue for this request * @param request * request message * @param timeout * timeout for waiting for a response * @param messageHandler * the handler of multiple messages * @throws AnzoException * if there was an exception sending request, or a timeout waiting for a response */ public void requestMultipleResponse(IOperationContext context, String destinationName, Message request, long timeout, IMessageHandler messageHandler) throws AnzoException { Destination destination = null; if (context.getAttribute(OPTIONS.DATASOURCE) != null) { URI datasourceUri = (URI) context.getAttribute(OPTIONS.DATASOURCE); Queue defaultDestination = (Queue) destinations.get(destinationName); if (datasourceUri.toString().equals("http://openanzo.org/datasource/systemDatasource")) { destination = defaultDestination; } else { String queueNamePrefix = UriGenerator.generateEncapsulatedString("", datasourceUri.toString()) + "/"; try { String[] parts = StringUtils.split(defaultDestination.getQueueName(), '/'); String queue = "services/" + queueNamePrefix + parts[1]; destination = destinations.get(queue); if (destination == null) { destination = session.createQueue(queue); destinations.put(queue, destination); } } catch (JMSException e) { throw new AnzoException(ExceptionConstants.COMBUS.NO_SUCH_DESTINATION, destinationName); } } } else { destination = destinations.get(destinationName); if (destination == null) { throw new AnzoException(ExceptionConstants.COMBUS.NO_SUCH_DESTINATION, destinationName); } } String correlationId = context.getOperationId(); if (correlationId == null) { correlationId = UUID.randomUUID().toString(); } try { request.setJMSCorrelationID(correlationId); request.setJMSReplyTo(tempQueue); request.setIntProperty(SerializationConstants.protocolVersion, Constants.VERSION); if (context.getOperationPrincipal() != null && !context.getOperationPrincipal().getName().equals(this.userName)) { request.setStringProperty(SerializationConstants.runAsUser, context.getOperationPrincipal().getName()); } if (context.getAttribute(OPTIONS.PRIORITY) != null) { Integer priority = (Integer) context.getAttribute(OPTIONS.PRIORITY); request.setJMSPriority(priority); messageProducer.setPriority(priority); } else { messageProducer.setPriority(4); } if (context.getAttribute(OPTIONS.SKIPCACHE) != null) { request.setBooleanProperty(OPTIONS.SKIPCACHE, context.getAttribute(OPTIONS.SKIPCACHE, Boolean.class)); } if (context.getAttribute(OPTIONS.INCLUDEMETADATAGRAPHS) != null) { request.setBooleanProperty(OPTIONS.INCLUDEMETADATAGRAPHS, context.getAttribute(OPTIONS.INCLUDEMETADATAGRAPHS, Boolean.class)); } if (log.isTraceEnabled()) { log.trace(LogUtils.COMBUS_MARKER, MessageUtils.prettyPrint(request, "Sending Request: (destination=" + destination + ")")); } messageProducer.send(destination, request); } catch (JMSException jmsex) { performDisconnect(true); throw new AnzoException(ExceptionConstants.COMBUS.COULD_NOT_PUBLISH, jmsex); } lock.lock(); try { long start = System.currentTimeMillis(); boolean done = false; int seq = 0; while (!done) { Collection<TextMessage> messageSet = correlationIdToMessage.remove(correlationId); while (messageSet == null) { if (timeout <= 0) { try { newMessage.await(2, TimeUnit.SECONDS); } catch (InterruptedException ie) { throw new AnzoException(ExceptionConstants.COMBUS.INTERRUPTED, correlationId); } if (closed || closing) { throw new AnzoException(ExceptionConstants.COMBUS.INTERRUPTED, correlationId); } messageSet = correlationIdToMessage.remove(correlationId); } else { try { newMessage.await(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException ie) { throw new AnzoException(ExceptionConstants.COMBUS.INTERRUPTED, correlationId); } if (closed || closing) { throw new AnzoException(ExceptionConstants.COMBUS.INTERRUPTED, correlationId); } messageSet = correlationIdToMessage.remove(correlationId); if (!connected) { log.error(LogUtils.COMBUS_MARKER, Messages.formatString( ExceptionConstants.COMBUS.ERROR_PROCESSING_MESSGE, "connection closed")); throw new AnzoException(ExceptionConstants.COMBUS.JMS_NOT_CONNECTED, correlationId); } if (messageSet == null && ((timeout > -1) && ((System.currentTimeMillis() - start) > timeout))) { throw new AnzoException(ExceptionConstants.COMBUS.NO_SERVER_RESPONSE, correlationId); } } } try { for (TextMessage message : messageSet) { if (log.isTraceEnabled()) { log.trace(LogUtils.COMBUS_MARKER, MessageUtils.prettyPrint(message, "Recieved Response:")); } if (message.propertyExists("done")) { done = message.getBooleanProperty("done"); } else { done = true; } if (message.propertyExists("sequence")) { int sequence = message.getIntProperty("sequence"); if (sequence != seq) { throw new AnzoException(ExceptionConstants.COMBUS.NO_SERVER_RESPONSE, correlationId); } else { seq++; } } int totalSize = 0; if (message.propertyExists(SerializationConstants.totalSolutions)) { totalSize = message.getIntProperty(SerializationConstants.totalSolutions); } if (message.getBooleanProperty(SerializationConstants.operationFailed)) { long errorCodes = message.propertyExists(SerializationConstants.errorTags) ? message.getLongProperty(SerializationConstants.errorCode) : ExceptionConstants.COMBUS.JMS_SERVICE_EXCEPTION; // if available, use enumerated args, since these can be reconstruct an AnzoException correctly. List<String> args = new ArrayList<String>(); for (int i = 0; true; i++) { String errorArg = message .getStringProperty(SerializationConstants.errorMessageArg + i); if (errorArg == null) { break; } args.add(errorArg); } // NOTE: This doesn't really make any sense, but it was here before and it's better to be too verbose than not verbose enough // when it comes to error messages, so it stays. For now at least. -jpbetz if (args.isEmpty()) { args.add(message.getText()); } throw new AnzoException(errorCodes, args.toArray(new String[0])); } else { messageHandler.handleMessage(message, seq, done, totalSize); } } } catch (JMSException jmsex) { log.debug(LogUtils.COMBUS_MARKER, Messages.formatString( ExceptionConstants.COMBUS.ERROR_PROCESSING_MESSGE, "request multiple response"), jmsex); } } } finally { lock.unlock(); } }
From source file:org.openanzo.combus.CombusConnection.java
/** * Send a request to a destination and wait for a response * /*from w w w . j a v a 2s . c o m*/ * @param context * context for this operational call * @param destinationName * destination queue for this request * @param request * request message * @param timeout * timeout for waiting for a response * @return response message * @throws AnzoException * if there was an exception sending request, or a timeout waiting for a response */ public TextMessage requestResponse(IOperationContext context, String destinationName, Message request, long timeout) throws AnzoException { Destination destination = null; if (context.getAttribute(OPTIONS.DATASOURCE) != null) { URI datasourceUri = (URI) context.getAttribute(OPTIONS.DATASOURCE); Queue defaultDestination = (Queue) destinations.get(destinationName); if (datasourceUri.toString().equals("http://openanzo.org/datasource/systemDatasource")) { destination = defaultDestination; } else { String queueNamePrefix = UriGenerator.generateEncapsulatedString("", datasourceUri.toString()) + "/"; try { String[] parts = StringUtils.split(defaultDestination.getQueueName(), '/'); String queue = "services/" + queueNamePrefix + parts[1]; destination = destinations.get(queue); if (destination == null) { destination = session.createQueue(queue); destinations.put(queue, destination); } } catch (JMSException e) { throw new AnzoException(ExceptionConstants.COMBUS.NO_SUCH_DESTINATION, destinationName); } } } else { destination = destinations.get(destinationName); if (destination == null) { throw new AnzoException(ExceptionConstants.COMBUS.NO_SUCH_DESTINATION, destinationName); } } if (context.getAttribute(COMBUS.TIMEOUT) != null) { timeout = (Long) context.getAttribute(COMBUS.TIMEOUT); } String correlationId = context.getOperationId(); if (correlationId == null) { correlationId = UUID.randomUUID().toString(); } try { request.setJMSCorrelationID(correlationId); request.setJMSReplyTo(tempQueue); request.setIntProperty(SerializationConstants.protocolVersion, Constants.VERSION); if (context.getOperationPrincipal() != null && !context.getOperationPrincipal().getName().equals(this.userName)) { request.setStringProperty(SerializationConstants.runAsUser, context.getOperationPrincipal().getName()); } if (context.getAttribute(OPTIONS.PRIORITY) != null) { Integer priority = (Integer) context.getAttribute(OPTIONS.PRIORITY); request.setJMSPriority(priority); messageProducer.setPriority(priority); } else { messageProducer.setPriority(4); } if (context.getAttribute(OPTIONS.SKIPCACHE) != null) { request.setBooleanProperty(OPTIONS.SKIPCACHE, context.getAttribute(OPTIONS.SKIPCACHE, Boolean.class)); } if (log.isTraceEnabled()) { log.trace(LogUtils.COMBUS_MARKER, MessageUtils.prettyPrint(request, "Sending Request: (destination=" + destination + ")")); } messageProducer.send(destination, request); } catch (JMSException jmsex) { performDisconnect(true); throw new AnzoException(ExceptionConstants.COMBUS.COULD_NOT_PUBLISH, jmsex); } lock.lock(); try { Collection<TextMessage> messageSet = correlationIdToMessage.remove(correlationId); long start = System.currentTimeMillis(); while (messageSet == null) { if (timeout <= 0) { try { newMessage.await(2, TimeUnit.SECONDS); } catch (InterruptedException ie) { throw new AnzoException(ExceptionConstants.COMBUS.INTERRUPTED, correlationId); } if (closed || closing) { throw new AnzoException(ExceptionConstants.COMBUS.INTERRUPTED, correlationId); } messageSet = correlationIdToMessage.remove(correlationId); } else { try { newMessage.await(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException ie) { throw new AnzoException(ExceptionConstants.COMBUS.INTERRUPTED, correlationId); } if (closed || closing) { throw new AnzoException(ExceptionConstants.COMBUS.INTERRUPTED, correlationId); } messageSet = correlationIdToMessage.remove(correlationId); if (!connected) { log.error(LogUtils.COMBUS_MARKER, "Request Response failed because connection was closed"); throw new AnzoException(ExceptionConstants.COMBUS.JMS_NOT_CONNECTED, correlationId); } if (messageSet == null && ((timeout > 0) && ((System.currentTimeMillis() - start) > timeout))) { throw new AnzoException(ExceptionConstants.COMBUS.NO_SERVER_RESPONSE, correlationId); } } } try { TextMessage message = messageSet.iterator().next(); if (log.isTraceEnabled()) { log.trace(LogUtils.COMBUS_MARKER, MessageUtils.prettyPrint(message, "Received Response:")); } if (message.getBooleanProperty(SerializationConstants.operationFailed)) { long errorCodes = message.propertyExists(SerializationConstants.errorTags) ? message.getLongProperty(SerializationConstants.errorCode) : ExceptionConstants.COMBUS.JMS_SERVICE_EXCEPTION; // if available, use enumerated args, since these can be reconstruct an AnzoException correctly. List<String> args = new ArrayList<String>(); for (int i = 0; true; i++) { String errorArg = message.getStringProperty(SerializationConstants.errorMessageArg + i); if (errorArg == null) { break; } args.add(errorArg); } // NOTE: This doesn't really make any sense, but it was here before and it's better to be too verbose than not verbose enough // when it comes to error messages, so it stays. For now at least. -jpbetz if (args.isEmpty()) { args.add(message.getText()); } throw new AnzoException(errorCodes, args.toArray(new String[0])); } /*Object prp = context.getAttribute("populateResponseProperties"); if (prp != null && ((Boolean) prp)) { HashMap<String, Object> props = new HashMap<String, Object>(); Enumeration<String> keys = message.getPropertyNames(); while (keys.hasMoreElements()) { String key = keys.nextElement(); props.put(key, message.getObjectProperty(key)); } context.setAttribute("responseProperties", props); }*/ return message; } catch (JMSException jmsex) { log.debug(LogUtils.COMBUS_MARKER, Messages.formatString( ExceptionConstants.COMBUS.ERROR_PROCESSING_MESSGE, "request response"), jmsex); } return null; } finally { lock.unlock(); } }
From source file:hermes.impl.DefaultXMLHelper.java
public Message createMessage(MessageFactory hermes, XMLMessage message) throws JMSException, IOException, ClassNotFoundException, DecoderException { try {//from ww w. ja va 2 s. co 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); } }