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:CarouselAdsExample.java

License:Open Source License

public static void main(String[] args) {
    try {//w  ww  . ja v a  2 s  .  co  m
        AdAccount account = new AdAccount(ACCOUNT_ID, context);
        Targeting targeting = new Targeting()
                .setFieldGeoLocations(new TargetingGeoLocation().setFieldCountries(Arrays.asList("US")))
                .setFieldAgeMin(18L).setFieldAgeMax(30L).setFieldUserOs(Arrays.asList("Android", "iOS"));

        Campaign campaign = account.createCampaign().setName("Java SDK Test Carousel Campaign")
                .setObjective(Campaign.EnumObjective.VALUE_LINK_CLICKS).setSpendCap(10000L)
                .setStatus(Campaign.EnumStatus.VALUE_PAUSED).execute();

        AdSet adset = account.createAdSet().setName("Java SDK Test Carousel 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).execute();

        AdImage image = account.createAdImage().addUploadFile("file", imageFile).execute();
        JsonArray childAttachments = new JsonArray();
        JsonObject attachment1 = new JsonObject();
        attachment1.addProperty("link", "https://www.example.com");
        attachment1.addProperty("description", "www.example.com");
        attachment1.addProperty("image_hash", image.getFieldHash());
        childAttachments.add(attachment1);
        JsonObject attachment2 = new JsonObject();
        attachment2.addProperty("link", "https://www.example.com");
        attachment2.addProperty("description", "www.example.com");
        attachment2.addProperty("image_hash", image.getFieldHash());
        childAttachments.add(attachment2);
        JsonObject attachment3 = new JsonObject();
        attachment3.addProperty("link", "https://www.example.com");
        attachment3.addProperty("description", "www.example.com");
        attachment3.addProperty("picture",
                "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png");
        childAttachments.add(attachment3);

        AdCreative creative = account.createAdCreative().setTitle("Java SDK Test Carousel Creative")
                .setBody("Java SDK Test Carousel Creative")
                .setObjectStorySpec(new AdCreativeObjectStorySpec().setFieldLinkData(new AdCreativeLinkData()
                        .setFieldChildAttachments(childAttachments.toString()).setFieldLink("www.example.com"))
                        .setFieldPageId(pageId))
                .setLinkUrl("www.example.com").execute();

        Ad ad = account.createAd().setName("Java SDK Test Carousel ad")
                .setAdsetId(Long.parseLong(adset.getId())).setCreative(creative).setStatus("PAUSED")
                .setBidAmount(100L).setRedownload(true).execute();

    } catch (APIException e) {
        e.printStackTrace();
    }
}

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 o m
    }
    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

@OnOpen
public void start(Session session) {
    this.session = session;
    connections.add(this);
    try {//w w  w .j av a2s .  co  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 {//w  w  w. jav  a 2  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   ww w.ja  v a2s  . c o  m*/

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

    return res.toString();

}

From source file:JavaAction.java

License:Apache License

public static JsonObject main(JsonObject args) {
    String text;/*from  w  w w .  j  av  a2s. c om*/

    try {
        text = args.getAsJsonPrimitive("text").getAsString();
    } catch (Exception e) {
        text = "stranger";
    }

    JsonObject response = new JsonObject();
    System.out.println("Hello " + text + "!");
    response.addProperty("payload", "Hello " + text + "!");
    return response;
}

From source file:Unicode.java

License:Apache License

public static JsonObject main(JsonObject args) throws InterruptedException {
    String delimiter = args.getAsJsonPrimitive("delimiter").getAsString();
    JsonObject response = new JsonObject();
    String str = delimiter + "  " + delimiter;
    System.out.println(str);/* w  w w .  j av  a 2 s .  c om*/
    response.addProperty("winter", str);
    return response;
}

From source file:dev1.java

License:Apache License

public static void main(String[] args) {

    DirectProvider tp = new DirectProvider();
    Topology topology = tp.newTopology("IotpQuickstart");

    // Declare a connection to IoTF Quickstart service
    String deviceId = "qs" + Long.toHexString(new Random().nextLong());
    /* IotDevice device = IotpDevice.quickstart(topology, deviceId); */
    IotDevice device = new IotpDevice(topology, new File("device.cfg"));

    System.out.println("Quickstart device type:" + IotpDevice.QUICKSTART_DEVICE_TYPE);
    System.out.println("Quickstart device id  :" + deviceId);
    System.out.println("https://quickstart.internetofthings.ibmcloud.com/#/device/" + deviceId);

    Random r = new Random();
    TStream<double[]> raw = topology.poll(() -> {
        double[] v = new double[3];

        v[0] = r.nextGaussian() * 10.0 + 40.0;
        v[1] = r.nextGaussian() * 10.0 + 50.0;
        v[2] = r.nextGaussian() * 10.0 + 60.0;

        return v;
    }, 1, TimeUnit.SECONDS);//from  w w w .  ja  v a 2  s .c o  m

    TStream<JsonObject> json = raw.map(v -> {
        JsonObject j = new JsonObject();
        j.addProperty("temp", v[0]);
        j.addProperty("humidity", v[1]);
        j.addProperty("objectTemp", v[2]);
        return j;
    });

    device.events(json, "sensors", QoS.FIRE_AND_FORGET);

    tp.submit(topology);
}

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 w  w  . j a  v a2 s. c o m
    jsonObj.addProperty("script", scriptBuffer.toString());

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

}