org.palo.it.devoxx.raspberry.rest.Sender.java Source code

Java tutorial

Introduction

Here is the source code for org.palo.it.devoxx.raspberry.rest.Sender.java

Source

/*
 *   PALO IT source code:
 *   ======================
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements.  See the NOTICE file distributed with
 *   this work for additional information regarding copyright ownership.
 *   The ASF licenses this file to You 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.
 *
 *   Links:
 *   ======
 *   Git      : https://github.com/Palo-IT/Devoxx2014Raspberry
 */
package org.palo.it.devoxx.raspberry.rest;

import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import javax.inject.Named;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.palo.it.devoxx.raspberry.model.ForgeModel;
import org.palo.it.devoxx.raspberry.model.events.SensorDataUpdateEvent;
import org.palo.it.devoxx.raspberry.service.ServiceCount;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import flexjson.JSONSerializer;

/**
 * Sender
 * 
 * @author pguillerm
 * @since 17 avr. 2014
 */
@ApplicationScoped
@Named
public class Sender implements Serializable {

    // =========================================================================
    // ATTRIBUTES
    // =========================================================================
    /** The Constant serialVersionUID. */
    private static final long serialVersionUID = -1971830156624439079L;

    private static final Logger LOGGER = LoggerFactory.getLogger(Sender.class);

    @Inject
    private ServiceCount serviceCount;

    // =========================================================================
    // CONSTRUCTORS
    // =========================================================================

    // =========================================================================
    // METHODS
    // =========================================================================
    public void observeUpdate(@Observes final SensorDataUpdateEvent event) {
        try {
            sendToPaloItForge();
            sendToJMA();
        } catch (final IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    // =========================================================================
    // OVERRIDES
    // =========================================================================

    /**
     * Send to palo it devoxx fronted
     * 
     * @throws IOException Signals that an I/O exception has occurred.
     */
    private void sendToPaloItForge() throws IOException {
        final ForgeModel model = new ForgeModel(serviceCount.getHistory());
        final String json = new JSONSerializer().exclude("*.class").deepSerialize(model);

        final HttpPost httppost = new HttpPost(
                "http://forge.palo-it.com/services/devoxxstalker-j/sensor/conference");
        httppost.setEntity(new StringEntity(json));
        httppost.setHeader("Content-type", "application/json");

        final int resultCode = sendPost(httppost);
        LOGGER.info("send info to Palo IT : result code = {}", resultCode);
    }

    /**
     * Send to j'aime attendre web site.
     * 
     * @throws IOException Signals that an I/O exception has occurred.
     */
    private void sendToJMA() throws IOException {

        final int nbCurrentUser = serviceCount.getSensors().get(0).getNbCurrentUser();

        int level = 2;
        if (nbCurrentUser > 15 && nbCurrentUser <= 30) {
            level = 3;
        } else if (nbCurrentUser > 30 && nbCurrentUser <= 45) {
            level = 4;
        } else if (nbCurrentUser > 45) {
            level = 5;
        }

        final HttpPost httppost = new HttpPost(
                "https://api.turba-webservices.com/v2/services/52f3aaf1653638000f070000/contributions");

        final ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
        postParameters.add(new BasicNameValuePair("api_key", "g58e65n70d42bdf9fba2230b"));
        postParameters.add(new BasicNameValuePair("event", "wait"));
        postParameters.add(new BasicNameValuePair("level", String.valueOf(level)));
        httppost.setEntity(new UrlEncodedFormEntity(postParameters));

        final int resultCode = sendPost(httppost);
        LOGGER.info("send info to JMA : result code = {}", resultCode);
    }

    // =========================================================================
    // UTILS
    // =========================================================================

    private int sendPost(final HttpPost httppost) throws UnsupportedEncodingException, IOException {
        final CloseableHttpClient httpclient = HttpClients.createDefault();

        int resultCode = 500;

        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httppost);
            resultCode = response.getStatusLine().getStatusCode();
        } catch (final IOException e) {
            LOGGER.error(e.getMessage(), e);
        } finally {
            if (response != null) {
                response.close();
            }
        }
        httpclient.close();
        return resultCode;
    }
}