Пример #1
0
 public void onMessage(Message message) {
   try {
     MapMessage request = (MapMessage) message;
     String correlationID = request.getJMSCorrelationID();
     int itemId = request.getInt("itemId");
     // Retrieve the connection factory
     connectionFactory =
         (TopicConnectionFactory) initialContext.lookup(BeanConfig.TopicConnectionFactoryName);
     // get the bids history
     String html = getBidHistory(itemId);
     // send the reply
     TemporaryTopic temporaryTopic = (TemporaryTopic) request.getJMSReplyTo();
     if (temporaryTopic != null) {
       // create a connection
       connection = connectionFactory.createTopicConnection();
       // create a session: no transaction, auto ack
       session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
       TextMessage reply = session.createTextMessage();
       reply.setJMSCorrelationID(correlationID);
       reply.setText(html);
       replier = session.createPublisher(null); // unidentified publisher
       connection.start();
       replier.publish(temporaryTopic, reply);
       replier.close();
       session.close();
       connection.stop();
       connection.close();
     }
   } catch (Exception e) {
     throw new EJBException("Message traitment failed for MDB_ViewBidHistory: " + e);
   }
 }
Пример #2
0
 public Message createMessage(Session session) throws JMSException {
   MapMessage msg = session.createMapMessage();
   msg.setString("JID", JID);
   msg.setString("URL", URL);
   msg.setString("DESC", DESC);
   return msg;
 }
 private MapMessage newMapMessage(Map<String, Object> body) throws JMSException {
   MapMessage message = new MapMessageImpl();
   for (String key : body.keySet()) {
     Object value = body.get(key);
     message.setObject(key, value);
   }
   return message;
 }
  @Test
  public void shouldMapSendOperationAttribute() throws JMSException {
    MappedApi service = service(new MappingBuilder("myop").build());

    // When
    service.mappedNoArgCall();

    // Then
    MapMessage message = (MapMessage) captureMessage();
    assertEquals("mappedNoArgCall", message.getObject("myop"));
  }
Пример #5
0
  public Value receive(Env env, @Optional("1") long timeout) throws JMSException {
    Message message = _consumer.receive(timeout);

    if (message == null) return BooleanValue.FALSE;

    if (message instanceof ObjectMessage) {
      Object object = ((ObjectMessage) message).getObject();

      return env.wrapJava(object);
    } else if (message instanceof TextMessage) {
      return env.createString(((TextMessage) message).getText());
    } else if (message instanceof StreamMessage) {
      Object object = ((StreamMessage) message).readObject();

      return env.wrapJava(object);
    } else if (message instanceof BytesMessage) {
      BytesMessage bytesMessage = (BytesMessage) message;
      int length = (int) bytesMessage.getBodyLength();

      StringValue bb = env.createBinaryBuilder(length);

      TempBuffer tempBuffer = TempBuffer.allocate();
      int sublen;

      while (true) {
        sublen = bytesMessage.readBytes(tempBuffer.getBuffer());

        if (sublen > 0) bb.append(tempBuffer.getBuffer(), 0, sublen);
        else break;
      }

      TempBuffer.free(tempBuffer);

      return bb;
    } else if (message instanceof MapMessage) {
      MapMessage mapMessage = (MapMessage) message;

      Enumeration mapNames = mapMessage.getMapNames();

      ArrayValue array = new ArrayValueImpl();

      while (mapNames.hasMoreElements()) {
        String name = mapNames.nextElement().toString();

        Object object = mapMessage.getObject(name);

        array.put(env.createString(name), env.wrapJava(object));
      }

      return array;
    } else {
      return BooleanValue.FALSE;
    }
  }
Пример #6
0
 @Override
 public Message convert(Map<String, Object> payload) throws TransformationException {
   try {
     MapMessage mapMsg = session.createMapMessage();
     for (Map.Entry<String, Object> entry : payload.entrySet()) {
       mapMsg.setObject(entry.getKey(), entry.getValue());
     }
     return mapMsg;
   } catch (JMSException e) {
     throw new TransformationException(e);
   }
 }
Пример #7
0
  public boolean send(@NotNull Value value, @Optional JMSQueue replyTo) throws JMSException {
    Message message = null;

    if (value.isArray()) {
      message = _session.createMapMessage();

      ArrayValue array = (ArrayValue) value;

      Set<Map.Entry<Value, Value>> entrySet = array.entrySet();

      for (Map.Entry<Value, Value> entry : entrySet) {
        if (entry.getValue() instanceof BinaryValue) {
          byte[] bytes = ((BinaryValue) entry.getValue()).toBytes();

          ((MapMessage) message).setBytes(entry.getKey().toString(), bytes);
        } else {
          // every primitive except for bytes can be translated from a string
          ((MapMessage) message).setString(entry.getKey().toString(), entry.getValue().toString());
        }
      }
    } else if (value instanceof BinaryValue) {
      message = _session.createBytesMessage();

      byte[] bytes = ((BinaryValue) value).toBytes();

      ((BytesMessage) message).writeBytes(bytes);
    } else if (value.isLongConvertible()) {
      message = _session.createStreamMessage();

      ((StreamMessage) message).writeLong(value.toLong());
    } else if (value.isDoubleConvertible()) {
      message = _session.createStreamMessage();

      ((StreamMessage) message).writeDouble(value.toDouble());
    } else if (value.toJavaObject() instanceof String) {
      message = _session.createTextMessage();

      ((TextMessage) message).setText(value.toString());
    } else if (value.toJavaObject() instanceof Serializable) {
      message = _session.createObjectMessage();

      ((ObjectMessage) message).setObject((Serializable) value.toJavaObject());
    } else {
      return false;
    }

    if (replyTo != null) message.setJMSReplyTo(replyTo._destination);

    _producer.send(message);

    return true;
  }
  @Test
  public void shouldMapSendAttributes() throws JMSException {
    // Given
    MappedApi proxy = MessageSender.of(MappedApi.class);

    // When
    proxy.mappedCall("a", 0L);

    // Then
    MapMessage message = (MapMessage) captureMessage();
    assertEquals("a", message.getObject("A"));
    assertEquals("0", message.getObject("B"));
  }
  @Test
  public void shouldMapSendOperationName() throws JMSException {
    // Given
    Mapping mapping =
        new MappingBuilder(OPERATION_FIELD_NAME) //
            .mapOperation("mappedNoArgCall", "MAPPED_NOARG_OP")
            .build();
    MappedApi service = service(mapping);

    // When
    service.mappedNoArgCall();

    // Then
    MapMessage message = (MapMessage) captureMessage();
    assertEquals("MAPPED_NOARG_OP", message.getObject(OPERATION_FIELD_NAME));
  }
Пример #10
0
  public void onMessage(Message message) {

    try {
      boolean accepted = false;

      // Get the data from the message
      MapMessage msg = (MapMessage) message;
      double salary = msg.getDouble("Salary");
      double loanAmt = msg.getDouble("LoanAmount");

      // Determine whether to accept or decline the loan
      if (loanAmt < 200000) {
        accepted = (salary / loanAmt) > .25;
      } else {
        accepted = (salary / loanAmt) > .33;
      }
      System.out.println(
          ""
              + "Percent = "
              + (salary / loanAmt)
              + ", loan is "
              + (accepted ? "Accepted!" : "Declined"));

      // Send the results back to the borrower
      TextMessage tmsg = qSession.createTextMessage();
      tmsg.setText(accepted ? "Accepted!" : "Declined");

      // correlation
      tmsg.setJMSCorrelationID(message.getJMSMessageID());

      // Create the sender and send the message
      qSender = qSession.createSender((Queue) message.getJMSReplyTo());
      qSender.send(tmsg);

      System.out.println("\nWaiting for loan requests...");

    } catch (JMSException jmse) {
      jmse.printStackTrace();
      System.exit(1);
    } catch (Exception jmse) {
      jmse.printStackTrace();
      System.exit(1);
    }
  }
Пример #11
0
 /**
  * Each message will be divided into groups and create the map message
  *
  * @param producer Used for sending messages to a destination
  * @param session Used to produce the messages to be sent
  * @param messagesList List of messages to be sent individual message event data should be in
  *     "attributeName(attributeType):attributeValue" format
  */
 public static void publishMapMessage(
     MessageProducer producer, Session session, List<String> messagesList)
     throws IOException, JMSException {
   String regexPattern = "(.*)\\((.*)\\):(.*)";
   Pattern pattern = Pattern.compile(regexPattern);
   for (String message : messagesList) {
     MapMessage mapMessage = session.createMapMessage();
     for (String line : message.split("\\n")) {
       if (line != null && !line.equalsIgnoreCase("")) {
         Matcher matcher = pattern.matcher(line);
         if (matcher.find()) {
           mapMessage.setObject(
               matcher.group(1), parseAttributeValue(matcher.group(2), matcher.group(3)));
         }
       }
     }
     producer.send(mapMessage);
   }
 }
Пример #12
0
  public void onMessage(Message message) {

    try {
      boolean accepted = false;

      // Get the data from the message
      MapMessage msg = (MapMessage) message;
      double salary = msg.getDouble("Salary");
      double expAmt = msg.getDouble("Years’ experience");

      // Determine whether to accept or decline the loan
      if (expAmt < 200000) {
        accepted = (salary / expAmt) > .25;
      } else {
        accepted = (salary / expAmt) > .33;
      }
      if (salary <= 32000) {
        accepted = true;
      } else {
        if (expAmt == 0) accepted = false;
        else accepted = ((double) (expAmt - 32000) / expAmt) < 3000.;
      }
      System.out.println(" Salary proposal is " + (accepted ? "Accepted!" : "Declined"));

      // Send the results back to the borrower
      TextMessage tmsg = qSession.createTextMessage();
      tmsg.setText(accepted ? "Accepted!" : "Declined");
      tmsg.setJMSCorrelationID(message.getJMSMessageID());

      // Create the sender and send the message
      QueueSender qSender = qSession.createSender((Queue) message.getJMSReplyTo());
      qSender.send(tmsg);

      System.out.println("\nWaiting for salary requests...");

    } catch (JMSException jmse) {
      jmse.printStackTrace();
      System.exit(1);
    } catch (Exception jmse) {
      jmse.printStackTrace();
      System.exit(1);
    }
  }
  @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"));
  }
Пример #14
0
  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();
  }
  /** @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);
    }
  }