Example usage for com.rabbitmq.client Channel close

List of usage examples for com.rabbitmq.client Channel close

Introduction

In this page you can find the example usage for com.rabbitmq.client Channel close.

Prototype

@Override
void close() throws IOException, TimeoutException;

Source Link

Document

Close this channel with the com.rabbitmq.client.AMQP#REPLY_SUCCESS close code and message 'OK'.

Usage

From source file:info.pancancer.arch3.utils.UtilitiesIT.java

License:Open Source License

/**
 * Test of setupExchange method, of class Utilities.
 *
 * @throws java.io.IOException//from ww w  .  j a  v a  2  s .  c om
 */
@Test
public void testSetupMultiQueue() throws IOException, TimeoutException {
    Utilities instance = new Utilities();
    Channel result = Utilities.setupExchange(getSettings(), "testing_queue");
    assertTrue("could not open channel", result.isOpen());
    result.close();
}

From source file:info.pancancer.arch3.worker.WorkerHeartbeat.java

License:Open Source License

@Override
public void run() {

    Channel reportingChannel = null;
    try {/*from w  w  w.  j a  v  a2  s.c  om*/
        try {
            reportingChannel = Utilities.setupExchange(settings, this.queueName);
        } catch (IOException | TimeoutException | AlreadyClosedException e) {
            LOG.error("Exception caught! Queue channel could not be opened, waiting. Exception is: "
                    + e.getMessage(), e);
            // retry after a minute, do not die simply because the launcher is unavailable, it may come back
            Thread.sleep(Base.ONE_MINUTE_IN_MILLISECONDS);
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        LOG.info("Caught interrupt signal, heartbeat shutting down.", e);
        return;
    }

    LOG.info("starting heartbeat thread, will send heartbeat message ever " + secondsDelay + " seconds.");
    while (!Thread.interrupted()) {
        // byte[] stdOut = this.getMessageBody().getBytes(StandardCharsets.UTF_8);
        try {
            try {
                Status heartbeatStatus = new Status();
                heartbeatStatus.setJobUuid(this.jobUuid);
                heartbeatStatus.setMessage("job is running; IP address: " + networkID);
                heartbeatStatus.setState(StatusState.RUNNING);
                heartbeatStatus.setType(Utilities.JOB_MESSAGE_TYPE);
                heartbeatStatus.setVmUuid(this.vmUuid);
                heartbeatStatus.setIpAddress(networkID);

                // String stdOut = this.statusSource.getStdOut();
                Lock lock = new ReentrantLock();
                lock.lock();
                String stdOut = this.statusSource.getStdOut(stdoutSnipSize);
                String stdErr = this.statusSource.getStdErr();
                lock.unlock();
                heartbeatStatus.setStdout(stdOut);
                heartbeatStatus.setStderr(stdErr);
                String heartBeatMessage = heartbeatStatus.toJSON();
                LOG.debug("Sending heartbeat message to " + queueName + ", with body: " + heartBeatMessage);
                reportingChannel.basicPublish(queueName, queueName, MessageProperties.PERSISTENT_TEXT_PLAIN,
                        heartBeatMessage.getBytes(StandardCharsets.UTF_8));
                reportingChannel.waitForConfirms();

                Thread.sleep((long) (secondsDelay * MILLISECONDS_PER_SECOND));
            } catch (IOException | AlreadyClosedException e) {
                LOG.error("IOException caught! Message may not have been published. Exception is: "
                        + e.getMessage(), e);
                // retry after a minute, do not die simply because the launcher is unavailable, it may come back
                Thread.sleep(Base.ONE_MINUTE_IN_MILLISECONDS);
            }
        } catch (InterruptedException e) {
            LOG.info("Heartbeat shutting down.");
            if (reportingChannel.getConnection().isOpen()) {
                try {
                    reportingChannel.getConnection().close();
                } catch (IOException e1) {
                    LOG.error("Error closing reportingChannel connection: " + e1.getMessage(), e1);
                }
            }
            if (reportingChannel.isOpen()) {
                try {
                    reportingChannel.close();
                } catch (IOException e1) {
                    LOG.error("Error (IOException) closing reportingChannel: " + e1.getMessage(), e1);
                } catch (TimeoutException e1) {
                    LOG.error("Error (TimeoutException) closing reportingChannel: " + e1.getMessage(), e1);
                }
            }
            LOG.debug("reporting channel open: " + reportingChannel.isOpen());
            LOG.debug("reporting channel connection open: " + reportingChannel.getConnection().isOpen());

            Thread.currentThread().interrupt();
        }
    }
}

From source file:info.pancancer.arch3.worker.WorkerRunnable.java

License:Open Source License

@Override
public void run() {

    int max = maxRuns;

    try {/*from w  w  w  . java  2 s .c om*/
        // the VM UUID
        log.info(" WORKER VM UUID provided as: '" + vmUuid + "'");
        // write to
        // TODO: Add some sort of "local debug" mode so that developers working on their local
        // workstation can declare the queue if it doesn't exist. Normally, the results queue is
        // created by the Coordinator.
        resultsChannel = Utilities.setupExchange(settings, this.resultsQueueName);

        while (max > 0 || this.endless) {
            log.debug(max + " remaining jobs will be executed");
            log.info(" WORKER IS PREPARING TO PULL JOB FROM QUEUE " + this.jobQueueName);

            if (!endless) {
                max--;
            }

            // jobChannel needs to be created inside the loop because it is closed inside the loop, and it is closed inside this loop to
            // prevent pre-fetching.
            Channel jobChannel = Utilities.setupQueue(settings, this.jobQueueName);
            if (jobChannel == null) {
                throw new NullPointerException("jobChannel is null for queue: " + this.jobQueueName
                        + ". Something bad must have happened while trying to set up the queue connections. Please ensure that your configuration is correct.");
            }
            QueueingConsumer consumer = new QueueingConsumer(jobChannel);
            jobChannel.basicConsume(this.jobQueueName, false, consumer);

            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            log.info(vmUuid + "  received " + delivery.getEnvelope().toString());
            if (delivery.getBody() != null) {
                String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
                if (message.trim().length() > 0) {

                    log.info(" [x] Received JOBS REQUEST '" + message + "' @ " + vmUuid);

                    Job job = new Job().fromJSON(message);

                    Status status = new Status(vmUuid, job.getUuid(), StatusState.RUNNING,
                            Utilities.JOB_MESSAGE_TYPE, "job is starting", this.networkAddress);
                    status.setStderr("");
                    status.setStdout("");
                    String statusJSON = status.toJSON();

                    log.info(" WORKER LAUNCHING JOB");

                    // greedy acknowledge, it will be easier to deal with lost jobs than zombie workers in hostile OpenStack
                    // environments
                    log.info(vmUuid + " acknowledges " + delivery.getEnvelope().toString());
                    jobChannel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                    // we need to close the channel IMMEDIATELY to complete the ACK.
                    jobChannel.close();
                    // Close the connection object as well, or the main thread may not exit because of still-open-and-in-use resources.
                    jobChannel.getConnection().close();

                    WorkflowResult workflowResult = new WorkflowResult();
                    if (testMode) {
                        workflowResult.setWorkflowStdout("everything is awesome");
                        workflowResult.setExitCode(0);
                    } else {
                        String seqwareEngine = settings.getString(Constants.WORKER_SEQWARE_ENGINE,
                                Constants.SEQWARE_WHITESTAR_ENGINE);
                        String seqwareSettingsFile = settings.getString(Constants.WORKER_SEQWARE_SETTINGS_FILE);
                        String dockerImage = settings.getString(Constants.WORKER_SEQWARE_DOCKER_IMAGE_NAME);
                        workflowResult = launchJob(statusJSON, job, seqwareEngine, seqwareSettingsFile,
                                dockerImage);
                    }

                    status = new Status(vmUuid, job.getUuid(),
                            workflowResult.getExitCode() == 0 ? StatusState.SUCCESS : StatusState.FAILED,
                            Utilities.JOB_MESSAGE_TYPE, "job is finished", networkAddress);
                    status.setStderr(workflowResult.getWorkflowStdErr());
                    status.setStdout(workflowResult.getWorkflowStdout());
                    statusJSON = status.toJSON();

                    log.info(" WORKER FINISHING JOB");

                    finishJob(statusJSON);
                } else {
                    log.info(NO_MESSAGE_FROM_QUEUE_MESSAGE);
                }
                // we need to close the channel *conditionally*
                if (jobChannel.isOpen()) {
                    jobChannel.close();
                }
                // Close the connection object as well, or the main thread may not exit because of still-open-and-in-use resources.
                if (jobChannel.getConnection().isOpen()) {
                    jobChannel.getConnection().close();
                }
            } else {
                log.info(NO_MESSAGE_FROM_QUEUE_MESSAGE);
            }

            if (endless) {
                log.info("attempting to reset workspace");
                DefaultExecutor executor = new DefaultExecutor();
                DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
                // attempt a cleanup
                CommandLine cli = new CommandLine("sudo");
                List<String> args = new ArrayList<>(Arrays.asList("rm", "-rf", "/datastore/*"));
                cli.addArguments(args.toArray(new String[args.size()]));
                executor.execute(cli, resultHandler);
                // Use the result handler for non-blocking call, so this way we should be able to get updates of
                // stdout and stderr while the command is running.
                resultHandler.waitFor();
                log.info("exit code for cleanup: " + resultHandler.getExitValue());
            }
        }
        log.info(" \n\n\nWORKER FOR VM UUID HAS FINISHED!!!: '" + vmUuid + "'\n\n");

        // turns out this is needed when multiple threads are reading from the same
        // queue otherwise you end up with multiple unacknowledged messages being undeliverable to other workers!!!
        if (resultsChannel != null && resultsChannel.isOpen()) {
            resultsChannel.close();
            resultsChannel.getConnection().close();
        }
        log.debug("result channel open: " + resultsChannel.isOpen());
        log.debug("result channel connection open: " + resultsChannel.getConnection().isOpen());
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
    }
}

From source file:io.druid.firehose.rabbitmq.RabbitMQFirehoseFactory.java

License:Apache License

@Override
public Firehose connect(StringInputRowParser firehoseParser) throws IOException {
    final StringInputRowParser stringParser = firehoseParser;

    ConnectionOptions lyraOptions = new ConnectionOptions(this.connectionFactory);
    Config lyraConfig = new Config().withRecoveryPolicy(new RetryPolicy().withMaxRetries(config.getMaxRetries())
            .withRetryInterval(Duration.seconds(config.getRetryIntervalSeconds()))
            .withMaxDuration(Duration.seconds(config.getMaxDurationSeconds())));

    String queue = config.getQueue();
    String exchange = config.getExchange();
    String routingKey = config.getRoutingKey();

    boolean durable = config.isDurable();
    boolean exclusive = config.isExclusive();
    boolean autoDelete = config.isAutoDelete();

    final Connection connection = Connections.create(lyraOptions, lyraConfig);

    connection.addShutdownListener(new ShutdownListener() {
        @Override/*from w  ww .  ja va2s .  c om*/
        public void shutdownCompleted(ShutdownSignalException cause) {
            log.warn(cause, "Connection closed!");
        }
    });

    final Channel channel = connection.createChannel();
    channel.queueDeclare(queue, durable, exclusive, autoDelete, null);
    channel.queueBind(queue, exchange, routingKey);
    channel.addShutdownListener(new ShutdownListener() {
        @Override
        public void shutdownCompleted(ShutdownSignalException cause) {
            log.warn(cause, "Channel closed!");
        }
    });

    // We create a QueueingConsumer that will not auto-acknowledge messages since that
    // happens on commit().
    final QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queue, false, consumer);

    return new Firehose() {
        /**
         * Storing the latest delivery as a member variable should be safe since this will only be run
         * by a single thread.
         */
        private Delivery delivery;

        /**
         * Store the latest delivery tag to be able to commit (acknowledge) the message delivery up to
         * and including this tag. See commit() for more detail.
         */
        private long lastDeliveryTag;

        @Override
        public boolean hasMore() {
            delivery = null;
            try {
                // Wait for the next delivery. This will block until something is available.
                delivery = consumer.nextDelivery();
                if (delivery != null) {
                    lastDeliveryTag = delivery.getEnvelope().getDeliveryTag();
                    // If delivery is non-null, we report that there is something more to process.
                    return true;
                }
            } catch (InterruptedException e) {
                // A little unclear on how we should handle this.

                // At any rate, we're in an unknown state now so let's log something and return false.
                log.wtf(e, "Got interrupted while waiting for next delivery. Doubt this should ever happen.");
            }

            // This means that delivery is null or we caught the exception above so we report that we have
            // nothing more to process.
            return false;
        }

        @Override
        public InputRow nextRow() {
            if (delivery == null) {
                //Just making sure.
                log.wtf("I have nothing in delivery. Method hasMore() should have returned false.");
                return null;
            }

            return stringParser.parse(StringUtils.fromUtf8(delivery.getBody()));
        }

        @Override
        public Runnable commit() {
            // This method will be called from the same thread that calls the other methods of
            // this Firehose. However, the returned Runnable will be called by a different thread.
            //
            // It should be (thread) safe to copy the lastDeliveryTag like we do below and then
            // acknowledge values up to and including that value.
            return new Runnable() {
                // Store (copy) the last delivery tag to "become" thread safe.
                final long deliveryTag = lastDeliveryTag;

                @Override
                public void run() {
                    try {
                        log.info("Acknowledging delivery of messages up to tag: " + deliveryTag);

                        // Acknowledge all messages up to and including the stored delivery tag.
                        channel.basicAck(deliveryTag, true);
                    } catch (IOException e) {
                        log.error(e, "Unable to acknowledge message reception to message queue.");
                    }
                }
            };
        }

        @Override
        public void close() throws IOException {
            log.info("Closing connection to RabbitMQ");
            channel.close();
            connection.close();
        }
    };
}

From source file:io.druid.segment.realtime.firehose.RabbitMQFirehoseFactory.java

License:Open Source License

@Override
public Firehose connect() throws IOException {
    String queue = config.getQueue();
    String exchange = config.getExchange();
    String routingKey = config.getRoutingKey();

    boolean durable = config.isDurable();
    boolean exclusive = config.isExclusive();
    boolean autoDelete = config.isAutoDelete();

    final Connection connection = connectionFactory.newConnection();
    connection.addShutdownListener(new ShutdownListener() {
        @Override// w  ww.  j a  v a 2 s  .  c o  m
        public void shutdownCompleted(ShutdownSignalException cause) {
            log.warn(cause, "Connection closed!");
            //FUTURE: we could try to re-establish the connection here. Not done in this version though.
        }
    });

    final Channel channel = connection.createChannel();
    channel.queueDeclare(queue, durable, exclusive, autoDelete, null);
    channel.queueBind(queue, exchange, routingKey);
    channel.addShutdownListener(new ShutdownListener() {
        @Override
        public void shutdownCompleted(ShutdownSignalException cause) {
            log.warn(cause, "Channel closed!");
            //FUTURE: we could try to re-establish the connection here. Not done in this version though.
        }
    });

    // We create a QueueingConsumer that will not auto-acknowledge messages since that
    // happens on commit().
    final QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queue, false, consumer);

    return new Firehose() {
        /**
         * Storing the latest delivery as a member variable should be safe since this will only be run
         * by a single thread.
         */
        private QueueingConsumer.Delivery delivery;

        /**
         * Store the latest delivery tag to be able to commit (acknowledge) the message delivery up to
         * and including this tag. See commit() for more detail.
         */
        private long lastDeliveryTag;

        @Override
        public boolean hasMore() {
            delivery = null;
            try {
                // Wait for the next delivery. This will block until something is available.
                delivery = consumer.nextDelivery();
                if (delivery != null) {
                    lastDeliveryTag = delivery.getEnvelope().getDeliveryTag();
                    // If delivery is non-null, we report that there is something more to process.
                    return true;
                }
            } catch (InterruptedException e) {
                // A little unclear on how we should handle this.

                // At any rate, we're in an unknown state now so let's log something and return false.
                log.wtf(e, "Got interrupted while waiting for next delivery. Doubt this should ever happen.");
            }

            // This means that delivery is null or we caught the exception above so we report that we have
            // nothing more to process.
            return false;
        }

        @Override
        public InputRow nextRow() {
            if (delivery == null) {
                //Just making sure.
                log.wtf("I have nothing in delivery. Method hasMore() should have returned false.");
                return null;
            }

            return parser.parse(new String(delivery.getBody()));
        }

        @Override
        public Runnable commit() {
            // This method will be called from the same thread that calls the other methods of
            // this Firehose. However, the returned Runnable will be called by a different thread.
            //
            // It should be (thread) safe to copy the lastDeliveryTag like we do below and then
            // acknowledge values up to and including that value.
            return new Runnable() {
                // Store (copy) the last delivery tag to "become" thread safe.
                final long deliveryTag = lastDeliveryTag;

                @Override
                public void run() {
                    try {
                        log.info("Acknowledging delivery of messages up to tag: " + deliveryTag);

                        // Acknowledge all messages up to and including the stored delivery tag.
                        channel.basicAck(deliveryTag, true);
                    } catch (IOException e) {
                        log.error(e, "Unable to acknowledge message reception to message queue.");
                    }
                }
            };
        }

        @Override
        public void close() throws IOException {
            log.info("Closing connection to RabbitMQ");
            channel.close();
            connection.close();
        }
    };
}

From source file:io.snappydata.rabbitmq.RabbitMQPublisher.java

License:Open Source License

public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(QUEUE_NAME, true, false, false, null);

    int logCount = 0;
    int totalNumLogs = 1000000;

    while (logCount <= totalNumLogs) {
        AdImpressionLog log = AdImpressionGenerator.nextRandomAdImpression();
        channel.basicPublish("", QUEUE_NAME, null, getLogBytes(log));
        logCount += 1;/*from w w  w.  j a  v  a 2  s. c o m*/
        if (logCount % 100000 == 0) {
            System.out.println("RabbitMQPublisher published total " + logCount + " messages");
        }
    }

    channel.close();
    connection.close();
}

From source file:it.txt.ens.authorisationService.util.AccessRequestEvaluator.java

License:Apache License

@Override
public void run() {
    Channel channel = null;
    String correlationId = requestProperties.getCorrelationId();
    String replyTo = requestProperties.getReplyTo();
    try {// w  ww  .  j a va2 s. com
        byte[] response = evaluate();
        channel = connection.createChannel();
        isClosed = false;
        channel.addShutdownListener(this);
        if (correlationId != null && replyTo != null) {
            AMQP.BasicProperties replyProperties = new AMQP.BasicProperties.Builder()
                    .correlationId(correlationId).build();
            channel.basicPublish("", replyTo, replyProperties, response);
            if (LOGGER.isLoggable(Level.FINER))
                LOGGER.log(Level.FINER, MESSAGES.getString("responsePublished"));
        } else {
            LOGGER.severe(MESSAGES.getString("missingCorrelationIDAndReplyTo"));
        }
        //            channel.basicAck(envelope.getDeliveryTag(), false);
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE,
                MessageFormat.format(MESSAGES.getString("responsePublishFailure"), correlationId, replyTo), e);
    } finally {
        if (channel != null)
            try {
                isClosed = true;
                channel.close();
            } catch (IOException e) {
            } catch (ShutdownSignalException 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   w ww.j av  a2 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 ww  w .j  av a  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:jenkins.plugins.logstash.persistence.RabbitMqDao.java

License:Open Source License

private void finalizeChannel(Channel channel) {
    if (channel != null && channel.isOpen()) {
        try {/*from w w w  .  ja  va  2 s. com*/
            channel.close();
        } catch (IOException e) {
            // This shouldn't happen but if it does there's nothing we can do
            e.printStackTrace();
        }
    }
}