public void testNoScheduledRedeliveryOfExpired() throws Exception {
    startBroker(true);
    ActiveMQConnection consumerConnection = (ActiveMQConnection) createConnection();
    consumerConnection.start();
    Session consumerSession = consumerConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    MessageConsumer consumer = consumerSession.createConsumer(destination);
    sendMessage(1500);
    Message message = consumer.receive(1000);
    assertNotNull("got message", message);

    // ensure there is another consumer to redispatch to
    MessageConsumer redeliverConsumer = consumerSession.createConsumer(destination);

    // allow consumed to expire so it gets redelivered
    TimeUnit.SECONDS.sleep(2);
    consumer.close();

    // should go to dlq as it has expired
    // validate DLQ
    MessageConsumer dlqConsumer =
        consumerSession.createConsumer(
            new ActiveMQQueue(SharedDeadLetterStrategy.DEFAULT_DEAD_LETTER_QUEUE_NAME));
    Message dlqMessage = dlqConsumer.receive(2000);
    assertNotNull("Got message from dql", dlqMessage);
    assertEquals(
        "message matches", message.getStringProperty("data"), dlqMessage.getStringProperty("data"));
  }
 @Override
 public void onMessageDo(Message msg) throws Exception {
   String type = msg.getStringProperty("type");
   if (ResmMessageListener.TYPE_OBJECT_SYNC.equals(type)) {
     TextMessage text = (TextMessage) msg;
     int id = StringUtil.parseInt(text.getText(), -1);
     logger.debug("接收到同步消息:资源ID=" + text.getText());
     if (id > 0) ServiceManager.getResourceUpdateService().syncResource(id);
   } else if (ResmMessageListener.TYPE_CACHE_ADD.equals(type)) {
     ObjectMessage object = (ObjectMessage) msg;
     String cacheName = msg.getStringProperty("cache");
     CacheableObject obj = (CacheableObject) object.getObject();
     logger.debug("接收到缓存增加消息:" + cacheName + " " + obj.getClass().getName());
     obj.onDeserialize();
     obj.dump();
     CacheManager.addCache(cacheName, obj);
   } else if (ResmMessageListener.TYPE_CACHE_REMOVE.equals(type)) {
     ObjectMessage object = (ObjectMessage) msg;
     String cacheName = msg.getStringProperty("cache");
     CacheableObject obj = (CacheableObject) object.getObject();
     logger.debug("接收到缓存删除消息:" + cacheName + " " + obj.getClass().getName());
     obj.onDeserialize();
     obj.dump();
     CacheManager.removeCache(cacheName, obj);
   } else {
     System.out.println(msg.toString());
   }
 }
 public String send(
     final T message,
     final Message correlatedMessage,
     final String correlationId,
     final URI dvbEndpointSelector,
     final String jmsGroupId,
     final Destination replyQueue) {
   try {
     final M jmsMessage = this.messageHandler.createEmptyMessage(this.sessionDelegate);
     jmsMessage.setJMSCorrelationID(determineCorrelationId(correlationId, correlatedMessage));
     Destination replyTo =
         replyQueue == null ? this.defaultReplyDestinationDelegate.delegate() : replyQueue;
     if (replyTo != null) {
       jmsMessage.setJMSReplyTo(replyTo);
     }
     final URI temp = DataUtilities.coalesce(dvbEndpointSelector, this.defaultEndpoint);
     if (temp != null) {
       jmsMessage.setStringProperty(
           JMSMessageSender.ENDPOINT_NAMESPACE, dvbEndpointSelector.toASCIIString());
     }
     if (correlatedMessage != null && this.copyPropertyPattern != null) {
       //noinspection unchecked
       for (final String name :
           Collections.list((Enumeration<String>) correlatedMessage.getPropertyNames())) {
         if (this.copyPropertyPattern.matcher(name).matches()) {
           if (correlatedMessage.getStringProperty(name) != null) {
             jmsMessage.setStringProperty(name, correlatedMessage.getStringProperty(name));
           } else {
             jmsMessage.setObjectProperty(name, correlatedMessage.getObjectProperty(name));
           }
         }
       }
     }
     this.messageHandler.fillMessage(message, jmsMessage);
     if (jmsGroupId != null) {
       jmsMessage.setStringProperty(JMSMessageSender.JMSX_GROUP_ID, jmsGroupId);
     }
     Delegate<MessageProducer> producer = this.producerDelegate;
     if (correlatedMessage != null && correlatedMessage.getJMSReplyTo() != null) {
       producer =
           new JMSMessageProducerDelegate(
               sessionDelegate, new UnmodifiableDelegate<>(correlatedMessage.getJMSReplyTo()));
     }
     producer.delegate().send(jmsMessage);
     return jmsMessage.getJMSMessageID();
   } catch (final JMSException e) {
     throw DelegatedException.delegate(e);
   }
 }
 static Map<String, Set<String>> get(final Message msg, final String prefix) throws JMSException {
   String regexSafeDelimiter = Pattern.quote(DELIMITER);
   final Map<String, Set<String>> map = new HashMap<String, Set<String>>();
   final Enumeration names = msg.getPropertyNames();
   while (names.hasMoreElements()) {
     final String name = names.nextElement().toString();
     final String value = msg.getStringProperty(name);
     if (name.startsWith(prefix) && name.endsWith(COPY) == false) {
       final String property = msg.getStringProperty(name + COPY);
       if (property != null) {
         map.put(value, new HashSet<String>(Arrays.asList(property.split(regexSafeDelimiter))));
       }
     }
   }
   return map;
 }
  public void invalidateObject(Session session, javax.jms.Message msg)
      throws javax.jms.JMSException {
    String tableName = msg.getStringProperty("TABLE");
    if (tableName == null) {
      return;
    }
    Class baseClass = (Class) tableNameToClass.get(tableName);
    if (baseClass == null) {
      return;
    }
    Vector pkFieldNames = (Vector) tableNameToPkFieldNames.get(tableName);
    if (pkFieldNames == null) {
      return;
    }

    // create DatabaseRecord corresponding to the message
    DatabaseRecord row = new DatabaseRecord(pkFieldNames.size());
    for (int i = 0; i < pkFieldNames.size(); i++) {
      String fieldName = (String) pkFieldNames.elementAt(i);
      Object value = msg.getObjectProperty(fieldName);
      row.put(fieldName, value);
    }

    // invalidate in TopLink cache the object corresponding to the row and the baseClass
    session.getIdentityMapAccessor().invalidateObject(row, baseClass);
  }
 /**
  * @param type
  * @param clazz
  * @param bool
  * @throws JMSException
  */
 private void bodyAssignableFrom(final JmsMessageType type, final boolean bool, Class... clazz)
     throws JMSException {
   Assert.assertNotNull("clazz!=null", clazz);
   Assert.assertTrue("clazz[] not empty", clazz.length > 0);
   Object body = createBodySendAndReceive(type);
   Message msg = queueConsumer.receive(500);
   Assert.assertNotNull("must have a msg", msg);
   Assert.assertEquals(type.toString(), msg.getStringProperty("type"));
   for (Class<?> c : clazz) {
     Assert.assertEquals(
         msg + " " + type + " & " + c + ": " + bool, bool, msg.isBodyAssignableTo(c));
     if (bool) {
       Object receivedBody = msg.getBody(c);
       Assert.assertTrue("correct type " + c, c.isInstance(receivedBody));
       if (body.getClass().isAssignableFrom(byte[].class)) {
         Arrays.equals((byte[]) body, (byte[]) receivedBody);
       } else {
         Assert.assertEquals(
             "clazz=" + c + ", bodies must match.. " + body.equals(receivedBody),
             body,
             receivedBody);
       }
     } else {
       try {
         Object foo = msg.getBody(c);
         Assert.fail("expected a " + MessageFormatException.class);
       } catch (MessageFormatException e) {
         // expected
       }
     }
   }
 }
  public static String getSourceFPSName(Message message) throws JMSException {
    if (!message.propertyExists(MessagePropertyNames.SOURCE)) {
      return SOURCE_FPS_NAME_DEF;
    }

    return message.getStringProperty(MessagePropertyNames.SOURCE);
  }
  @Override
  public void onMessage(Message msg) {
    try {
      if (!msg.propertyExists(AppConsts.MESSAGE_TYPE) || !(msg instanceof TextMessage)) {
        throw new IOError(null);
      }
      String type = msg.getStringProperty(AppConsts.MESSAGE_TYPE);
      if (type.equals(AppConsts.CHANGE_BALANCE_MT)) {
        String text = ((TextMessage) msg).getText();
        ChangeBalanceDTO dto = null;
        try {
          dto = ju.fromXml(text, ChangeBalanceDTO.class);
        } catch (Exception e) {
          log.error("Could not convert xml to object", e);
          throw new IOError(null);
        }
        if (db.changeBalance(dto.getPhoneNumber(), dto.getDelta()) == null) {
          throw new IOError(null);
        }

      } else {
        throw new IOError(null);
      }
    } catch (IOError e) {
      forwardMessageToNone(msg);
    } catch (JMSException e) {
      log.trace(e.getMessage(), e);
    }
  }
Beispiel #9
0
  private void addMessageIDInHeader(final Message msg) throws Exception {
    // We concatenate the old message id as a header in the message
    // This allows the target to then use this as the JMSCorrelationID of any response message
    // thus enabling a distributed request-response pattern.
    // Each bridge (if there are more than one) in the chain can concatenate the message id
    // So in the case of multiple bridges having routed the message this can be used in a multi-hop
    // distributed request/response
    if (JMSBridgeImpl.trace) {
      HornetQJMSServerLogger.LOGGER.trace("Adding old message id in Message header");
    }

    JMSBridgeImpl.copyProperties(msg);

    String val = null;

    val = msg.getStringProperty(HornetQJMSConstants.JBOSS_MESSAGING_BRIDGE_MESSAGE_ID_LIST);

    if (val == null) {
      val = msg.getJMSMessageID();
    } else {
      StringBuffer sb = new StringBuffer(val);

      sb.append(",").append(msg.getJMSMessageID());

      val = sb.toString();
    }

    msg.setStringProperty(HornetQJMSConstants.JBOSS_MESSAGING_BRIDGE_MESSAGE_ID_LIST, val);
  }
  public static String getUserDefinedId(Message message) throws JMSException {
    if (!message.propertyExists(MessagePropertyNames.USER_DEFINED_DOC_ID)) {
      return USER_DEFINED_DOC_ID_DEF;
    }

    return message.getStringProperty(MessagePropertyNames.USER_DEFINED_DOC_ID);
  }
  public static final void printMessageHeaders(Message pMessge, Object pHandler) {
    StringWriter stringWriter = new StringWriter();

    PrintWriter writer = new PrintWriter(stringWriter);

    try {
      writer.println("===================================================");
      writer.println("MDB Event Handler class=[" + pHandler.getClass().getName() + "]");
      writer.println("");
      writer.println("JMS Message Id: " + pMessge.getJMSMessageID());

      for (Enumeration em = pMessge.getPropertyNames(); em.hasMoreElements(); ) {
        String property = (String) em.nextElement();
        writer.println(
            "JMS Prop=[" + property + "] value=[" + pMessge.getStringProperty(property) + "]");
      }

      writer.println("===================================================");
    } catch (JMSException e) {
      e.printStackTrace();
    }

    writer.flush();
    System.out.println(stringWriter.toString());
  }
  public static String getEventProcessVersion(Message message) throws JMSException {
    if (!message.propertyExists(MessagePropertyNames.EVENT_PROCESS_VERSION)) {
      return EVENT_PROCESS_VERSION_DEF;
    }

    return message.getStringProperty(MessagePropertyNames.EVENT_PROCESS_VERSION);
  }
  public static String getEventStatus(Message message) throws JMSException {
    if (!message.propertyExists(MessagePropertyNames.EVENT_STATUS)) {
      return EVENT_STATUS_DEF;
    }

    return message.getStringProperty(MessagePropertyNames.EVENT_STATUS);
  }
  public static String getCompInstName(Message message) throws JMSException {
    if (!message.propertyExists(MessagePropertyNames.COMP_INST_NAME)) {
      return COMP_INST_NAME_DEF;
    }

    return message.getStringProperty(MessagePropertyNames.COMP_INST_NAME);
  }
  public static String getEventProcessName(Message message) throws JMSException {
    if (!message.propertyExists(MessagePropertyNames.EVENT_PROCESS_NAME)) {
      return EVENT_PROCESS_NAME_DEF;
    }

    return message.getStringProperty(MessagePropertyNames.EVENT_PROCESS_NAME);
  }
Beispiel #16
0
  @Override
  public void onMessage(Message message) {
    if (!(message instanceof ObjectMessage)) {
      return;
    }

    try {
      Object objectInMessage = ((ObjectMessage) message).getObject();
      if (!(objectInMessage instanceof LectureWrapperDTO)) {
        return;
      }

      final String messageAction = message.getStringProperty("action");
      if (messageAction == null) {
        return;
      }
      LectureWrapperDTO lectureWrapperDTO = (LectureWrapperDTO) objectInMessage;

      if (messageAction.equals(ISchedulerListener.InfoType.CREATED.toString())) {
        schedulerListener.notify(ISchedulerListener.InfoType.CREATED, lectureWrapperDTO);
      } else if (messageAction.equals(ISchedulerListener.InfoType.INFO.toString())) {
        schedulerListener.notify(ISchedulerListener.InfoType.INFO, lectureWrapperDTO);
      } else if (messageAction.equals(ISchedulerListener.InfoType.DENIED.toString())) {
        schedulerListener.notify(ISchedulerListener.InfoType.DENIED, lectureWrapperDTO);
      } else if (messageAction.equals(ISchedulerListener.InfoType.STREAMED.toString())) {
        schedulerListener.notify(ISchedulerListener.InfoType.STREAMED, lectureWrapperDTO);
      }
    } catch (JMSException e) {
      e.printStackTrace();
    }
  }
  public static String getSink(Message message) throws JMSException {
    if (!message.propertyExists(MessagePropertyNames.SINK)) {
      return null;
    }

    return message.getStringProperty(MessagePropertyNames.SINK);
  }
  public static String getComment(Message message) throws JMSException {
    if (!message.propertyExists(MessagePropertyNames.COMMENT)) {
      return COMMENT_DEF;
    }

    return message.getStringProperty(MessagePropertyNames.COMMENT);
  }
  @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);
    }
  }
  public static String getPortName(Message message) throws JMSException {
    if (!message.propertyExists(MessagePropertyNames.PORT_NAME)) {
      return PORT_NAME_DEF;
    }

    return message.getStringProperty(MessagePropertyNames.PORT_NAME);
  }
  public static String getDocumentID(Message message) throws JMSException {
    if (!message.propertyExists(MessagePropertyNames.DOCUMENT_ID)) {
      return DOCUMENT_ID_DEF;
    }

    return message.getStringProperty(MessagePropertyNames.DOCUMENT_ID);
  }
  public static String getEventDescription(Message message) throws JMSException {
    if (!message.propertyExists(MessagePropertyNames.EVENT_DESCRIPTION)) {
      return EVENT_DESCRIPTION_DEF;
    }

    return message.getStringProperty(MessagePropertyNames.EVENT_DESCRIPTION);
  }
  public static String getEventCategory(Message message) throws JMSException {
    if (!message.propertyExists(MessagePropertyNames.EVENT_CATEGORY)) {
      return EVENT_MODULE_DEF;
    }

    return message.getStringProperty(MessagePropertyNames.EVENT_CATEGORY);
  }
  public static String getWorkFlowInstId(Message message) throws JMSException {
    if (!message.propertyExists(MessagePropertyNames.WORK_FLOW_INST_ID)) {
      return WORK_FLOW_INST_ID_DEF;
    }

    return message.getStringProperty(MessagePropertyNames.WORK_FLOW_INST_ID);
  }
 /**
  * {@inheritDoc}
  *
  * @see javax.jms.MessageListener#onMessage(javax.jms.Message)
  */
 public void onMessage(Message message) {
   try {
     String fromServer = message.getStringProperty(ClusterTrackingService.EVENT_FROM_SERVER);
     String toServer = message.getStringProperty(ClusterTrackingService.EVENT_TO_SERVER);
     String trackingCookie =
         message.getStringProperty(ClusterTrackingService.EVENT_TRACKING_COOKIE);
     String remoteUser = message.getStringProperty(ClusterTrackingService.EVENT_USER);
     LOGGER.info(
         "Started handling cluster user jms message. from:{} to:{} cookie:{} user:{}",
         new Object[] {fromServer, toServer, trackingCookie, remoteUser});
     clusterTrackingServiceImpl.pingTracking(trackingCookie, remoteUser, false);
   } catch (PingRemoteTrackingFailedException e) {
     LOGGER.error(e.getMessage());
   } catch (JMSException e) {
     LOGGER.error(e.getMessage(), e);
   }
 }
Beispiel #26
0
 @Override
 public void onMessage(Message message) {
   try {
     log.info("pms heart beat receive :" + message.getStringProperty("messageType"));
   } catch (JMSException e) {
     e.printStackTrace();
   }
 }
  /**
   * Get property
   *
   * @param name The name
   * @return The value
   * @throws JMSException Thrown if an error occurs
   */
  @Override
  public String getStringProperty(final String name) throws JMSException {
    if (ActiveMQRAMessage.trace) {
      ActiveMQRALogger.LOGGER.trace("getStringProperty(" + name + ")");
    }

    return message.getStringProperty(name);
  }
  private List<Message> filterForEvent(GameEvent event) throws JMSException {
    ArrayList ret = new ArrayList();
    List<Message> ml = mockTopic.getReceivedMessageList();
    for (Message msg : ml) {
      if (msg.getStringProperty("GAME_EVENT").equals(event.name())) ret.add(msg);
    }

    return ret;
  }
Beispiel #29
0
      @Override
      public void run() {

        try {

          int count = 0;

          // Keep reading as long as it hasn't been told to shutdown
          while (!shutdown) {

            if (idList.size() >= totalToExpect) {
              LOG.info("Got {} for q: {}", +idList.size(), qName);
              session.commit();
              break;
            }
            Message m = mc.receive(4000);

            if (m != null) {

              // We received a non-null message, add the ID to our list

              idList.add(m.getStringProperty("KEY"));

              count++;

              // If we've reached our batch size, commit the batch and reset the count

              if (count == batchSize) {
                session.commit();
                count = 0;
              }
            } else {

              // We didn't receive anything this time, commit any current batch and reset the count

              session.commit();
              count = 0;

              // Sleep a little before trying to read after not getting a message

              try {
                if (idList.size() < totalToExpect) {
                  LOG.info("did not receive on {}, current count: {}", qName, idList.size());
                }
                // sleep(3000);
              } catch (Exception e) {
              }
            }
          }
        } catch (Exception e) {
          e.printStackTrace();
        } finally {

          // Once we exit, close everything
          close();
        }
      }
Beispiel #30
0
  public static void constructConnectorMessageProperties(
      Message jmsMsg, CustomMessagePropertyList customMessagePropertyList) throws JMSException {
    List<CustomMessageProperty> customMessageProperties =
        customMessagePropertyList.getCustomMessageProperty();
    int index = 0;

    while (index < JMSConstants.ARR_CUSTOM_PROPS.length) {
      if (jmsMsg.getStringProperty(JMSConstants.ARR_CUSTOM_PROPS[index]) != null
          && jmsMsg.getStringProperty(JMSConstants.ARR_CUSTOM_PROPS[index]).isEmpty()) {
        CustomMessageProperty customMessageProperty = new CustomMessageProperty();
        customMessageProperty.setName(JMSConstants.ARR_CUSTOM_PROPS[index]);
        customMessageProperty.setValue(
            jmsMsg.getStringProperty(JMSConstants.ARR_CUSTOM_PROPS[index]));
        customMessageProperties.add(customMessageProperty);
        index++;
      }
    }
  }