Example usage for com.rabbitmq.client Connection createChannel

List of usage examples for com.rabbitmq.client Connection createChannel

Introduction

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

Prototype

Channel createChannel() throws IOException;

Source Link

Document

Create a new channel, using an internally allocated channel number.

Usage

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 {//w  w  w . j av  a2  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() });
    }/* w w  w.  j  av  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 www .ja va2 s  .  c o m
    String patternLayout = "%5p %d{yyyy-MM-dd HH:mm:ss,sss} %file %t %L: %m%n";

    try {
        // Initialise logger context and logger pattern encoder
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        PatternLayoutEncoder patternLayoutEncoder = new PatternLayoutEncoder();

        // Set logging pattern (UTF-8 log)
        // logging patterns defined at http://logback.qos.ch/manual/layouts.html
        patternLayoutEncoder.setPattern(patternLayout);
        patternLayoutEncoder.setContext(loggerContext);
        patternLayoutEncoder.setCharset(Charset.forName("UTF-8"));
        patternLayoutEncoder.start();

        // log to console
        ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<ILoggingEvent>();
        appender.setContext(loggerContext);
        appender.setEncoder(patternLayoutEncoder);
        appender.start();

        // Finally setup the logger itself
        logger = (Logger) LoggerFactory.getLogger(ExampleRabbitmqClient.class.getName());
        logger.addAppender(appender);
        logger.setLevel(Level.DEBUG);
        logger.setAdditive(false);
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }

    /*try {
    VisualIndexer.init("/home/kandreadou/webservice/learning_files/","127.0.0.1",LoggerFactory.getLogger(ExampleRabbitmqClient.class));
    VisualIndexer v = new VisualIndexer("simtest");
    v.index("http://resources0.news.com.au/images/2012/08/16/1226451/587056-120816-obama.jpg","obama1");
    } catch (Exception ex) {
    System.out.println(ex);
    }*/

    logger.info("rabitmq client started");

    // send a UTF-8 encoded JSON tweet to the RabbitMQ (for stormspout to pick up and send to bolt)
    try {
        // check args
        /*if ( args.length < 1 ) {
        logger.error( "Usage: example_rabbitmq_client <JSON_filename>" );
        System.exit( 1 );
        }
        logger.info( "JSON file = " + args[0] );*/
        String strJSONFilePath = "/home/kandreadou/mklab/example-tweet-utf8.json";

        // check if the path to JSON file exists
        File fileJSON = new File(strJSONFilePath);

        System.out.println(fileJSON.getAbsolutePath());

        if (fileJSON.exists() == false) {
            logger.info("JSON file does not exist : " + strJSONFilePath);
            logger.info("Usage: example_rabbitmq_client <JSON_filename>");
            System.exit(1);
        }

        // read UTF-8 JSON text from file
        logger.info("ExampleRabbitmqClient started");

        List<String> lines = Files.readAllLines(Paths.get(strJSONFilePath), Charset.forName("UTF-8"));
        String strJSON = "";
        for (String line : lines) {
            if (line.length() > 0) {
                strJSON = strJSON + "\n";
            }
            strJSON = strJSON + line;
        }
        logger.info("JSON test message = " + strJSON);

        // connect to rabbitmq broker
        // first of all create connection factory
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUri("amqp://guest:guest@localhost:5672/%2F");
        long timestampSinceEpoch = System.currentTimeMillis() / 1000;

        // initialise connection and define channel
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        // initialise amqp basic peoperties object
        BasicProperties.Builder basicProperties = new BasicProperties.Builder();
        basicProperties.build();
        basicProperties.timestamp(new Date(timestampSinceEpoch)).build();
        basicProperties.contentType("text/json").build();
        basicProperties.deliveryMode(1).build();

        // publish message
        /* Exchange name should be {assessment_id}+ "_exchange" */
        channel.basicPublish("indexing_exchange", "test-routing", basicProperties.build(),
                strJSON.getBytes("UTF-8"));

        // close connection and channel
        channel.close();
        connection.close();

        logger.info("ExampleRabbitmqClient finished");

    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage());
        System.exit(1);
    }
}

From source file:javarpc_server.JavaRPC_Server.java

/**
 * @param args the command line arguments
 * @throws java.io.IOException//www .  j  a  va2  s.c o  m
 * @throws java.lang.InterruptedException
 */
public static void main(String[] args) throws IOException, InterruptedException {
    // TODO code application logic here

    ConnectionFactory factory = new ConnectionFactory();
    System.out.println(factory.getUsername() + " " + factory.getPassword());
    factory.setHost("localhost");

    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);

    channel.basicQos(1);

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(RPC_QUEUE_NAME, false, consumer);

    System.out.println(" [x] Awaiting RPC requests");

    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();

        BasicProperties props = delivery.getProperties();
        BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId())
                .build();

        String message = new String(delivery.getBody());

        System.out.println(" [.] convert(" + message + ")");
        String response = "" + convert(message);

        channel.basicPublish("", props.getReplyTo(), replyProps, response.getBytes());

        channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
    }
}

From source file:jenkins.plugins.logstash.persistence.RabbitMqDao.java

License:Open Source License

@Override
public void push(String data) throws IOException {
    Connection connection = null;
    Channel channel = null;/*from  w w w  .jav  a 2s . c  o  m*/
    try {
        connection = pool.newConnection();
        channel = connection.createChannel();

        // Ensure the queue exists
        try {
            channel.queueDeclarePassive(key);
        } catch (IOException e) {
            // The queue does not exist and the channel has been closed
            finalizeChannel(channel);

            // Create the queue
            channel = connection.createChannel();
            channel.queueDeclare(key, true, false, false, null);
        }

        channel.basicPublish("", key, null, data.getBytes());
    } finally {
        finalizeChannel(channel);
        finalizeConnection(connection);
    }
}

From source file:joram.amqp.PersistenceSimpleTest.java

License:Open Source License

public void recover1() throws Exception {
    ConnectionFactory cnxFactory = new ConnectionFactory();
    Connection connection = cnxFactory.newConnection();

    Channel channel = connection.createChannel();
    DeclareOk declareOk = channel.queueDeclare("testqueue", true, false, false, null);

    channel.txSelect();/*from w  w w .j  a  v  a2 s . co m*/
    for (int i = 0; i < 5; i++) {
        channel.basicPublish("", declareOk.getQueue(), MessageProperties.PERSISTENT_BASIC,
                "this is a test message !!!".getBytes());
    }
    channel.txCommit();

    killAgentServer((short) 0);

    startAgentServer((short) 0);

    connection = cnxFactory.newConnection();
    channel = connection.createChannel();
    declareOk = channel.queueDeclarePassive("testqueue");

    for (int i = 0; i < 5; i++) {
        GetResponse msg = channel.basicGet("testqueue", true);
        assertNotNull(msg);
        assertEquals("this is a test message !!!", new String(msg.getBody()));
    }

    GetResponse msg = channel.basicGet("testqueue", true);
    assertNull(msg);

    channel.queueDelete(declareOk.getQueue());
}

From source file:joram.amqp.PersistenceSimpleTest.java

License:Open Source License

public void recover2() throws Exception {
    ConnectionFactory cnxFactory = new ConnectionFactory();
    Connection connection = cnxFactory.newConnection();

    Channel channel = connection.createChannel();
    DeclareOk declareOk = channel.queueDeclare("testqueue", true, false, false, null);

    channel.txSelect();/*  w ww .  j av a 2 s  .c  o m*/
    for (int i = 0; i < 5; i++) {
        channel.basicPublish("", declareOk.getQueue(), MessageProperties.PERSISTENT_BASIC,
                "this is a test message !!!".getBytes());
    }
    channel.txCommit();

    killAgentServer((short) 0);

    startAgentServer((short) 0);
    Thread.sleep(500);

    connection = cnxFactory.newConnection();
    channel = connection.createChannel();
    declareOk = channel.queueDeclarePassive("testqueue");

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(declareOk.getQueue(), true, consumer);

    for (int i = 0; i < 5; i++) {
        Delivery msg = consumer.nextDelivery(1000);
        assertNotNull(msg);
        assertEquals("this is a test message !!!", new String(msg.getBody()));
    }

    Delivery msg = consumer.nextDelivery(1000);
    assertNull(msg);

    channel.queueDelete(declareOk.getQueue());

}

From source file:joram.amqp.QueueTest.java

License:Open Source License

public void queueDeclareName() throws Exception {
    ConnectionFactory cnxFactory = new ConnectionFactory();
    Connection connection = cnxFactory.newConnection();

    Channel channel = connection.createChannel();
    DeclareOk declareOk = channel.queueDeclare("testqueue", true, false, false, null);

    assertEquals("testqueue", declareOk.getQueue());
}

From source file:joram.bridgeamqp.AMQPSender.java

License:Open Source License

public void run() {
    ConnectionFactory cnxFactory = null;
    Connection connection = null;
    Channel channel = null;//from w ww.  j a v a 2  s.com
    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);/*  w w  w  .j a v  a2  s .com*/
    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();

}