Example usage for com.google.gson JsonObject JsonObject

List of usage examples for com.google.gson JsonObject JsonObject

Introduction

In this page you can find the example usage for com.google.gson JsonObject JsonObject.

Prototype

JsonObject

Source Link

Usage

From source file:be.iminds.iot.dianne.jsonrpc.DianneSSEServlet.java

License:Open Source License

@Override
public void handleEvent(Event event) {
    // construct server sent event
    JsonObject data = new JsonObject();

    if (event.getTopic().contains("progress")) {
        // progress
        data.add("type", new JsonPrimitive("progress"));
        data.add("jobId", new JsonPrimitive(event.getProperty("jobId").toString()));

        if (event.containsProperty("iteration")) {
            data.add("iteration", new JsonPrimitive((Long) event.getProperty("iteration")));
        }/*from w  w w  . j  av a2  s . co m*/

        if (event.containsProperty("minibatchLoss")) {
            data.add("minibatchLoss", new JsonPrimitive((Float) event.getProperty("minibatchLoss")));
        }

        if (event.containsProperty("validationLoss")) {
            data.add("validationLoss", new JsonPrimitive((Float) event.getProperty("validationLoss")));
        }

        if (event.containsProperty("q")) {
            data.add("q", new JsonPrimitive((Float) event.getProperty("q")));
        }

        if (event.containsProperty("reward")) {
            data.add("reward", new JsonPrimitive((Float) event.getProperty("reward")));
        }

        if (event.containsProperty("sequence")) {
            data.add("sequence", new JsonPrimitive((Long) event.getProperty("sequence")));
        }
    } else {
        // notification
        if (event.containsProperty("jobId"))
            data.add("jobId", new JsonPrimitive(event.getProperty("jobId").toString()));
        data.add("type", new JsonPrimitive("notification"));
        data.add("message", new JsonPrimitive((String) event.getProperty("message")));
        data.add("level", new JsonPrimitive(event.getProperty("level").toString()));
        long timestamp = (Long) event.getProperty("timestamp");
        data.add("timestamp", new JsonPrimitive(timestamp));
    }

    StringBuilder builder = new StringBuilder();
    builder.append("data: ").append(data.toString()).append("\n\n");
    String sse = builder.toString();

    // send to all clients
    Iterator<Entry<String, AsyncContext>> it = clients.entrySet().iterator();
    while (it.hasNext()) {
        AsyncContext client = it.next().getValue();
        try {
            PrintWriter writer = client.getResponse().getWriter();
            writer.write(sse);
            writer.flush();
        } catch (Exception e) {
            it.remove();
        }
    }
}

From source file:be.iminds.iot.dianne.nn.util.DianneJSONConverter.java

License:Open Source License

public static JsonObject toJson(NeuralNetworkDTO dto) {
    JsonObject nn = new JsonObject();

    JsonObject modules = new JsonObject();
    for (ModuleDTO m : dto.modules.values()) {
        JsonObject module = toJson(m);/*from w w  w  .j a  v  a  2s.  co  m*/
        modules.add(m.id.toString(), module);
    }

    String name = dto.name == null ? "unnamed" : dto.name;
    nn.add("name", new JsonPrimitive(name));
    nn.add("modules", modules);
    return nn;
}

From source file:be.iminds.iot.dianne.nn.util.DianneJSONConverter.java

License:Open Source License

public static JsonObject toJson(ModuleDTO dto) {
    JsonObject module = new JsonObject();

    module.add("id", new JsonPrimitive(dto.id.toString()));
    module.add("type", new JsonPrimitive(dto.type));

    if (dto.next != null) {
        JsonArray next = new JsonArray();
        for (UUID n : dto.next) {
            next.add(new JsonPrimitive(n.toString()));
        }/*www .j a v a  2s .  c o m*/
        module.add("next", next);
    }

    if (dto.prev != null) {
        JsonArray prev = new JsonArray();
        for (UUID p : dto.prev) {
            prev.add(new JsonPrimitive(p.toString()));
        }
        module.add("prev", prev);
    }

    if (dto.properties != null) {
        for (String k : dto.properties.keySet()) {
            module.add(k, new JsonPrimitive(dto.properties.get(k)));
        }
    }

    return module;
}

From source file:be.iminds.iot.dianne.nn.util.DianneJSONRPCRequestFactory.java

License:Open Source License

public static JsonObject createLearnRequest(int id, NeuralNetworkDTO nn, String dataset,
        Map<String, String> properties) {
    JsonObject request = new JsonObject();
    request.add("jsonrpc", new JsonPrimitive("2.0"));
    request.add("method", new JsonPrimitive("learn"));
    request.add("id", new JsonPrimitive(id));

    JsonArray params = new JsonArray();
    params.add(DianneJSONConverter.toJson(nn));
    params.add(new JsonPrimitive(dataset));
    params.add(createJsonFromMap(properties));
    request.add("params", params);

    return request;
}

From source file:be.iminds.iot.dianne.nn.util.DianneJSONRPCRequestFactory.java

License:Open Source License

public static JsonObject createEvalRequest(int id, String nnName, String dataset,
        Map<String, String> properties) {
    JsonObject request = new JsonObject();
    request.add("jsonrpc", new JsonPrimitive("2.0"));
    request.add("method", new JsonPrimitive("eval"));
    request.add("id", new JsonPrimitive(id));

    JsonArray params = new JsonArray();
    params.add(new JsonPrimitive(nnName));
    params.add(new JsonPrimitive(dataset));
    params.add(createJsonFromMap(properties));
    request.add("params", params);

    return request;

}

From source file:be.iminds.iot.dianne.nn.util.DianneJSONRPCRequestFactory.java

License:Open Source License

public static JsonObject createDeployRequest(int id, String nnName) {
    JsonObject request = new JsonObject();
    request.add("jsonrpc", new JsonPrimitive("2.0"));
    request.add("method", new JsonPrimitive("deploy"));
    request.add("id", new JsonPrimitive(id));

    JsonArray params = new JsonArray();
    params.add(new JsonPrimitive(nnName));
    request.add("params", params);

    return request;
}

From source file:be.iminds.iot.dianne.nn.util.DianneJSONRPCRequestFactory.java

License:Open Source License

public static JsonObject createUndeployRequest(int id, String nnId) {
    JsonObject request = new JsonObject();
    request.add("jsonrpc", new JsonPrimitive("2.0"));
    request.add("method", new JsonPrimitive("undeploy"));
    request.add("id", new JsonPrimitive(id));

    JsonArray params = new JsonArray();
    params.add(new JsonPrimitive(nnId));
    request.add("params", params);

    return request;
}

From source file:be.iminds.iot.dianne.nn.util.DianneJSONRPCRequestFactory.java

License:Open Source License

public static JsonObject createForwardRequest(int id, String nnId, int[] dims) {
    JsonObject request = new JsonObject();
    request.add("jsonrpc", new JsonPrimitive("2.0"));
    request.add("method", new JsonPrimitive("forward"));
    request.add("id", new JsonPrimitive(id));

    JsonArray params = new JsonArray();
    params.add(new JsonPrimitive(nnId));

    // create input
    JsonArray input = new JsonArray();
    List<JsonArray> toAdd = new ArrayList<>();
    toAdd.add(input);/*from ww  w .j  a v  a 2s  . c  om*/
    for (int i = 0; i < dims.length; i++) {
        List<JsonArray> nextAdd = new ArrayList<>();
        int d = dims[i];
        for (int k = 0; k < d; k++) {
            if (i == dims.length - 1) {
                // add floats
                for (JsonArray a : toAdd) {
                    a.add(new JsonPrimitive(0.0f));
                }
            } else {
                // add jsonarrays
                for (JsonArray a : toAdd) {
                    JsonArray newArray = new JsonArray();
                    a.add(newArray);
                    nextAdd.add(newArray);
                }
            }
        }
        toAdd = nextAdd;
    }
    params.add(input);

    request.add("params", params);

    return request;
}

From source file:be.iminds.iot.dianne.nn.util.DianneJSONRPCRequestFactory.java

License:Open Source License

private static JsonObject createJsonFromMap(Map<String, String> map) {
    JsonObject json = new JsonObject();
    for (Entry<String, String> e : map.entrySet()) {
        json.add(e.getKey(), new JsonPrimitive(e.getValue()));
    }//  w  w  w .  j ava 2  s  . co m
    return json;
}

From source file:be.uantwerpen.dc.studyassistant.StudyAssistant.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//w w w.j a v a  2s. c o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    String urlPath = request.getServletPath();

    if (urlPath.equalsIgnoreCase("/resources")) {

        ArrayList<Environment> lcs = this.getEnvironmentResources();

        Integer min = Integer.MAX_VALUE;
        Integer max = Integer.MIN_VALUE;
        for (Environment e : lcs) {
            if (e.getArduinoloudness() != null && e.getArduinoloudness() < min) {
                min = e.getArduinoloudness();
            }
            if (e.getArduinoloudness() != null && e.getArduinoloudness() > max) {
                max = e.getArduinoloudness();
            }
        }

        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet StudyAssistant</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet StudyAssistant at " + request.getContextPath() + "</h1>");
            for (Environment e : lcs) {
                out.println(e.toString());
            }

            out.println("Noise MAX: " + max);
            out.println("Noise MIN: " + min);

            out.println("</body>");
            out.println("</html>");
        }
    } else if (urlPath.equalsIgnoreCase("/resources/gauge")) {
        Environment lastRecord = this.getLastEnvironmentRecord();

        StudyIndex inx = new StudyIndex(lastRecord);
        double index = inx.getStudyIndex();
        index *= 100;

        index = Math.round(index * 100.0) / 100.0;

        JsonObject obj = new JsonObject();

        // create an array called cols
        JsonArray cols = new JsonArray();
        JsonArray rows = new JsonArray();
        JsonArray messages = new JsonArray();

        JsonObject col = new JsonObject();
        col.addProperty("id", "Index");
        col.addProperty("label", "Index");
        col.addProperty("type", "string");
        cols.add(col);

        JsonObject col2 = new JsonObject();
        col2.addProperty("id", "Value");
        col2.addProperty("label", "Value");
        col2.addProperty("type", "number");
        cols.add(col2);

        obj.add("cols", cols);

        JsonObject c = new JsonObject();
        JsonArray row = new JsonArray();

        JsonObject v1 = new JsonObject();
        v1.addProperty("v", "Index");
        row.add(v1);

        JsonObject v2 = new JsonObject();
        v2.addProperty("v", index);
        row.add(v2);

        c.add("c", row);

        rows.add(c);

        obj.add("rows", rows);

        String msg = "";
        if ((inx.alcoholIndex < 0.90) || (inx.methaneIndex < 0.90)) {
            msg += "Room needs better air circulation.";
            JsonObject msg1 = new JsonObject();
            msg1.addProperty("text", msg);
            messages.add(msg1);
        }

        JsonObject msg2 = new JsonObject();
        msg = "";
        if (lastRecord.getArduinolight() < StudyIndex.lightOptimalValue) {
            msg += "Increase room luminance!";
        } else if (lastRecord.getArduinolight() > StudyIndex.lightOptimalValue) {
            msg += "Lower room luminance!";
        } else {
            msg += "Room luminance is optimal!";
        }
        msg2.addProperty("text", msg);
        messages.add(msg2);

        JsonObject msg3 = new JsonObject();
        msg = "";
        if (lastRecord.getDs18b20temp() < StudyIndex.temperatureOptimalValue) {
            msg += "Increase room temperature!";
        } else if (lastRecord.getDs18b20temp() > StudyIndex.temperatureOptimalValue) {
            msg += "Lower room temperature!";
        } else {
            msg += "Room temperature is optimal!";
        }
        msg3.addProperty("text", msg);
        messages.add(msg3);

        JsonObject msg4 = new JsonObject();
        msg = "";
        if (lastRecord.getArduinoloudness() > StudyIndex.loudnessOptimalValue) {
            msg += "Room is too noisy!";
            msg4.addProperty("text", msg);
            messages.add(msg4);
        }

        JsonObject msg5 = new JsonObject();
        msg = "";
        if (lastRecord.getDs18b20temp() < StudyIndex.temperatureOptimalValue) {
            msg += "Humidity is less than optimal.";
        } else if (lastRecord.getDs18b20temp() > StudyIndex.temperatureOptimalValue) {
            msg += "Humidity is above optimal.";
        } else {
            msg += "Humidity is optimal!";
        }
        msg5.addProperty("text", msg);
        messages.add(msg5);

        obj.add("messages", messages);

        Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls()
                .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();

        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");

        PrintWriter out = response.getWriter();

        out.print(gson.toJson(obj));
    } else if (urlPath.equalsIgnoreCase("/resources/humidity")) {
        JsonObject obj = this.getCoreChartsJson("Humidity");
        this.printJson(obj, response);
    } else if (urlPath.equalsIgnoreCase("/resources/temperature")) {
        JsonObject obj = this.getCoreChartsJson("Temperature");
        this.printJson(obj, response);
    } else if (urlPath.equalsIgnoreCase("/resources/loudness")) {
        JsonObject obj = this.getCoreChartsJson("Loudness");
        this.printJson(obj, response);
    } else if (urlPath.equalsIgnoreCase("/resources/light")) {
        JsonObject obj = this.getCoreChartsJson("Light");
        this.printJson(obj, response);
    } else if (urlPath.equalsIgnoreCase("/resources/bubbleindex")) {
        JsonObject obj = this.getCoreChartsJson("Environment Index Score");
        this.printJson(obj, response);
    } else if (urlPath.equalsIgnoreCase("/resources/minmax")) {
        JsonObject obj = this.findMinMax();
        this.printJson(obj, response);
    }
}