@Override
 public Message convert(byte[] payload) throws TransformationException {
   try {
     BytesMessage bytesMsg = session.createBytesMessage();
     bytesMsg.writeBytes(payload);
     return bytesMsg;
   } catch (JMSException e) {
     throw new TransformationException(e);
   }
 }
Esempio n. 2
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;
    }
  }
  public static void setBytesData(Message message, byte[] data) throws JMSException {
    if (data == null) {
      return;
    }

    if (message instanceof BytesMessage) {
      BytesMessage bytesMessage = (BytesMessage) message;
      bytesMessage.clearBody();
      bytesMessage.writeBytes(data);
    } else {
      message.setObjectProperty(MessagePropertyNames.BYTES_DATA, data);
    }
  }
  public static byte[] getBytesData(Message message) throws JMSException {
    if (message instanceof BytesMessage) {
      BytesMessage bytesMessage = (BytesMessage) message;
      byte bytes[] = new byte[(int) bytesMessage.getBodyLength()];
      bytesMessage.readBytes(bytes);
      return bytes;
    }

    if (!message.propertyExists(MessagePropertyNames.BYTES_DATA)) {
      return BYTES_DATA_DEF;
    }

    return (byte[]) message.getObjectProperty(MessagePropertyNames.BYTES_DATA);
  }
Esempio n. 5
0
 public void run() {
   try {
     while (true) {
       consume();
       BytesMessage tMsg = (BytesMessage) message;
       byte[] bytes = new byte[(int) ((BytesMessage) message).getBodyLength()];
       tMsg.readBytes(bytes);
       System.out.println(bytes);
       for (byte b : bytes) {
         System.out.println((char) b);
       }
     }
   } catch (Exception e) {
     System.out.println("Receiver Run Error");
   }
 }
Esempio n. 6
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;
  }
  /**
   * Receives a message from the given blocking queue, waiting up to the given timeout value.
   *
   * @param queue the queue from which to consume
   * @param timeout greater than 0 to wait the given number of milliseconds, 0 for unlimited
   *     blocking wait, less than zero for no wait
   * @return the message received or null if no message was received
   * @throws JMSException
   */
  protected Message receive(BlockingQueue<byte[]> queue, long timeout) throws JMSException {

    // Figure out the receive strategy.
    ReceiveStrategy receiver = null;
    if (timeout < 0) {
      receiver = new IndefiniteBlockingReceive();
    } else {
      receiver = new TimedBlockingReceive(timeout);
    }

    Message msg = null;
    do {
      synchronized (STOP_GUARD) {
        try {
          byte[] msgData = receiver.receive(queue);

          // Check that we got message data
          if (msgData != null) {

            // Convert the message data back into a JMS message
            msg = messageMarshaller.toMessage(msgData);

            // Switch Bytes messages to read mode
            if (msg instanceof BytesMessage) {
              ((BytesMessage) msg).reset();
            }

            // Check for message expiration
            long expirationTime = msg.getJMSExpiration();

            if (expirationTime != 0 && expirationTime <= System.currentTimeMillis()) {
              log.info(
                  format("Dropping message [%s] because it has expired.", msg.getJMSMessageID()));
              msg = null;
            }
          }
        } catch (InterruptedException ex) {
          throw new JMSException("Error receiving message: " + ex.getMessage());
        } catch (IOException ex) {
          throw new JMSException("Error receiving message: " + ex.getMessage());
        }
      }
    } while (msg == null && receiver.isRetryable());

    return msg;
  }
  public void send(ExampleCommand command, String queueName, String filter)
      throws JMSException, IOException {
    try (Session session = connection.createSession()) {

      Message message;
      if (binaryMode) {
        message = session.createBytesMessage();
        ((BytesMessage) message).writeBytes(command.toBytes());
      } else {
        message = session.createTextMessage(command.toXml());
      }

      if (filter != null && !blank(filter)) {
        String[] parts = filter.split("\\s*=\\s*");
        message.setStringProperty(parts[0], parts[1]);
      }
      try (MessageProducer p = session.createProducer(ActiveMQJMSClient.createQueue(queueName))) {
        p.send(message, DeliveryMode.PERSISTENT, 4, 0);
      }
    }
  }
  // @Test
  public void testFetchGraphSimple() {
    try {

      String neId = "21100799";
      String group = "bw"; // interesting for the BW

      String titleX = "Bandwidth";
      String titleY = "bps";
      int timespan = 0; // Daily

      /*
      String neId = "1005255";
      String group = "cpu";    // interesting for the CPU

      String titleX = "CPU Utilization";
      String titleY = "Utilization";
      int timespan = 0;   // Daily
                */
      FetchGraphSimpleCommandMessage message =
          CommandMessageFactory.createRRDGraphSimpleCommandMessage(
              neId, group, timespan, titleX, titleY);

      MessageProducer producer = null;
      MessageConsumer consumer = null;

      try {
        // time to send the JMS request
        TextMessage reqMsg;
        Message replyMsg;

        producer = session.createProducer(new HornetQQueue(SERVICE_QUEUE));

        // this will uniquelly identify the request
        String UIID = UUID.randomUUID().toString();

        reqMsg = session.createTextMessage();
        reqMsg.setStringProperty("ServiceRRD_msg_type", "fetchGraphSimple");
        reqMsg.setStringProperty("ServiceRRD_correlation_id", UIID);

        String body = JsonUtil.getInstance().toJSON(message);

        reqMsg.setText(body);

        logger.info("SEND:\n" + body);

        producer.send(reqMsg);

        consumer =
            session.createConsumer(
                new HornetQQueue(SERVICE_REPLY_QUEUE),
                "ServiceRRD_correlation_id = '" + UIID + "'");

        replyMsg = consumer.receive(30000);

        if (replyMsg == null) {
          logger.info("ServiceRRD timeout on receive()");
        } else {
          if (replyMsg instanceof BytesMessage) {

            BytesMessage graphStream = (BytesMessage) replyMsg;

            byte[] graph = new byte[(int) graphStream.getBodyLength()];
            graphStream.readBytes(graph);

            FileOutputStream image =
                new FileOutputStream(
                    "/Users/cvasilak/Temp/svc-rrd-images/"
                        + neId
                        + "_"
                        + group
                        + "_"
                        + timespan
                        + ".png");

            image.write(graph);
            image.close();

            logger.info("image retrieved and saved!");

          } else if (replyMsg instanceof TextMessage) { // the server responded with an error
            logger.info(((TextMessage) replyMsg).getText());
          }
        }

      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        try {
          if (producer != null) producer.close();
          if (consumer != null) consumer.close();
        } catch (JMSException e) {
        }
      }
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }