Example usage for com.rabbitmq.client ConnectionFactory ConnectionFactory

List of usage examples for com.rabbitmq.client ConnectionFactory ConnectionFactory

Introduction

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

Prototype

ConnectionFactory

Source Link

Usage

From source file:it.jugtorino.one.msvc.way.rabbit.geoip.reference.client.RpcClientExample.java

License:Open Source License

private static Channel setupRabbitMQ() throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    Connection connection = factory.newConnection(Collections.singletonList(new Address("localhost")));
    Channel channel = connection.createChannel();
    channel.queueDeclare("geoip_service_v1", false, false, false, null);
    return channel;
}

From source file:it.jugtorino.one.msvc.way.rabbit.geoip.reference.service.Main.java

License:Open Source License

private static Channel setupRabbitMQ() throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    Connection connection = factory.newConnection(Arrays.asList(new Address("localhost")));
    Channel channel = connection.createChannel();
    channel.queueDeclare("geoip_service_v1", false, false, false, null);
    return channel;
}

From source file:it.jugtorino.one.msvc.way.rabbit.reference.webapp.GeoIPResource.java

License:Open Source License

public GeoIPResource() throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    Connection connection = factory.newConnection(Collections.singletonList(new Address("localhost")));
    Channel channel = connection.createChannel();
    channel.queueDeclare("geoip_service_v1", false, false, false, null);

    client = new RpcClient(channel, "geoip_service_v1");
    client.startConsuming();//w  w  w .  j  a  va2  s .  co m
}

From source file:it.polimi.hegira.queue.Queue.java

License:Apache License

public Queue() throws QueueException {
    factory = new ConnectionFactory();
    String queueProperty = PropertiesManager.getQueueProperty("host");
    if (queueProperty == null || queueProperty.isEmpty()) {
        throw new QueueException();
    }/* w ww.jav  a2 s.c om*/
    factory.setHost(queueProperty);
    try {
        connection = factory.newConnection();
        //SENDER PART
        channelPublish = connection.createChannel();
        /**
         * direct exchange: a message goes to the queues whose binding key 
         * exactly matches the routing key of the message.
         */
        channelPublish.exchangeDeclare(EXCHANGE_NAME, "direct");
        log.debug("Publish channel created. Exchange: " + EXCHANGE_NAME + " type: direct");

        //RECEIVER PART
        channelConsume = connection.createChannel();
        channelConsume.exchangeDeclare(EXCHANGE_NAME, "direct");
        log.debug("Consuming channel created. Exchange: " + EXCHANGE_NAME + " type: direct");

        //String queueName = channelConsume.queueDeclare().getQueue();
        /**
         * queueDeclare(java.lang.String queue, boolean durable, 
         * boolean exclusive, boolean autoDelete, 
         * java.util.Map<java.lang.String,java.lang.Object> arguments) 
         */
        String queueName = channelConsume.queueDeclare("Q1", false, false, false, null).getQueue();

        /**
         * routing key bindings: relationship between an exchange and a queue.
         */
        channelConsume.queueBind(queueName, EXCHANGE_NAME, LISTEN_RK);
        log.debug("Binding the consuming channel. ROUTING KEY: " + LISTEN_RK + " QUEUE NAME: " + queueName);

        /**
         * Telling the server to deliver us the messages from the queue. 
         * Since it will push us messages asynchronously, we provide a callback 
         * in the form of an object (QueueingConsumer) that will buffer the messages 
         * until we're ready to use them.
         */
        consumer = new QueueingConsumer(channelConsume);
        /**
         * basicConsume(java.lang.String queue, boolean autoAck, Consumer callback)
         * Starts a non-nolocal, non-exclusive consumer, 
         * with a server-generated consumerTag.
         */
        channelConsume.basicConsume(queueName, true, consumer);
        log.debug("Consumer started on queue: " + queueName);
    } catch (IOException e) {
        log.error(e.toString());
    }
}

From source file:it.polimi.hegira.queue.ServiceQueue.java

License:Apache License

/**
 * Creates a service queue between the given component and hegira-api.
 * @param componentType The type of component creating the queue, i.e. SRC or TWC.
 * @param queueAddress The address of RabbitMQ broker.
 *///w w w  .ja  v  a 2  s.c  om
public ServiceQueue(String componentType, String queueAddress) {
    LISTEN_RK = componentType;

    factory = new ConnectionFactory();
    factory.setHost(queueAddress);
    try {
        connection = factory.newConnection();
        //SENDER PART
        channelPublish = connection.createChannel();
        /**
         * direct exchange: a message goes to the queues whose binding key 
         * exactly matches the routing key of the message.
         */
        channelPublish.exchangeDeclare(EXCHANGE_NAME, "direct");
        log.debug("Publish channel created. Exchange: " + EXCHANGE_NAME + " type: direct");

        //RECEIVER PART
        channelConsume = connection.createChannel();
        channelConsume.exchangeDeclare(EXCHANGE_NAME, "direct");
        log.debug("Consuming channel created. Exchange: " + EXCHANGE_NAME + " type: direct");

        //String queueName = channelConsume.queueDeclare().getQueue();
        /**
         * queueDeclare(java.lang.String queue, boolean durable, 
         * boolean exclusive, boolean autoDelete, 
         * java.util.Map<java.lang.String,java.lang.Object> arguments) 
         */
        String queueName;
        switch (componentType) {
        case "SRC":
            queueName = channelConsume.queueDeclare("Q2", false, false, false, null).getQueue();
            break;
        case "TWC":
            queueName = channelConsume.queueDeclare("Q3", false, false, false, null).getQueue();
            break;
        default:
            queueName = channelConsume.queueDeclare().getQueue();
            break;
        }

        /**
         * routing key bindings: relationship between an exchange and a queue.
         * Binds the queue, just created, with an exchange and with a routing key.
         */
        channelConsume.queueBind(queueName, EXCHANGE_NAME, LISTEN_RK);
        log.debug("Binding the consuming channel. ROUTING KEY: " + LISTEN_RK + " QUEUE NAME: " + queueName);

        /**
         * Telling the server to deliver us the messages from the queue. 
         * Since it will push us messages asynchronously, we provide a callback 
         * in the form of an object (QueueingConsumer) that will buffer the messages 
         * until we're ready to use them.
         */
        consumer = new QueueingConsumer(channelConsume);
        /**
         * basicConsume(java.lang.String queue, boolean autoAck, Consumer callback)
         * Starts a non-nolocal, non-exclusive consumer, 
         * with a server-generated consumerTag.
         */
        channelConsume.basicConsume(queueName, true, consumer);
        log.debug("Consumer started on queue: " + queueName);
    } catch (IOException e) {
        log.error(e.toString());
    }
}

From source file:it.polimi.hegira.queue.TaskQueue.java

License:Apache License

/**
 * Creates a task queue between the SRC and the TWC.
 * @param mode The component calling it, i.e. SRC or TWC
 * @param threads The number of threads that will consume from the queue (only for the TWC).
 * @param queueAddress The address where the RabbitMQ broker is deployed. Default: localhost
 * @throws QueueException If a connection cannot be established.
 *///from ww  w  . j  a  v a  2 s . c o m
public TaskQueue(String mode, int threads, String queueAddress) throws QueueException {
    if (mode == null)
        return;

    factory = new ConnectionFactory();
    if (queueAddress == null || queueAddress.isEmpty()) {
        factory.setHost("localhost");
    } else {
        factory.setHost(queueAddress);
    }

    try {
        connection = factory.newConnection();
        channel = connection.createChannel();
        /**
         * Declaring a durable queue
         * queueDeclare(java.lang.String queue, boolean durable, 
         * boolean exclusive, boolean autoDelete, 
         * java.util.Map<java.lang.String,java.lang.Object> arguments) 
         */
        channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);

        //queue settings differentiation
        switch (mode) {
        case Constants.PRODUCER:
            consumer = null;
            break;
        case Constants.CONSUMER:
            if (threads > 10 && threads <= 60) {
                this.THREADS_NO = threads;
            } else if (threads > 60) {
                this.THREADS_NO = MAX_THREADS_NO;
                log.info(DefaultErrors.getThreadsInformation(MAX_THREADS_NO));
            }
            if (factory.getHost().equals("localhost"))
                channel.basicQos(1);
            else
                channel.basicQos(20);
            consumer = new QueueingConsumer(channel);
            /**
             * basicConsume(java.lang.String queue, boolean autoAck, Consumer callback)
             * Starts a non-nolocal, non-exclusive consumer, 
             * with a server-generated consumerTag.
             */
            channel.basicConsume(TASK_QUEUE_NAME, false, consumer);
            break;
        }

    } catch (IOException e) {
        e.printStackTrace();
        throw new QueueException(e.getMessage());
    }
}

From source file:it.polimi.tower4clouds.observers.hdb.manager.Queue.java

License:Apache License

private void connect() throws IOException {
    if (connected)
        return;//from  w ww .j  a va 2  s .  com

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(Configuration.getHost(queueHost));

    int port = Configuration.getPort(queueHost);
    if (port > 0)
        factory.setPort(port);

    connection = factory.newConnection();
    channel = connection.createChannel();
    logger.debug("Connected to the queue {} on {}.", queueName, queueHost);

    connected = true;
}

From source file:it.txt.ens.authorisationService.amqp.AMQPConnectionHelper.java

License:Apache License

/**   
 * Create an AMQP connection and a channel relating to that connection.
 * //from  ww w. ja va  2  s. c o  m
*/
public Connection connection(String user, String password, String vHost, String Host, Integer port)
        throws IOException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(user);
    factory.setPassword(password);
    factory.setVirtualHost(vHost);
    factory.setHost(Host);
    factory.setPort(port);
    Connection conn = factory.newConnection();
    final Channel c = conn.createChannel();

    channel = c;

    return conn;
}

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  ww.j  a v a 2s  . c  o  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.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() });
    }/*  w  w  w  . j a  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;
    }
}