pl.polsl.java.znaj.dawid.rabbit.RabbitInvoiceServer.java Source code

Java tutorial

Introduction

Here is the source code for pl.polsl.java.znaj.dawid.rabbit.RabbitInvoiceServer.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.polsl.java.znaj.dawid.rabbit;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.ConsumerCancelledException;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.ShutdownSignalException;
import java.io.IOException;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bson.types.ObjectId;
import pl.polsl.java.znaj.dawid.controler.db.DBConfiguration;
import pl.polsl.java.znaj.dawid.enums.EventType;
import pl.polsl.java.znaj.dawid.enums.InvoiceType;
import pl.polsl.java.znaj.dawid.model.dao.InvoiceDAO;
import pl.polsl.java.znaj.dawid.model.entity.Invoice;
import pl.polsl.java.znaj.dawid.model.service.InvoiceService;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.util.Map;

/**
 *
 * @author Dawid
 */
public class RabbitInvoiceServer implements Runnable {

    private final String queueName;
    private final ConnectionFactory factory;
    private final Connection connection;
    private final Channel channel;
    private final QueueingConsumer consumer;
    private static final int PORT = 9200;
    private final DBConfiguration dbConfiguration;
    private final InvoiceDAO invoiceDAO;

    public RabbitInvoiceServer(DBConfiguration dbConfiguration, HashMap<String, Object> applicationConfiguration)
            throws IOException {
        this.queueName = (String) applicationConfiguration.get("invoiceQueueName");

        this.dbConfiguration = dbConfiguration;
        invoiceDAO = new InvoiceDAO(Invoice.class, dbConfiguration.getDatastore());

        factory = new ConnectionFactory();
        factory.setHost((String) applicationConfiguration.get("rabbitHost"));
        factory.setVirtualHost((String) applicationConfiguration.get("rabbitVirtualHost"));
        factory.setPort(Integer.parseInt((String) applicationConfiguration.get("rabbitInvoiceServerPort")));
        System.out.println(factory.getPort());

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

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

        channel.basicQos(1);

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

    }

    public Object processInvoiceBasedOnEventType(Map<String, Object> invoiceModelProperties) throws ParseException {
        Object result = null;
        InvoiceService invoiceService = new InvoiceService();

        switch ((String) invoiceModelProperties.get("eventType")) {
        case "CREATE":
            result = invoiceService.add(invoiceModelProperties, invoiceDAO, InvoiceType.PURCHASE);
            break;
        case "EDIT":
            result = invoiceService.update(invoiceModelProperties, (Invoice) invoiceModelProperties.get("invoice"),
                    invoiceDAO);
            break;
        case "DELETE":
            result = invoiceService.delete((ObjectId) invoiceModelProperties.get("id"), invoiceDAO);
            break;
        case "FILTER":
            result = invoiceService.findByCriteria(invoiceModelProperties, invoiceDAO);
            break;
        default:
            result = invoiceService.generateFailedStatus("Unknown event type");
            break;
        }

        return result;

    }

    @Override
    public void run() {

        try {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            BasicProperties props = delivery.getProperties();
            BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId())
                    .build();

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

            Gson g = new Gson();
            Type type = new TypeToken<HashMap<String, Object>>() {
            }.getType();

            Map<String, Object> invoiceModelProperties = g.fromJson(message, type);
            Object result = processInvoiceBasedOnEventType(invoiceModelProperties);

            String response = result != null ? g.toJson(result) : "false";

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

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

            channel.close();

        } catch (InterruptedException | ShutdownSignalException | ConsumerCancelledException | IOException
                | ParseException ex) {
            Logger.getLogger(RabbitInvoiceServer.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

}