com.codio.collab.core.queue.QueueFactory.java Source code

Java tutorial

Introduction

Here is the source code for com.codio.collab.core.queue.QueueFactory.java

Source

/**
 * Copyright Suchkov Dmitrii
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.codio.collab.core.queue;

import com.codio.collab.core.interfaces.BackendProcessor;
import com.codio.collab.core.interfaces.FrontendProcessor;
import com.codio.collab.core.queue.config.CommonRmqConfig;
import com.codio.collab.core.queue.config.ConnectionConfig;
import com.codio.collab.core.utils.Utils;
import com.rabbitmq.client.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class QueueFactory {

    private static final Logger LOG = LoggerFactory.getLogger(QueueFactory.class);

    private ConnectionConfig connectionConfig;
    private CommonRmqConfig documentRequest;
    private CommonRmqConfig documentResponse;

    private Connection connection;
    private Channel documentRequestChannel;
    private Channel documentResponseChannel;
    private AMQP.BasicProperties publishProperties;

    private boolean isRequestChannelDeclared = false;
    private boolean isResponseChannelDeclared = false;

    public QueueFactory() {
        LOG.debug("init queue factory");

        AMQP.BasicProperties.Builder propsBuilder = new AMQP.BasicProperties.Builder();
        propsBuilder.contentType("application/json");
        publishProperties = propsBuilder.build();
    }

    private void openConnection() {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setVirtualHost(getConnectionConfig().getVhost());
        factory.setUsername(getConnectionConfig().getUser());
        factory.setPassword(getConnectionConfig().getPassword());
        factory.setPort(getConnectionConfig().getPort());
        factory.setHost(getConnectionConfig().getHost());
        factory.setAutomaticRecoveryEnabled(true);
        try {
            connection = factory.newConnection();
        } catch (IOException e) {
            LOG.error("Can not open rmq connection {}", e.getMessage());
        }
    }

    private void checkConnection() {
        if (connection == null || !connection.isOpen()) {
            openConnection();
        }
    }

    private void checkResponseChannel() {
        checkConnection();
        if (documentResponseChannel == null || !documentResponseChannel.isOpen()) {
            try {
                documentResponseChannel = connection.createChannel();
            } catch (IOException e) {
                LOG.error("Can not create rmq response channel {}", e);
            }
        }
    }

    private void checkRequestChannel() {
        checkConnection();
        if (documentRequestChannel == null || !documentRequestChannel.isOpen()) {
            try {
                documentRequestChannel = connection.createChannel();
            } catch (IOException e) {
                LOG.error("Can not create rmq response channel {}", e);
            }
        }
    }

    private String getResponseQueueName() {
        return getDocumentResponse().getQueue() + "-" + Utils.getHost();
    }

    private void declareResponseChannel() {
        if (isResponseChannelDeclared) {
            return;
        }
        isResponseChannelDeclared = true;
        checkResponseChannel();
        try {
            final String queueName = getResponseQueueName();
            documentResponseChannel.exchangeDeclare(getDocumentResponse().getExchange(),
                    getDocumentResponse().getType(), getDocumentResponse().getDurable(),
                    getDocumentResponse().getAutoDelete(), null);
            documentResponseChannel.queueDeclare(queueName, getDocumentRequest().getDurable(), false,
                    getDocumentRequest().getAutoDelete(), null);
            documentResponseChannel.queueBind(queueName, getDocumentResponse().getExchange(), "");
        } catch (IOException e) {
            LOG.error("Can not declare response channel {}", e);
        }
    }

    private void declareRequestChannel() {
        if (isRequestChannelDeclared) {
            return;
        }
        isRequestChannelDeclared = true;
        checkRequestChannel();
        try {
            final String queueName = getRequestQueueName();
            documentRequestChannel.exchangeDeclare(getDocumentRequest().getExchange(),
                    getDocumentRequest().getType(), getDocumentRequest().getDurable(),
                    getDocumentRequest().getAutoDelete(), null);
            documentRequestChannel.queueDeclare(queueName, getDocumentRequest().getDurable(), false,
                    getDocumentRequest().getAutoDelete(), null);
            documentRequestChannel.queueBind(queueName, getDocumentRequest().getExchange(), "");
        } catch (IOException e) {
            LOG.error("Can not create rmq channel {}", e.getMessage());
        }
    }

    private String getRequestQueueName() {
        return getDocumentRequest().getQueue() + "-" + Utils.getHost();
    }

    public void sendDocumentRequestMessage(final String message) {
        declareRequestChannel();
        try {
            documentRequestChannel.basicPublish(getDocumentRequest().getExchange(), "", publishProperties,
                    message.getBytes());
        } catch (IOException e) {
            LOG.error("Can not send message to request exchange {}", e);
        }
    }

    public void sendDocumentResponseMessage(final String message) {
        declareRequestChannel();
        try {
            documentResponseChannel.basicPublish(getDocumentResponse().getExchange(), "", publishProperties,
                    message.getBytes());
        } catch (IOException e) {
            LOG.error("Can not send message to response exchange {}", e);
        }
    }

    public void startDocumentResponsePerformer(final FrontendProcessor processor) {
        declareResponseChannel();
        for (int i = 0; i < getDocumentResponse().getPrefetchCount(); i++) {
            DocumentResponsePerformer performer = new DocumentResponsePerformer(connection, getResponseQueueName(),
                    processor);
            Thread workingThread = new Thread(performer);
            workingThread.start();
        }
    }

    public void startDocumentRequestPerformer(final BackendProcessor processor) {
        declareRequestChannel();
        for (int i = 0; i < getDocumentRequest().getPrefetchCount(); i++) {
            DocumentRequestPerformer performer = new DocumentRequestPerformer(connection, getRequestQueueName(),
                    processor);
            Thread workingThread = new Thread(performer);
            workingThread.start();
        }
    }

    public ConnectionConfig getConnectionConfig() {
        return connectionConfig;
    }

    public void setConnectionConfig(ConnectionConfig connectionConfig) {
        this.connectionConfig = connectionConfig;
    }

    public CommonRmqConfig getDocumentRequest() {
        return documentRequest;
    }

    public void setDocumentRequest(CommonRmqConfig documentRequest) {
        this.documentRequest = documentRequest;
    }

    public CommonRmqConfig getDocumentResponse() {
        return documentResponse;
    }

    public void setDocumentResponse(CommonRmqConfig documentResponse) {
        this.documentResponse = documentResponse;
    }

}