com.wss.log.LogController.java Source code

Java tutorial

Introduction

Here is the source code for com.wss.log.LogController.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 com.wss.log;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import javax.servlet.ServletRequest;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 *
 * @author apple
 */
public class LogController {
    private final Logger logger = Logger.getLogger(LogController.class.getName());
    private final String SUCCESS = "[]";

    private final ConnectionFactory factory;
    private final Connection connection;
    private final Channel channel;

    public LogController() throws IOException, TimeoutException {
        factory = new ConnectionFactory();
        factory.setUsername(Constant.RABBITMQ_USERNAME);
        factory.setPassword(Constant.RABBITMQ_PASSWORD);
        factory.setVirtualHost(Constant.RABBITMQ_VIRTUAL_HOST);
        factory.setRequestedChannelMax(Constant.NUM_BROKER);
        factory.setHost(Constant.RABBITMQ_HOST);
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(Constant.QUEUE_NAME, Constant.QUEUE_DURABLE, false, false, null);
    }

    @RequestMapping(method = RequestMethod.POST, value = "post_log") // headers = {"Content-type=application/json", "Accept:application/json"}
    public @ResponseBody String insertProduct(ServletRequest request) throws IOException {
        BufferedReader reader = request.getReader();
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
            sb.append("\n");
        }
        String log = sb.toString();

        try {
            sendMessage(log);
        } catch (IOException ex) {
            logger.debug(log, ex);
            return ex.getMessage();
        }
        return SUCCESS;
    }

    private void sendMessage(String message) throws IOException {
        channel.basicPublish("", Constant.QUEUE_NAME, null, message.getBytes());
    }

    private void destroy() throws IOException, TimeoutException {
        channel.close();
        connection.close();
    }
}