private void initSFSB(String[] args) {

    System.out.println("[apiClient] Inside init....");
    try {
      Context ic = null;
      Object objref = null;
      if ((args[0] == null) || (args[1] == null)) {
        ic = new InitialContext();
        System.out.println("[apiClient] Lookingup Bean apiClient ");
        objref = ic.lookup("java:comp/env/ejb/apiSecurity");
      } else {
        Properties env = new Properties();
        env.put("java.naming.provider.url", args[0]);
        env.put("java.naming.factory.initial", args[1]);
        ic = new InitialContext(env);
        objref = ic.lookup(args[2]);
      }

      RpaHome home = (RpaHome) PortableRemoteObject.narrow(objref, RpaHome.class);

      hr = home.create("LizHurley");

      System.out.println("[passivateactivate] Initalization done");
      // stat.addStatus("init apiClient", stat.PASS);
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("[apiClient] Exception in init....");
      e.printStackTrace();
      // stat.addStatus("client initSFSB", stat.FAIL);
    }
  }
Example #2
0
  public static void main(String[] args) {
    try {

      // Gets the JgetTopicName()NDI context
      Context jndiContext = new InitialContext();

      // Looks up the administered objects
      ConnectionFactory connectionFactory =
          (ConnectionFactory) jndiContext.lookup("jms/javaee6/ConnectionFactory");
      Queue queue = (Queue) jndiContext.lookup("jms/javaee6/Queue");

      // Creates the needed artifacts to connect to the queue
      Connection connection = connectionFactory.createConnection();
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageConsumer consumer = session.createConsumer(queue);
      connection.start();

      // Loops to receive the messages
      System.out.println("\nInfinite loop. Waiting for a message...");
      while (true) {
        TextMessage message = (TextMessage) consumer.receive();
        System.out.println("Message received: " + message.getText());
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  @Before
  public void setUp() {
    // Set up connection to the broker
    try {
      Map<String, Object> connectionParams = new HashMap<String, Object>();

      connectionParams.put(
          org.hornetq.integration.transports.netty.TransportConstants.HOST_PROP_NAME, "localhost");
      connectionParams.put(
          org.hornetq.integration.transports.netty.TransportConstants.PORT_PROP_NAME, 5445);

      TransportConfiguration transport =
          new TransportConfiguration(NettyConnectorFactory.class.getName(), connectionParams);

      hornetQConnectionFactory = new HornetQConnectionFactory(false, transport);

      connection = hornetQConnectionFactory.createConnection();
      connection.start();

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

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public static void main(String[] args) {
    try {
      Context ctx = new InitialContext();
      ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory");
      Queue queue = (Queue) ctx.lookup("inbound");

      Connection con = factory.createConnection();
      final Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
      final MessageConsumer consumer = session.createConsumer(queue);

      consumer.setMessageListener(
          new MessageListener() {
            @Override
            public void onMessage(Message message) {
              final String type;
              try {
                type = message.getStringProperty("type");
                if (type != null && type.equals("xml")) {

                  System.out.println(((TextMessage) message).getText());
                }

              } catch (JMSException e) {
                e.printStackTrace();
              }
            }
          });

      con.start();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public void testSynch(String[] args) {
    // invoke 3 overloaded methods on the EJB
    try {
      System.out.println("Calling authorized method - addItem");
      hr.addItem("lipstick", 30);
      hr.addItem("mascara", 40);
      hr.addItem("lipstick2", 50);
      hr.addItem("sandals", 200);
      System.out.println(hr.getTotalCost());
      hr.deleteItem("lipstick2");
      java.lang.String[] shoppingList = hr.getItems();
      System.out.println("Shopping list for LizHurley");
      for (int i = 0; i < shoppingList.length; i++) {
        System.out.println(shoppingList[i]);
      }

      System.out.println("Total Cost for Ms Hurley = " + hr.getTotalCost());

    } catch (Exception re) {
      re.printStackTrace();
      System.out.println("RealmPerApp:RpaLoginBean Test Failed");
      System.exit(-1);
    }
    System.out.println("RealmPerApp:RpaLoginBean Test Passed");
  }
Example #6
0
 private void shutdown() {
   try {
     _session.close();
     _connection.stop();
     _connection.close();
   } catch (Exception e) {
     e.printStackTrace(System.out);
   }
 }
Example #7
0
  private void report() {
    log.debug("private void report(): called");

    try {
      String msg = getReport();
      _controller.send(createReportResponseMessage(msg));
      log.debug("Sent report: " + msg);
    } catch (Exception e) {
      e.printStackTrace(System.out);
    }
  }
Example #8
0
 private void initSLSB() {
   System.out.println("[txtests] Inside init....");
   try {
     Context ic = new InitialContext();
     Object objref = ic.lookup("java:comp/env/ejb/SLSBHome");
     this.home = (SLSBHome) PortableRemoteObject.narrow(objref, SLSBHome.class);
     System.out.println("[txtests] Initalization done");
   } catch (Exception e) {
     System.out.println("[txtests] Exception in init....");
     e.printStackTrace();
   }
 }
Example #9
0
  @GET
  @Path("/jms")
  public Response doGet() throws IOException {

    try {
      sendTextMessage("Hello!");

      return Response.ok("Message sent!").build();

    } catch (Exception e) {
      e.printStackTrace();
    }
    return Response.serverError().build();
  }
Example #10
0
 public void doRollbackTest() {
   try {
     int intVal = (int) System.currentTimeMillis();
     SLSB slsb = (SLSB) home.create();
     boolean retVal = slsb.doRollbackTest(intVal);
     if (retVal) {
       stat.addStatus("txtests doRollbackTest", stat.PASS);
     } else {
       stat.addStatus("txtests doRollbackTest", stat.FAIL);
     }
   } catch (Exception ex) {
     ex.printStackTrace();
     stat.addStatus("txtests doRollbackTest", stat.FAIL);
   }
 }
Example #11
0
  // TextMessage message;
  // 构造ConnectionFactory实例对象,此处采用ActiveMq的实现jar
  public ActiveMQSender(String broker) {
    try {
      connectionFactory =
          new ActiveMQConnectionFactory(
              ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, broker);
      // 构造从工厂得到连接对象
      connection = connectionFactory.createConnection();
      // 启动
      connection.start();
      /** ********************************** */
    } catch (Exception e) {
      e.printStackTrace();
    } finally {

    }
  }
Example #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 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);
    }
  }
Example #13
0
 public void _sendOne(String topic, String msg) {
   Session session = null;
   try {
     session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
     Destination destination = session.createQueue(topic);
     MessageProducer producer = session.createProducer(destination);
     producer.setDeliveryMode(DeliveryMode.PERSISTENT);
     TextMessage message = session.createTextMessage(JSON.toJSONString(msg));
     producer.send(message);
     session.commit();
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     try {
       if (null != session) session.close();
     } catch (Throwable ignore) {
     }
   }
 }
  public static void main(String[] args) {
    try {
      QueueConnectionFactory queueConnectionFactory;
      QueueConnection queueConnection;
      QueueSession queueSession;
      QueueReceiver queueReceiver;
      Queue queue;
      TextMessage msg;

      // JNDI InitialContextを作成します
      InitialContext ctx = new InitialContext();
      // Connection FactoryとQueueをLook upします
      queueConnectionFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);
      queue = (Queue) ctx.lookup(QUEUE);

      // コネクションを作成
      queueConnection = queueConnectionFactory.createQueueConnection();
      // セッションを作成
      queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
      // キューレシーバーを作成
      queueReceiver = queueSession.createReceiver(queue);
      // メッセージの配送をスタート
      queueConnection.start();
      // メッセージの受信
      while (true) {
        Message m = queueReceiver.receive(1);
        if (m != null) {
          if (m instanceof TextMessage) {
            msg = (TextMessage) m;
            System.out.println(msg.getText());
          } else {
            break;
          }
        }
      }
      // 接続を切断
      queueReceiver.close();
      queueSession.close();
      queueConnection.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Example #15
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);
    }
  }
Example #16
0
    public void run() {
      try {

        // Create a ConnectionFactory
        String conStr = "tcp://localhost:61616";

        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(conStr);

        System.out.println("Connecting...");
        // Create a Connection
        Connection connection = connectionFactory.createConnection();
        connection.start();

        connection.setExceptionListener(this);

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

        // Create the destination (Topic or Queue)
        Destination destination = session.createTopic("TEST.FOO");

        // Create a MessageConsumer from the Session to the Topic or
        // Queue
        MessageConsumer consumer = session.createConsumer(destination);

        while (true) {
          // Wait for a message
          Message message = consumer.receive(1000);

          if (message instanceof TextMessage) {
            TextMessage textMessage = (TextMessage) message;
            String text = textMessage.getText();
            System.out.println("Received: " + text);
          } else {
            System.out.println("Received: " + message);
          }
        }
      } catch (Exception e) {
        System.out.println("Caught: " + e);
        e.printStackTrace();
      }
    }
  /** Tasks to be carried out in the STARTUP_EVENT. Logs a message */
  private void onStartTask() {
    ctx.log("LifecycleTopic: STARTUP_EVENT");
    // my code
    QueueSession qsession[] = new QueueSession[10];
    Queue queue[] = new Queue[10];

    try {
      for (int i = 0; i < 10; i++) {
        // Get initial context
        ctx.log("Get initial context");
        InitialContext initialContext = new InitialContext();

        // look up the connection factory from the object store
        ctx.log("Looking up the queue connection factory from JNDI");
        QueueConnectionFactory factory =
            (QueueConnectionFactory) initialContext.lookup("jms/QCFactory");

        // look up queue from the object store
        ctx.log("Create queue connection");
        QueueConnection qconn = factory.createQueueConnection();

        ctx.log("Create queue session");
        qsession[i] = qconn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

        ctx.log("Looking up the queue from JNDI");
        queue[i] = (Queue) initialContext.lookup("jms/SampleQueue");
      }

      updateDB();

    } catch (Exception e) {
      ctx.log("Exception caught in test code");
      e.printStackTrace();
    }

    // end my code

    // my code
    // createAccount();
    // end my code
  }
Example #18
0
 public void sendOne(String topic, String msg) {
   long s = System.currentTimeMillis();
   Session session = null;
   try {
     session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
     Destination destination = session.createQueue(topic);
     MessageProducer producer = session.createProducer(destination);
     producer.setDeliveryMode(DeliveryMode.PERSISTENT);
     TextMessage message = session.createTextMessage(msg);
     producer.send(message);
     session.commit();
     logger.info("cost: {}ms {}/{}", System.currentTimeMillis() - s, topic, msg);
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     try {
       if (null != session) session.close();
     } catch (Throwable ignore) {
     }
   }
 }
Example #19
0
  @Override
  public void run() {

    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    boolean finished = false;
    while (!finished) {
      try {
        String ans = in.readLine();
        ans = ans.trim().toLowerCase();
        if (ans.startsWith("ingest")) {
          String[] toks = ans.split("\\s+");
          if (toks.length == 3) {
            Map<String, String> pm = new HashMap<String, String>(7);
            pm.put("srcNifId", toks[1]);
            pm.put("batchId", toks[2]);
            sendMessage("ingest", pm);
          }
        }

      } catch (Exception x) {
        x.printStackTrace();
      }
    }
  }
  // @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();
    }
  }
  @Test
  public void testFetchLast() {
    try {

      String neId =
          "1005255"; // KLNNMS02(cpuusage=YES cpu1min=YES memutil=YES) KLNNMS05(cpuusage=YES
                     // bususage=YES)
      // String neId = "1006119";    // KLNNMS02(cpuusage=YES cpu1min=YES memutil=YES
      // KLNNMS05(cpuusage=NO bususage=NO)

      Set<String> rras = new HashSet<String>();
      // klnnms02
      rras.add("cpu5sec");
      rras.add("cpu1min");
      rras.add("memutil");

      // klnnms05
      rras.add("cpuusage");
      rras.add("bususage");

      FetchLastCommandMessage message =
          CommandMessageFactory.createRRDLastCommandMessage(neId, "AVERAGE", 0, 0, null, rras);

      MessageProducer producer = null;
      MessageConsumer consumer = null;

      // time to send the JMS request
      try {
        TextMessage reqMsg, 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", "fetchLast");
        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 = (TextMessage) consumer.receive(30000);

        if (replyMsg == null) {
          logger.info("ServiceRRD timeout on receive()");
        } else {
          logger.info("REPLY:\n" + 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();
    }
  }
Example #22
0
  public synchronized boolean send() {
    Boolean complete_send_to_crm = true;

    SimpleDateFormat format = new SimpleDateFormat();
    format.applyPattern("dd/MM/yyyy HH:mm:ss");

    try {
      BasicXmlData xml = new BasicXmlData("action");
      xml.setAttribute("name", "Comment");

      BasicXmlData xml_level_1 = new BasicXmlData("parameters");

      BasicXmlData xml_level_2_id_trouble = new BasicXmlData("parameter");
      xml_level_2_id_trouble.setAttribute("name", "id_trouble");
      xml_level_2_id_trouble.setAttribute("value", String.valueOf(trouble.getId()));
      xml_level_1.addKid(xml_level_2_id_trouble);

      BasicXmlData xml_level_2_id_comment = new BasicXmlData("parameter");
      xml_level_2_id_comment.setAttribute("name", "id_comment");
      xml_level_2_id_comment.setAttribute("value", String.valueOf(comment.getId()));
      xml_level_1.addKid(xml_level_2_id_comment);

      BasicXmlData xml_level_2_author = new BasicXmlData("parameter");
      xml_level_2_author.setAttribute("name", "author");
      xml_level_2_author.setAttribute("value", comment.getAuthor().getFio());
      xml_level_1.addKid(xml_level_2_author);

      BasicXmlData xml_level_2_desc = new BasicXmlData("parameter");
      xml_level_2_desc.setAttribute("name", "content");
      xml_level_2_desc.setAttribute("value", comment.getText());
      xml_level_1.addKid(xml_level_2_desc);

      BasicXmlData xml_level_2_date = new BasicXmlData("parameter");
      xml_level_2_date.setAttribute("name", "date");
      xml_level_2_date.setAttribute(
          "value", format.format(new Date(Long.valueOf(comment.getTime()))));
      xml_level_1.addKid(xml_level_2_date);

      xml.addKid(xml_level_1);

      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      xml.save(baos);

      SendToCrm.send(baos);
    } catch (Exception e) {
      log.error(
          "Comment ["
              + comment.getId()
              + "] to trouble "
              + trouble.getTitle()
              + " ["
              + trouble.getId()
              + "] is not sent to CRM - "
              + e.getMessage());
      e.printStackTrace();
      complete_send_to_crm = false;
    }

    if (complete_send_to_crm) {
      log.info(
          "Comment ["
              + trouble.getId()
              + "] to trouble "
              + trouble.getTitle()
              + " ["
              + trouble.getId()
              + "] successfully submitted to CRM successfully.");
    }

    return complete_send_to_crm;
  }