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:com.nesscomputing.amqp.AmqpUtils.java

License:Apache License

/**
 * Close a session./*from  w  w w . j a  va 2  s  .c o m*/
 *
 * @param session
 */
public static void closeQuietly(final Channel channel) {
    if (channel != null && channel.isOpen()) {
        try {
            channel.close();
        } catch (IOException ioe) {
            LOG.warnDebug(ioe, "While closing session");
        }
    }
}

From source file:com.netcore.hsmart.dlrreceiverserver.PublishDlr.java

@POST
@Path("post")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response processDlrRequestPOST(@DefaultValue(DEFAULT_GATEWAY_ID) @QueryParam("gid") String tempGatewayId,
        @Context HttpServletRequest requestContext, MultivaluedMap<String, String> queryParams)
        throws TimeoutException, IOException {

    Logger logger = LoggerFactory.getLogger(PublishDlr.class);

    logger.info("IP:" + requestContext.getRemoteAddr() + "|METHOD:" + requestContext.getMethod()
            + "|GATEWAY_ID:" + AppConstants.getGatewayIdByCode(tempGatewayId) + "|QUERY_STRING:"
            + queryParams.toString());//from w  ww .  j  a  v  a  2  s.co m

    if (tempGatewayId == null || DEFAULT_GATEWAY_ID.equals(tempGatewayId) || "".equals(tempGatewayId)) { // gateway param in GET is not present

        if (queryParams.containsKey("gid")) {
            tempGatewayId = queryParams.get("gid").get(0);
            logger.info("gid param in POST");
            queryParams.add("gid", tempGatewayId);
        } else {
            queryParams.add("gid", null);
            logger.info("gid paramter missing");
        }
    } else {
        logger.info("gid param in GET");
        queryParams.add("gid", tempGatewayId);
    }

    logger.info("GID: " + tempGatewayId);

    if (queryParams.get("gid") != null
            && Utilities.isValidGateway(AppConstants.getGatewayIdByCode(tempGatewayId))) {

        String gatewayId = AppConstants.getGatewayIdByCode(tempGatewayId);

        // adding gateway stats per hour wise
        AppConstants.getHazelcastClient().getAtomicLong(
                "PUBDLR_GATEWAY_" + gatewayId + "_" + new SimpleDateFormat("yyyy-MM-dd-HH").format(new Date()))
                .incrementAndGet();

        try {

            // adding DLR type too

            PAYLOAD.put("gateway_id", gatewayId);
            PAYLOAD.put("dlr_type", "DLR");

            queryParams.forEach((k, v) -> buildPayload(k, v.get(0)));

            logger.info("PAYLOAD_FOR_MQ:" + PAYLOAD);

            Channel channel = AppConstants.getRabbitMqConnection().createChannel();

            channel.exchangeDeclare(AppConstants.getDlrReceiverExchangeName(), "direct");
            channel.queueDeclare(AppConstants.getDlrReceiverQueuePrefix() + gatewayId, true, false, false,
                    null);
            channel.queueBind(AppConstants.getDlrReceiverQueuePrefix() + gatewayId,
                    AppConstants.getDlrReceiverExchangeName(), gatewayId);
            channel.basicPublish(AppConstants.getDlrReceiverExchangeName(), gatewayId, null,
                    Utilities.encrypt(PAYLOAD.toString()).getBytes());

            channel.close();

            logger.info("PUBLISH_STATUS:SUCCESS");

            return Response.status(200).entity(buildJsonResponse("SUCCESS", "NULL", "NULL").toString()).build();

        } catch (Exception e) {
            logger.error("ERROR:HSMART_PUBDLR_1600");
            logger.error("EXCEPTION:" + e.getMessage());
            logger.info("PUBLISH_STATUS:FAIL");
            return Response.status(AppConstants.getApplicationCodeHttpStatus("HSMART_PUBDLR_1600"))
                    .entity(buildJsonResponse("FAIL", "HSMART_PUBDLR_1600",
                            AppConstants.getApplicationCodeMessage("HSMART_PUBDLR_1600")).toString())
                    .build();

        }

    } else {
        logger.error("ERROR:HSMART_PUBDLR_1001");
        logger.error("ERROR_MSG:" + AppConstants.getApplicationCodeMessage("HSMART_PUBDLR_1001"));
        logger.info("PUBLISH_STATUS:FAIL");
        return Response.status(AppConstants.getApplicationCodeHttpStatus("HSMART_PUBDLR_1001"))
                .entity(buildJsonResponse("fail", "HSMART_PUBDLR_1001",
                        AppConstants.getApplicationCodeMessage("HSMART_PUBDLR_1001")).toString())
                .build();

    }

}

From source file:com.netcore.hsmart.dlrreceiverserver.PublishDlr.java

@GET
@Path("get")
public Response processDlrRequestGET(@DefaultValue(DEFAULT_GATEWAY_ID) @QueryParam("gid") String tempGatewayId,
        @Context HttpServletRequest requestContext) throws TimeoutException, IOException {

    Logger logger = LoggerFactory.getLogger(PublishDlr.class);

    Map<String, String[]> queryParams = requestContext.getParameterMap();

    logger.info("IP:" + requestContext.getRemoteAddr() + "|METHOD:" + requestContext.getMethod()
            + "|QUERY_STRING:" + requestContext.getQueryString());

    logger.info(AppConstants.getGatewayIdByCode(tempGatewayId));

    if (queryParams.get("gid") != null
            && Utilities.isValidGateway(AppConstants.getGatewayIdByCode(tempGatewayId))) {

        String gatewayId = AppConstants.getGatewayIdByCode(tempGatewayId);

        // adding gateway stats per hour wise
        AppConstants.getHazelcastClient().getAtomicLong(
                "PUBDLR_GATEWAY_" + gatewayId + "_" + new SimpleDateFormat("yyyy-MM-dd-HH").format(new Date()))
                .incrementAndGet();//  w w w.  ja  va2s.  c om

        try {

            // adding DLR type too
            // PAYLOAD = AppConstants.getPayloadGroupSeparator() +
            // "gateway_id" + AppConstants.getPayloadKVSeparator()
            // + gatewayId+AppConstants.getPayloadGroupSeparator() +
            // "dlr_type" + AppConstants.getPayloadKVSeparator()
            // + "DLR";
            PAYLOAD.put("gateway_id", gatewayId);
            PAYLOAD.put("dlr_type", "DLR");

            // queryParams.forEach((k, v) -> buildPayload(k, v));

            Iterator i = queryParams.keySet().iterator();

            while (i.hasNext()) {

                String key = (String) i.next();
                String value = ((String[]) queryParams.get(key))[0];
                buildPayload(key, value);

            }

            logger.info("PAYLOAD_FOR_MQ:" + PAYLOAD);

            Channel channel = AppConstants.getRabbitMqConnection().createChannel();

            channel.exchangeDeclare(AppConstants.getDlrReceiverExchangeName(), "direct");
            channel.queueDeclare(AppConstants.getDlrReceiverQueuePrefix() + gatewayId, true, false, false,
                    null);
            channel.queueBind(AppConstants.getDlrReceiverQueuePrefix() + gatewayId,
                    AppConstants.getDlrReceiverExchangeName(), gatewayId);
            channel.basicPublish(AppConstants.getDlrReceiverExchangeName(), gatewayId, null,
                    Utilities.encrypt(PAYLOAD.toString()).getBytes());

            channel.close();

            logger.info("PUBLISH_STATUS:SUCCESS");

            return Response.status(200).entity(buildJsonResponse("SUCCESS", "NULL", "NULL").toString()).build();

        } catch (Exception e) {
            logger.error("ERROR:HSMART_PUBDLR_1600");
            logger.error("EXCEPTION:" + e.getMessage());
            logger.info("PUBLISH_STATUS:FAIL");
            return Response.status(AppConstants.getApplicationCodeHttpStatus("HSMART_PUBDLR_1600"))
                    .entity(buildJsonResponse("FAIL", "HSMART_PUBDLR_1600",
                            AppConstants.getApplicationCodeMessage("HSMART_PUBDLR_1600")).toString())
                    .build();

        }

    } else {
        logger.error("ERROR:HSMART_PUBDLR_1001");
        logger.error("ERROR_MSG:" + AppConstants.getApplicationCodeMessage("HSMART_PUBDLR_1001"));
        logger.info("PUBLISH_STATUS:FAIL");
        return Response.status(AppConstants.getApplicationCodeHttpStatus("HSMART_PUBDLR_1001"))
                .entity(buildJsonResponse("fail", "HSMART_PUBDLR_1001",
                        AppConstants.getApplicationCodeMessage("HSMART_PUBDLR_1001")).toString())
                .build();

    }

}

From source file:com.netcore.hsmart.smsreceiverserver.PublishSms.java

@GET
public Response processSmsRequest(@DefaultValue(DEFAULT_MSIDIN) @QueryParam("mobile_number") String msisdn,
        @DefaultValue(DEFAULT_MSG_TYPE) @QueryParam("message_type") String msgType,
        @DefaultValue(DEFAULT_MESSAGE) @QueryParam("message") String message,
        @DefaultValue(DEFAULT_GATEWAY_ID) @QueryParam("gateway_id") String gatewayId,
        @DefaultValue(DEFAULT_SENDER_ID) @QueryParam("sender_id") String senderId,
        @DefaultValue(DEFAULT_PRIORITY) @QueryParam("priority") String priority,
        @Context HttpServletRequest requestContext) throws TimeoutException, IOException {

    Logger logger = LoggerFactory.getLogger(PublishSms.class);
    Long REF_ID = null;//from   ww  w.  j  av  a 2 s .  c  o m
    try {

        REF_ID = AppConstants.refIdCounter().getAndIncrement();

        //adding gateway stats per hour wise
        AppConstants.getHazelcastClient().getAtomicLong(
                "PUBSMS_GATEWAY_" + gatewayId + "_" + new SimpleDateFormat("yyyy-MM-dd-HH").format(new Date()))
                .incrementAndGet();

        //logger.info("TOTAL_HITS:"+AppConstants.getHazelcastClient().getAtomicLong("PUBSMS_GATEWAY_"+gatewayId+"_"+new SimpleDateFormat("yyyy-MM-dd-HH").format(new Date())).get());

    } catch (Exception e) {
        logger.error("REF_ID:" + REF_ID + "|HAZELCAST_ERROR:" + e.getMessage());
        logger.error(
                "REF_ID:" + REF_ID + "|ERROR:" + AppConstants.getApplicationCodeMessage("HSMART_PUBSMS_1001"));
        logger.info("REF_ID:" + REF_ID + "|PUBLISH_STATUS:"
                + AppConstants.getApplicationCodeMessage("HSMART_GEN_1001"));
        return Response.status(400).entity(
                "<?xml version='1.0'?><HTTP><response><status>fail</status><error><code>HSMART_PUBSMS_1001</code><desc>"
                        + AppConstants.getApplicationCodeMessage("HSMART_PUBSMS_1001")
                        + "</desc></error></response></HTTP>")
                .build();
    }

    logger.info("REF_ID:" + REF_ID + "|QUERY_STRING:" + requestContext.getQueryString());
    logger.info("REF_ID:" + REF_ID + "|IP:" + requestContext.getRemoteAddr());
    //logger.info("REF_ID:" + REF_ID + "|GAT:" + AppConstants.getGatewayCode(gatewayId));

    if ((msisdn == null ? (DEFAULT_MSIDIN != null) : !msisdn.equals(DEFAULT_MSIDIN) && !msisdn.isEmpty())
            && (msgType == null ? (DEFAULT_MSG_TYPE != null)
                    : !msgType.equals(DEFAULT_MSG_TYPE) && !msgType.isEmpty())
            && (message == null ? (DEFAULT_MESSAGE != null)
                    : !message.equals(DEFAULT_MESSAGE) && !message.isEmpty())
            && (gatewayId == null ? (DEFAULT_GATEWAY_ID != null)
                    : !gatewayId.equals(DEFAULT_GATEWAY_ID) && !gatewayId.isEmpty())
            && (senderId == null ? (DEFAULT_SENDER_ID != null)
                    : !senderId.equals(DEFAULT_SENDER_ID) && !senderId.isEmpty())
            && (priority == null ? (DEFAULT_PRIORITY != null)
                    : !priority.equals(DEFAULT_PRIORITY) && !priority.isEmpty())) {

        Boolean isValidGateway = Utilities.isValidGateway(gatewayId);

        if (isValidGateway) {

            try {
                final String payload = "ref_id" + AppConstants.getPayloadKVSeparator() + REF_ID
                        + AppConstants.getPayloadGroupSeparator() + "gateway_id"
                        + AppConstants.getPayloadKVSeparator() + gatewayId
                        + AppConstants.getPayloadGroupSeparator() + "message"
                        + AppConstants.getPayloadKVSeparator() + URLEncoder.encode(message, "UTF-8")
                        + AppConstants.getPayloadGroupSeparator() + "msisdn"
                        + AppConstants.getPayloadKVSeparator() + msisdn
                        + AppConstants.getPayloadGroupSeparator() + "sender_id"
                        + AppConstants.getPayloadKVSeparator() + senderId
                        + AppConstants.getPayloadGroupSeparator() + "message_type"
                        + AppConstants.getPayloadKVSeparator() + msgType;

                logger.info("REF_ID:" + REF_ID + "|PAYLOAD_FOR_MQ:" + payload);

                Channel channel = AppConstants.getRabbitMqConnection().createChannel();
                channel.exchangeDeclare(AppConstants.getSmsReceiverExchangeName(), "direct");
                channel.queueDeclare(AppConstants.getSmsReceiverQueuePrefix() + gatewayId, true, false, false,
                        null);
                channel.queueBind(AppConstants.getSmsReceiverQueuePrefix() + gatewayId,
                        AppConstants.getSmsReceiverExchangeName(), gatewayId);
                channel.basicPublish(AppConstants.getSmsReceiverExchangeName(), gatewayId, null,
                        payload.getBytes());

                channel.close();
                //AppConstants.getRabbitMqConnection().close();
                logger.info("REF_ID:" + REF_ID + "|PUBLISH_STATUS:"
                        + AppConstants.getApplicationCodeMessage("HSMART_GEN_1000"));

                return Response.status(200).entity("<?xml version='1.0'?><HTTP><response><requestid>" + REF_ID
                        + "</requestid></response></HTTP>").build();
            } catch (NumberFormatException | IOException | TimeoutException e) {
                logger.error("REF_ID:" + REF_ID + "|EXCEPTION:" + e.getMessage());
                logger.error("REF_ID:" + REF_ID + "|ERROR:"
                        + AppConstants.getApplicationCodeMessage("HSMART_PUBSMS_1001"));
                logger.info("REF_ID:" + REF_ID + "|PUBLISH_STATUS:"
                        + AppConstants.getApplicationCodeMessage("HSMART_GEN_1001"));
                return Response.status(400).entity(
                        "<?xml version='1.0'?><HTTP><response><status>fail</status><error><code>HSMART_PUBSMS_1001</code><desc>"
                                + AppConstants.getApplicationCodeMessage("HSMART_PUBSMS_1001")
                                + "</desc></error></response></HTTP>")
                        .build();
            }

        } else {
            logger.error("REF_ID:" + REF_ID + "|ERROR:"
                    + AppConstants.getApplicationCodeMessage("HSMART_PUBSMS_1002"));
            logger.info("REF_ID:" + REF_ID + "|PUBLISH_STATUS:"
                    + AppConstants.getApplicationCodeMessage("HSMART_GEN_1001"));
            return Response.status(400).entity(
                    "<?xml version='1.0'?><HTTP><response><status>fail</status><error><code>HSMART_PUBSMS_1002</code><desc>"
                            + AppConstants.getApplicationCodeMessage("HSMART_PUBSMS_1002")
                            + "</desc></error></response></HTTP>")
                    .build();
        }
    } else {
        logger.error(
                "REF_ID:" + REF_ID + "|ERROR:" + AppConstants.getApplicationCodeMessage("HSMART_PUBSMS_1003"));
        logger.info("REF_ID:" + REF_ID + "|PUBLISH_STATUS:"
                + AppConstants.getApplicationCodeMessage("HSMART_GEN_1001"));
        return Response.status(400).entity(
                "<?xml version='1.0'?><HTTP><response><status>fail</status><error><code>HSMART_PUBSMS_1003</code><desc>"
                        + AppConstants.getApplicationCodeMessage("HSMART_PUBSMS_1003")
                        + "</desc></error></response></HTTP>")
                .build();
    }
}

From source file:com.nxttxn.vramel.components.rabbitMQ.pool.PoolableChannelFactory.java

License:Apache License

@Override
public void destroyObject(Channel t) throws Exception {
    t.close();
}

From source file:com.pcs.test.amqp.Publisher.java

License:Open Source License

public static void main(String[] args) throws IOException, TimeoutException {
    System.out.println("starting");
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("pcss-hdop04");
    factory.setAutomaticRecoveryEnabled(true);
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    String message = "first message , hello world";
    channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
    System.out.println("message sent");

    channel.close();
    connection.close();// w ww  . ja v a2  s . co m
}

From source file:com.project.finalproject.Send.java

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, false, false, false, null);

    try {//from w  w w  .java2  s  .  c  o m
        InputStream is = new FileInputStream("hr.json");
        String jsontxt = IOUtils.toString(is);
        JSONObject jsonObject = new JSONObject(jsontxt);
        JSONArray stream = jsonObject.getJSONArray("stream");
        for (int i = 0; i < stream.length(); i++) {
            String message = stream.getJSONObject(i).getString("value");
            channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
            System.out.println(" [x] Sent '" + message + "'");
            TimeUnit.SECONDS.sleep(1);
        }
    } catch (FileNotFoundException fe) {
        fe.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

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

From source file:com.service.OperationFacadeREST.java

@POST
@Override//ww w .j ava2 s .c  o  m
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public void create(Operation entity) {
    if (!entity.getState().equals("waiting")) {
        super.create(entity);
        return;
    }
    if (entity.getOperationType())//venda
    {
        ArrayList<ClientStock> l = new ArrayList<>(getEntityManager()
                .find(Client.class, entity.getFkOwnerId().getClientId()).getClientStockCollection());
        Boolean fail = false;
        for (int i = 0; i < l.size(); i++) {
            if (l.get(i).getStock().equals(entity.getFkStockId())) {
                if (l.get(i).getQuantity() < entity.getQuantity())
                    return;
                l.get(i).setQuantity(l.get(i).getQuantity() - entity.getQuantity());
                getEntityManager().persist(l.get(i));
                entity.getFkOwnerId().setClientStockCollection(l);

                entity.setCreationDate(Date.from(Instant.now()));
                super.create(entity);
            }
        }
        if (fail)
            return;
    } else {
        entity.setCreationDate(Date.from(Instant.now()));
        if (entity.getFkStockId().getQuantity() > entity.getQuantity()) {

            System.out.println("yes");
            super.create(entity);
        } else {
            return;
        }
    }

    try {

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare("hello", false, false, false, null);
        System.out.println(super.findAll().get(super.findAll().size() - 1).getOperationId() + ","
                + entity.getFkOwnerId().getName() + "," + entity.getFkStockId().getName() + ","
                + entity.getQuantity());

        String message = super.findAll().get(super.findAll().size() - 1).getOperationId() + ","
                + entity.getFkOwnerId().getName() + "," + entity.getFkStockId().getName() + ","
                + entity.getQuantity();
        channel.basicPublish("", "hello", null, message.getBytes());
        System.out.println(" [x] Sent '" + message + "'");
        channel.close();
        connection.close();
    } catch (IOException ex) {
        Logger.getLogger(ClientFacadeREST.class.getName()).log(Level.SEVERE, null, ex);
    } catch (TimeoutException ex) {
        Logger.getLogger(ClientFacadeREST.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.sitewhere.protobuf.test.ActiveMQTests.java

License:Open Source License

@Test
public void doRabbitMQTest() throws Exception {
    String exchangeName = "sitewhere";
    String queueName = "SITEWHERE.IN";
    String routingKey = "sitewhere";

    ConnectionFactory factory = new ConnectionFactory();
    factory.setUri("amqp://localhost:5672/SITEWHERE.IN");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(exchangeName, "direct", true);
    channel.queueDeclare(queueName, true, false, false, null);
    channel.queueBind(queueName, exchangeName, routingKey);

    byte[] messageBodyBytes = generateEncodedMeasurementsMessage();
    channel.basicPublish(exchangeName, routingKey, null, messageBodyBytes);

    channel.close();
    connection.close();//www.  j  a  v  a 2  s  .  c o  m
}

From source file:com.sitewhere.sources.ActiveMQTests.java

License:Open Source License

@Test
public void doRabbitMQTest() throws Exception {
    String exchangeName = "sitewhere";
    String queueName = "sitewhere.input";
    String routingKey = "sitewhere";

    ConnectionFactory factory = new ConnectionFactory();
    factory.setUri("amqp://localhost:5672");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(exchangeName, "direct", true);
    channel.queueDeclare(queueName, true, false, false, null);
    channel.queueBind(queueName, exchangeName, routingKey);

    byte[] messageBodyBytes = EventsHelper.generateEncodedMeasurementsMessage(HARDWARE_ID);
    channel.basicPublish(exchangeName, routingKey, null, messageBodyBytes);

    channel.close();
    connection.close();//from   ww  w  .j a v  a2s. c om
}