List of usage examples for com.rabbitmq.client ConnectionFactory setHost
public void setHost(String host)
From source file:scratchpad.SimpleConsumer.java
License:Mozilla Public License
public static void main(String[] args) { try {/*from w ww .j a v a 2 s .c o m*/ String hostName = (args.length > 0) ? args[0] : "localhost"; int portNumber = (args.length > 1) ? Integer.parseInt(args[1]) : AMQP.PROTOCOL.PORT; String queueName = (args.length > 2) ? args[2] : "eventName"; ConnectionFactory connFactory = new ConnectionFactory(); connFactory.setHost(hostName); connFactory.setPort(portNumber); Connection conn = connFactory.newConnection(); final Channel ch = conn.createChannel(); ch.queueDeclare(); QueueingConsumer consumer = new QueueingConsumer(ch); ch.basicConsume(queueName, consumer); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); Envelope envelope = delivery.getEnvelope(); System.out .println("Routing Key: " + envelope.getRoutingKey() + ":" + new String(delivery.getBody())); ch.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } } catch (Exception ex) { System.err.println("Main thread caught exception: " + ex); ex.printStackTrace(); System.exit(1); } }
From source file:sd_aula06.Send.java
public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("reindeer.rmq.cloudamqp.com"); factory.setUsername("jmodzuaw"); factory.setPassword("Kwuy7kd81ED1fIj9gxEti1J4FTPBj2Jz"); factory.setVirtualHost("jmodzuaw"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); String message = "RafaelReis: VSF!"; channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8")); System.out.println(" [x] Sent '" + message + "'"); channel.close();//w w w. j a v a2s .com connection.close(); }
From source file:server.Worker.java
License:Open Source License
/** * @param args/*from w w w . j a va 2 s .co m*/ * @throws IOException * @throws TimeoutException */ public static void main(String[] args) throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection requestConnection = factory.newConnection(); Channel requestChannel = requestConnection.createChannel(); requestChannel.queueDeclare(REQUEST_QUEUE_NAME, false, false, false, null); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); Connection responseConnection = factory.newConnection(); final Channel responseChannel = responseConnection.createChannel(); responseChannel.queueDeclare(RESPONSE_QUEUE_NAME, false, false, false, null); Consumer consumer = new DefaultConsumer(requestChannel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { PriorityRequest request = (PriorityRequest) SerializationUtils.deserialize(body); System.out.println(" [x] Received"); System.out.println(request.request.toString()); System.out.println("*************************************"); System.out.println(request.request.getMethod()); HttpResponse response = PluginManager.getInstance().process(request.request, request.rootDir); if (response == null) { response = HttpResponseFactory.create400BadRequest(Protocol.CLOSE); } try { System.out.println(request.id); } catch (Exception e) { e.printStackTrace(); } response.id = request.id; byte[] data = SerializationUtils.serialize(response); responseChannel.basicPublish("", RESPONSE_QUEUE_NAME, null, data); } }; requestChannel.basicConsume(REQUEST_QUEUE_NAME, true, consumer); }
From source file:src.main.java.server.MsgReceiveServer.java
public MsgReceiveServer(int SERVER_PORT, String logDirname, String zipDirname, String dbUser, String dbPwd, boolean withLog) throws IOException, TimeoutException, JSONException { super(SERVER_PORT); this.withLog = withLog; this.logDir = logDirname; this.zipDir = zipDirname; dataSource = new DataSource(dbUser, dbPwd); HashMap<String, Message> user2msg; allMsg = new HashMap<String, HashMap<String, Message>>(); ArrayList<Pair<String, String>> res = dataSource.getGroupUser(); for (Pair<String, String> p : res) { msg = new Message("{}", p.getR()); msg.init(p.getR(), "localhost"); msg.bindTo(p.getL(), p.getR());/*from ww w . j ava2 s.com*/ if (allMsg.containsKey(p.getL())) { allMsg.get(p.getL()).put(p.getR(), msg); } else { user2msg = new HashMap<String, Message>(); user2msg.put(p.getR(), msg); allMsg.put(p.getL(), user2msg); } } loginMsg = new Message("{}", ""); loginMsg.init("login_request", "localhost"); loginMsg.bindTo("login_auth", "login_request"); normalMsg = new Message("{}", ""); normalMsg.init("normal_msg", "localhost"); normalMsg.bindTo("msg_send", "normal_msg"); logoutMsg = new Message("{}", ""); logoutMsg.init("logout_msg", "localhost"); logoutMsg.bindTo("msg_send", "logout_msg"); reloginMsg = new Message("{}", ""); reloginMsg.init("relogin_msg", "localhost"); reloginMsg.bindTo("msg_send", "relogin_msg"); ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel loginSuccessChannel = connection.createChannel(); loginSuccessChannel.queueDeclare("login_success", true, false, false, null); loginSuccessConsumer = new DefaultConsumer(loginSuccessChannel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String sLoginSuccessMsg = new String(body, "UTF-8"); try { Message loginSuccessMsg = new Message("{}", ""); loginSuccessMsg.reset(sLoginSuccessMsg); String loginSuccessUsername = loginSuccessMsg.getValue("username"); if (user_list.contains(loginSuccessUsername) == false) { user_list.add(loginSuccessUsername); } System.out.println(user_list.size()); } catch (JSONException e) { e.printStackTrace(); } } }; loginSuccessChannel.basicConsume("login_success", true, loginSuccessConsumer); }
From source file:ss.udapi.sdk.services.MQListener.java
License:Apache License
public synchronized void assureConnectionIsOpen() throws Exception { if (isConnectionOpen()) return;//from ww w . j av a2 s . c om if (channel == null) { logger.debug("MQ Channel not created"); } else { logger.debug("MQ Channel is open: " + channel.isOpen()); } try { logger.debug("Opening MQ channel"); // try { String path = resourceQURI.getRawPath(); String host = resourceQURI.getHost(); String userInfo = resourceQURI.getRawUserInfo(); String virtualHost = uriDecode(path.substring(1, path.indexOf('/', 1))); int port = resourceQURI.getPort(); // Set up the connection. ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setRequestedHeartbeat(Integer.parseInt(SystemProperties.get("ss.conn_heartbeat"))); connectionFactory.setHost(host); connectionFactory.setVirtualHost("/" + virtualHost); userInfo = URLDecoder.decode(userInfo, "UTF-8"); if (userInfo != null) { String userPass[] = userInfo.split(":"); if (userPass.length > 2) { throw new Exception("Invalid user details format in AMQP URI: " + userInfo); } connectionFactory.setUsername(uriDecode(userPass[0])); if (userPass.length == 2) { connectionFactory.setPassword(uriDecode(userPass[1])); } } if (port != -1) { connectionFactory.setPort(port); } // Start up the connection connection = connectionFactory.newConnection(); /* * And create a consumer using the first queue. This consumer allows * subsequent queue listeners to be added and removed as resources * are created / deleted. */ boolean connectSuccess = false; for (int retries = 1; retries <= CONNECT_RETRIES; retries++) { logger.info("Attempting new connection to MQ..."); try { channel = connection.createChannel(); channel.basicQos(0, 10, false); consumer = new RabbitMqConsumer(channel); // Create a queue listener for the first fixture. connectSuccess = true; break; } catch (IOException ex) { } } if (connectSuccess == false) { throw new IOException("Failure creating channel after " + CONNECT_RETRIES + " attempts"); } logger.info("Connection made to MQ"); } catch (UnsupportedEncodingException e) { logger.error("Unsupported encoding while opening MQ connection: " + e); throw e; } catch (IOException e) { logger.error("IO error while opening MQ connection: " + e); throw e; } catch (Exception e) { logger.error("Generic error while opening MQ connection: " + e); throw e; } }
From source file:taucalcmanager.TaucalcManager.java
/** * @param args the command line arguments * @throws java.io.IOException//from w w w .j a v a2s. c o m * @throws java.util.concurrent.TimeoutException */ public static void main(String[] args) throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(WORKQUEUENAME, false, false, false, null); channel.queueDeclare(RESULTQUEUENAME, false, false, false, null); channel.basicQos(1); int calcs = Integer.parseInt(args[0]); int triesPerCalc = Integer.parseInt(args[1]); int[] results = new int[calcs]; byte[] task = { (byte) (triesPerCalc >> 24), (byte) (triesPerCalc >> 16), (byte) (triesPerCalc >> 8), (byte) (triesPerCalc) }; System.out.println("Start Publishing"); for (int i = 0; i < calcs; i++) { channel.basicPublish("", WORKQUEUENAME, null, task); } System.out.println("Done Publishing"); GetResponse response; System.out.println("Start Gathering results"); for (int i = 0; i < calcs; i++) { System.out.println("Waiting for next result: ( " + i + " )"); do { response = channel.basicGet(RESULTQUEUENAME, true); } while (response == null); results[i] = ByteBuffer.wrap(response.getBody()).getInt(); System.out.println("Received result: " + results[i]); } System.out.println("Done gathering results"); System.out.println("Calculating tau"); BigDecimal result = sumToTau(sum(results), calcs, triesPerCalc); System.out.println("Tau = " + result); BigDecimal two = new BigDecimal(2); System.out.println("pi = tau/2 = " + result.divide(two, RoundingMode.HALF_UP)); channel.close(); connection.close(); }
From source file:taucalcworker.TaucalcWorker.java
/** * @param args the command line arguments * @throws java.io.IOException/*from w w w . j av a 2s. c o m*/ * @throws java.util.concurrent.TimeoutException */ public static void main(String[] args) throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(WORKQUEUENAME, false, false, false, null); channel.queueDeclare(RESULTQUEUENAME, false, false, false, null); channel.basicQos(1); byte[] inputbyte = { 0, 0, 0, 0 }; String input = ""; do { if (System.in.available() > 0) { System.in.read(inputbyte); input = new String(inputbyte); } GetResponse response = channel.basicGet(WORKQUEUENAME, false); if (response != null) { long deliverytag = response.getEnvelope().getDeliveryTag(); byte[] body = response.getBody(); int tries = ByteBuffer.wrap(body).getInt(); System.out.println("Task received: " + tries); int success = 0; for (int i = 0; i < tries; i++) { double x = Math.random(); double y = Math.random(); if (x * x + y * y <= 1) { success++; } } System.out.println("success: " + success + " out of " + tries); double tau = ((double) success / tries) * 8; System.out.println("Tau = " + tau); byte[] resultbytes = new byte[8]; ByteBuffer.wrap(resultbytes).putDouble(tau); channel.basicPublish("", RESULTQUEUENAME, null, resultbytes); channel.basicAck(deliverytag, false); } } while (!input.equals("stop")); channel.close(); connection.close(); System.out.println("You stopped the program."); }
From source file:tracer.manager.Manager.java
License:Apache License
public void connectToRabbitNode() { try {//from ww w . j av a 2 s .c om com.rabbitmq.client.ConnectionFactory myFactory = new ConnectionFactory(); myFactory.setHost(HOST); myFactory.setPort(PORT); myFactory.setUsername(USER_NAME); myFactory.setPassword(PASSWORD); myFactory.setVirtualHost(VIRTUAL_HOST_NAME); myFactory.setConnectionTimeout(TIMEOUT); //Automatic recovery from network failures myFactory.setAutomaticRecoveryEnabled(true); System.out.println("automatic recovery from network failures is " + "enabled"); System.out.println("creating new connection.."); myConnection = myFactory.newConnection(); System.out.println("host: " + HOST + " is connected.."); System.out.println("creating new channel.."); myChannel = myConnection.createChannel(); System.out.println("declaring new Exchange.."); switch (getExchageParams()) { case 0: myChannel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE, false, false, false, null); break; case 1: myChannel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE, true, false, false, null); break; case 2: myChannel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE, false, true, false, null); break; case 3: myChannel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE, false, false, true, null); break; case 4: myChannel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE, true, true, false, null); break; case 5: myChannel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE, true, false, true, null); break; case 6: myChannel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE, false, true, true, null); break; case 7: myChannel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE, true, true, true, null); break; default: break; } System.out.println("creating random queue.."); String QUEUE_NAME = myChannel.queueDeclare().getQueue(); for (String bindingKey : BINDING_KEYS) { System.out.println("binding to exchange=" + EXCHANGE_NAME + " using Binding Key=" + bindingKey); myChannel.queueBind(QUEUE_NAME, EXCHANGE_NAME, bindingKey); } System.out.println("waiting for messages, this may take few seconds" + ".."); System.out.println(" - rk: routing key"); System.out.println(" - en: exchange name"); System.out.println(" - ts: time stamp"); System.out.println(" - ct: content type"); System.out.println(" - ce: content encoding"); System.out.println(" - mp: message preview"); myStatsUpdater.start(); com.rabbitmq.client.Consumer myConsumer = new DefaultConsumer(myChannel) { int messageCounter = 1; @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String messageCore = new String(body, "UTF-8"); String currentRoutingKey = envelope.getRoutingKey(); //currentRPC is used for display in the global tracing table String currentRPC = getRPCMethod(messageCore); //there are redendant RPCs. to make the difference, we add //the routing key to the RPC String currentRPCandRK = currentRoutingKey + " * " + currentRPC; addNewMessageToInbox(new Object[] { messageCounter, getFormattedTime(), EXCHANGE_NAME, envelope.getRoutingKey(), messageCore, properties }); //verify if it's a new or a deja-vu RPC in the main //rpc method tracking list if (!rpcMethodsList.contains(currentRPCandRK)) { rpcMethodsList.add(currentRPCandRK); } //verify if it's a new or a deja-vu routing key in the main //routing keys tracking list if (!routingKeysList.contains(currentRoutingKey)) { routingKeysList.add(currentRoutingKey); } //verify if it's a new or a deja-vu routing key in the stats //recording list and init stats //logically it can be added to the condition above but //I prefer it this way if (!myRKStatsCounterMap.containsKey(currentRoutingKey)) { myRKStatsCounterMap.put(currentRoutingKey, 1); myRKStatsPercentageMap.put(currentRoutingKey, (1.0f / messageCounter) * 100); myRKStatsFiveSecondsCounterMap.put(currentRoutingKey, 1); myRKStatsTotalDataSizeMap.put(currentRoutingKey, (body.length / 1024F)); myRKStatsMeanDataSizeMap.put(currentRoutingKey, (body.length / 1024F)); dynamicRKRates.add(1); } else { //FIXED: chaos.. update: everything is fine myRKStatsCounterMap.put(currentRoutingKey, myRKStatsCounterMap.get(currentRoutingKey) + 1); for (String rk : routingKeysList) { //loop all routing keys because it depends on the //total number of recieved messages. myRKStatsPercentageMap.put(rk, (((float) myRKStatsCounterMap.get(rk)) / messageCounter) * 100); } myRKStatsTotalDataSizeMap.put(currentRoutingKey, myRKStatsTotalDataSizeMap.get(currentRoutingKey) + (body.length / 1024.0F)); myRKStatsMeanDataSizeMap.put(currentRoutingKey, ((float) myRKStatsTotalDataSizeMap.get(currentRoutingKey)) / myRKStatsCounterMap.get(currentRoutingKey)); } //verify if it's a new or a deja-vu rpc in the stats //recording list and init stats if (!myRPCStatsCounterMap.containsKey(currentRPCandRK)) { myRPCStatsCounterMap.put(currentRPCandRK, 1); myRPCStatsPercentageMap.put(currentRPCandRK, (1.0f / messageCounter) * 100); myRPCRKExchangeMap.put(currentRPCandRK, new String[] { EXCHANGE_NAME, currentRoutingKey, currentRPC }); } else { myRPCStatsCounterMap.put(currentRPCandRK, myRPCStatsCounterMap.get(currentRPCandRK) + 1); for (String rpc : rpcMethodsList) { //loop all rpc because it depends on the //total number of received messages. //using the messageCounter is OK because even //messages that are not RPCs are considered as //RPCs with a 'N/A' RPC type. myRPCStatsPercentageMap.put(rpc, (((float) myRPCStatsCounterMap.get(rpc)) / messageCounter) * 100); } } // Properties object added to message object displayNewMessage(new Object[] { messageCounter, getFormattedTime(), EXCHANGE_NAME, envelope.getRoutingKey(), currentRPC, properties }); //FIXED: custom messages (ex. used for test) may be less //longer than 30 character which raises an exception. String messagePreview = messageCore; if (messageCore.length() > 100) { messagePreview = messageCore.substring(0, 85) + "..."; } System.out.println("MSG [" + messageCounter + "]:" + " | rk: " + envelope.getRoutingKey() + " | en: " + envelope.getExchange() + " | ts: " + properties.getTimestamp() + " | ct: " + properties.getContentType() + " | ce: " + properties.getContentEncoding() + " | mp: " + messagePreview + " |"); messageCounter++; } private String getFormattedTime() { return myDateFormatter.format(new Date()); } private String getRPCMethod(String messageCore) { String rpcMethodName = "N/A"; //clean up the message core messageCore = messageCore.replaceAll("[\\p{Punct}&&[^,:_]]", ""); //transform the message core to a list of tokens StringTokenizer st1 = new StringTokenizer(messageCore, ","); //locate the string token 'method' and save the next //one which is the rpc method name while (st1.hasMoreElements()) { String token = (String) st1.nextElement(); if (token.trim().startsWith("method")) { rpcMethodName = token.substring(9); } } return rpcMethodName; } }; myChannel.basicConsume(QUEUE_NAME, true, myConsumer); } catch (IOException ex) { ex.printStackTrace(System.out); } catch (TimeoutException ex) { ex.printStackTrace(System.out); } }
From source file:tracer.ui.LoggerUI.java
License:Apache License
private void connectRMQNode(Object[] rmqNodeData) { try {/*ww w. j a v a 2 s.c o m*/ com.rabbitmq.client.ConnectionFactory myFactory = new ConnectionFactory(); myFactory.setHost((String) rmqNodeData[0]); myFactory.setPort((Integer) rmqNodeData[1]); myFactory.setUsername((String) rmqNodeData[2]); myFactory.setPassword((String) rmqNodeData[3]); myFactory.setVirtualHost((String) rmqNodeData[4]); myFactory.setConnectionTimeout((Integer) rmqNodeData[5]); //Automatic recovery from network failures myFactory.setAutomaticRecoveryEnabled(true); System.out.println("automatic recovery from network failures is " + "enabled"); System.out.println("creating new connection.."); myConnection = myFactory.newConnection(); System.out.println("creating new channel.."); myChannel = myConnection.createChannel(); System.out.println("declaring the log exchange.."); myChannel.exchangeDeclare(LOG_EXCHANGE_NAME, LOG_EXCHANGE_TYPE, true, false, true, null); System.out.println("creating random queue.."); String QUEUE_NAME = myChannel.queueDeclare().getQueue(); System.out.println("binding to exchange=" + LOG_EXCHANGE_NAME + " using binding key=" + LOG_BK); myChannel.queueBind(QUEUE_NAME, LOG_EXCHANGE_NAME, LOG_BK); System.out.println("waiting for messages, this may take few seconds" + ".."); com.rabbitmq.client.Consumer myConsumer = new DefaultConsumer(myChannel) { int messageCounter = 1; @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String messageCore = new String(body, "UTF-8"); addNewMessageToInbox(new Object[] { messageCounter, getFormattedTime(), envelope.getRoutingKey(), messageCore }); // Properties object added to message object displayNewMessage(new Object[] { messageCounter, getFormattedTime(), envelope.getRoutingKey(), messageCore }); messageCounter++; } private String getFormattedTime() { return myDateFormatter.format(new Date()); } public void addNewMessageToInbox(Object[] message) { //inbox.add(message); } private void displayNewMessage(Object[] data) { DefaultTableModel logTableModel = (DefaultTableModel) logTable.getModel(); logTableModel.addRow(data); // for (int i = 0; i < data.length; i++) { // logTable.setValueAt(data[i], logTable.getRowCount()+1, // i); // } } }; myChannel.basicConsume(QUEUE_NAME, true, myConsumer); } catch (IOException ex) { ex.printStackTrace(System.out); } catch (TimeoutException ex) { ex.printStackTrace(System.out); } }
From source file:translators.ToOurXmlBank.java
public static void main(String[] args) throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("datdb.cphbusiness.dk"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(exchangeName, "direct"); String queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, exchangeName, "ourBankSoapXML"); //get banks from queue. "Get banks" component QueueingConsumer consumer = new QueueingConsumer(channel) { @Override//w w w. j a v a 2 s. com public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); Message messageFromJson = getFromJson(message); connectToWebService(messageFromJson, properties.getCorrelationId(), EXCHANGE_NAME_SCHOOL, replyQueueName); } }; channel.basicConsume(queueName, true, consumer); }