Exemplo n.º 1
0
  public static void main(String[] args) throws Exception {
    try {
      Context context = init();
      ConnectionFactory connectionFactory =
          (ConnectionFactory) context.lookup("net4j.jms.ConnectionFactory"); // $NON-NLS-1$
      Destination destination = (Destination) context.lookup("StockTopic"); // $NON-NLS-1$

      Connection connection = connectionFactory.createConnection();
      Session session = connection.createSession(true, 0);

      MessageProducer publisher = session.createProducer(destination);
      MessageConsumer subscriber1 = session.createConsumer(destination);
      MessageConsumer subscriber2 = session.createConsumer(destination);
      subscriber1.setMessageListener(new MessageLogger("subscriber1")); // $NON-NLS-1$
      subscriber2.setMessageListener(new MessageLogger("subscriber2")); // $NON-NLS-1$

      connection.start();

      publisher.send(session.createObjectMessage("Message 1")); // $NON-NLS-1$
      publisher.send(session.createObjectMessage("Message 2")); // $NON-NLS-1$
      publisher.send(session.createObjectMessage("Message 3")); // $NON-NLS-1$
      publisher.send(session.createObjectMessage("Message 4")); // $NON-NLS-1$

      session.commit();
    } finally {
      ConcurrencyUtil.sleep(500);
      Server.INSTANCE.deactivate();
    }
  }
Exemplo n.º 2
0
 protected Message createJmsMessage(Exception cause, Session session) throws JMSException {
   LOG.trace("Using JmsMessageType: {}", Object);
   Message answer = session.createObjectMessage(cause);
   // ensure default delivery mode is used by default
   answer.setJMSDeliveryMode(Message.DEFAULT_DELIVERY_MODE);
   return answer;
 }
Exemplo n.º 3
0
  public void sendMessage(CommonMessage message) {
    try {
      connection = MQConnectionCreator.createConnection();
      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      destinationQueue = session.createQueue(queueName);
      producer = session.createProducer(destinationQueue);

      ObjectMessage objMessage = session.createObjectMessage();
      objMessage.setObject(message);
      /**
       * Note: set value to property of Message that will be sent and A Listener can use match the
       * specified message by queue Selector
       */
      String messageSelector = message.getMessageSelector();
      if (StringUtils.isNotBlank(messageSelector)) {
        objMessage.setStringProperty(message.getMessageSelectorKey(), messageSelector);
      }
      producer.send(objMessage);

    } catch (JMSException e) {
      handleJMSException(e);
    } finally {
      stop();
    }
  }
Exemplo n.º 4
0
  /*
   * Initiate the snapshot by sending a Marker message to one of the Players (Player0)
   * Any Player could have been used to initiate the snapshot.
   */
  private void sendInitSnapshot() {
    try {
      // Gather necessary JMS resources
      Context ctx = new InitialContext();
      ConnectionFactory cf = (ConnectionFactory) ctx.lookup("jms/myConnectionFactory");
      Queue q = (Queue) ctx.lookup("jms/PITplayer0");
      Connection con = cf.createConnection();
      Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer writer = session.createProducer(q);

      /*
       * As part of the snapshot algorithm, players need to record
       * what other Players they receive markers from.
       * "-1" indicates to the PITplayer0 that this marker is coming from
       * the monitor, not another Player.
       */
      Marker m = new Marker(-1);
      ObjectMessage msg = session.createObjectMessage(m);
      System.out.println("Initiating Snapshot");
      writer.send(msg);
      con.close();
    } catch (JMSException e) {
      System.out.println("JMS Exception thrown" + e);
    } catch (Throwable e) {
      System.out.println("Throwable thrown" + e);
    }
  }
  @Test
  public void testSendReceiveMessage() throws Exception {
    Connection conn = createConnection();

    Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

    MessageProducer prod = sess.createProducer(queue1);

    // Make persistent to make sure message gets serialized
    prod.setDeliveryMode(DeliveryMode.PERSISTENT);

    MessageConsumer cons = sess.createConsumer(queue1);

    TestMessage tm = new TestMessage(123, false);

    ObjectMessage om = sess.createObjectMessage();

    om.setObject(tm);

    conn.start();

    prod.send(om);

    ObjectMessage om2 = (ObjectMessage) cons.receive(1000);

    ProxyAssertSupport.assertNotNull(om2);

    TestMessage tm2 = (TestMessage) om2.getObject();

    ProxyAssertSupport.assertEquals(123, tm2.getID());

    conn.close();
  }
Exemplo n.º 6
0
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   resp.setContentType("text/html");
   PrintWriter out = resp.getWriter();
   Connection connection = null;
   out.write("<h1>Produce JMS ObjectMessages</h1>");
   try {
     connection = connectionFactory.createConnection();
     Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
     MessageProducer producer = session.createProducer(queue);
     ObjectMessage message = session.createObjectMessage();
     MyResource resource = new MyResource("This is my resource");
     message.setObject(resource);
     producer.send(message);
     out.write("<p>Send JMS Message with object: " + resource + "</p>");
   } catch (JMSException e) {
     e.printStackTrace();
     out.write("<h2>A problem occurred during the delivery of this message</h2>");
     out.write("</br>");
     out.write(
         "<p><i>Go your the JBoss Application Server console or Server log to see the error stack trace</i></p>");
   } finally {
     if (connection != null) {
       try {
         connection.close();
       } catch (JMSException e) {
         e.printStackTrace();
       }
     }
     if (out != null) {
       out.close();
     }
   }
 }
Exemplo n.º 7
0
  public void sendResponse(
      Destination destination, Serializable message, String correlationId, String transactionId)
      throws JMSException {
    Connection connection = null;
    Session session = null;

    try {
      InitialContext initialContext = new InitialContext(initialContextProperties);
      // InitialContext initialContext = new InitialContext();

      connectionFactoryName = "/ConnectionFactory";

      if (connectionFactory == null)
        connectionFactory = (ConnectionFactory) initialContext.lookup(connectionFactoryName);

      if (destination == null) destination = (Destination) initialContext.lookup(destinationName);

      if (userName == null || password == null) connection = connectionFactory.createConnection();
      else connection = connectionFactory.createConnection(userName, password);

      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      // session.

      MessageProducer producer = session.createProducer(destination);
      connection.start();

      ObjectMessage objectMessage = session.createObjectMessage(message);
      // objectMessage.setLongProperty(MessageConstants.PROPERTY_REQUEST_ID, requestId);
      objectMessage.setStringProperty(MessageConstants.PROPERTY_CORRELATION_ID, correlationId);
      objectMessage.setStringProperty(MessageConstants.PROPERTY_TRANSACTION_ID, transactionId);
      // objectMessage.setObjectProperty(MessageConstants.PROPERTY_MESSAGE_CONTENT, message);
      objectMessage.setJMSReplyTo(null);

      producer.send(objectMessage);

    } catch (NamingException e) {
      connectionFactory = null;
      destination = null;
      throw ExceptionUtil.rewrap(e);

    } catch (JMSException e) {
      connectionFactory = null;
      destination = null;
      throw e;

    } finally {
      // it is important to close session
      if (session != null) session.close();
      try {
        // Closing a connection automatically returns the connection and
        // its session plus producer to the resource reference pool.
        if (connection != null) connection.close();
      } catch (JMSException e) {
        // ignore
      }
      ;
    }
  }
Exemplo n.º 8
0
  private void execute() throws Exception {

    context = getContext();

    ConnectionFactory connectionFactory = null;
    Connection connection = null;
    Session session = null;
    MessageProducer producer = null;
    Destination destination = null;

    try {
      connectionFactory = (ConnectionFactory) context.lookup("jms/RemoteConnectionFactory");
      System.out.println("Acquiring connection factory success, " + connectionFactory);

      destination = (Destination) context.lookup("jms/queue/DistributedQueue");
      System.out.println("Acquiring destination success, " + destination);

      connection = connectionFactory.createConnection("democlient", "password1!");
      System.out.println("Creating connection success, " + connection);

      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      System.out.println("Creating session success, " + session);

      producer = session.createProducer(destination);
      System.out.println("Creating producer success, " + producer);

      connection.start();

      HashMap<String, Serializable> map = new HashMap<String, Serializable>();
      map.put("delay", new Long(1000 * 10));
      map.put("message", "WildFly 9 HornetQ Messaging High Available");
      System.out.println("Send 10 messages to DistributedQueue");
      for (int index = 1; index <= 10; index++) {
        map.put("count", index);
        ObjectMessage objectMessage = session.createObjectMessage();
        objectMessage.setObject(map);
        producer.send(objectMessage);
      }

      System.out.println("JMSClient exit");
    } catch (Exception e) {
      throw e;
    } finally {

      if (producer != null) {
        producer.close();
      }

      if (session != null) {
        session.close();
      }

      if (connection != null) {
        connection.close();
      }
    }
  }
Exemplo n.º 9
0
 /**
  * Create the {@link Message}
  *
  * @return jmsMessage or null if the mapping was not successfully
  */
 protected Message createJmsMessageForType(
     Exchange exchange,
     Object body,
     Map<String, Object> headers,
     Session session,
     CamelContext context,
     JmsMessageType type)
     throws JMSException {
   switch (type) {
     case Text:
       {
         TextMessage message = session.createTextMessage();
         if (body != null) {
           String payload = context.getTypeConverter().convertTo(String.class, exchange, body);
           message.setText(payload);
         }
         return message;
       }
     case Bytes:
       {
         BytesMessage message = session.createBytesMessage();
         if (body != null) {
           byte[] payload = context.getTypeConverter().convertTo(byte[].class, exchange, body);
           message.writeBytes(payload);
         }
         return message;
       }
     case Map:
       {
         MapMessage message = session.createMapMessage();
         if (body != null) {
           Map<?, ?> payload = context.getTypeConverter().convertTo(Map.class, exchange, body);
           populateMapMessage(message, payload, context);
         }
         return message;
       }
     case Object:
       ObjectMessage message = session.createObjectMessage();
       if (body != null) {
         try {
           Serializable payload =
               context.getTypeConverter().mandatoryConvertTo(Serializable.class, exchange, body);
           message.setObject(payload);
         } catch (NoTypeConversionAvailableException e) {
           // cannot convert to serializable then thrown an exception to avoid sending a null
           // message
           JMSException cause = new MessageFormatException(e.getMessage());
           cause.initCause(e);
           throw cause;
         }
       }
       return message;
     default:
       break;
   }
   return null;
 }
Exemplo n.º 10
0
  @Override
  public void info(long lectureWrapperId) {
    InfoLectureWrapperDTO infoLectureWrapperDTO = new InfoLectureWrapperDTO(lectureWrapperId);

    try {
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      ObjectMessage objectMessage = session.createObjectMessage(infoLectureWrapperDTO);
      session.createProducer(serverQueue).send(objectMessage);
    } catch (JMSException e) {
      e.printStackTrace();
    }
  }
  @Test
  public void testServer() throws Exception {
    // BrokerService broker = BrokerFactory
    // .createBroker(JMSServer.BROKER_CLIENT);
    ActiveMQTopic topic = new ActiveMQTopic("topicTest");
    // broker.setDestinations(new ActiveMQDestination[] { topic });
    // broker.start();

    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(JMSServer.BROKER_CLIENT);
    Connection conn = factory.createConnection();
    conn.start();
    Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = session.createProducer(topic);
    producer.send(session.createObjectMessage("msg test 1"));
    producer.send(session.createObjectMessage("msg test 2"));
    producer.send(session.createObjectMessage("msg test 3"));
    producer.send(session.createObjectMessage("msg test 4"));
    session.close();
    conn.stop();
    conn.close();
  }
Exemplo n.º 12
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;
  }
Exemplo n.º 13
0
  public static void main(String[] args) throws Exception {
    ConnectionFactory factory = new ActiveMQJMSConnectionFactory("tcp://localhost:61616");
    Destination destination = ActiveMQDestination.fromPrefixedName("queue://orders");

    try (Connection conn = factory.createConnection()) {
      Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer producer = session.createProducer(destination);
      ObjectMessage message = session.createObjectMessage();

      Order order = new Order("Bill", "$199.99", "iPhone4");
      message.setObject(order);
      producer.send(message);
    }
  }
Exemplo n.º 14
0
  public static void main(String[] args) {

    ActiveMQConnectionFactory connectionFactory =
        new ActiveMQConnectionFactory("admin", "password", BROKER_URL);
    Connection connection = null;

    try {

      connection = connectionFactory.createConnection();
      connection.setClientID("duravel");
      connection.start();

      Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);

      Destination destination;
      MessageProducer producer = null;
      for (int i = 0; i < NUM_MESSAGES_TO_SEND; i++) {

        System.out.println("Sending message #" + i);

        Operacao op = gerarOperacao();
        destination = session.createTopic(op.getDescricao());
        producer = session.createProducer(destination);

        ObjectMessage message = session.createObjectMessage(op);

        swingBasic.start(op);

        producer.send(message);
        Thread.sleep(DELAY);
      }

      producer.send(session.createTextMessage("END"));

      producer.close();
      session.close();

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (connection != null) {
        try {
          connection.close();
        } catch (JMSException e) {
          e.printStackTrace();
        }
      }
    }
  }
Exemplo n.º 15
0
 void sendMessage(String cmd, Map<String, String> paramMap) throws JMSException {
   Destination destination = session.createQueue(this.queueName);
   JSONObject json = new JSONObject();
   json.put("cmd", cmd);
   for (String name : paramMap.keySet()) {
     json.put(name, paramMap.get(name));
   }
   System.out.println(
       "sending user JMS message with payload:"
           + json.toString(2)
           + " to queue:"
           + this.queueName);
   Message message = session.createObjectMessage(json.toString());
   this.producer.send(destination, message);
 }
Exemplo n.º 16
0
  public void sendMessage(Serializable message) throws JMSException {
    Connection connection = null;
    Session session = null;

    try {
      InitialContext initialContext = new InitialContext(initialContextProperties);
      // InitialContext initialContext = new InitialContext();

      if (connectionFactory == null)
        connectionFactory = (ConnectionFactory) initialContext.lookup(connectionFactoryName);

      if (destination == null) destination = (Destination) initialContext.lookup(destinationName);

      if (userName == null || password == null) connection = connectionFactory.createConnection();
      else connection = connectionFactory.createConnection(userName, password);

      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      // session.

      MessageProducer producer = session.createProducer(destination);
      connection.start();

      ObjectMessage objectMessage = session.createObjectMessage(message);
      producer.send(objectMessage);

    } catch (NamingException e) {
      connectionFactory = null;
      destination = null;
      throw ExceptionUtil.rewrap(e);

    } catch (JMSException e) {
      connectionFactory = null;
      destination = null;
      throw e;

    } finally {
      // it is important to close session
      if (session != null) session.close();
      try {
        // Closing a connection automatically returns the connection and
        // its session plus producer to the resource reference pool.
        if (connection != null) connection.close();
      } catch (JMSException e) {
        // ignore
      }
      ;
    }
  }
Exemplo n.º 17
0
 private Message createMessage(Session session, int messageType) throws JMSException {
   switch (messageType) {
     case MessageImpl.TEXT_MESSAGE:
       return session.createTextMessage();
     case MessageImpl.BYTES_MESSAGE:
       return session.createBytesMessage();
     case MessageImpl.MAP_MESSAGE:
       return session.createMapMessage();
     case MessageImpl.STREAM_MESSAGE:
       return session.createStreamMessage();
     case MessageImpl.OBJECT_MESSAGE:
       return session.createObjectMessage();
     default:
       return session.createTextMessage();
   }
 }
Exemplo n.º 18
0
  public void testReceiveResponse_output_rpc() throws Exception {
    // prepare messaging objects
    Connection connection = integrationControl.getJmsConnection();
    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    try {
      Destination replyTo =
          integrationControl.getIntegrationServiceFactory().getResponseDestination();
      MessageProducer producer = session.createProducer(replyTo);
      // create parts map
      Map responseParts = createOutputRpcParts();
      // send message to queue
      ObjectMessage jmsResponse = session.createObjectMessage((Serializable) responseParts);
      // use current time in place of the request id
      String requestId = Long.toString(System.currentTimeMillis());
      jmsResponse.setJMSCorrelationID(requestId);
      producer.send(jmsResponse);

      // receive the above message
      SoapHandler soapHandler = createRpcHandler();
      jmsResponse = soapHandler.receiveResponse(session, replyTo, requestId, jbpmContext);
      responseParts = (Map) jmsResponse.getObject();

      // simple part
      Element intPart = (Element) responseParts.get("intPart");
      assertEquals("intPart", intPart.getLocalName());
      assertNull(intPart.getNamespaceURI());
      // value
      assertEquals("2020", DatatypeUtil.toString(intPart));

      // complex part
      Element complexPart = (Element) responseParts.get("complexPart");
      assertEquals("complexPart", complexPart.getLocalName());
      assertNull(complexPart.getNamespaceURI());
      // attributes
      assertEquals("hi", complexPart.getAttribute("attributeOne"));
      assertEquals("ho", complexPart.getAttribute("attributeTwo"));
      // child elements
      Element one = XmlUtil.getElement(complexPart, "urn:uriOne", "elementOne");
      assertEquals("ram", DatatypeUtil.toString(one));
      Element two = XmlUtil.getElement(complexPart, "urn:uriTwo", "elementTwo");
      assertEquals("ones", DatatypeUtil.toString(two));
    } finally {
      session.close();
    }
  }
 public void scheduleStoreAndRemember(StoreAndRememberContext ctx) {
   try {
     Connection conn = connFactory.createConnection();
     try {
       Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
       MessageProducer producer = session.createProducer(storeAndRememberQueue);
       ObjectMessage msg = session.createObjectMessage(ctx);
       long delay = ctx.getDelay();
       if (delay > 0) {
         msg.setLongProperty("_HQ_SCHED_DELIVERY", System.currentTimeMillis() + delay);
       }
       producer.send(msg);
     } finally {
       conn.close();
     }
   } catch (JMSException e) {
     throw new RuntimeException("Error while scheduling archiving JMS message", e);
   }
 }
  public void onMessage(Message message) {
    Connection connection = null;
    try {
      if (message instanceof ObjectMessage) {
        ObjectMessage receivedObject = (ObjectMessage) message;

        log.info("****************************************************");
        log.info("Received Message ");
        log.info("****************************************************");

        // Send the reply
        Destination replyDestination = message.getJMSReplyTo();
        String correlationID = message.getJMSCorrelationID();
        // ID which got from the client Message
        log.info("input correlationID" + correlationID);

        ConnectionFactory connectionFactory = (ConnectionFactory) ctx.lookup("/ConnectionFactory");
        connection = connectionFactory.createConnection();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageProducer replyProducer = session.createProducer(replyDestination);
        ObjectMessage replyMessage = session.createObjectMessage();
        setCreateReplyObjectMessage(replyMessage, receivedObject);

        replyMessage.setJMSCorrelationID(correlationID);
        replyProducer.send(replyMessage);

        log.info("****************************************************");
        log.info("Sent reply");
        log.info("	Time:       " + System.currentTimeMillis() + " ms");
        log.info("	Message ID: " + replyMessage.getJMSMessageID());
        log.info("	Correl. ID: " + replyMessage.getJMSCorrelationID());
        log.info("	Reply to:   " + replyMessage.getJMSReplyTo());
        log.info("	Contents: " + replyMessage);
        log.info("****************************************************");
      } else {
        log.error("Expected an Object Message");
      }
      connection.close();
    } catch (Throwable t) {
      t.printStackTrace();
    } finally {
    }
  }
Exemplo n.º 21
0
  @org.junit.Ignore
  public void testSendObjectToQueue() throws Exception {
    final TestRunner runner = TestRunners.newTestRunner(GetJMSQueue.class);
    runner.setProperty(JmsProperties.JMS_PROVIDER, JmsProperties.ACTIVEMQ_PROVIDER);
    runner.setProperty(JmsProperties.URL, "tcp://localhost:61616");
    runner.setProperty(JmsProperties.DESTINATION_TYPE, JmsProperties.DESTINATION_TYPE_QUEUE);
    runner.setProperty(JmsProperties.DESTINATION_NAME, "queue.testing");
    runner.setProperty(JmsProperties.ACKNOWLEDGEMENT_MODE, JmsProperties.ACK_MODE_AUTO);
    WrappedMessageProducer wrappedProducer =
        JmsFactory.createMessageProducer(runner.getProcessContext(), true);
    final Session jmsSession = wrappedProducer.getSession();
    final MessageProducer producer = wrappedProducer.getProducer();

    // Revision class is used because test just needs any Serializable class in core NiFi
    final ObjectMessage message = jmsSession.createObjectMessage(new Revision(1L, "ID"));

    producer.send(message);
    jmsSession.commit();
    producer.close();
    jmsSession.close();
  }
Exemplo n.º 22
0
  public static void publish(String dest, Serializable object, String contentType, String tag)
      throws Exception {
    Connection conn = connectionFactory.createConnection();
    try {
      Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Destination destination = createDestination(dest);
      MessageProducer producer = session.createProducer(destination);
      ObjectMessage message = session.createObjectMessage();

      if (contentType != null) {
        message.setStringProperty(HttpHeaderProperty.CONTENT_TYPE, contentType);
      }
      if (tag != null) {
        message.setStringProperty("MyTag", tag);
      }
      message.setObject(object);

      producer.send(message);
    } finally {
      conn.close();
    }
  }
  public static Message createMessage(Session session, Class messageClazz) throws JMSException {
    if (session == null) {
      throw new JMSException("session cannot be null");
    }
    if (Message.class.isAssignableFrom(messageClazz)) {
      throw new JMSException("cannot create message of type: " + messageClazz.getName());
    }

    if (TextMessage.class.equals(messageClazz)) {
      return session.createTextMessage();
    } else if (StreamMessage.class.equals(messageClazz)) {
      return session.createStreamMessage();
    } else if (MapMessage.class.equals(messageClazz)) {
      return session.createMapMessage();
    } else if (ObjectMessage.class.equals(messageClazz)) {
      return session.createObjectMessage();
    } else if (BytesMessage.class.equals(messageClazz)) {
      return session.createBytesMessage();
    } else if (Message.class.equals(messageClazz)) {
      return session.createMessage();
    } else {
      throw new JMSException("cannot create message of type: " + messageClazz.getName());
    }
  }
Exemplo n.º 24
0
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // not connected
    if (request.getSession().getAttribute("user") == null) {
      request.getSession().setAttribute("backTo", "post_application");
      request.setAttribute("errorMessage", "error_not_logged_applications");
      URLHelper.redirectTo(Page.connection, request, response);
    }
    // form is ok
    else if (FileUpload.isMultipartContent(request)) {

      String msg = "application_posted";
      Connection connection = null;
      MessageProducer messageProducer = null;
      try {
        connection = connectionFactory.createConnection();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        messageProducer = session.createProducer(queue);

        ObjectMessage message = session.createObjectMessage();
        // here we create NewsEntity, that will be sent in JMS message
        Application e = new Application();
        // upload File and Icon on the server
        UploadFileHelper.uploadApplication(request, e, getServletContext().getRealPath("/"));
        // create the new app
        appFacade.create(e);
        // link app to User
        LinuxStoreUser user = (LinuxStoreUser) request.getSession().getAttribute("user");
        e = appFacade.findByName(e.getName());
        e.setOwner(user);
        appFacade.edit(e);
        List<Application> applist = new LinkedList<Application>();
        applist.add(e);
        user.addToMyApplications(applist);
        userFacade.edit(user);

        //                message.setObject(new UserAndApp(user,e));
        //                messageProducer.send(message);

      } catch (Exception ex) {
        msg = ex.getMessage();
        //                msg = "application_not_posted";
      } finally {
        try {
          messageProducer.close();
          connection.close();
        } catch (JMSException ex) {
          // do nothing
        }
      }
      if (msg.equals("application_posted")) {
        request.setAttribute("confirmationMessage", msg);
        URLHelper.redirectTo(Page.confirmation, request, response);
      } else {
        request.setAttribute("errorMessage", msg);
        request.setAttribute("categories", Category.values());
        URLHelper.redirectTo(Page.post_application, request, response);
      }
    }
    // access to form
    else {
      request.setAttribute("fileTypes", UploadFileHelper.listOfAppExtensions);
      request.setAttribute("imgTypes", UploadFileHelper.listOfImgExtensions);
      request.setAttribute("categories", Category.values());
      URLHelper.redirectTo(Page.post_application, request, response);
    }
  }
Exemplo n.º 25
0
  protected Message createJmsMessage(
      Exchange exchange,
      Object body,
      Map<String, Object> headers,
      Session session,
      CamelContext context)
      throws JMSException {
    JmsMessageType type = null;

    // special for transferExchange
    if (endpoint != null && endpoint.isTransferExchange()) {
      LOG.trace("Option transferExchange=true so we use JmsMessageType: Object");
      Serializable holder = DefaultExchangeHolder.marshal(exchange);
      Message answer = session.createObjectMessage(holder);
      // ensure default delivery mode is used by default
      answer.setJMSDeliveryMode(Message.DEFAULT_DELIVERY_MODE);
      return answer;
    }

    // use a custom message converter
    if (endpoint != null && endpoint.getMessageConverter() != null) {
      if (LOG.isTraceEnabled()) {
        LOG.trace(
            "Creating JmsMessage using a custom MessageConverter: {} with body: {}",
            endpoint.getMessageConverter(),
            body);
      }
      return endpoint.getMessageConverter().toMessage(body, session);
    }

    // check if header have a type set, if so we force to use it
    if (headers.containsKey(JmsConstants.JMS_MESSAGE_TYPE)) {
      type =
          context
              .getTypeConverter()
              .convertTo(JmsMessageType.class, headers.get(JmsConstants.JMS_MESSAGE_TYPE));
    } else if (endpoint != null && endpoint.getConfiguration().getJmsMessageType() != null) {
      // force a specific type from the endpoint configuration
      type = endpoint.getConfiguration().getJmsMessageType();
    } else {
      type = getJMSMessageTypeForBody(exchange, body, headers, session, context);
    }

    // create the JmsMessage based on the type
    if (type != null) {
      if (body == null && (endpoint != null && !endpoint.getConfiguration().isAllowNullBody())) {
        throw new JMSException(
            "Cannot send message as message body is null, and option allowNullBody is false.");
      }
      LOG.trace("Using JmsMessageType: {}", type);
      Message answer = createJmsMessageForType(exchange, body, headers, session, context, type);
      // ensure default delivery mode is used by default
      answer.setJMSDeliveryMode(Message.DEFAULT_DELIVERY_MODE);
      return answer;
    }

    // check for null body
    if (body == null && (endpoint != null && !endpoint.getConfiguration().isAllowNullBody())) {
      throw new JMSException(
          "Cannot send message as message body is null, and option allowNullBody is false.");
    }

    // warn if the body could not be mapped
    if (body != null && LOG.isWarnEnabled()) {
      LOG.warn(
          "Cannot determine specific JmsMessage type to use from body class."
              + " Will use generic JmsMessage."
              + " Body class: "
              + ObjectHelper.classCanonicalName(body)
              + ". If you want to send a POJO then your class might need to implement java.io.Serializable"
              + ", or you can force a specific type by setting the jmsMessageType option on the JMS endpoint.");
    }

    // return a default message
    Message answer = session.createMessage();
    // ensure default delivery mode is used by default
    answer.setJMSDeliveryMode(Message.DEFAULT_DELIVERY_MODE);
    return answer;
  }