Example usage for com.rabbitmq.client Channel basicPublish

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

Introduction

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

Prototype

void basicPublish(String exchange, String routingKey, BasicProperties props, byte[] body) throws IOException;

Source Link

Document

Publish a message.

Usage

From source file:dreamteamjson.DreamTeamJSON.java

/**
 * @param args the command line arguments
 * @throws java.io.IOException/*  w ww .ja  v a2 s.c om*/
 */
public static void main(String[] args) throws IOException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("datdb.cphbusiness.dk");
    factory.setUsername("Dreamteam");
    factory.setPassword("bastian");
    Connection connection = factory.newConnection();
    Channel listeningChannel = connection.createChannel();
    Channel sendingChannel = connection.createChannel();

    listeningChannel.queueDeclare(LISTENING_QUEUE_NAME, false, false, false, null);
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    Consumer consumer = new DefaultConsumer(listeningChannel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            message = new String(body, "UTF-8");
            System.out.println(" [x] Received '" + message + "'");

            Message m = gson.fromJson(message, Message.class);
            System.out.println(m.toString());

            double interestRate = 14;

            if (m.creditScore > 600) {
                interestRate -= 4.5;
            } else if (m.creditScore < 601 && m.creditScore > 500) {
                interestRate -= 2.7;
            } else if (m.creditScore < 501 && m.creditScore > 400) {
                interestRate -= 0.9;
            }

            int durationCut = m.loanDuration / 360;

            interestRate -= (durationCut * 0.18);

            double amountCut = m.loanAmount / 100000;

            interestRate -= (amountCut * 0.18);

            // Insert bank logic

            String loanResponse = "{\"interestRate\":" + interestRate + ",\"ssn\":" + m.ssn + "}";

            sendingChannel.queueDeclare(SENDING_QUEUE_NAME, false, false, false, null);
            sendingChannel.basicPublish("", SENDING_QUEUE_NAME, null, loanResponse.getBytes());
        }
    };
    listeningChannel.basicConsume(LISTENING_QUEUE_NAME, true, consumer);

}

From source file:dummyloanbroker.DummyLoanBroker.java

public static void main(String[] args) throws IOException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("datdb.cphbusiness.dk");
    factory.setUsername("student");
    factory.setPassword("cph");
    com.rabbitmq.client.Connection connection = factory.newConnection();
    com.rabbitmq.client.Channel channel = connection.createChannel();
    String corrId = java.util.UUID.randomUUID().toString();

    LoanRequestDTO loanRequest = new LoanRequestDTO("123456-7890", 456289.0, 25, -1);

    Gson gson = new Gson();

    String message = gson.toJson(loanRequest);

    AMQP.BasicProperties props = new AMQP.BasicProperties.Builder().correlationId(corrId).build();
    channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);

    channel.basicPublish("", TASK_QUEUE_NAME, props, message.getBytes());

    channel.close();//  w  w  w .  j a va 2  s  . com
    connection.close();
}

From source file:edu.iit.rabbitmq.Send.java

/**
 *
 * @param message//  w  ww  . jav  a 2 s  . c o m
 * @throws Exception
 */
public void sendMessage(String message) throws Exception {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(RABBITMQ);
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    try {
        channel.queueDeclare(QUEUENAME, false, false, false, null);
    } catch (Exception e) {
        System.out.println("Queue already exists, moving on");
    }

    channel.basicPublish("", QUEUENAME, null, message.getBytes("UTF-8"));
    System.out.println(" [x] Sent '" + message + "'");

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

From source file:edu.jhu.pha.vospace.jobs.JobsProcessorQueuedImpl.java

License:Apache License

public void submitJob(final String login, final JobDescription job) {
    super.submitJob(login, job);
    if (job.getDirection() == DIRECTION.PUSHFROMVOSPACE || job.getDirection() == DIRECTION.PULLTOVOSPACE
            || job.getDirection() == DIRECTION.LOCAL) {
        QueueConnector.goAMQP("submitJob", new QueueConnector.AMQPWorker<Boolean>() {
            @Override/*from  w  ww .  j a  v a 2 s .  c  o m*/
            public Boolean go(com.rabbitmq.client.Connection conn, com.rabbitmq.client.Channel channel)
                    throws IOException {

                channel.exchangeDeclare(conf.getString("transfers.exchange.submited"), "topic", true);

                byte[] jobSer = (new ObjectMapper()).writeValueAsBytes(job);
                channel.basicPublish(conf.getString("transfers.exchange.submited"),
                        "direction." + job.getDirection(), null, jobSer);

                return true;
            }
        });
    }
}

From source file:edu.jhu.pha.vospace.node.ContainerNode.java

License:Apache License

@Override
public void copy(VospaceId newLocationId, boolean keepBytes) {
    if (!isStoredMetadata())
        throw new NotFoundException("NodeNotFound");

    if (getMetastore().isStored(newLocationId)) {
        throw new ForbiddenException("DestinationNodeExists");
    }/*from   w ww .  ja  va2 s.  c o  m*/

    if (newLocationId.getNodePath().isParent(this.getUri().getNodePath())) {
        throw new ForbiddenException("Forbidden to copy into itself");
    }

    Node newDataNode = NodeFactory.createNode(newLocationId, owner, this.getType());
    newDataNode.setNode(null);
    newDataNode.getStorage().updateNodeInfo(newLocationId.getNodePath(), newDataNode.getNodeInfo());
    newDataNode.getMetastore().storeInfo(newLocationId, newDataNode.getNodeInfo());
    newDataNode.getMetastore().updateUserProperties(newLocationId, getNodeMeta(PropertyType.property));

    NodesList childrenList = getDirectChildren(false, 0, -1);
    List<Node> children = childrenList.getNodesList();

    for (Node child : children) {
        Node childNode = NodeFactory.getNode(child.getUri(), owner);
        String relativePath = childNode.getUri().getNodePath()
                .getParentRelativePath(this.getUri().getNodePath());
        try {
            VospaceId newChildId = newLocationId.appendPath(new NodePath(relativePath));
            logger.debug("Copying child " + childNode.getUri() + " with relpath " + relativePath + " to "
                    + newChildId.toString());
            childNode.copy(newChildId, keepBytes);
        } catch (URISyntaxException e) {
            logger.error("Error copying child " + childNode.getUri().toString() + ": " + e.getMessage());
        }
    }

    if (!keepBytes) {
        getMetastore().remove(this.getUri());

        if (this.getUri().getNodePath().getNodeStoragePathArray().length == 1) { // moving first-level container to another one
            getStorage().remove(this.getUri().getNodePath(), false);
        }
    }

    QueueConnector.goAMQP("movedNode", new QueueConnector.AMQPWorker<Boolean>() {
        @Override
        public Boolean go(com.rabbitmq.client.Connection conn, com.rabbitmq.client.Channel channel)
                throws IOException {

            channel.exchangeDeclare(conf.getString("vospace.exchange.nodechanged"), "fanout", false);

            Map<String, Object> nodeData = new HashMap<String, Object>();
            nodeData.put("uri", getUri().toString());
            nodeData.put("owner", getOwner());
            nodeData.put("container", getUri().getNodePath().getParentPath().getNodeStoragePath());

            byte[] jobSer = (new ObjectMapper()).writeValueAsBytes(nodeData);
            channel.basicPublish(conf.getString("vospace.exchange.nodechanged"), "", null, jobSer);

            return true;
        }
    });
}

From source file:edu.jhu.pha.vospace.node.ContainerNode.java

License:Apache License

@Override
public void markRemoved(boolean isRemoved) {
    if (!isStoredMetadata())
        throw new NotFoundException("NodeNotFound");

    NodesList childrenList = getDirectChildren(false, 0, -1);
    List<Node> children = childrenList.getNodesList();
    for (Node child : children) {
        child.markRemoved(isRemoved);//from   www.  j a  v a  2  s  . c o m
    }

    getMetastore().markRemoved(getUri(), isRemoved);
    QueueConnector.goAMQP("mark removed Container", new QueueConnector.AMQPWorker<Boolean>() {
        @Override
        public Boolean go(com.rabbitmq.client.Connection conn, com.rabbitmq.client.Channel channel)
                throws IOException {

            channel.exchangeDeclare(conf.getString("vospace.exchange.nodechanged"), "fanout", false);

            Map<String, Object> nodeData = new HashMap<String, Object>();
            nodeData.put("uri", getUri().toString());
            nodeData.put("owner", getOwner());
            nodeData.put("container", getUri().getNodePath().getParentPath().getNodeStoragePath());

            byte[] jobSer = (new ObjectMapper()).writeValueAsBytes(nodeData);
            channel.basicPublish(conf.getString("vospace.exchange.nodechanged"), "", null, jobSer);

            return true;
        }
    });
}

From source file:edu.jhu.pha.vospace.node.DataNode.java

License:Apache License

/**
 * Set the node content// ww  w  .  j  a va 2 s.co m
 * @param data The new node content
 */
public void setData(InputStream data) {
    if (!getMetastore().isStored(getUri()))
        throw new NotFoundException("NodeNotFound");
    logger.debug("Updating node " + getUri().toString());

    // put the node data into storage
    getStorage().putBytes(getUri().getNodePath(), data);

    // update node size from storage to metadata
    getStorage().updateNodeInfo(getUri().getNodePath(), getNodeInfo());

    getNodeInfo().setRevision(getNodeInfo().getRevision() + 1);//increase revision version to store in DB

    getMetastore().storeInfo(getUri(), getNodeInfo());

    QueueConnector.goAMQP("setData", new QueueConnector.AMQPWorker<Boolean>() {
        @Override
        public Boolean go(com.rabbitmq.client.Connection conn, com.rabbitmq.client.Channel channel)
                throws IOException {

            channel.exchangeDeclare(conf.getString("vospace.exchange.nodechanged"), "fanout", false);
            channel.exchangeDeclare(conf.getString("process.exchange.nodeprocess"), "fanout", true);

            Map<String, Object> nodeData = new HashMap<String, Object>();
            nodeData.put("uri", getUri().toString());
            nodeData.put("owner", getOwner());
            nodeData.put("container", getUri().getNodePath().getParentPath().getNodeStoragePath());

            byte[] jobSer = (new ObjectMapper()).writeValueAsBytes(nodeData);
            channel.basicPublish(conf.getString("vospace.exchange.nodechanged"), "", null, jobSer);
            channel.basicPublish(conf.getString("process.exchange.nodeprocess"), "",
                    MessageProperties.PERSISTENT_TEXT_PLAIN, jobSer);

            return true;
        }
    });

}

From source file:edu.jhu.pha.vospace.node.DataNode.java

License:Apache License

public void setChunkedData(String uploadId) {
    if (!getMetastore().isStored(getUri()))
        throw new NotFoundException("NodeNotFound");
    logger.debug("Updating chunked node " + getUri().toString());

    VoSyncMetaStore vosyncMeta = new VoSyncMetaStore(this.owner);

    // put the node data into storage
    getStorage().putChunkedBytes(getUri().getNodePath(), uploadId);

    vosyncMeta.deleteNodeChunks(this.getUri());
    vosyncMeta.mapChunkedToNode(this.getUri(), uploadId);

    // update node size from storage to metadata
    getStorage().updateNodeInfo(getUri().getNodePath(), getNodeInfo());

    getNodeInfo().setRevision(getNodeInfo().getRevision() + 1);//increase revision version to store in DB

    getMetastore().storeInfo(getUri(), getNodeInfo());

    QueueConnector.goAMQP("setData", new QueueConnector.AMQPWorker<Boolean>() {
        @Override/*  ww w  .jav  a 2  s  .c  o m*/
        public Boolean go(com.rabbitmq.client.Connection conn, com.rabbitmq.client.Channel channel)
                throws IOException {

            channel.exchangeDeclare(conf.getString("vospace.exchange.nodechanged"), "fanout", false);
            channel.exchangeDeclare(conf.getString("process.exchange.nodeprocess"), "fanout", true);

            Map<String, Object> nodeData = new HashMap<String, Object>();
            nodeData.put("uri", getUri().toString());
            nodeData.put("owner", getOwner());
            nodeData.put("container", getUri().getNodePath().getParentPath().getNodeStoragePath());

            byte[] jobSer = (new ObjectMapper()).writeValueAsBytes(nodeData);
            channel.basicPublish(conf.getString("vospace.exchange.nodechanged"), "", null, jobSer);
            channel.basicPublish(conf.getString("process.exchange.nodeprocess"), "",
                    MessageProperties.PERSISTENT_TEXT_PLAIN, jobSer);

            return true;
        }
    });

}

From source file:edu.jhu.pha.vospace.node.Node.java

License:Apache License

public void copy(VospaceId newLocationId, final boolean keepBytes) {
    if (!isStoredMetadata())
        throw new NotFoundException("NodeNotFound");

    if (getMetastore().isStored(newLocationId))
        throw new ForbiddenException("DestinationNodeExists");

    getStorage().copyBytes(getUri().getNodePath(), newLocationId.getNodePath(), keepBytes);

    if (!keepBytes) {
        // update node's container size metadata
        try {/*from   w  w w. j  a v a 2  s . c o  m*/
            ContainerNode contNode = (ContainerNode) NodeFactory.getNode(
                    new VospaceId(new NodePath(getUri().getNodePath().getContainerName())), getOwner());
            getStorage().updateNodeInfo(contNode.getUri().getNodePath(), contNode.getNodeInfo());
            getMetastore().storeInfo(contNode.getUri(), contNode.getNodeInfo());
        } catch (URISyntaxException e) {
            logger.error("Updating root node size failed: " + e.getMessage());
        }
    }

    final Node newDataNode = NodeFactory.createNode(newLocationId, owner, this.getType());
    newDataNode.setNode(null);
    newDataNode.getStorage().updateNodeInfo(newLocationId.getNodePath(), newDataNode.getNodeInfo());
    newDataNode.getMetastore().storeInfo(newLocationId, newDataNode.getNodeInfo());
    newDataNode.getMetastore().updateUserProperties(newLocationId, getNodeMeta(PropertyType.property));

    // Update chunks table to point to the new node if the node is chunked
    // copy with keepBytes=true is prohibited for chunked files by swift storage
    if (null != this.getNodeInfo().getChunkedName()) {
        VoSyncMetaStore vosyncMeta = new VoSyncMetaStore(this.owner);
        vosyncMeta.mapChunkedToNode(newDataNode.getUri(), this.getNodeInfo().getChunkedName());
    }

    if (!keepBytes)
        newDataNode.getMetastore().remove(this.getUri());

    QueueConnector.goAMQP("copyNode", new QueueConnector.AMQPWorker<Boolean>() {
        @Override
        public Boolean go(com.rabbitmq.client.Connection conn, com.rabbitmq.client.Channel channel)
                throws IOException {

            channel.exchangeDeclare(conf.getString("vospace.exchange.nodechanged"), "fanout", false);
            channel.exchangeDeclare(conf.getString("process.exchange.nodeprocess"), "fanout", true);

            Map<String, Object> nodeData = new HashMap<String, Object>();
            nodeData.put("uri", newDataNode.getUri().toString());
            nodeData.put("owner", getOwner());
            nodeData.put("container", newDataNode.getUri().getNodePath().getParentPath().getNodeStoragePath());

            byte[] jobSer = (new ObjectMapper()).writeValueAsBytes(nodeData);
            channel.basicPublish(conf.getString("vospace.exchange.nodechanged"), "", null, jobSer);
            channel.basicPublish(conf.getString("process.exchange.nodeprocess"), "",
                    MessageProperties.PERSISTENT_TEXT_PLAIN, jobSer);

            if (!keepBytes) {
                Map<String, Object> oldNodeData = new HashMap<String, Object>();
                oldNodeData.put("uri", getUri().toString());
                oldNodeData.put("owner", getOwner());
                oldNodeData.put("container", getUri().getNodePath().getParentPath().getNodeStoragePath());

                byte[] oldNodejobSer = (new ObjectMapper()).writeValueAsBytes(oldNodeData);
                channel.basicPublish(conf.getString("vospace.exchange.nodechanged"), "", null, oldNodejobSer);
            }
            return true;
        }
    });
}

From source file:edu.jhu.pha.vospace.node.Node.java

License:Apache License

/**
 * Marks the node as removed in metadata database
 *//*from  w ww  . jav  a  2 s . c o  m*/
public void markRemoved(boolean isRemoved) {
    if (!isStoredMetadata())
        throw new NotFoundException("NodeNotFound");

    getMetastore().markRemoved(getUri(), isRemoved);

    QueueConnector.goAMQP("markRemovedNode", new QueueConnector.AMQPWorker<Boolean>() {
        @Override
        public Boolean go(com.rabbitmq.client.Connection conn, com.rabbitmq.client.Channel channel)
                throws IOException {

            channel.exchangeDeclare(conf.getString("vospace.exchange.nodechanged"), "fanout", false);

            Map<String, Object> nodeData = new HashMap<String, Object>();
            nodeData.put("uri", getUri().toString());
            nodeData.put("owner", getOwner());
            nodeData.put("container", getUri().getNodePath().getParentPath().getNodeStoragePath());

            byte[] jobSer = (new ObjectMapper()).writeValueAsBytes(nodeData);
            channel.basicPublish(conf.getString("vospace.exchange.nodechanged"), "", null, jobSer);

            return true;
        }
    });
}