pt.souplesse.spark.Server.java Source code

Java tutorial

Introduction

Here is the source code for pt.souplesse.spark.Server.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 pt.souplesse.spark;

import com.google.common.collect.Lists;
import com.google.gson.*;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import static org.apache.http.impl.client.HttpClientBuilder.create;
import org.apache.http.util.EntityUtils;
import org.jinq.jpa.JinqJPAStreamProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static spark.Spark.*;

/**
 *
 * @author brsantos
 */
public class Server {

    private static final Gson gson = new GsonBuilder().registerTypeAdapter(Date.class,
            (JsonSerializer<Date>) (src, typeOfSrc, context) -> new JsonPrimitive(src.getTime())).create();
    private static final Logger log = LoggerFactory.getLogger(Server.class);

    public static void main(String[] args) {
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("guestbook");
        EntityManager manager = factory.createEntityManager();
        JinqJPAStreamProvider streams = new JinqJPAStreamProvider(factory);
        get("/messages", (req, rsp) -> {
            rsp.type("application/json");
            return gson.toJson(streams.streamAll(manager, Message.class).collect(Collectors.toList()));
        });
        post("/messages", (req, rsp) -> {
            try {
                Message msg = gson.fromJson(req.body(), Message.class);
                if (StringUtils.isBlank(msg.getMessage()) || StringUtils.isBlank(msg.getName())) {
                    halt(400);
                }
                manager.getTransaction().begin();
                manager.persist(msg);
                manager.getTransaction().commit();
            } catch (JsonSyntaxException e) {
                halt(400);
            }
            rsp.type("application/json");
            return gson.toJson(streams.streamAll(manager, Message.class).collect(Collectors.toList()));
        });
        get("/comments", (req, rsp) -> {
            rsp.type("application/json");
            Map<String, List<Body>> body = new HashMap<>();
            try (CloseableHttpClient client = create().build()) {
                String url = String.format("https://api.github.com/repos/%s/events", req.queryMap("repo").value());
                log.info(url);
                body = client.execute(new HttpGet(url), r -> {
                    List<Map<String, Object>> list = gson.fromJson(EntityUtils.toString(r.getEntity()), List.class);
                    Map<String, List<Body>> result = new HashMap<>();
                    list.stream().filter(m -> m.getOrDefault("type", "").equals("IssueCommentEvent"))
                            .map(m -> new Body(((Map<String, String>) m.get("actor")).get("login"),
                                    ((Map<String, Map<String, String>>) m.get("payload")).get("comment")
                                            .get("body")))
                            .forEach(b -> result.compute(b.getLogin(), (k, v) -> v == null ? new ArrayList<>()
                                    : Lists.asList(b, v.toArray(new Body[v.size()]))));
                    return result;
                });
            } catch (IOException e) {
                log.error(null, e);
                halt(400, e.getMessage());
            }
            return gson.toJson(body);
        });
    }
}