List of usage examples for com.rabbitmq.client ConnectionFactory newConnection
public Connection newConnection() throws IOException, TimeoutException
From source file:it.txt.ens.authorisationService.util.AccessRequestEvaluator.java
License:Apache License
private Permission createSubscribingPermissionsAndResources(boolean userAlreadyExists, String operativeHost, int httpPort, int operativePort, String operativeVhost, String ensUsername, String ensPwd, String adminUsername, String adminPwd, PermissionService permissionService, String queueName, String exchangeName) throws ENSResponseFactoryException { if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine(MessageFormat.format(MESSAGES.getString("evaluationStep9ExplainationS"), ensUsername, namespace, routingKey)); Connection adminConnection = null; ConnectionFactory factory = new ConnectionFactory(); factory.setUsername(adminUsername);/*w w w . j a va2s. c om*/ factory.setPassword(adminPwd); factory.setVirtualHost(operativeVhost); factory.setHost(operativeHost); factory.setPort(operativePort); try { adminConnection = factory.newConnection(); Channel channel = adminConnection.createChannel(); //check if the queue exists if (AMQPQueueHelper.exists(channel, queueName)) { FailureResponseDetails failureDetails = new FailureResponseDetails(); String reason = ErrorCodes.INTERNAL_ERROR; failureDetails.setErrorReason(reason); failureDetails.setErrorCode(ErrorCodes.INTERNAL_ERROR); responseType = ensResponseFactory.createFailureResponse(requestType.getRequestID(), requestType.getTimeStamp(), failureDetails); if (LOGGER.isLoggable(Level.INFO)) LOGGER.log(Level.INFO, MessageFormat.format(MESSAGES.getString("evaluationStep9Failure"), ErrorCodes.INTERNAL_ERROR, reason, MessageFormat.format(MESSAGES.getString("alreadyExistingQueue"), queueName, operativeVhost, operativeHost + ":" + operativePort))); return null; } //forcing creating a new Connection because the following exception is thrown even on new Channel // com.rabbitmq.client.AlreadyClosedException: clean connection shutdown; reason: Attempt to use closed channel // at com.rabbitmq.client.impl.AMQChannel.ensureIsOpen(AMQChannel.java:190) // at com.rabbitmq.client.impl.AMQChannel.rpc(AMQChannel.java:223) // at com.rabbitmq.client.impl.AMQChannel.privateRpc(AMQChannel.java:209) // at com.rabbitmq.client.impl.AMQChannel.exnWrappingRpc(AMQChannel.java:118) // at com.rabbitmq.client.impl.ChannelN.queueDeclare(ChannelN.java:766) // at com.rabbitmq.client.impl.ChannelN.queueDeclare(ChannelN.java:61) // at it.txt.ens.authorisationService.amqp.AMQPQueueHelper.creates(AMQPQueueHelper.java:42) // at it.txt.ens.authorisationService.util.AccessRequestEvaluator.createSubscribingPermissionsAndResources(AccessRequestEvaluator.java:893) // at it.txt.ens.authorisationService.util.AccessRequestEvaluator.executeRabbitMQOperations(AccessRequestEvaluator.java:499) // at it.txt.ens.authorisationService.util.AccessRequestEvaluator.evaluate(AccessRequestEvaluator.java:284) // at it.txt.ens.authorisationService.util.AccessRequestEvaluator.run(AccessRequestEvaluator.java:216) // at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) // at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source) // at java.util.concurrent.FutureTask.run(Unknown Source) // at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) // at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) // at java.lang.Thread.run(Unknown Source) adminConnection.close(); adminConnection = factory.newConnection(); AMQPQueueHelper.creates(adminConnection.createChannel(), queueName, false, false, true); if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine(MessageFormat.format(MESSAGES.getString("evaluationStep9OK-1S"), queueName, operativeVhost, operativeHost + ":" + operativePort)); adminConnection.createChannel().queueBind(queueName, exchangeName, routingKey); if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine( MessageFormat.format(MESSAGES.getString("evaluationStep9OK-2S"), queueName, exchangeName)); // if (userAlreadyExists) // return mergePermissions(permissionService , operativeVhost, ensUsername, "", "", queueName); // else return new Permission(operativeVhost, ensUsername, "", "", queueName); } catch (Exception e) { FailureResponseDetails failureDetails = new FailureResponseDetails(); String reason = MESSAGES.getString(ErrorCodes.ENS_RESOURCE_RESERVATION_FAILURE); failureDetails.setErrorReason(reason); failureDetails.setErrorCode(ErrorCodes.ENS_RESOURCE_RESERVATION_FAILURE); responseType = ensResponseFactory.createFailureResponse(requestType.getRequestID(), requestType.getTimeStamp(), failureDetails); if (LOGGER.isLoggable(Level.INFO)) LOGGER.log(Level.INFO, MessageFormat.format(MESSAGES.getString("evaluationStep9Failure"), ErrorCodes.ENS_RESOURCE_RESERVATION_FAILURE, reason, e.getMessage()), e); return null; } finally { if (adminConnection != null) try { adminConnection.close(); } catch (IOException e) { } } }
From source file:it.txt.ens.core.util.AMQPFactory.java
License:Apache License
public static Connection createConnection(ENSAuthzServiceConnectionParameters params) throws IOException { //create and configure the RabbitMQ Connection Factory ConnectionFactory factory = new ConnectionFactory(); factory.setUsername(params.getSubjectID()); factory.setPassword(params.getAccessToken()); factory.setPort(params.getBrokerPort()); factory.setHost(params.getBrokerHost()); factory.setVirtualHost(params.getVirtualHost()); return factory.newConnection(); }
From source file:itinno.example.ExampleRabbitmqClient.java
public static void main(String[] args) { Logger logger = null;//w w w. j a va 2 s. c o m String patternLayout = "%5p %d{yyyy-MM-dd HH:mm:ss,sss} %file %t %L: %m%n"; try { // Initialise logger context and logger pattern encoder LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); PatternLayoutEncoder patternLayoutEncoder = new PatternLayoutEncoder(); // Set logging pattern (UTF-8 log) // logging patterns defined at http://logback.qos.ch/manual/layouts.html patternLayoutEncoder.setPattern(patternLayout); patternLayoutEncoder.setContext(loggerContext); patternLayoutEncoder.setCharset(Charset.forName("UTF-8")); patternLayoutEncoder.start(); // log to console ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<ILoggingEvent>(); appender.setContext(loggerContext); appender.setEncoder(patternLayoutEncoder); appender.start(); // Finally setup the logger itself logger = (Logger) LoggerFactory.getLogger(ExampleRabbitmqClient.class.getName()); logger.addAppender(appender); logger.setLevel(Level.DEBUG); logger.setAdditive(false); } catch (Exception e) { e.printStackTrace(); System.exit(1); } /*try { VisualIndexer.init("/home/kandreadou/webservice/learning_files/","127.0.0.1",LoggerFactory.getLogger(ExampleRabbitmqClient.class)); VisualIndexer v = new VisualIndexer("simtest"); v.index("http://resources0.news.com.au/images/2012/08/16/1226451/587056-120816-obama.jpg","obama1"); } catch (Exception ex) { System.out.println(ex); }*/ logger.info("rabitmq client started"); // send a UTF-8 encoded JSON tweet to the RabbitMQ (for stormspout to pick up and send to bolt) try { // check args /*if ( args.length < 1 ) { logger.error( "Usage: example_rabbitmq_client <JSON_filename>" ); System.exit( 1 ); } logger.info( "JSON file = " + args[0] );*/ String strJSONFilePath = "/home/kandreadou/mklab/example-tweet-utf8.json"; // check if the path to JSON file exists File fileJSON = new File(strJSONFilePath); System.out.println(fileJSON.getAbsolutePath()); if (fileJSON.exists() == false) { logger.info("JSON file does not exist : " + strJSONFilePath); logger.info("Usage: example_rabbitmq_client <JSON_filename>"); System.exit(1); } // read UTF-8 JSON text from file logger.info("ExampleRabbitmqClient started"); List<String> lines = Files.readAllLines(Paths.get(strJSONFilePath), Charset.forName("UTF-8")); String strJSON = ""; for (String line : lines) { if (line.length() > 0) { strJSON = strJSON + "\n"; } strJSON = strJSON + line; } logger.info("JSON test message = " + strJSON); // connect to rabbitmq broker // first of all create connection factory ConnectionFactory factory = new ConnectionFactory(); factory.setUri("amqp://guest:guest@localhost:5672/%2F"); long timestampSinceEpoch = System.currentTimeMillis() / 1000; // initialise connection and define channel Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); // initialise amqp basic peoperties object BasicProperties.Builder basicProperties = new BasicProperties.Builder(); basicProperties.build(); basicProperties.timestamp(new Date(timestampSinceEpoch)).build(); basicProperties.contentType("text/json").build(); basicProperties.deliveryMode(1).build(); // publish message /* Exchange name should be {assessment_id}+ "_exchange" */ channel.basicPublish("indexing_exchange", "test-routing", basicProperties.build(), strJSON.getBytes("UTF-8")); // close connection and channel channel.close(); connection.close(); logger.info("ExampleRabbitmqClient finished"); } catch (Exception e) { e.printStackTrace(); logger.error(e.getMessage()); System.exit(1); } }
From source file:javarpc_client.RPCClient.java
public RPCClient() throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); connection = (Connection) factory.newConnection(); channel = connection.createChannel(); replyQueueName = channel.queueDeclare().getQueue(); consumer = new QueueingConsumer(channel); channel.basicConsume(replyQueueName, true, consumer); }
From source file:javarpc_server.JavaRPC_Server.java
/** * @param args the command line arguments * @throws java.io.IOException/*from w ww .j av a 2s . c om*/ * @throws java.lang.InterruptedException */ public static void main(String[] args) throws IOException, InterruptedException { // TODO code application logic here ConnectionFactory factory = new ConnectionFactory(); System.out.println(factory.getUsername() + " " + factory.getPassword()); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null); channel.basicQos(1); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(RPC_QUEUE_NAME, false, consumer); System.out.println(" [x] Awaiting RPC requests"); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); BasicProperties props = delivery.getProperties(); BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId()) .build(); String message = new String(delivery.getBody()); System.out.println(" [.] convert(" + message + ")"); String response = "" + convert(message); channel.basicPublish("", props.getReplyTo(), replyProps, response.getBytes()); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } }
From source file:joram.amqp.PersistenceSimpleTest.java
License:Open Source License
public void recover1() throws Exception { ConnectionFactory cnxFactory = new ConnectionFactory(); Connection connection = cnxFactory.newConnection(); Channel channel = connection.createChannel(); DeclareOk declareOk = channel.queueDeclare("testqueue", true, false, false, null); channel.txSelect();//from w w w . j a v a2 s.c om for (int i = 0; i < 5; i++) { channel.basicPublish("", declareOk.getQueue(), MessageProperties.PERSISTENT_BASIC, "this is a test message !!!".getBytes()); } channel.txCommit(); killAgentServer((short) 0); startAgentServer((short) 0); connection = cnxFactory.newConnection(); channel = connection.createChannel(); declareOk = channel.queueDeclarePassive("testqueue"); for (int i = 0; i < 5; i++) { GetResponse msg = channel.basicGet("testqueue", true); assertNotNull(msg); assertEquals("this is a test message !!!", new String(msg.getBody())); } GetResponse msg = channel.basicGet("testqueue", true); assertNull(msg); channel.queueDelete(declareOk.getQueue()); }
From source file:joram.amqp.PersistenceSimpleTest.java
License:Open Source License
public void recover2() throws Exception { ConnectionFactory cnxFactory = new ConnectionFactory(); Connection connection = cnxFactory.newConnection(); Channel channel = connection.createChannel(); DeclareOk declareOk = channel.queueDeclare("testqueue", true, false, false, null); channel.txSelect();/*w w w . ja v a 2s. co m*/ for (int i = 0; i < 5; i++) { channel.basicPublish("", declareOk.getQueue(), MessageProperties.PERSISTENT_BASIC, "this is a test message !!!".getBytes()); } channel.txCommit(); killAgentServer((short) 0); startAgentServer((short) 0); Thread.sleep(500); connection = cnxFactory.newConnection(); channel = connection.createChannel(); declareOk = channel.queueDeclarePassive("testqueue"); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(declareOk.getQueue(), true, consumer); for (int i = 0; i < 5; i++) { Delivery msg = consumer.nextDelivery(1000); assertNotNull(msg); assertEquals("this is a test message !!!", new String(msg.getBody())); } Delivery msg = consumer.nextDelivery(1000); assertNull(msg); channel.queueDelete(declareOk.getQueue()); }
From source file:joram.amqp.QueueTest.java
License:Open Source License
public void queueDeclareName() throws Exception { ConnectionFactory cnxFactory = new ConnectionFactory(); Connection connection = cnxFactory.newConnection(); Channel channel = connection.createChannel(); DeclareOk declareOk = channel.queueDeclare("testqueue", true, false, false, null); assertEquals("testqueue", declareOk.getQueue()); }
From source file:joram.bridgeamqp.AMQPReceiver.java
License:Open Source License
public static AMQPReceiver createAMQPConsumer(String queue) throws IOException { ConnectionFactory cnxFactory = new ConnectionFactory(); connection = cnxFactory.newConnection(); Channel channel = connection.createChannel(); AMQPReceiver consumer = new AMQPReceiver(channel, queue); channel.basicConsume(queue, true, consumer); return consumer; }
From source file:joram.bridgeamqp.AMQPSender.java
License:Open Source License
public void run() { ConnectionFactory cnxFactory = null; Connection connection = null; Channel channel = null;/*from w w w. j a v a2 s . co m*/ try { cnxFactory = new ConnectionFactory(); connection = cnxFactory.newConnection(); channel = connection.createChannel(); // channel.queueDeclare(queue, true, false, false, null); } catch (Exception exc) { exc.printStackTrace(); return; } System.out.println(SenderId + " starts"); // Convert message properties AMQP.BasicProperties props = new AMQP.BasicProperties(); if (persistent) { props.setDeliveryMode(Integer.valueOf(org.objectweb.joram.shared.messages.Message.PERSISTENT)); } else { props.setDeliveryMode(Integer.valueOf(org.objectweb.joram.shared.messages.Message.NON_PERSISTENT)); } props.setCorrelationId(null); props.setPriority(4); props.setType(String.valueOf(org.objectweb.joram.shared.messages.Message.TEXT)); props.setExpiration("0"); try { for (int i = 0; i < nbmsgs; i++) { props.setTimestamp(new Date()); props.setMessageId(SenderId + i); channel.basicPublish("", queue, props, getBody("Message number " + i)); if (delay > 0) Thread.sleep(delay); } } catch (Exception exc) { exc.printStackTrace(); } finally { try { System.out.println(SenderId + " stops"); connection.close(); } catch (IOException exc) { exc.printStackTrace(); } } }