Example usage for com.google.gson JsonObject add

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

Introduction

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

Prototype

public void add(String property, JsonElement value) 

Source Link

Document

Adds a member, which is a name-value pair, to self.

Usage

From source file:serverSocket.java

License:Apache License

public JsonObject sortJson(JsonArray arr) {

    List<JsonObject> tmp = new ArrayList<JsonObject>();
    for (JsonElement obj : arr) {
        tmp.add(obj.getAsJsonObject());// ww  w . j  a v a2  s . c om
    }
    Collections.sort(tmp, new Comparator<JsonObject>() {
        @Override
        public int compare(JsonObject a, JsonObject b) {
            return (int) (a.get("epoch").getAsLong() - b.get("epoch").getAsLong());
        }
    });

    //classify by time slots
    long start = tmp.get(0).get("epoch").getAsLong();
    //15 mins
    long slot = 15L * 60L;

    start += slot;
    JsonArray collection = new JsonArray();
    JsonObject done = new JsonObject();
    for (JsonObject obj : tmp) {
        if (obj.get("epoch").getAsLong() > start) {
            done.add(String.valueOf(start), collection);
            start = obj.get("epoch").getAsLong();
            start += slot;
            collection = new JsonArray();
            collection.add(obj);
        } else {
            collection.add(obj);

        }

    }

    return done;
}

From source file:serverSocket.java

License:Apache License

@OnMessage
public void incoming(String message) throws Exception {
    //System.out.println(message);
    JsonObject element = jsonParser.parse(message).getAsJsonObject();
    //System.out.println(element);
    try {//ww  w  .  j  a  v  a2  s .c  om
        String act = element.get("action").toString();
        //critical: escape ", "a" -> a
        act = act.substring(1, act.length() - 1);

        switch (act) {
        case "ELAPSE":
            JsonObject obj = new JsonObject();
            obj.add("elapse", list);
            sendMsg(session, obj.toString());
            break;
        case "UpdateKeyWords":
            obj = new JsonObject();
            obj.add("update", element.get("data"));
            //System.out.println(obj.toString());
            broadcast(obj.toString());
            break;
        case "geo_search":
            //System.out.println(element.get("lat").toString()+element.get("lng").toString());

            sendMsg(session, geoQuery(element.get("lat").toString(), element.get("lng").toString()));

            break;

        case "key_search":

            //critical: escape string \" \"
            String keyw = element.get("keyword").toString();
            keyw = keyw.substring(1, keyw.length() - 1);

            //                ArrayList<String> kx = new ArrayList<String>();
            //                kx.add("key");
            //                kx.add("sentiment");
            //               list to json
            //                  query1.addProperty("fields", new Gson().toJson(kx));

            sendMsg(session, queryKeyHistroy(keyw));
            break;
        }

    } catch (NullPointerException e) {
        System.out.println(message);
        e.printStackTrace();

    }
    // Never trust the client

}

From source file:serverSocket.java

License:Apache License

public String geoQuery(String lat, String lng) {
    JsonObject query0 = new JsonObject();

    query0.addProperty("lat", lat);
    query0.addProperty("lon", lng);
    JsonObject query1 = new JsonObject();
    query1.add("location", query0);
    query1.addProperty("distance", "50km");
    JsonObject query2 = new JsonObject();
    query2.add("geo_distance", query1);

    JsonObject query5 = new JsonObject();

    query5.add("filter", query2);

    JsonObject query6 = new JsonObject();
    query6.add("filtered", query5);

    JsonObject query7 = new JsonObject();
    query7.add("query", query6);

    String response = HttpRequest.post(esURL).send(query7.toString()).body();
    JsonObject sr = jsonParser.parse(response).getAsJsonObject();
    JsonArray asr = sr.get("hits").getAsJsonObject().get("hits").getAsJsonArray();

    JsonObject rb = new JsonObject();
    rb.add("geo_res", asr);

    return rb.toString();

}

From source file:serverSocket.java

License:Apache License

public String queryKeyHistroy(String keyw) {

    JsonObject query1 = new JsonObject();

    JsonObject query0 = new JsonObject();
    query0.addProperty("key", keyw);
    //query0.addProperty("sentiment", 5);

    JsonObject query4 = new JsonObject();
    query4.add("term", query0);
    query1.add("query", query4);
    query1.addProperty("from", 0);
    query1.addProperty("size", 10000);

    String response1 = HttpRequest.post(esURL1).send(query1.toString()).body();
    JsonObject sr1 = jsonParser.parse(response1).getAsJsonObject();
    JsonArray asr1 = sr1.get("hits").getAsJsonObject().get("hits").getAsJsonArray();

    JsonObject line = new JsonObject();
    for (JsonElement x : asr1) {
        line.add(x.getAsJsonObject().get("_source").getAsJsonObject().get("tid").toString(),
                x.getAsJsonObject().get("_source"));
    }/*from w  w  w  .  jav  a 2  s. com*/

    JsonObject res = new JsonObject();
    res.add("update", line);

    return res.toString();

}

From source file:JestMain.java

public static String generateEsUpdateScriptFromMap(Map<String, String> updatesMap) {
    JsonObject jsonObj = new JsonObject();
    StringBuffer scriptBuffer = new StringBuffer();
    JsonObject jsonObject_1 = new JsonObject();
    for (Map.Entry<String, String> entrySet : updatesMap.entrySet()) {
        String key = entrySet.getKey();
        String value = entrySet.getValue();
        scriptBuffer.append("ctx._source.").append(key).append("=" + key + ";");
        jsonObject_1.addProperty(key, value);

    }/*from  w ww .  j  ava  2  s.  c  o m*/
    jsonObj.addProperty("script", scriptBuffer.toString());

    jsonObj.add("params", jsonObject_1);
    return new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create().toJson(jsonObj);

}

From source file:AlertGeneration.java

License:Open Source License

@SuppressWarnings("unchecked")
public static void main(String[] args) throws InterruptedException {
    Yaml yaml = new Yaml();
    InputStream ios = AlertGeneration.class.getClassLoader().getResourceAsStream("properties.yml");
    Map<String, Object> result = (Map<String, Object>) yaml.load(ios);

    String apiBaseURL = (String) result.get("api.base.url");
    String apiClientKey = (String) result.get("api.client.key");
    String apiClientSecret = (String) result.get("api.client.secret");
    String apiGrantType = (String) result.get("api.grant.type");

    long clientId = new Long((Integer) result.get("client.id")).longValue();

    JsonObject json = new JsonObject();
    json.addProperty("subject", "Test Alert Subject");
    json.addProperty("description", "Test alert description");
    json.addProperty("serviceName", "system.ping.rta");
    json.addProperty("app", "Vistara");

    JsonObject device = new JsonObject();
    device.addProperty("hostName", "meena");
    device.addProperty("resourceUUID", "e32f9e6a-8909-4181-8684-910e82bd6f33");
    json.add("device", device);

    RestAssured.useRelaxedHTTPSValidation();
    RestAssured.baseURI = apiBaseURL;/*from   w  w  w  .  j a v  a 2s .  com*/
    String accessToken = generateAccessToken(apiBaseURL, apiClientKey, apiClientSecret, apiGrantType);

    for (int i = 1; i <= 600; i++) {
        try {
            Calendar cal = Calendar.getInstance();
            int currentSecond = cal.get(Calendar.SECOND);

            if ((currentSecond / 5) % 2 == 0) {
                json.addProperty("currentState", "Ok");
            } else {
                json.addProperty("currentState", "Critical");
            }

            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            json.addProperty("alertTime", formatter.format(cal.getTime()));
            System.out.println("Input payload " + i + ":" + json.toString());

            Response response = RestAssured.given().auth().oauth2(accessToken).contentType(ContentType.JSON)
                    .body(json.toString()).post("/api/v2/tenants/client_" + clientId + "/alert");
            System.out.println("Response: " + response.getStatusCode() + ",Output: " + response.prettyPrint());
            Thread.sleep(5000);
        } catch (Exception e) {
            e.printStackTrace();
            accessToken = generateAccessToken(apiBaseURL, apiClientKey, apiClientSecret, apiGrantType);
        }
    }
}

From source file:RunnerRepository.java

License:Apache License

public static void generateJSon() {
    JsonObject root = new JsonObject();
    JsonObject array = new JsonObject();
    array.addProperty("Embedded", "embedded");
    array.addProperty("DEFAULT", "Embedded");
    JsonObject array2 = new JsonObject();
    array2.addProperty("NimbusLookAndFeel", "javax.swing.plaf.nimbus.NimbusLookAndFeel");
    array2.addProperty("MetalLookAndFeel", "javax.swing.plaf.metal.MetalLookAndFeel");
    array2.addProperty("MotifLookAndFeel", "com.sun.java.swing.plaf.motif.MotifLookAndFeel");
    array2.addProperty("WindowsLookAndFeel", "com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    array2.addProperty("JGoodiesWindowsLookAndFeel", "com.jgoodies.looks.windows.WindowsLookAndFeel");
    array2.addProperty("Plastic3DLookAndFeel", "com.jgoodies.looks.plastic.Plastic3DLookAndFeel");
    array2.addProperty("PlasticXPLookAndFeel", "com.jgoodies.looks.plastic.PlasticXPLookAndFeel");
    array2.addProperty("DEFAULT", "MetalLookAndFeel");
    root.add("plugins", new JsonArray());
    root.add("editors", array);
    root.add("looks", array2);
    root.add("layout", new JsonObject());
    try {//www.j a  v a  2s.  c  o m
        FileWriter writer = new FileWriter(TWISTERINI);
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        writer.write(gson.toJson(root));
        writer.close();
    } catch (Exception e) {
        System.out.println("Could not write default JSon to twister.conf");
        e.printStackTrace();
    }
    System.out.println("twister.conf successfully created");
}

From source file:RunnerRepository.java

License:Apache License

public static void saveMainLayout() {
    JsonObject lay = getLayouts();
    lay.add("mainsize", new JsonPrimitive(window.getSize().getWidth() + " " + window.getSize().getHeight()));
    lay.add("mainlocation", new JsonPrimitive(window.getLocation().getX() + " " + window.getLocation().getY()));
    lay.add("mainvsplitlocation", new JsonPrimitive(window.mainpanel.p1.splitPane.getDividerLocation()));
    lay.add("mainh1splitlocation", new JsonPrimitive(window.mainpanel.p1.splitPane3.getDividerLocation()));
    lay.add("mainh2splitlocation", new JsonPrimitive(window.mainpanel.p1.splitPane2.getDividerLocation()));
    writeJSon();/*from   w  ww .j  a v  a  2  s  .  co m*/
}

From source file:RunnerRepository.java

License:Apache License

public static void saveUTLayout(Dimension size, Point p, int divloc) {
    JsonObject lay = getLayouts();
    lay.add("UTsize", new JsonPrimitive(size.getWidth() + " " + size.getHeight()));
    lay.add("UTlocation", new JsonPrimitive(p.getX() + " " + p.getY()));
    lay.add("UTh1splitlocation", new JsonPrimitive(divloc));
    writeJSon();/*from  ww  w .  jav a2  s.com*/
}

From source file:HyperLogLog.java

public String ToJson() {
    Gson g = new Gson();
    JsonObject elm = new JsonObject();
    elm.addProperty("M", this.m);
    elm.addProperty("B", this.b);
    elm.addProperty("A", this.alpha);
    JsonArray registerArr = new JsonArray();
    for (int i = 0; i < registers.length; i++) {
        registerArr.add(new JsonPrimitive(registers[i]));
    }/*from  w  w w . j ava 2s  . com*/
    elm.add("R", registerArr);
    return g.toJson(elm);
}