Example usage for com.google.gson JsonObject toString

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

Introduction

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

Prototype

@Override
public String toString() 

Source Link

Document

Returns a String representation of this element.

Usage

From source file:serverSocket.java

License:Apache License

@OnOpen
public void start(Session session) {
    this.session = session;
    connections.add(this);
    try {//from   w  w  w.j  a va2s  .c  o m
        synchronized (this) {
            JsonObject ret = new JsonObject();
            ret.addProperty("access_key", uuid);
            this.session.getBasicRemote().sendText(ret.toString());
            connPool.put(uuid, session);
        }
    } catch (IOException e) {
        e.printStackTrace();

        try {
            this.session.close();
        } catch (IOException e1) {
            // Ignore
        }

    }

    jsonParser = new JsonParser();

    //tricky, put tweets_data in this path
    //System.out.println(this.getClass().getResource("").getPath());

    JsonArray rawlist = new JsonArray();
    try {
        BufferedReader br = new BufferedReader(
                new InputStreamReader(serverSocket.class.getResourceAsStream("/tweets_data.txt")));
        String line = br.readLine();
        rawlist = jsonParser.parse(line).getAsJsonArray();

        br.close();
        //System.out.println(list);

    } catch (IOException e) {
        System.out.println(this.getClass().getResource("").getPath());
        e.printStackTrace();
    }

    list = sortJson(rawlist);

}

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 {//from w ww .  j av  a2  s  .  co m
        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  ww . j a  v  a  2  s .  c  o m

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

    return res.toString();

}

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  ww.ja va 2s  .co m*/
    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:contactDAO.java

@GET
@Path("/add")
public String addContact(@QueryParam("myEmail") String myEmail, @QueryParam("fEmail") String fEmail) {

    JsonObject jsonResponse = new JsonObject();

    /////// 0. Extract My ID from DB
    int userID = getUserId(myEmail);

    if (userID == -1) {
        //// internal error in DB
        jsonResponse.addProperty("status", "failed");
        jsonResponse.addProperty("result", "Errors with our Servers, Try again later!");

    } else {//from  w w w. j a v  a 2 s  .  c  o m

        /////// 1. Check if user already exists
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        Query query = entityManager.createNamedQuery("User.findByEmail").setParameter("email", fEmail);
        List<User> users = query.getResultList();

        if (!users.isEmpty()) {
            /////// 2. if YES
            ////////////////////////// add to contacts and return POSITIVE response

            User friend = users.get(0);

            int friendId = friend.getId();
            Contact contact = new Contact(userID, friendId);

            entityManager.getTransaction().begin();
            entityManager.persist(contact);
            entityManager.getTransaction().commit();

            ///// prepare response as JSON
            jsonResponse.addProperty("status", "success");

            Gson gson = new Gson();
            jsonResponse.addProperty("result", gson.toJson(friend));

        } else {
            /////// 3. if NO
            /////////////////////// return user not found NEGATIVE response
            jsonResponse.addProperty("status", "failed");
            jsonResponse.addProperty("result", "Corresponding user is not fount, Check his email");

        }

    }

    return jsonResponse.toString();
}

From source file:EAIJSONConverter.java

License:Open Source License

public void doInvokeMethod(String methodName, SiebelPropertySet input, SiebelPropertySet output)
        throws SiebelBusinessServiceException {

    if (methodName.equals("PropSetToJSON")) {
        JsonObject myJSON = new JsonObject();
        myJSON = traversePS(input, myJSON);
        output.setValue(myJSON.toString());
    }/*  w ww  .  j  a va  2s  .c om*/

    if (methodName.equals("JSONToPropSet")) {
        JsonObject obj = new JsonObject();
        obj = new Gson().fromJson(input.getValue(), JsonObject.class);
        SiebelPropertySet op = new SiebelPropertySet();
        output.addChild(JsonObjectToPropertySet(obj, op));
    }

}

From source file:CustomAudienceExample.java

License:Open Source License

public static void main(String[] args) {
    try {//from   www .  j a v a  2s  .c  o m
        AdAccount account = new AdAccount(ACCOUNT_ID, context);

        CustomAudience audience = account.createCustomAudience().setName("Java SDK Test Custom Audience")
                .setDescription("Test Audience").setSubtype(EnumSubtype.VALUE_CUSTOM).execute();

        // Audience payload schema
        JsonArray schema = new JsonArray();
        schema.add(new JsonPrimitive("EMAIL_SHA256"));
        schema.add(new JsonPrimitive("PHONE_SHA256"));

        // Audience payload data
        JsonArray personA = new JsonArray();
        personA.add(new JsonPrimitive(sha256("aaa@example.com")));
        personA.add(new JsonPrimitive(sha256("1234567890")));
        JsonArray personB = new JsonArray();
        personB.add(new JsonPrimitive(sha256("bbb@example.com")));
        personB.add(new JsonPrimitive(sha256("1234567890")));
        JsonArray personC = new JsonArray();
        personC.add(new JsonPrimitive(sha256("ccc@example.com")));
        personC.add(new JsonPrimitive(sha256("1234567890")));

        JsonArray data = new JsonArray();
        data.add(personA);
        data.add(personB);
        data.add(personC);

        JsonObject payload = new JsonObject();
        payload.add("schema", schema);
        payload.add("data", data);

        audience.createUser().setPayload(payload.toString()).execute();

        System.out.println(audience.fetch());

        Targeting targeting = new Targeting().setFieldCustomAudiences("[{id:" + audience.getId() + "}]");

        Campaign campaign = account.createCampaign().setName("Java SDK Test Campaign")
                .setObjective(Campaign.EnumObjective.VALUE_LINK_CLICKS).setSpendCap(10000L)
                .setStatus(Campaign.EnumStatus.VALUE_PAUSED).execute();
        AdSet adset = account.createAdSet().setName("Java SDK Test AdSet").setCampaignId(campaign.getFieldId())
                .setStatus(AdSet.EnumStatus.VALUE_PAUSED)
                .setBillingEvent(AdSet.EnumBillingEvent.VALUE_IMPRESSIONS).setDailyBudget(1000L)
                .setBidAmount(100L).setOptimizationGoal(AdSet.EnumOptimizationGoal.VALUE_IMPRESSIONS)
                .setTargeting(targeting).setRedownload(true).requestAllFields().execute();
        System.out.println(adset);
        AdImage image = account.createAdImage().addUploadFile("file", imageFile).execute();
        AdCreative creative = account.createAdCreative().setTitle("Java SDK Test Creative")
                .setBody("Java SDK Test Creative").setImageHash(image.getFieldHash())
                .setLinkUrl("www.facebook.com").setObjectUrl("www.facebook.com").execute();
        Ad ad = account.createAd().setName("Java SDK Test ad").setAdsetId(Long.parseLong(adset.getId()))
                .setCreative(creative).setStatus("PAUSED").setBidAmount(100L).setRedownload(true).execute();
    } catch (APIException e) {
        e.printStackTrace();
    }
}

From source file:account.PurchsaeReturnRegisterDetailAccount.java

private void setAccountDetailMobile(String param_cd, String value) {
    try {/*ww  w.j  a  v a  2  s . c  o m*/
        JsonObject call = lb.getRetrofit().create(StartUpAPI.class)
                .getDataFromServer(param_cd, value.toUpperCase()).execute().body();

        if (call != null) {
            System.out.println(call.toString());
            AccountHead header = (AccountHead) new Gson().fromJson(call, AccountHead.class);
            if (header.getResult() == 1) {
                SelectAccount sa = new SelectAccount(null, true);
                sa.setLocationRelativeTo(null);
                sa.fillData((ArrayList) header.getAccountHeader());
                sa.setVisible(true);
                if (sa.getReturnStatus() == SelectAccount.RET_OK) {
                    int row = sa.row;
                    if (row != -1) {
                        ac_cd = header.getAccountHeader().get(row).getACCD();
                        jtxtAcAlias.setText(ac_cd);
                        jtxtAcName.setText(header.getAccountHeader().get(row).getFNAME());
                        jtxtFromDate.requestFocusInWindow();
                    }
                }
            } else {
                lb.showMessageDailog(header.getCause().toString());
            }
        }
    } catch (Exception ex) {
        lb.printToLogFile("Exception at setData at account master in sales invoice", ex);
    }

}

From source file:account.SalesRegisterDetailCardWise.java

private void setAccountDetailMobile(String param_cd, String value) {
    try {/*from   ww w.j av  a 2s .  c  o m*/
        JsonObject call = lb.getRetrofit().create(StartUpAPI.class)
                .getDataFromServer(param_cd, value.toUpperCase()).execute().body();

        if (call != null) {
            System.out.println(call.toString());
            AccountHead header = (AccountHead) new Gson().fromJson(call, AccountHead.class);
            if (header.getResult() == 1) {
                SelectAccount sa = new SelectAccount(null, true);
                sa.setLocationRelativeTo(null);
                sa.fillData((ArrayList) header.getAccountHeader());
                sa.setVisible(true);
                if (sa.getReturnStatus() == SelectAccount.RET_OK) {
                    int row = sa.row;
                    if (row != -1) {
                        ac_cd = header.getAccountHeader().get(row).getACCD();
                        jtxtAcAlias.setText(ac_cd);
                        jtxtAcName.setText(header.getAccountHeader().get(row).getFNAME());
                        jbtnView.requestFocusInWindow();
                    }
                }
            } else {
                lb.showMessageDailog(header.getCause().toString());
            }
        }
    } catch (Exception ex) {
        lb.printToLogFile("Exception at setData at account master in sales invoice", ex);
    }

}