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); } }
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"); }
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(); } }
@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(); } }
/** * Initializes the qpid connection with a jndiName of cow, and a host and port taken from the * cow-server.properties file. */ public void init() { String connectionFactorylocation = "amqp://*****:*****@clientid/test?brokerlist='tcp://" + host + ":" + port + "'"; String destinationType = "topic"; String jndiName = "cow"; String destinationName = "myTopic"; try { properties = new Properties(); properties.setProperty( Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jndi.PropertiesFileInitialContextFactory"); properties.setProperty("connectionfactory.amqpConnectionFactory", connectionFactorylocation); properties.setProperty(destinationType + "." + jndiName, destinationName); context = new InitialContext(properties); ConnectionFactory connectionFactory = (ConnectionFactory) context.lookup("amqpConnectionFactory"); Connection connection = connectionFactory.createConnection(); connection.start(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = (Destination) context.lookup(jndiName); messageProducer = session.createProducer(destination); initialized = true; } catch (Exception e) { log.debug(e.getMessage()); initialized = false; } }
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(); } }
private void shutdown() { try { _session.close(); _connection.stop(); _connection.close(); } catch (Exception e) { e.printStackTrace(System.out); } }
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); } }
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(); } }
/** * Wait for 'count' messages on controlQueue before continuing. Called by a publisher to make sure * that subscribers have started before it begins publishing messages. * * <p>If controlQueue doesn't exist, the method throws an exception. * * @param prefix prefix (publisher or subscriber) to be displayed * @param controlQueueName name of control queue * @param count number of messages to receive */ public static void receiveSynchronizeMessages(String prefix, String controlQueueName, int count) throws Exception { QueueConnectionFactory queueConnectionFactory = null; QueueConnection queueConnection = null; QueueSession queueSession = null; Queue controlQueue = null; QueueReceiver queueReceiver = null; try { queueConnectionFactory = SampleUtilities.getQueueConnectionFactory(); queueConnection = queueConnectionFactory.createQueueConnection(); queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); controlQueue = getQueue(controlQueueName, queueSession); queueConnection.start(); } catch (Exception e) { System.out.println("Connection problem: " + e.toString()); if (queueConnection != null) { try { queueConnection.close(); } catch (JMSException ee) { } } throw e; } try { System.out.println( prefix + "Receiving synchronize messages from " + controlQueueName + "; count = " + count); queueReceiver = queueSession.createReceiver(controlQueue); while (count > 0) { queueReceiver.receive(); count--; System.out.println(prefix + "Received synchronize message; expect " + count + " more"); } } catch (JMSException e) { System.out.println("Exception occurred: " + e.toString()); throw e; } finally { if (queueConnection != null) { try { queueConnection.close(); } catch (JMSException e) { } } } }
private void updateDB() { try { // Class.forName("com.inet.ora.OraDriver"); Class.forName("org.apache.derby.jdbc.ClientDriver"); //// String url = "jdbc:inetora::wrx.india.sun.com:1521:dbsmpl1"; String url = "jdbc:derby://localhost:1527/testdb;create=true;"; java.sql.Connection con = DriverManager.getConnection(url, "dbuser", "dbpassword"); String qry = "update lifecycle_test1 set status=1"; con.createStatement().executeUpdate(qry); con.close(); } catch (Exception e) { System.out.println("Error:" + e.getMessage()); } }
/** * Publishes a message to qpid that describes what action a user has just performed on a task. * These actions may be either TaskTaken or TaskCompleted. This calls checkInitialized to see if * there is a valid connection to qpid. * * @param task the task that has been acted upon * @param exchangeName the exchange name for messaging * @param eventName the event that correlates with the action * @param taskId the id of the task that was acted upon */ public void amqpTaskPublish(Task task, String exchangeName, String eventName, String taskId) { String info = ""; if (checkInitialized()) { if (eventName.equals("TaskTaken")) { try { info = "eventType=" + eventName + ";" + "processID=" + task.getProcessInstanceId() + ";" + "taskID=" + task.getId() + ";" + "assignee=" + task.getAssignee() + ";"; } catch (Exception e) { log.debug(e.getMessage()); } } else if (eventName.equals("TaskCompleted")) { try { org.jbpm.task.Task ht = taskRepo.findById(Long.decode(taskId)); String processName = ht.getTaskData().getProcessId(); String processId = Long.toString(ht.getTaskData().getProcessInstanceId()); String assignee = ht.getTaskData().getActualOwner().getId(); info = "eventType=" + eventName + ";" + "processID=" + processName + "." + processId + ";" + "taskID=" + taskId + ";" + "assignee=" + assignee + ";"; } catch (Exception e) { log.debug(e.getMessage()); } } sendMessage(info, exchangeName); } }
public static Object lookupObject(Context context, String reference) throws NamingException { Object ref = context.lookup(reference); if (ref instanceof Reference) { String className = ((Reference) ref).getClassName(); try { ref = ClassHelper.loadClass(className, JmsTestUtils.class).newInstance(); } catch (Exception e) { throw new NamingException( "Failed to instanciate class: " + className + ". Exception was: " + e.toString()); } } return ref; }
@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(); }
// Sends a message using the exchange name over qpid private void sendMessage(String message, String exchangeName) { TextMessage textMessage; properties.setProperty("topic" + "." + "cow", exchangeName); try { context = new InitialContext(properties); Destination destination = (Destination) context.lookup("cow"); messageProducer = session.createProducer(destination); textMessage = session.createTextMessage(message); messageProducer.send(textMessage); } catch (Exception e) { log.debug(e.getMessage()); initialized = false; } }
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); } }
// 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 { } }
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); } }
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(); } }
/** * Send a message to controlQueue. Called by a subscriber to notify a publisher that it is ready * to receive messages. * * <p>If controlQueue doesn't exist, the method throws an exception. * * @param prefix prefix (publisher or subscriber) to be displayed * @param controlQueueName name of control queue */ public static void sendSynchronizeMessage(String prefix, String controlQueueName) throws Exception { QueueConnectionFactory queueConnectionFactory = null; QueueConnection queueConnection = null; QueueSession queueSession = null; Queue controlQueue = null; QueueSender queueSender = null; TextMessage message = null; try { queueConnectionFactory = SampleUtilities.getQueueConnectionFactory(); queueConnection = queueConnectionFactory.createQueueConnection(); queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); controlQueue = getQueue(controlQueueName, queueSession); } catch (Exception e) { System.out.println("Connection problem: " + e.toString()); if (queueConnection != null) { try { queueConnection.close(); } catch (JMSException ee) { } } throw e; } try { queueSender = queueSession.createSender(controlQueue); message = queueSession.createTextMessage(); message.setText("synchronize"); System.out.println(prefix + "Sending synchronize message to " + controlQueueName); queueSender.send(message); } catch (JMSException e) { System.out.println("Exception occurred: " + e.toString()); throw e; } finally { if (queueConnection != null) { try { queueConnection.close(); } catch (JMSException e) { } } } }
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 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); } }
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 }
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) { } } }
@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(); } }
public static void main(String... args) throws Exception { ConnectionFactory connectionFactory = null; Connection connection = null; Session session = null; MessageProducer producer = null; MessageConsumer consumer = null; Destination destination = null; TextMessage message = null; Context context = null; try { // Set up the context for the JNDI lookup final Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY); env.put(Context.PROVIDER_URL, System.getProperty(Context.PROVIDER_URL, PROVIDER_URL)); env.put(Context.SECURITY_PRINCIPAL, System.getProperty("username", DEFAULT_USERNAME)); env.put(Context.SECURITY_CREDENTIALS, System.getProperty("password", DEFAULT_PASSWORD)); context = new InitialContext(env); // Perform the JNDI lookups String connectionFactoryString = System.getProperty("connection.factory", DEFAULT_CONNECTION_FACTORY); log.info("Attempting to acquire connection factory \"" + connectionFactoryString + "\""); connectionFactory = (ConnectionFactory) context.lookup(connectionFactoryString); log.info("Found connection factory \"" + connectionFactoryString + "\" in JNDI"); String destinationString = System.getProperty("destination", DEFAULT_DESTINATION); log.info("Attempting to acquire destination \"" + destinationString + "\""); destination = (Destination) context.lookup(destinationString); log.info("Found destination \"" + destinationString + "\" in JNDI"); // Create the JMS connection, session, producer, and consumer connection = connectionFactory.createConnection( System.getProperty("username", DEFAULT_USERNAME), System.getProperty("password", DEFAULT_PASSWORD)); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); producer = session.createProducer(destination); consumer = session.createConsumer(destination); connection.start(); int count = Integer.parseInt(System.getProperty("message.count", DEFAULT_MESSAGE_COUNT)); String content = System.getProperty("message.content", DEFAULT_MESSAGE); log.info("Sending " + count + " messages with content: " + content); // Send the specified number of messages for (int i = 0; i < count; i++) { message = session.createTextMessage(content); producer.send(message); } // Then receive the same number of messages that were sent for (int i = 0; i < count; i++) { message = (TextMessage) consumer.receive(5000); log.info("Received message with content " + message.getText()); } } catch (Exception exception) { log.severe(exception.getMessage()); throw exception; } finally { if (context != null) { context.close(); } // closing the connection takes care of the session, producer, and consumer if (connection != null) { connection.close(); } } }
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; }