org.maximachess.jdrone.HipChatNotifier.java Source code

Java tutorial

Introduction

Here is the source code for org.maximachess.jdrone.HipChatNotifier.java

Source

/**
 * JDrone
 * Copyright (C) 2015-2016 Erik van het Hof and Hermen Reitsma
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, If not, see <http://www.gnu.org/licenses/>.
 */
package org.maximachess.jdrone;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.StringWriter;
import javax.mail.Authenticator;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.maximachess.chess.Game;
import org.maximachess.jdrone.io.Router;
import org.maximachess.jdrone.io.RouterListener;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HipChatNotifier extends Authenticator implements RouterListener {

    private static final Logger LOGGER = LogManager.getLogger();

    private final String id;

    private final Router router;

    private String roomUrl = null;

    private CloseableHttpClient httpclient;

    private final ObjectMapper mapper = new ObjectMapper();

    private final JsonFactory jsonFactory = new JsonFactory();

    public HipChatNotifier(Router router, String id) {
        this.router = router;
        this.id = id;
        this.router.addListener(this);

        /* initialize mail */
        Config cfg = router.getClient().getConfig();
        if (cfg.getProperty("hipchat.url") != null) {
            roomUrl = cfg.getProperty("hipchat.url");

            httpclient = HttpClients.createDefault();
        }
    }

    public void on(String type, String id, String data) {

    }

    public void on(String type, String id, String data, Object obj) {
        if ("ics".equals(type) && "gameend".equals(data)) {
            handleGameEnd((Game) obj);
        }
    }

    private void handleGameEnd(Game g) {
        if (g.getRated() == false) {
            return;
        }
        boolean notify = false;
        switch (g.getResult()) {
        case 1: //1-0
            if (g.playBlack()) { //engine lost
                notify = true;
            }
            break;
        case 2: //0-1
            if (g.playWhite()) { //engine lost
                notify = true;
            }
            break;
        case 3: // 1/2-1/2
            break;
        default: // *
            break;
        }
        //todo: titled players, win/draw against (much) higher rated opp,
        //loss/draw against (much) lower rated opponent.
        if (notify) {
            sendNotification(g);
        }
    }

    private void sendNotification(Game g) {
        sendNotification(g.toPGN());
    }

    public void sendNotification(String text) {

        /* no config? */
        if (roomUrl == null) {
            /* return silently hipchat is not configured */
            return;
        }

        /* generate message */
        StringWriter sw = new StringWriter();
        try (JsonGenerator generator = jsonFactory.createGenerator(sw)) {
            generator.writeStartObject();
            generator.writeStringField("color", "red");
            generator.writeStringField("message", text);
            generator.writeBooleanField("notify", false);
            generator.writeStringField("message_format", "text");
            generator.writeEndObject();
        } catch (IOException e) {
            sw.append(e.getMessage());
        }
        LOGGER.trace("HipChat API Message {}", sw.toString());

        try {
            HttpPost httppost = new HttpPost(roomUrl);
            httppost.setHeader("Content-Type", "application/json");
            httppost.setEntity(new StringEntity(sw.toString()));

            try (CloseableHttpResponse response = httpclient.execute(httppost)) {
                LOGGER.trace("Http POST reponse {}", response.getStatusLine());
            }
        } catch (IOException ex) {
            LOGGER.error(ex);
        }
    }
}