Example usage for com.google.gson JsonArray add

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

Introduction

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

Prototype

public void add(JsonElement element) 

Source Link

Document

Adds the specified element to self.

Usage

From source file:CarouselAdsExample.java

License:Open Source License

public static void main(String[] args) {
    try {// ww  w  .  jav  a  2s  . com
        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());// w w  w  .j a v  a  2s  .  co 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:RunnerRepository.java

License:Apache License

public static void removePlugin(String filename) {
    JsonArray array = new JsonArray();
    int size = getPlugins().size();
    for (int i = 0; i < size; i++) {
        if (getPlugins().get(i).getAsString().equals(filename))
            continue;
        array.add(getPlugins().get(i));
    }//w w  w  . j a  v  a2  s . c o  m
    plugins = array;
    inifile.add("plugins", array);
    writeJSon();
}

From source file:RunnerRepository.java

License:Apache License

public static void addPlugin(String pluginfilename) {
    if (getPlugins().isJsonArray()) {
        getPlugins().getAsJsonArray().add(new JsonPrimitive(pluginfilename));
    } else {/*from   w  w w .  j ava  2 s  .c  om*/
        JsonPrimitive primitive = new JsonPrimitive(pluginfilename);
        JsonArray array = new JsonArray();
        array.add(primitive);
        inifile.add("plugins", array);
    }
    writeJSon();
}

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 ww .  j  ava2  s  .  co m*/
    elm.add("R", registerArr);
    return g.toJson(elm);
}

From source file:ListAction.java

@Override
public void execute(HttpServletRequest request, PrintWriter out, File folder) {

    try {/*w  w  w . j av a  2s  .co m*/
        String type = request.getParameter("type");

        JsonArray list = new JsonArray();

        switch (type) {
        case "movie":
            File[] movies = Service.listAllMovies(folder);

            for (int i = 0; i < movies.length; i++) {
                JsonObject m = new JsonObject();
                m.addProperty("title", movies[i].getName());
                list.add(m);
            }

            break;

        case "series":
            File[] series = Service.listAllSeries(folder);

            for (int i = 0; i < series.length; i++) {
                JsonObject m = new JsonObject();
                m.addProperty("title", series[i].getName());
                list.add(m);
            }

            break;

        case "episode":
            String series_title = request.getParameter("series");

            folder = new File(folder.getAbsolutePath() + "\\Series\\" + series_title);

            List<File> episodes = Service.listAllEpisodes(folder);

            for (File f : episodes) {
                JsonObject episode = new JsonObject();

                String title = f.getName().split(" - ")[0];

                episode.addProperty("title", series_title + " - " + title);

                list.add(episode);
            }

            break;
        }

        JsonObject container = new JsonObject();

        container.add("list", list);

        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String json = gson.toJson(container);
        out.println(json);
    } catch (Exception e) {
        throw e;
    }
}

From source file:EAIJSONConverter.java

License:Open Source License

public JsonObject traversePS(SiebelPropertySet ps, JsonObject jObj) {
    JsonObject siebJSON = new JsonObject();
    String propName;// w w  w . j  ava2s  .co  m
    String propVal;
    propName = ps.getFirstProperty();

    while (propName != "") {
        propVal = ps.getProperty(propName);
        siebJSON.addProperty(propName, propVal);
        propName = ps.getNextProperty();
    }

    JsonObject child;

    for (int i = 0; i < ps.getChildCount(); i++) {
        child = new JsonObject();

        if (ps.getChild(i).getType().startsWith("ListOf-"))

        {
            JsonArray ja = new JsonArray();
            for (int o = 0; o < ps.getChild(i).getChildCount(); o++) {
                ja.add(traversePS(ps.getChild(i).getChild(o), child));
            }
            siebJSON.add(ps.getChild(i).getType().substring(7), ja);
        } else if (ps.getChild(i).getType().startsWith("StringList-"))

        {
            JsonArray ja = new JsonArray();
            SiebelPropertySet auxps = ps.getChild(i);
            Enumeration e = auxps.getPropertyNames();
            List list = Collections.list(e);
            Collections.sort(list);
            e = Collections.enumeration(list);

            while (e.hasMoreElements()) {
                String propName1 = (String) e.nextElement();
                ja.add(new JsonPrimitive(auxps.getProperty(propName1)));
            }
            siebJSON.add(auxps.getType().substring(11), ja);
        } else {
            child = traversePS(ps.getChild(i), child);
            siebJSON.add(ps.getChild(i).getType(), child);
        }
    }

    return siebJSON;
}

From source file:CustomAudienceExample.java

License:Open Source License

public static void main(String[] args) {
    try {/*from  w ww .j a va2 s . 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.BajajReport.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w w  w .j  a  v a2s .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 {
    final String from_date = request.getParameter("from_date");
    final String to_date = request.getParameter("to_date");
    final String ac_cd = request.getParameter("ac_cd");
    final int branch_cd = Integer.parseInt(request.getParameter("branch_cd"));
    final DBHelper helper = DBHelper.GetDBHelper();
    final Connection dataConnection = helper.getConnMpAdmin();
    final JsonObject jResultObj = new JsonObject();
    final Library lb = Library.getInstance();
    if (dataConnection != null) {
        try {
            String sql = "select v1.v_type,v1.branch_cd,v.ref_no,v1.inv_no,a.FNAME,s.SR_NAME,v1.V_DATE as ins_date,v.TAG_NO,p.BAJAJ_AMT,p.SFID,a1.fname as bajaj_name from vilsdt v "
                    + " left join SERIESMST s on v.SR_CD=s.SR_CD left join VILSHD v1 on v.REF_NO=v1.REF_NO left join acntmst a on v1.AC_CD=a.AC_CD "
                    + " left join payment p on v1.ref_no=p.ref_no left join acntmst a1 on p.bajaj_name=a1.ac_cd "
                    + " where v1.V_DATE>='" + from_date + "'" + " and v1.V_DATE<='" + to_date
                    + "' and v1.is_del=0 and p.bajaj_amt <>0 "
                    + " and (v.IMEI_NO<>'' or v.SERAIL_NO<>'') and v.is_main=1";
            if (branch_cd != 0) {
                sql += " and v1.branch_cd=" + branch_cd;
            }
            if (!ac_cd.equalsIgnoreCase("")) {
                sql += " and p.bajaj_name='" + ac_cd + "'";
            }
            sql += " order by v1.V_DATE";
            PreparedStatement pstLocal = dataConnection.prepareStatement(sql);
            ResultSet viewDataRs = pstLocal.executeQuery();

            JsonArray array = new JsonArray();
            while (viewDataRs.next()) {
                JsonObject object = new JsonObject();
                object.addProperty("INV_NO", viewDataRs.getString("INV_NO"));
                object.addProperty("V_TYPE", viewDataRs.getString("V_TYPE"));
                object.addProperty("FNAME", viewDataRs.getString("FNAME"));
                object.addProperty("SR_NAME", viewDataRs.getString("SR_NAME"));
                object.addProperty("TAG_NO", viewDataRs.getString("TAG_NO"));
                object.addProperty("INS_DATE", viewDataRs.getString("ins_date"));
                object.addProperty("branch_cd", viewDataRs.getString("branch_cd"));
                object.addProperty("RATE", viewDataRs.getDouble("BAJAJ_AMT"));
                object.addProperty("REF_NO", viewDataRs.getString("REF_NO"));
                object.addProperty("SFID", viewDataRs.getString("SFID"));
                object.addProperty("BAJAJ_NAME", viewDataRs.getString("BAJAJ_NAME"));
                array.add(object);
            }
            lb.closeResultSet(viewDataRs);
            lb.closeStatement(pstLocal);
            jResultObj.addProperty("result", 1);
            jResultObj.addProperty("Cause", "success");
            jResultObj.add("data", array);
        } catch (SQLNonTransientConnectionException ex1) {
            jResultObj.addProperty("result", -1);
            jResultObj.addProperty("Cause", "Server is down");
        } catch (SQLException ex) {
            jResultObj.addProperty("result", -1);
            jResultObj.addProperty("Cause", ex.getMessage());
        } finally {
            lb.closeConnection(dataConnection);
        }
    }
    response.getWriter().print(jResultObj);
}

From source file:account.BankBook.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   www.  ja  va 2  s .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 {
    DBHelper helper = DBHelper.GetDBHelper();
    dataConnection = helper.getConnMpAdmin();
    final JsonObject jResultObj = new JsonObject();
    ac_cd = request.getParameter("ac_cd");
    rec_date = Boolean.parseBoolean(request.getParameter("rec_date"));
    from_date = request.getParameter("from_date");
    to_date = request.getParameter("to_date");
    try {
        if (dataConnection != null) {
            makeQuery();
            double opbRs = 0.00;
            JsonArray array = new JsonArray();
            while (viewDataRS.next()) {
                JsonObject object = new JsonObject();
                object.addProperty("DOC_REF_NO", viewDataRS.getString("INV_NO"));
                object.addProperty("DOC_DATE", viewDataRS.getString("DOC_DATE"));
                object.addProperty("REC_DATE", viewDataRS.getString("REC_DATE"));
                object.addProperty("DOC_CD", viewDataRS.getString("DOC_CD"));
                object.addProperty("DR", viewDataRS.getDouble("DR"));
                object.addProperty("CR", viewDataRS.getDouble("CR"));
                opbRs += viewDataRS.getDouble("DR") - viewDataRS.getDouble("CR");
                object.addProperty("BAL", opbRs);
                object.addProperty("PARTICULAR", viewDataRS.getString("PARTICULAR"));
                object.addProperty("OPP_AC_CD", viewDataRS.getString("OPP_AC_CD"));
                object.addProperty("REC_DATE", viewDataRS.getString("REC_DATE"));
                object.addProperty("OPP_NAME", viewDataRS.getString("OPP_NAME"));
                object.addProperty("REF_NO", viewDataRS.getString("doc_ref_no"));
                object.addProperty("CHQ_NO", viewDataRS.getString("CHQ_NO"));
                object.addProperty("REC_BANK_NAME", viewDataRS.getString("REC_BANK_NAME"));
                array.add(object);
            }

            String sql = "(select (select case when sum(val) is null then 0 else sum(val)end  from OLDB2_2 where AC_CD='"
                    + ac_cd + "' and ((doc_date <'" + from_date + "') and (REC_DATE <'" + from_date
                    + "')) and CRDR=0) -"
                    + "(select case when sum(val) is null then 0 else sum(val)end  from OLDB2_2 where AC_CD='"
                    + ac_cd + "' " + "and ((doc_date <'" + from_date + "') and (REC_DATE <'" + from_date
                    + "')) and CRDR=1)  as opb from dual) ";
            PreparedStatement pstLocal = dataConnection.prepareStatement(sql);
            viewDataRS = pstLocal.executeQuery();
            if (viewDataRS.next()) {
                jResultObj.addProperty("opb", viewDataRS.getDouble("opb"));
            } else {
                jResultObj.addProperty("opb", 0.00);
            }
            jResultObj.addProperty("result", 1);
            jResultObj.addProperty("Cause", "success");
            jResultObj.add("data", array);
        }
    } catch (SQLNonTransientConnectionException ex1) {
        jResultObj.addProperty("result", -1);
        jResultObj.addProperty("Cause", "Server is down");
    } catch (SQLException ex) {
        jResultObj.addProperty("result", -1);
        jResultObj.addProperty("Cause", ex.getMessage());
    }
    response.getWriter().print(jResultObj);
}