List of usage examples for com.rabbitmq.client Channel basicPublish
void basicPublish(String exchange, String routingKey, BasicProperties props, byte[] body) throws IOException;
From source file:gash.router.server.MessageServer.java
License:Apache License
public void createQueue() throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException, SQLException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare("inbound_queue", false, false, false, null); channel.basicQos(1);/*from w ww. ja v a 2 s. co m*/ postgre = new PostgreSQL(url, username, password, dbname, ssl); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume("inbound_queue", false, consumer); // Map<String, byte[]> map = new HashMap<String, byte[]>(); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); BasicProperties props = delivery.getProperties(); String request = props.getType(); System.out.println(request); if (request != null) { if (request.equals("get")) { String key = new String(delivery.getBody()); BasicProperties replyProps = new BasicProperties.Builder() .correlationId(props.getCorrelationId()).build(); byte[] image = postgre.get(key); channel.basicPublish("", props.getReplyTo(), replyProps, image); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } if (request.equals("put")) { byte[] image = delivery.getBody(); postgre.put(props.getUserId(), image); BasicProperties replyProps = new BasicProperties.Builder() .correlationId(props.getCorrelationId()).build(); channel.basicPublish("", props.getReplyTo(), replyProps, image); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } if (request.equals("post")) { System.out.println("Message Server"); String key = postgre.post(delivery.getBody()); BasicProperties replyProps = new BasicProperties.Builder() .correlationId(props.getCorrelationId()).build(); channel.basicPublish("", props.getReplyTo(), replyProps, key.getBytes()); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } if (request.equals("delete")) { String key = new String(delivery.getBody()); postgre.delete(key); } } } }
From source file:getbanks2.GetBanks2.java
/** * @param args the command line arguments * @throws java.io.IOException/*from w ww. j av a2 s .c o m*/ * @throws java.util.concurrent.TimeoutException */ public static void main(String[] args) throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("datdb.cphbusiness.dk"); factory.setUsername("Dreamteam"); factory.setPassword("bastian"); Connection connection = factory.newConnection(); Channel listeningChannel = connection.createChannel(); Channel sendingChannel = connection.createChannel(); listeningChannel.queueDeclare(LISTENING_QUEUE_NAME, false, false, false, null); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); Consumer consumer = new DefaultConsumer(listeningChannel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { message = new String(body, "UTF-8"); System.out.println(" [x] Received '" + message + "'"); String[] arr = message.split(","); String banks = getBanks(arr[0], Integer.parseInt(arr[1]), Double.parseDouble(arr[2]), Integer.parseInt(arr[3])); message += "," + banks; System.out.println(message); sendingChannel.queueDeclare(SENDING_QUEUE_NAME, false, false, false, null); sendingChannel.basicPublish("", SENDING_QUEUE_NAME, null, message.getBytes()); } }; listeningChannel.basicConsume(LISTENING_QUEUE_NAME, true, consumer); }
From source file:getcreditscore.GetCreditScore.java
public static void main(String[] args) throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("datdb.cphbusiness.dk"); factory.setUsername("Dreamteam"); factory.setPassword("bastian"); Connection connection = factory.newConnection(); Channel sendingChannel = connection.createChannel(); Channel listeningChannel = connection.createChannel(); listeningChannel.queueDeclare(LISTENING_QUEUE_NAME, false, false, false, null); Consumer consumer = new DefaultConsumer(listeningChannel) { @Override/* ww w.j a va 2s . com*/ public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { message = new String(body, "UTF-8"); System.out.println(" [x] Received '" + message + "'"); String[] arr = message.split(","); sendingChannel.queueDeclare(SENDING_QUEUE_NAME, false, false, false, null); String message = arr[0] + "," + creditScore(arr[0]) + "," + arr[1] + "," + arr[2]; sendingChannel.basicPublish("", SENDING_QUEUE_NAME, null, message.getBytes()); System.out.println(" [x] Sent '" + message + "'"); } }; listeningChannel.basicConsume(LISTENING_QUEUE_NAME, true, consumer); }
From source file:grnet.com.entry.Actions.java
License:Open Source License
private void logRepo(Repository repo, String status) { StringBuffer buffer = new StringBuffer(); buffer.append(repo.getName());//from w ww . j a v a2 s . c o m buffer.append(" " + status); buffer.append(" " + repo.getUrl()); buffer.append(" " + repo.getPrefix()); buffer.append(" " + repo.getOaiVersion()); buffer.append(" " + repo.getDelPolicy()); buffer.append(" " + repo.getGranularity()); buffer.append(" " + repo.getResponsible()); slf4jLogger.info(buffer.toString()); ConnectionFactory factory = new ConnectionFactory(); factory.setHost(props.getProperty(Constants.queueHost)); factory.setUsername(props.getProperty(Constants.queueUser)); factory.setPassword(props.getProperty(Constants.queuePass)); Connection connection; try { connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); channel.basicPublish("", QUEUE_NAME, null, buffer.toString().getBytes()); channel.close(); connection.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:grnet.filter.XMLFiltering.java
License:Open Source License
public static void main(String[] args) throws IOException { // TODO Auto-generated method ssstub Enviroment enviroment = new Enviroment(args[0]); if (enviroment.envCreation) { Core core = new Core(); XMLSource source = new XMLSource(args[0]); File sourceFile = source.getSource(); if (sourceFile.exists()) { Collection<File> xmls = source.getXMLs(); System.out.println("Filtering repository:" + enviroment.dataProviderFilteredIn.getName()); System.out.println("Number of files to filter:" + xmls.size()); Iterator<File> iterator = xmls.iterator(); FilteringReport report = null; if (enviroment.getArguments().getProps().getProperty(Constants.createReport) .equalsIgnoreCase("true")) { report = new FilteringReport(enviroment.getArguments().getDestFolderLocation(), enviroment.getDataProviderFilteredIn().getName()); }/*from ww w. j a v a2 s.c om*/ ConnectionFactory factory = new ConnectionFactory(); factory.setHost(enviroment.getArguments().getQueueHost()); factory.setUsername(enviroment.getArguments().getQueueUserName()); factory.setPassword(enviroment.getArguments().getQueuePassword()); while (iterator.hasNext()) { StringBuffer logString = new StringBuffer(); logString.append(enviroment.dataProviderFilteredIn.getName()); File xmlFile = iterator.next(); String name = xmlFile.getName(); name = name.substring(0, name.indexOf(".xml")); logString.append(" " + name); boolean xmlIsFilteredIn = core.filterXML(xmlFile, enviroment.getArguments().getQueries()); if (xmlIsFilteredIn) { logString.append(" " + "FilteredIn"); slf4jLogger.info(logString.toString()); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); channel.basicPublish("", QUEUE_NAME, null, logString.toString().getBytes()); channel.close(); connection.close(); try { if (report != null) { report.appendXMLFileNameNStatus(xmlFile.getPath(), Constants.filteredInData); report.raiseFilteredInFilesNum(); } FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderFilteredIn()); } catch (IOException e) { // TODO Auto-generated catch block // e.printStackTrace(); e.printStackTrace(); System.out.println("Filtering failed."); } } else { logString.append(" " + "FilteredOut"); slf4jLogger.info(logString.toString()); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); channel.basicPublish("", QUEUE_NAME, null, logString.toString().getBytes()); channel.close(); connection.close(); try { if (report != null) { report.appendXMLFileNameNStatus(xmlFile.getPath(), Constants.filteredOutData); report.raiseFilteredOutFilesNum(); } FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderFilteredOuT()); } catch (IOException e) { // TODO Auto-generated catch block // e.printStackTrace(); e.printStackTrace(); System.out.println("Filtering failed."); } } } if (report != null) { report.appendXPathExpression(enviroment.getArguments().getQueries()); report.appendGeneralInfo(); } System.out.println("Filtering is done."); } } }
From source file:grnet.validation.XMLValidation.java
License:Open Source License
public static void main(String[] args) throws IOException { // TODO Auto-generated method ssstub Enviroment enviroment = new Enviroment(args[0]); if (enviroment.envCreation) { String schemaUrl = enviroment.getArguments().getSchemaURL(); Core core = new Core(schemaUrl); XMLSource source = new XMLSource(args[0]); File sourceFile = source.getSource(); if (sourceFile.exists()) { Collection<File> xmls = source.getXMLs(); System.out.println("Validating repository:" + sourceFile.getName()); System.out.println("Number of files to validate:" + xmls.size()); Iterator<File> iterator = xmls.iterator(); System.out.println("Validating against schema:" + schemaUrl + "..."); ValidationReport report = null; if (enviroment.getArguments().createReport().equalsIgnoreCase("true")) { report = new ValidationReport(enviroment.getArguments().getDestFolderLocation(), enviroment.getDataProviderValid().getName()); }/*ww w . j a v a 2s . c om*/ ConnectionFactory factory = new ConnectionFactory(); factory.setHost(enviroment.getArguments().getQueueHost()); factory.setUsername(enviroment.getArguments().getQueueUserName()); factory.setPassword(enviroment.getArguments().getQueuePassword()); while (iterator.hasNext()) { StringBuffer logString = new StringBuffer(); logString.append(sourceFile.getName()); logString.append(" " + schemaUrl); File xmlFile = iterator.next(); String name = xmlFile.getName(); name = name.substring(0, name.indexOf(".xml")); logString.append(" " + name); boolean xmlIsValid = core.validateXMLSchema(xmlFile); if (xmlIsValid) { logString.append(" " + "Valid"); slf4jLogger.info(logString.toString()); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); channel.basicPublish("", QUEUE_NAME, null, logString.toString().getBytes()); channel.close(); connection.close(); try { if (report != null) { report.raiseValidFilesNum(); } FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderValid()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { logString.append(" " + "Invalid"); slf4jLogger.info(logString.toString()); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); channel.basicPublish("", QUEUE_NAME, null, logString.toString().getBytes()); channel.close(); connection.close(); try { if (report != null) { if (enviroment.getArguments().extendedReport().equalsIgnoreCase("true")) report.appendXMLFileNameNStatus(xmlFile.getPath(), Constants.invalidData, core.getReason()); report.raiseInvalidFilesNum(); } FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderInValid()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } if (report != null) { report.writeErrorBank(core.getErrorBank()); report.appendGeneralInfo(); } System.out.println("Validation is done."); } } }
From source file:hu.sztaki.stratosphere.workshop.RMQ.BasicRMQSender.java
License:Apache License
public static void main(String[] argv) throws java.io.IOException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String message;//ww w .ja v a 2s. co m while (true) { System.out.println("Enter next message (q to quit):"); message = br.readLine(); if (message.equals("q")) { channel.basicPublish("", QUEUE_NAME, null, message.getBytes()); break; } channel.basicPublish("", QUEUE_NAME, null, message.getBytes()); } channel.close(); connection.close(); }
From source file:hu.sztaki.stratosphere.workshop.RMQ.RMQALSSender.java
License:Apache License
public static void main(String[] argv) throws java.io.IOException, InterruptedException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); Random rnd = new Random(); for (int i = 0; i < 1000; i++) { Thread.sleep(10);/*www. java 2 s . com*/ channel.basicPublish("", QUEUE_NAME, null, Integer.toString(rnd.nextInt(250)).getBytes()); } channel.close(); connection.close(); }
From source file:hudson.plugins.collabnet.orchestrate.AmqpOrchestrateClient.java
License:Apache License
/** {@inheritDoc} */ public void postBuild(String serverUrl, String serverUsername, String serverPassword, String buildInformation) throws IOException { Connection conn = null;//from ww w .j ava2 s.co m Channel channel = null; try { // verify serverUrl, and clear trailing slash if need be URI uri = new URI(serverUrl); if (serverUrl.endsWith("/")) { serverUrl = serverUrl.substring(0, serverUrl.lastIndexOf("/")); } factory.setUri(serverUrl); // add username / password credentials to request, if needed if (!StringUtils.isBlank(serverUsername)) { factory.setUsername(serverUsername); factory.setPassword(serverPassword); } conn = factory.newConnection(); channel = conn.createChannel(); channel.queueDeclare(routingKey, true, false, false, null); byte[] messageBodyBytes = buildInformation.getBytes("UTF-8"); channel.basicPublish(exchangeName, routingKey, properties, messageBodyBytes); } catch (Exception e) { String errorMsg = "Unable to send build info to the message queue"; throw new IOException(errorMsg, e); } finally { if (channel != null) { try { channel.close(); } catch (TimeoutException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (conn != null) { conn.close(); } } }
From source file:in.cs654.chariot.ashva.AshvaServer.java
License:Open Source License
public static void main(String[] args) { Connection connection = null; Channel channel; try {/*from w w w . j a va 2 s .c o m*/ final ConnectionFactory factory = new ConnectionFactory(); factory.setHost(HOST_IP_ADDR); connection = factory.newConnection(); channel = connection.createChannel(); channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null); channel.basicQos(1); final QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(RPC_QUEUE_NAME, false, consumer); LOGGER.info("Ashva Server started. Waiting for requests..."); AshvaHelper.joinOrStartChariotPool(); AshvaHelper.startHeartbeat(); while (true) { final QueueingConsumer.Delivery delivery = consumer.nextDelivery(); BasicResponse response = new BasicResponse(); BasicRequest request = new BasicRequest(); final BasicProperties props = delivery.getProperties(); final BasicProperties replyProps = new BasicProperties.Builder() .correlationId(props.getCorrelationId()).build(); try { final DatumReader<BasicRequest> avroReader = new SpecificDatumReader<BasicRequest>( BasicRequest.class); decoder = DecoderFactory.get().binaryDecoder(delivery.getBody(), decoder); request = avroReader.read(request, decoder); response = AshvaProcessor.process(request); } catch (Exception e) { e.printStackTrace(); LOGGER.severe("Error in handling request: " + e.getMessage()); response = ResponseFactory.getErrorResponse(request); } finally { baos.reset(); final DatumWriter<BasicResponse> avroWriter = new SpecificDatumWriter<BasicResponse>( BasicResponse.class); encoder = EncoderFactory.get().binaryEncoder(baos, encoder); avroWriter.write(response, encoder); encoder.flush(); LOGGER.info("Responding to request id " + request.getRequestId() + " " + response.getStatus()); channel.basicPublish("", props.getReplyTo(), replyProps, baos.toByteArray()); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } } } catch (Exception e) { e.printStackTrace(); LOGGER.severe("Error in RPC server: " + e.getMessage()); } finally { if (connection != null) { try { connection.close(); } catch (Exception ignore) { } } } }