List of usage examples for com.rabbitmq.client Connection close
@Override void close() throws IOException;
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.ja v a 2 s . co m 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.authorisationService.util.AccessRequestEvaluator.java
License:Apache License
private Permission createPublishingPermissionsAndResources(boolean userAlreadyExists, String operativeHost, int httpPort, int operativePort, String operativeVhost, String ensUsername, String ensPwd, String adminUsername, String adminPwd, PermissionService permissionService, String exchangeName) throws ENSResponseFactoryException { if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine(MessageFormat.format(MESSAGES.getString("evaluationStep9ExplainationP"), ensUsername, namespace, routingKey)); AMQPConnectionHelper mc = new AMQPConnectionHelper(); Connection adminConnection = null; try {//from w w w . ja v a 2 s . c o m adminConnection = mc.connection(adminUsername, adminPwd, operativeVhost, operativeHost, operativePort); Channel channel = adminConnection.createChannel(); //check if the exchange exists AMQPExchangeHelper exchHelper = new AMQPExchangeHelper(); if (!exchHelper.exists(channel, exchangeName)) { exchHelper.creates(channel, exchangeName, "topic", true, false); if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine(MessageFormat.format(MESSAGES.getString("evaluationStep9OK-1P"), exchangeName, operativeVhost, operativeHost + ":" + operativePort)); } else if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(MESSAGES.getString("evaluationStep9OK-2P")); } // if (userAlreadyExists) // return mergePermissions(permissionService , operativeVhost, ensUsername, "", exchangeName, ""); // else return new Permission(operativeVhost, ensUsername, "", exchangeName, ""); } catch (IOException 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); return null; } finally { if (adminConnection != null) try { adminConnection.close(); } catch (IOException e) { } } }
From source file:it.txt.ens.client.impl.BasicENSClient.java
License:Apache License
@Override public void connect() throws ENSClientException, ENSConnectionException { //create and configure the RabbitMQ Connection Factory factory = new ConnectionFactory(); factory.setUsername(authzServiceConnParams.getSubjectID()); factory.setPassword(authzServiceConnParams.getAccessToken()); factory.setPort(authzServiceConnParams.getBrokerPort()); factory.setHost(authzServiceConnParams.getBrokerHost()); factory.setVirtualHost(authzServiceConnParams.getVirtualHost()); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "authorisation.step1", new Object[] { capabilityDirectory.getAbsoluteFile(), subjectID, targetResource.getURI().toString(), operation.toString() }); }//from www .ja v a 2 s. c o m //START CAPABILITY SEARCH //retrieve the best suitable capabilities CapabilityXQuerySaxURISearch capabilityFinder = new CapabilityXQuerySaxURISearch(capabilityDirectory); URIResourceIDSections uriSections = new URIResourceIDSections(); uriSections.setAuthority(targetResource.getHost()); uriSections.setScheme(ENSResource.URI_SCHEME); uriSections.setNamespace(targetResource.getNamespace()); uriSections.setPattern(targetResource.getPattern()); uriSections.setService(targetResource.getPath()); List<CapabilitySearchReturn> capabilities; try { capabilities = capabilityFinder.doSearchCapability(subjectID, uriSections.toURI().toString(), operation.toString()); } catch (UnsupportedEncodingException e) { ENSClientException ece = new ENSClientException( ENSClientExceptionCodes.TARGET_RESOURCE_URI_CREATION_ERROR, e); LOGGER.log(Level.SEVERE, ece.getMessage(), e); throw ece; } catch (URISyntaxException e) { ENSClientException ece = new ENSClientException( ENSClientExceptionCodes.TARGET_RESOURCE_URI_CREATION_ERROR, e); LOGGER.log(Level.SEVERE, ece.getMessage(), e); throw ece; } if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "capabilitySearch.selectedCapabilities", capabilities.size()); } if (capabilities.isEmpty()) throw new ENSClientException(ENSClientExceptionCodes.NO_SUITABLE_CAPABILITY_FOUND); if (capabilities.size() > 1) Collections.sort(capabilities, new Comparator<CapabilitySearchReturn>() { public int compare(CapabilitySearchReturn o1, CapabilitySearchReturn o2) { XMLGregorianCalendar issueDate1 = o1.getCapabilityIssueDateToXmlGregorianCalendar(); XMLGregorianCalendar isssueDate2 = o2.getCapabilityIssueDateToXmlGregorianCalendar(); return issueDate1.compare(isssueDate2); } }); CapabilitySearchReturn selectedCapability = capabilities.get(0); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "authorisation.step1OK", new Object[] { selectedCapability.getCapabilityID(), selectedCapability .getCapabilityIssueDateToXmlGregorianCalendar().toGregorianCalendar().getTime(), selectedCapability.getCapabilityFile().getAbsolutePath() }); LOGGER.log(Level.FINE, "authorisation.step2"); } //STOP CAPABILITY SEARCH //create a JAXB request object FileInputStream capabilityStream = null; RequestType requestType = null; try { capabilityStream = new FileInputStream(selectedCapability.getCapabilityFile()); requestType = requestFactory.create(targetResource.getURI(), subjectID, operation.toString(), sessionExpiration, capabilityStream); } catch (FileNotFoundException e) { if (LOGGER.isLoggable(Level.SEVERE)) LOGGER.log(Level.SEVERE, MessageFormat.format(LOG_MESSAGES.getString("capabilitySearch.missingExistingFile"), selectedCapability.getCapabilityFile().getAbsolutePath()), e); throw new ENSClientException(ENSClientExceptionCodes.MISSING_SELECTED_CAPABILITY, e); } catch (ENSRequestFactoryException e) { ENSClientException clientExc = new ENSClientException(ENSClientExceptionCodes.REQUEST_CREATION, e); if (LOGGER.isLoggable(Level.SEVERE)) LOGGER.log(Level.SEVERE, clientExc.getMessage(), e); throw clientExc; } //here we are sure that the request type has been instantiated Document requestDOM = null; try { requestDOM = requestFactory.marshal(requestType); } catch (ENSRequestFactoryException e) { ENSClientException clientExc = new ENSClientException(ENSClientExceptionCodes.REQUEST_MARSHALLING_ERROR, e); if (LOGGER.isLoggable(Level.SEVERE)) LOGGER.log(Level.SEVERE, clientExc.getMessage(), e); throw clientExc; } //we are sure that the request DOM has been instantiated if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "authorisation.step2OK", XMLPrinter.printDocumentElement(requestDOM.getDocumentElement(), true)); LOGGER.log(Level.FINE, "authorisation.step3"); } X509DocumentSignerInfo signerInfo = new X509DocumentSignerInfo(); signerInfo.setKeystorePath(keystoreParams.getKeystorePath().getAbsolutePath()); signerInfo.setKeystorePwd(keystoreParams.getKeystorePassword()); signerInfo.setPrivateKeyPwd(certParams.getPrivateKeyPassword()); signerInfo.setSignerID(certParams.getX509CertificateSubject()); try { X509CertificateKeyValues keyValues = X509DocumentSigner.getCertificateKeyValues(signerInfo); X509DocumentSigner.signXMLElement(requestDOM.getDocumentElement(), keyValues, ENSAuthorisationRequestFactory.SIGN_DOCUMENT_AFTER_NODE); } catch (GeneralSecurityException e) { ENSClientException clientExc = new ENSClientException( ENSClientExceptionCodes.DIGITAL_SIGNATURE_CREATION_ERROR, e); if (LOGGER.isLoggable(Level.SEVERE)) LOGGER.log(Level.SEVERE, clientExc.getMessage(), e); throw clientExc; } if (LOGGER.isLoggable(Level.FINE)) LOGGER.log(Level.FINE, "authorisation.step3OK", XMLPrinter.printDocumentElement(requestDOM.getDocumentElement(), true)); //transformation of the digitally signed XML DOM into an array of byte ByteArrayOutputStream xmlos; try { xmlos = (ByteArrayOutputStream) XMLPrinter .convertDOMIntoByteStream(requestDOM, false, null, new ByteArrayOutputStream()) .getOutputStream(); } catch (TransformerException e) { ENSClientException clientExc = new ENSClientException(ENSClientExceptionCodes.SIGNATURE_TO_BYTES_ERROR, e); if (LOGGER.isLoggable(Level.SEVERE)) LOGGER.log(Level.SEVERE, clientExc.getMessage(), e); throw clientExc; } if (LOGGER.isLoggable(Level.FINE)) LOGGER.log(Level.FINE, "authorisation.step4"); Connection authorisationConnection = null; Channel authorisationChannel = null; String rawResponse = null; try { //initialise the connection to the ENS access request broker authorisationConnection = factory.newConnection(); authorisationChannel = authorisationConnection.createChannel(); //create an RPC Client //FIXME SHOULD WE INDICATE THE EXCHANGE?? RpcClient client = new RpcClient(authorisationChannel, "", authzServiceConnParams.getDestinationName(), TIMEOUT); rawResponse = client.stringCall(xmlos.toString(ENCODING)); // rawResponse = client.stringCall(xmlos.toString()); } catch (IOException e) { ENSConnectionException connExc = new ENSConnectionException( ENSConnectionExceptionCodes.ACCESS_REQUEST_BROKER_CONNECTION_ERROR, e); if (LOGGER.isLoggable(Level.SEVERE)) LOGGER.log(Level.SEVERE, connExc.getMessage(), e); throw connExc; } catch (ShutdownSignalException e) { ENSConnectionException connExc = new ENSConnectionException( ENSConnectionExceptionCodes.ACCESS_REQUEST_BROKER_CONNECTION_ERROR, e); if (LOGGER.isLoggable(Level.SEVERE)) LOGGER.log(Level.SEVERE, connExc.getMessage(), e); throw connExc; } catch (TimeoutException e) { ENSConnectionException connExc = new ENSConnectionException( ENSConnectionExceptionCodes.ACCESS_REQUEST_BROKER_CONNECTION_ERROR, e); if (LOGGER.isLoggable(Level.SEVERE)) LOGGER.log(Level.SEVERE, connExc.getMessage(), e); throw connExc; } finally { if (authorisationChannel != null) try { authorisationChannel.close(); } catch (IOException e) { } if (authorisationConnection != null) try { authorisationConnection.close(); } catch (IOException e) { } } if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "authorisation.step4OK", rawResponse); } if (ENSStatus.FailureCodes.INTERNAL_ERROR.equalsIgnoreCase(rawResponse)) { throw new ENSClientException(ENSClientExceptionCodes.INTERNAL_SERVER_ERROR); } ResponseType responseObject = null; ByteArrayInputStream inputStream = null; try { inputStream = new ByteArrayInputStream(rawResponse.getBytes(ENCODING)); // inputStream = new ByteArrayInputStream(rawResponse.getBytes()); responseObject = responseFactory.parseInputStream(inputStream); Document responseDOM = responseFactory.marshal(responseObject); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "authorisation.step5"); } boolean isSignatureVerified = X509DocumentSigner.verifyXMLElementSign(responseDOM.getDocumentElement(), new X509CertificateSubjectInfo()); if (!isSignatureVerified) { throw new ENSClientException(ENSClientExceptionCodes.TAMPERED_RESPONSE); } } catch (UnsupportedEncodingException e) { ENSClientException ece = new ENSClientException(ENSClientExceptionCodes.UNSUPPORTED_ENCODING, e, ENCODING, debugID); if (LOGGER.isLoggable(Level.SEVERE)) LOGGER.log(Level.SEVERE, ece.getMessage(), e); throw ece; } catch (ENSResponseFactoryException e) { ENSClientException ece = new ENSClientException(ENSClientExceptionCodes.RESPONSE_MARSHALLING_ERROR, e); if (LOGGER.isLoggable(Level.SEVERE)) LOGGER.log(Level.SEVERE, ece.getMessage(), e); throw ece; } catch (GeneralSecurityException e) { ENSClientException ece = new ENSClientException( ENSClientExceptionCodes.DIGITAL_SIGNATURE_VERIFICATION_ERROR, e); if (LOGGER.isLoggable(Level.SEVERE)) LOGGER.log(Level.SEVERE, ece.getMessage(), e); throw ece; } if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "authorisation.step5OK"); LOGGER.log(Level.FINE, "authorisation.step6"); } //analysis of the response if (responseObject.isResult()) { SuccessResponseType success = responseObject.getResultDetails().getSuccessResponse(); ENSBrokerConnectionParameters operativeBrokerConnParams = connParamsFactory.create( success.getSubject().getSubjectID(), success.getAccessToken(), success.getBrokerHost(), success.getBrokerPort().intValue(), success.getVirtualHost(), success.getQueueName(), success.isUseTLS(), success.getSessionExpiration().toGregorianCalendar().getTime(), success.getSessionToken()); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, "authorisation.step6OK", new String[] { debugID, operativeBrokerConnParams.toString() }); } factory = new ConnectionFactory(); factory.setHost(operativeBrokerConnParams.getBrokerHost()); factory.setPassword(operativeBrokerConnParams.getAccessToken()); factory.setPort(operativeBrokerConnParams.getBrokerPort()); factory.setUsername(operativeBrokerConnParams.getSubjectID()); factory.setVirtualHost(operativeBrokerConnParams.getVirtualHost()); useENSBrokerConnectionParameters(operativeBrokerConnParams); try { connection = factory.newConnection(); } catch (IOException e) { ENSClientException ce = new ENSClientException(ENSClientExceptionCodes.OPERATIVE_CONNECTION_ERROR, e, factory.getVirtualHost(), factory.getHost()); LOGGER.log(Level.SEVERE, ce.getMessage(), e); throw ce; } } else { FailureResponseType failure = responseObject.getResultDetails().getFailureResponse(); ENSClientException failureException = new ENSClientException(failure); if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, "authorisation.step6FAILURE", new String[] { failure.getErrorCode(), failure.getErrorReason() }); } throw failureException; } }
From source file:itinno.example.ExampleRabbitmqClient.java
public static void main(String[] args) { Logger logger = null;//from w ww .j ava 2 s . co 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:jenkins.plugins.logstash.persistence.RabbitMqDao.java
License:Open Source License
private void finalizeConnection(Connection connection) { if (connection != null && connection.isOpen()) { try {/*w w w . j ava2 s.c om*/ connection.close(); } catch (IOException e) { // This shouldn't happen but if it does there's nothing we can do e.printStackTrace(); } } }
From source file:joram.bridgeamqp.AMQPSender.java
License:Open Source License
public void run() { ConnectionFactory cnxFactory = null; Connection connection = null; Channel channel = null;/* ww w . j a v a 2s . 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(); } } }
From source file:loanbroker.Aggregator.java
private void send(entity.Message m, String routingKey) throws IOException, TimeoutException, InterruptedException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(hostName);/*from w ww . j a va 2 s. c om*/ factory.setPort(5672); factory.setUsername("student"); factory.setPassword("cph"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(ExchangeName.GLOBAL, "direct"); //creating LoanResponse object LoanResponse lp = new LoanResponse(parseInt(m.getSsn()), m.getCreditScore(), m.getLoanDuration(), ""); Gson gson = new GsonBuilder().create(); String fm = gson.toJson(lp); BasicProperties props = new BasicProperties.Builder().build(); channel.basicPublish(ExchangeName.GLOBAL, routingKey, props, fm.getBytes()); System.out.println(" [x] Sent '" + ExchangeName.GLOBAL + routingKey + "':'" + fm + "'"); channel.close(); connection.close(); }
From source file:loanbroker.GetCreditScore.java
public void send(entity.Message creditScoreMessage) throws IOException, TimeoutException, Exception { ConnectionFactory connfac = new ConnectionFactory(); connfac.setHost(hostName);/*from w w w . j a v a 2 s . c o m*/ connfac.setPort(5672); connfac.setUsername("student"); connfac.setPassword("cph"); Gson gson = new GsonBuilder().create(); String fm = gson.toJson(creditScoreMessage); Connection connection = connfac.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(ExchangeName.OUTPUT_GET_CREDITSCORE, "fanout"); channel.basicPublish(ExchangeName.OUTPUT_GET_CREDITSCORE, "", null, fm.getBytes()); System.out.println(" [x] Sent '" + fm.toString() + "'"); channel.close(); connection.close(); }
From source file:loanbroker.normalizer.CallTeachersJsonBank.java
public static void main(String[] args) { Gson gson = new Gson(); DtoJsonBank jsonBank = null;// w ww .j a va2s . co m try { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("datdb.cphbusiness.dk"); factory.setPort(5672); factory.setUsername("student"); factory.setPassword("cph"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "fanout"); //reply String corrId = java.util.UUID.randomUUID().toString(); BasicProperties props = new BasicProperties.Builder().correlationId("test1122").replyTo(replyQueueName) .build(); String message = gson.toJson(new DtoJsonBank("1605789787", 598, 10.0, "")); channel.basicPublish(EXCHANGE_NAME, "", props, message.getBytes()); channel.close(); connection.close(); } catch (IOException | TimeoutException e) { e.printStackTrace(); } }
From source file:localdomain.localhost.RabbitMQClient.java
License:Apache License
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {/*from ww w .j av a 2 s. c om*/ ConnectionFactory factory = new ConnectionFactory(); String messages = new String(); String uri = System.getProperty("CLOUDAMQP_URL"); factory.setUri(uri); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, true, false, false, null); QueueingConsumer consumer = new QueueingConsumer(channel); boolean autoACK = false; channel.basicConsume(QUEUE_NAME, autoACK, consumer); System.out.println(" [*] Waiting 100ms for a message"); QueueingConsumer.Delivery delivery = consumer.nextDelivery(100); while (delivery != null) { String message = new String(delivery.getBody()); System.out.println(" [x] Received '" + message + "'"); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); messages = message + " <br/> " + messages; delivery = consumer.nextDelivery(100); } request.setAttribute("messages", messages); request.getRequestDispatcher("/index.jsp").forward(request, response); channel.close(); connection.close(); } catch (Exception e) { request.setAttribute("throwable", e); request.getRequestDispatcher("/index.jsp").forward(request, response); } }