/** * @see MessageListener#onMessage(Message) * <p>This method expects a MapMessage containing information about a flight that has been * added to the database. This method will print out the information about the flight. */ public void onMessage(Message message) { try { if (message instanceof MapMessage) { MapMessage msg = (MapMessage) message; StringBuffer sb = new StringBuffer(); sb.append("Flight #: " + msg.getString("flightId") + "\n"); sb.append("Flight Date: " + msg.getString("flightDate") + "\n"); sb.append("Departure Airport: " + msg.getString("departureAirport") + "\n"); sb.append("Destination Airport: " + msg.getString("destinationAirport") + "\n"); sb.append("Number of Seats: " + msg.getInt("numSeats") + "\n"); sb.append("Seat Cost: $" + msg.getDouble("cost") + "\n"); sb.append("Airplane #: " + msg.getString("airplaneId") + "\n"); sb.append("*************************************************** \n\n"); System.out.println( "\n**" + getClass().getSimpleName() + ": Flight Added!\n" + sb.toString()); } else { System.out.println( getClass().getSimpleName() + " - Error: The message provided was not of type MapMessage!"); } } catch (JMSException e) { System.out.println( getClass().getSimpleName() + ": Error occuredwhen attempting to read the MapMessage"); e.printStackTrace(); } }
public Object fromMessage(Message msg) throws JMSException, MessageConversionException { log.debug("--OperationlogMsgConverter fromMessage--"); if (!(msg instanceof MapMessage)) { throw new MessageConversionException("Message isn't a MapMessage"); } if ((msg == null) || (msg.getBooleanProperty("NullMessage"))) { return null; } MapMessage mapMessage = (MapMessage) msg; OperationLog optLog = new OperationLog(); @SuppressWarnings("unused") DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); optLog.setMainType(Integer.valueOf(mapMessage.getInt("mainType"))); optLog.setMinorType(Integer.valueOf(mapMessage.getInt("minorType"))); optLog.setCtrlUnitId(Integer.valueOf(mapMessage.getInt("ctrlUnitId"))); optLog.setUserId(Integer.valueOf(mapMessage.getInt("userId"))); optLog.setTriggerTime(Calendar.getInstance().getTime()); optLog.setResourceId(Integer.valueOf(mapMessage.getInt("resourceId"))); try { if (mapMessage.getString("logTxt") == null) { return null; } optLog.setLogTxt(new String(mapMessage.getString("logTxt").getBytes("ISO-8859-1"), "UTF-8")); } catch (UnsupportedEncodingException e) { log.error(e.getMessage()); } return optLog; }
public Mail receiveMail() { ConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61616"); Destination destination = new ActiveMQQueue("mail.queue"); Connection conn = null; try { conn = cf.createConnection(); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer(destination); conn.start(); MapMessage message = (MapMessage) consumer.receive(); Mail mail = new Mail(); mail.setFrom(message.getString("from")); mail.setTo(message.getString("to")); mail.setSubject(message.getString("subject")); mail.setContent(message.getString("content")); mail.setDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(message.getString("date"))); session.close(); return mail; } catch (JMSException e) { throw new RuntimeException(e); } catch (ParseException e) { throw new RuntimeException(e); } finally { if (conn != null) { try { conn.close(); } catch (JMSException e) { } } } }
/** Invoked for received messages */ private void handleMapMessage(final MapMessage message) { try { final String text = message.getString(JMSLogMessage.TEXT); Runnable action = null; // Create action, or handle the message right away // Alarm state change? if (JMSAlarmMessage.TEXT_STATE.equals(text)) { // Received a state update from server, reset timeout timeout_timer.reset(); action = new UpdateAction(AlarmUpdateInfo.fromMapMessage(message)); model.updateServerState(false); } else if (JMSAlarmMessage.TEXT_STATE_MAINTENANCE.equals(text)) { timeout_timer.reset(); action = new UpdateAction(AlarmUpdateInfo.fromMapMessage(message)); model.updateServerState(true); } // Idle messages in absence of 'real' traffic? else if (JMSAlarmMessage.TEXT_IDLE.equals(text)) { timeout_timer.reset(); model.updateServerState(false); } else if (JMSAlarmMessage.TEXT_IDLE_MAINTENANCE.equals(text)) { timeout_timer.reset(); model.updateServerState(true); } // Enable/disable? else if (JMSAlarmMessage.TEXT_ENABLE.equals(text)) { timeout_timer.reset(); final String name = message.getString(JMSLogMessage.NAME); action = new EnableAction(name, true); } else if (JMSAlarmMessage.TEXT_DISABLE.equals(text)) { timeout_timer.reset(); final String name = message.getString(JMSLogMessage.NAME); action = new EnableAction(name, false); } // Configuration change else if (JMSAlarmMessage.TEXT_CONFIG.equals(text)) { final String name = message.getString(JMSLogMessage.NAME); model.readConfig(name); } // Debug trigger else if (JMSAlarmMessage.TEXT_DEBUG.equals(text)) model.dump(); if (action == null) return; // Queue or dispatch? synchronized (queue) { if (use_queue) { queue.execute(action); return; } } // else: Not using queue, and queue no longer locked action.run(); } catch (Throwable ex) { Activator.getLogger().log(Level.SEVERE, "Message handler error", ex); } }
/** @return */ public Nombre recibir() { MapMessage mapMessage = (MapMessage) jmsTemplate.receive("spitter.queue"); Nombre n = new Nombre(); try { n.setApellido(mapMessage.getString("lastName")); n.setName(mapMessage.getString("name")); } catch (JMSException e) { throw JmsUtils.convertJmsAccessException(e); } return n; }
private void handleReportMessage(MapMessage message) throws JMSException { String sender = message.getStringProperty(SENDER); String payload = message.getString(MESSAGE); String timeStamp = message.getString(TIMESTAMP); String severity = message.getString(SEVERITY); messages.add( new ReportMessage( sender, payload, dateTimeProvider.stringToInstant(timeStamp), severity, dateTimeProvider.now())); }
@SuppressWarnings("static-access") @Override public void onMessage(Message message, Session session) throws JMSException { logger.debug("receive Syn Product Status msg!"); MapMessage mapMessage = (MapMessage) message; Long merchantId = mapMessage.getLong("merchantId"); String merchantProdCode = mapMessage.getString("merchantProdCode"); String status = mapMessage.getString("status"); HopsRequestEvent hre = new HopsRequestEvent(SynProductStatusMessageListener.class); hre = new SynProductStatusEvent( SynProductStatusMessageListener.class, merchantId, merchantProdCode, status); publisher.publishRequestEvent(hre); }
@Override protected String extractString(JMSBindingData binding) throws Exception { Message content = binding.getMessage(); if (content instanceof TextMessage) { return TextMessage.class.cast(content).getText(); } else if (content instanceof BytesMessage) { BytesMessage sourceBytes = BytesMessage.class.cast(content); if (sourceBytes.getBodyLength() > Integer.MAX_VALUE) { throw JCAMessages.MESSAGES .theSizeOfMessageContentExceedsBytesThatIsNotSupportedByThisOperationSelector( "" + Integer.MAX_VALUE); } byte[] bytearr = new byte[(int) sourceBytes.getBodyLength()]; sourceBytes.readBytes(bytearr); return new String(bytearr); } else if (content instanceof ObjectMessage) { ObjectMessage sourceObj = ObjectMessage.class.cast(content); return String.class.cast(sourceObj.getObject()); } else if (content instanceof MapMessage) { MapMessage sourceMap = MapMessage.class.cast(content); return sourceMap.getString(KEY); } else { return content.getStringProperty(KEY); } }
/** * Runs the service defined in the MapMessage * * @param message * @return Map */ protected Map<String, Object> runService(MapMessage message) { Map<String, ? extends Object> context = null; String serviceName = null; String xmlContext = null; try { serviceName = message.getString("serviceName"); xmlContext = message.getString("serviceContext"); if (serviceName == null || xmlContext == null) { Debug.logError("Message received is not an OFB service message. Ignored!", module); return null; } Object o = XmlSerializer.deserialize(xmlContext, dispatcher.getDelegator()); if (Debug.verboseOn()) Debug.logVerbose("De-Serialized Context --> " + o, module); if (ObjectType.instanceOf(o, "java.util.Map")) context = UtilGenerics.checkMap(o); } catch (JMSException je) { Debug.logError(je, "Problems reading message.", module); } catch (Exception e) { Debug.logError(e, "Problems deserializing the service context.", module); } try { ModelService model = dispatcher.getDispatchContext().getModelService(serviceName); if (!model.export) { Debug.logWarning("Attempt to invoke a non-exported service: " + serviceName, module); return null; } } catch (GenericServiceException e) { Debug.logError(e, "Unable to get ModelService for service : " + serviceName, module); } if (Debug.verboseOn()) Debug.logVerbose("Running service: " + serviceName, module); Map<String, Object> result = null; if (context != null) { try { result = dispatcher.runSync(serviceName, context); } catch (GenericServiceException gse) { Debug.logError(gse, "Problems with service invocation.", module); } } return result; }
@Test public void shouldSendAttributesUsingExplicitConversion(boolean flag) throws JMSException { // Given LocalDate today = new LocalDate(); String pattern = "dd.MM.YYYY"; Mapping mapping = new MappingBuilder(OPERATION_FIELD_NAME) // .mapField("date", FieldMapping.map("date", new JodaLocalDateConverter(pattern))) // .mapField("flag", FieldMapping.map("flag", new StringToBooleanConverter("1", "0"))) // .build(); MapJmsPayloadHandler payloadHandler = new MapJmsPayloadHandler(mapping); JodaTimeApi service = JmsSenderFactory.create(CONFIG, payloadHandler).create(JodaTimeApi.class); // When service.localDateCall(today, flag); // Then MapMessage message = (MapMessage) captureMessage(); assertEquals(today.toString(pattern), message.getString("date")); assertEquals(flag ? "1" : "0", message.getString("flag")); }
@Test public void reportMessage_shouldBeReflectedInReportMessagesObject_whenMapMessageReceived() throws JMSException { Mockito.when(mapMessage.getStringProperty("sender")).thenReturn("service"); Mockito.when(mapMessage.getString("message")).thenReturn("db load error"); Mockito.when(mapMessage.getString("timestamp")).thenReturn("999"); Mockito.when(mapMessage.getString("severity")).thenReturn("error"); Mockito.when(dateTimeProvider.now()).thenReturn(now); Mockito.when(dateTimeProvider.stringToInstant("999")).thenReturn(sendTime); sut.onMessage(mapMessage); List<ReportMessage> reportMessages = messages.getMessages(); assertEquals(1, reportMessages.size()); ReportMessage reportMessage = reportMessages.get(0); assertEquals("service", reportMessage.getSender()); assertEquals("db load error", reportMessage.getMessage()); assertEquals("error", reportMessage.getSeverity()); assertEquals(now, reportMessage.getReceivedOn()); assertEquals(sendTime, reportMessage.getTimestamp()); }
public static String extractMapMessagePayloadToXML(MapMessage mapMessage) throws JMSException { StringBuffer sb = new StringBuffer("<message>\n"); Enumeration<?> mapNames = mapMessage.getMapNames(); while (mapNames.hasMoreElements()) { String key = (String) mapNames.nextElement(); String value = mapMessage.getString(key); sb.append("<" + key + ">" + XmlUtils.entitize(value) + "</" + key + ">\n"); } sb.append("</message>"); return sb.toString(); }
public static String extractMapMessagePayloadToString(MapMessage mapMessage) throws JMSException { StringBuffer sb = new StringBuffer(); Enumeration<?> mapNames = mapMessage.getMapNames(); while (mapNames.hasMoreElements()) { String key = (String) mapNames.nextElement(); String value = mapMessage.getString(key); sb.append(key + ": " + value); } return sb.toString(); }
public void onMessage(Message msg) { // TODO Auto-generated method stub if (observer != null) { MapMessage msg1 = (MapMessage) msg; L1Data data = new L1Data(); try { data.symbol_ = msg1.getString("Symbol"); data.price_ = msg1.getDouble("LastPrice"); } catch (JMSException e) { // TODO Auto-generated catch block e.printStackTrace(); } observer.update(data); } }
@Override public void widgetSelected(SelectionEvent ev) { SendMapMessage sender = new SendMapMessage(); try { sender.startSender(); MapMessage message = sender.getSessionMessageObject(); PropertyList properties = messageTable.getPropertyList(); Vector<Property> propertyList = properties.getProperties(); ListIterator<Property> it = propertyList.listIterator(); while (it.hasNext()) { Property p = (Property) it.next(); message.setString(p.getProperty(), p.getValue()); } int count; try { count = Integer.parseInt(_countField.getText()); } catch (NumberFormatException e) { count = 1; } if (count == 1) { message.setString("EVENTTIME", (_jmsDateFormat.format(Calendar.getInstance().getTime()))); sender.sendMessage(_topicField.getText()); } else { for (int i = 0; i < count; i++) { String name = message.getString("NAME"); String[] nameParts = name.split("_"); name = nameParts[0] + "_" + i; message.setString("NAME", name); message.setString( "EVENTTIME", (_jmsDateFormat.format(Calendar.getInstance().getTime()))); sender.sendMessage(_topicField.getText()); } } } catch (Exception e) { MessageDialog.openError(null, "JMS Sender", "Error sending JMS message: " + e.getMessage()); } finally { try { sender.stopSender(); } catch (Exception e) { e.printStackTrace(); } } }
/** * @param message JMSMap message * @return XML representation of JMS Map message */ public static OMElement convertJMSMapToXML(MapMessage message) { OMFactory fac = OMAbstractFactory.getOMFactory(); OMNamespace jmsMapNS = OMAbstractFactory.getOMFactory().createOMNamespace(JMSConstants.JMS_MAP_NS, ""); OMElement jmsMap = fac.createOMElement(JMSConstants.JMS_MAP_ELEMENT_NAME, jmsMapNS); try { Enumeration names = message.getMapNames(); while (names.hasMoreElements()) { String nextName = names.nextElement().toString(); String nextVal = message.getString(nextName); OMElement next = fac.createOMElement(nextName.replace(" ", ""), jmsMapNS); next.setText(nextVal); jmsMap.addChild(next); } } catch (JMSException e) { log.error("Error while processing the JMS Map Message. " + e.getMessage()); } return jmsMap; }
public static void main(String[] args) throws Exception { stopMQService(); ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(); Connection connection = connectionFactory.createConnection(); connection.start(); final Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createQueue("my-queue"); MessageConsumer consumer = session.createConsumer(destination); /* * //listener 方式 consumer.setMessageListener(new MessageListener() { * * public void onMessage(Message msg) { MapMessage message = * (MapMessage) msg; //TODO something.... System.out.println("收到消息:" + * new Date(message.getLong("count"))); session.commit(); } * * }); Thread.sleep(30000); */ int i = 0; int num = 0; while (i < 3) { num++; MapMessage message = (MapMessage) consumer.receive(); session.commit(); // TODO something.... // System.out.println("收到消息:" + new Date(message.getLong("count"))); System.out.println("2收到第" + num + "条消息:" + message.getString("count")); // System.out.println("收到第"+num+"条消息:" + message.getString("mes")); } session.close(); connection.close(); }
public Object fromMessage(Message message) throws JMSException, MessageConversionException { MapMessage mapMessage = (MapMessage) message; Person person = new Person(mapMessage.getString("name"), mapMessage.getInt("age")); return person; }
/** @param message - map message which contains data to tenant creation via a rest call. */ @Override public void onMessage(Message message) { TenantInfoBean tenantInfoBean = null; MapMessage mapMessage; if (message instanceof MapMessage) { mapMessage = (MapMessage) message; String tenantInfoJson; try { tenantInfoJson = mapMessage.getString(AppFactoryConstants.TENANT_INFO); ObjectMapper mapper = new ObjectMapper(); tenantInfoBean = mapper.readValue(tenantInfoJson, TenantInfoBean.class); if (log.isDebugEnabled()) { log.debug("Received a message for tenant domain " + tenantInfoBean.getTenantDomain()); } mapMessage.acknowledge(); } catch (JMSException e) { log.error("Error while getting message content.", e); throw new RuntimeException(e); } catch (JsonParseException e) { log.error("Error while converting the json to object.", e); throw new RuntimeException(e); } catch (JsonMappingException e) { log.error("Error while converting the json to object.", e); throw new RuntimeException(e); } catch (IOException e) { log.error("Error while converting the json to object.", e); throw new RuntimeException(e); } } try { int tenantId = ServiceHolder.getRealmService() .getTenantManager() .getTenantId(tenantInfoBean.getTenantDomain()); if (tenantId == MultitenantConstants.INVALID_TENANT_ID) { addTenant(tenantInfoBean); } else { if (log.isDebugEnabled()) { log.debug( "Tenant Already exist, skipping the tenant addition. Tenant domain : " + tenantInfoBean.getTenantDomain() + "and tenant Id : " + tenantInfoBean.getTenantId()); } } } catch (JMSException e) { String msg = "Can not read received map massage"; log.error(msg, e); throw new RuntimeException(e); } catch (AppFactoryException e) { String msg = "Can not create tenant"; log.error(msg, e); throw new RuntimeException(e); } catch (Exception e) { String msg = "Can not create tenant"; log.error(msg, e); throw new RuntimeException(e); } }