Example usage for com.google.gson JsonObject getAsJsonArray

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

Introduction

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

Prototype

public JsonArray getAsJsonArray(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonArray.

Usage

From source file:io.urmia.md.model.job.JobStatus.java

License:Open Source License

public JobStatus(String json, Stats stats) {

    JsonObject rootObj = parser.parse(json).getAsJsonObject();

    this.id = rootObj.getAsJsonPrimitive("id").getAsString();
    this.phases = JobDefinition.Phase.fromJsonArray(rootObj.getAsJsonArray("phases"));

    this.timeCreated = fromISO8601ToMillis(rootObj.getAsJsonPrimitive("timeCreated").getAsString());
    this.timeDone = fromISO8601ToMillis(rootObj.getAsJsonPrimitive("timeDone").getAsString());
    this.timeArchiveStarted = fromISO8601ToMillis(
            rootObj.getAsJsonPrimitive("timeArchiveStarted").getAsString());
    this.timeArchiveDone = fromISO8601ToMillis(rootObj.getAsJsonPrimitive("timeArchiveDone").getAsString());

    this.stats = stats;
}

From source file:io.winterdev.server.SmsManager.java

public boolean sendSms(String num, String text) {

    try {//from   w  w w.j  a  va 2s .c om
        JsonObject response = ApiGetter.get("https://rest.nexmo.com/sms/json?api_key=" + Private.NEXMO_KEY
                + "&api_secret=" + Private.NEXMO_SECRET + "&to=" + num + "&text=" + text + "&from="
                + Private.NEXMO_NUMBER);
        JsonObject messages = response.getAsJsonArray("messages").get(0).getAsJsonObject();
        JsonPrimitive status = messages.getAsJsonPrimitive("status");
        if (status.getAsString().equalsIgnoreCase("0"))
            return true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

From source file:it.intecs.pisa.util.json.JsonXpath.java

License:Open Source License

private static Object get(JsonObject obj, StringTokenizer tokenizer) {
    String tok;/*from  w  ww.j a va  2 s . c  o m*/

    tok = tokenizer.nextToken();
    JsonArray array;
    JsonObject focusedObj;

    String token;
    if (tok.endsWith("]")) {
        String index;
        index = tok.substring(tok.indexOf("[") + 1, tok.indexOf("]"));

        String tokenName;
        tokenName = tok.substring(0, tok.indexOf("["));

        array = obj.getAsJsonArray(tokenName);
        JsonElement a = array.get(Integer.valueOf(index) - 1);
        if (a instanceof JsonPrimitive)
            return a;
        else
            focusedObj = a.getAsJsonObject();
    } else
        focusedObj = obj;

    return focusedObj.get(tok);

}

From source file:it.reply.orchestrator.dto.security.IndigoUserInfo.java

License:Apache License

/**
 * Create a {@link UserInfo} from its JSON representation.
 * /*  w  w  w . j  a  v  a  2 s.  c o  m*/
 * @param obj
 *          {@link JsonObject} containing the JSON representation.
 * @return the UserInfo.
 */
public static UserInfo fromJson(JsonObject obj) {
    IndigoUserInfo result = new IndigoUserInfo(DefaultUserInfo.fromJson(obj));
    if (obj.has(GROUPS_KEY) && obj.get(GROUPS_KEY).isJsonArray()) {
        List<String> groups = Lists.newArrayList();
        JsonArray groupsJson = obj.getAsJsonArray(GROUPS_KEY);
        for (JsonElement groupJson : groupsJson) {
            if (groupJson != null && groupJson.isJsonPrimitive()) {
                groups.add(groupJson.getAsString());
            }
        }
        result.setGroups(groups);
    }
    result.setOrganizationName(
            obj.has(ORGANIZATION_NAME_KEY) && obj.get(ORGANIZATION_NAME_KEY).isJsonPrimitive()
                    ? obj.get(ORGANIZATION_NAME_KEY).getAsString()
                    : null);
    return result;
}

From source file:it.unibo.arces.wot.sepa.pattern.JSAP.java

License:Open Source License

private JsonObject merge(JsonObject temp, JsonObject jsap, boolean replace) {
    for (Entry<String, JsonElement> entry : temp.entrySet()) {
        JsonElement value = entry.getValue();
        String key = entry.getKey();

        if (!jsap.has(key)) {
            jsap.add(key, value);/*from w ww. ja  v a2 s . c  o m*/
            continue;
        }

        if (value.isJsonPrimitive()) {
            if (!replace)
                continue;
            jsap.add(key, value);
        } else if (value.isJsonObject()) {
            JsonObject obj = merge(value.getAsJsonObject(), jsap.getAsJsonObject(key), replace);
            jsap.add(key, obj);
        } else if (value.isJsonArray()) {
            for (JsonElement arr : value.getAsJsonArray()) {
                jsap.getAsJsonArray(key).add(arr);
            }
        }
    }

    return jsap;
}

From source file:jcred.NodeDeserializer.java

License:Open Source License

@Override
public Node deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    JsonObject jsonObject = (JsonObject) json;
    Node result;/*from w  w w .  j  a  v a2 s.co  m*/

    if (jsonObject.get("groupName") != null) {
        result = new Group(jsonObject.get("groupName").getAsString());
    } else {
        result = new Credential(jsonObject.get("title").getAsString(), jsonObject.get("user").getAsString(),
                jsonObject.get("password").getAsString());
    }

    JsonArray jsonArray = jsonObject.getAsJsonArray("children");
    for (JsonElement childJson : jsonArray) {
        result.addChild(deserialize(childJson, Node.class, context));
    }

    return result;
}

From source file:jobs.FoursquareDiscoverHereNowJob.java

License:Apache License

@Override
public Object doJobWithResult() throws Exception {

    LinkedList<Object> dataList = new LinkedList<Object>();
    HereNow hereNow = new HereNow();
    HttpResponse resp = null;/*from ww  w  .j a  v  a2s.com*/
    WSRequest req = null;
    for (PoiModelFoursquare poi : poiList) {

        try {

            LinkedList<HereNow> herenow = Cache.get(CACHE_KEYPREFIX_HERENOW + poi.oid, LinkedList.class);
            if (herenow != null) {
                poi.herenow = new LinkedList<HereNow>();
                poi.herenow.addAll(herenow);
                Logger.info("Found in CACHE! # %s", herenow.size());

                dataList.add(poi);
                continue;
            }

            // https://developer.foursquare.com/docs/venues/herenow
            // https://api.foursquare.com/v2/venues/VENUE_ID/herenow
            req = WS.url(baseUrl + herenowSearch.replace("/%s/", "/" + poi.oid + "/") + "?"
                    + LocoUtils.buildUrlParams(params));
            Logger.info("req.url : %s", req.url);

            resp = req.get();

            Gson gson = new GsonBuilder().create();

            JsonObject jsonResp = resp.getJson().getAsJsonObject();
            //Logger.info("jsonResp : %s", jsonResp);

            poi.herenow = new LinkedList<HereNow>();

            JsonObject respPart = jsonResp.getAsJsonObject("response");
            respPart = respPart.getAsJsonObject("hereNow");
            JsonArray items = respPart.getAsJsonArray("items");
            JsonObject item;
            for (int i = 0; i < items.size(); i++) {
                item = items.get(i).getAsJsonObject();
                //-Logger.info("item #%s : %s", i, item);

                hereNow = new HereNow();
                //-hereNow = gson.fromJson(item, PoiHerenowModelFoursquare.class);
                hereNow.oid = item.has("id") ? item.get("id").getAsString() : "";

                hereNow.type = item.has("type") ? item.get("type").getAsString() : "";
                hereNow.timeZone = item.has("timeZone") ? item.get("timeZone").getAsString() : "";
                //-hereNow.createdAt = item.has("createdAt")?item.get("createdAt").getAsLong():0L;
                //-if (item.has("createdAt")) hereNow.setCreatedAt(item.get("createdAt").getAsLong());
                if (item.has("createdAt"))
                    hereNow.setCreatedAt(item.get("createdAt").getAsLong(), hereNow.timeZone);

                if (item.has("user")) {
                    item = item.getAsJsonObject("user");
                    hereNow.user_id = item.has("id") ? item.get("id").getAsString() : "";
                    hereNow.user_firstName = item.has("firstName") ? item.get("firstName").getAsString() : "";
                    hereNow.user_lastName = item.has("lastName") ? item.get("lastName").getAsString() : "";
                    hereNow.user_photo = item.has("photo") ? item.get("photo").getAsString() : "";
                    hereNow.user_gender = item.has("gender") ? item.get("gender").getAsString() : "";
                    hereNow.user_homeCity = item.has("homeCity") ? item.get("homeCity").getAsString() : "";
                    hereNow.user_canonicalUrl = item.has("canonicalUrl")
                            ? item.get("canonicalUrl").getAsString()
                            : "";

                    if (!StringUtils.isEmpty(hereNow.user_photo)) {
                        hereNow.user_photo_hres = hereNow.user_photo.replace("/userpix_thumbs/", "/userpix/");
                    }
                }

                //-Logger.info("hereNow #%s : %s", i, hereNow);

                poi.herenow.add(hereNow);

                try {
                    hereNow.poiId = poi.oid;
                    hereNow.lat = poi.lat;
                    hereNow.lng = poi.lng;
                    hereNow.updateLatlng();
                    hereNow.save();
                } catch (Exception ex) {
                    Logger.warn("Exception while persisting %s | %s", hereNow, ex.toString());
                }
            }

            if (poi.herenow.size() > 0) {
                Cache.set(CACHE_KEYPREFIX_HERENOW + poi.oid, poi.herenow, CACHE_TTL_HERENOW);
                Logger.info("CACHEd hereNow.size: %s", poi.herenow.size());
            }
            if (poi.stats != null)
                poi.stats.herenowCount = poi.herenow.size();

            dataList.add(poi);
        } catch (Exception ex) {

            Logger.error("exception : %s", ex.toString());
        }

    }

    return dataList;
}

From source file:jobs.FoursquareDiscoverPoiJob.java

License:Apache License

@Override
public Object doJobWithResult() throws Exception {

    WSRequest req = null;//  w w  w .  j a v  a2s.com
    HttpResponse resp = null;
    JsonObject jsonResp = null;
    Gson gson = new GsonBuilder().create();

    LinkedList<Object> dataList = new LinkedList<Object>();
    PoiModelFoursquare fsqPoi = null;

    if (idsList.size() > 0) {// check & load each fsq-POI

        for (String fsqId : idsList) {

            try {

                //fsqPoi = (PoiModelFoursquare)Cache.get(CACHE_KEYPREFIX_SINGLEPOI+fsqId);
                fsqPoi = Cache.get(CACHE_KEYPREFIX_SINGLEPOI + fsqId, PoiModelFoursquare.class);
                if (fsqPoi != null) {

                    Logger.info("Found in CACHE! : %s", fsqPoi);
                    dataList.add(fsqPoi);
                    continue;
                }

                // https://developer.foursquare.com/docs/venues/search
                // https://api.foursquare.com/v2/venues/search
                req = WS.url(baseUrl + singlePoiSearch.replace("/%s", "/" + fsqId) + "?"
                        + LocoUtils.buildUrlParams(params));
                Logger.info("req.url : %s", req.url);

                resp = req.get();

                jsonResp = resp.getJson().getAsJsonObject();
                //-Logger.info("jsonResp : %s", jsonResp);

                JsonObject respPart = jsonResp.getAsJsonObject("response");
                JsonObject venue = respPart.getAsJsonObject("venue");

                //-Logger.info("venue : %s", venue);

                fsqPoi = gson.fromJson(venue, PoiModelFoursquare.class);
                if (fsqPoi != null)
                    fsqPoi.updateCategoryIcons();
                Logger.info("fsqPoi : %s", fsqPoi);

                if (venue.has("hereNow")) {
                    fsqPoi.stats.herenowCount = venue.get("hereNow").getAsJsonObject().get("count").getAsInt();
                }

                fsqPoi.locType = BaseLocations.LocType.FSQ_POI;

                if (fsqPoi != null && !StringUtils.isEmpty(fsqPoi.oid)) {
                    try {
                        Cache.set(CACHE_KEYPREFIX_SINGLEPOI + fsqPoi.oid, fsqPoi, CACHE_TTL);

                        // TODO: using mongoDB is temporary, we should make this parametric enable/disable
                        //if (fsqPoi!=null && fsqPoi.location!=null) {
                        if (fsqPoi.location != null) {
                            fsqPoi.lat = fsqPoi.location.lat;
                            fsqPoi.lng = fsqPoi.location.lng;
                            fsqPoi.updateLatlng();
                        }
                        fsqPoi.save();
                    } catch (Exception ex) {
                        Logger.warn("Exception while persisting %s | %s", fsqPoi, ex.toString());
                    }

                    dataList.add(fsqPoi);
                }

            } catch (Exception ex) {

                Logger.error("exception : %s", ex.toString());
            }
        }
        // TODO: calculate distance and sort!
    } else {// load complete set from 4sq

        try {

            // https://developer.foursquare.com/docs/venues/search
            // https://api.foursquare.com/v2/venues/search
            req = WS.url(baseUrl + poiSearch + "?" + LocoUtils.buildUrlParams(params));
            Logger.info("req.url : %s", req.url);

            resp = req.get();

            //Gson gson = new GsonBuilder().create();

            jsonResp = resp.getJson().getAsJsonObject();
            //-Logger.info("jsonResp : %s", jsonResp);

            JsonObject respPart = jsonResp.getAsJsonObject("response");
            JsonArray venues = respPart.getAsJsonArray("venues");
            JsonObject venue;
            //PoiModelFoursquare fsqPoi = null;
            for (int i = 0; i < venues.size(); i++) {
                venue = venues.get(i).getAsJsonObject();
                //-Logger.info("venue #%s : %s", i, venue);

                fsqPoi = gson.fromJson(venue, PoiModelFoursquare.class);
                if (fsqPoi != null)
                    fsqPoi.updateCategoryIcons();
                Logger.info("fsqPoi #%s : %s", i, fsqPoi);

                if (venue.has("hereNow")) {
                    fsqPoi.stats.herenowCount = venue.get("hereNow").getAsJsonObject().get("count").getAsInt();
                }

                fsqPoi.locType = BaseLocations.LocType.FSQ_POI;

                if (fsqPoi != null && !StringUtils.isEmpty(fsqPoi.oid)) {
                    try {
                        Cache.set(CACHE_KEYPREFIX_SINGLEPOI + fsqPoi.oid, fsqPoi, CACHE_TTL);

                        // TODO: using mongoDB is temporary, we should make this parametric enable/disable
                        //if (fsqPoi!=null && fsqPoi.location!=null) {
                        if (fsqPoi.location != null) {
                            fsqPoi.lat = fsqPoi.location.lat;
                            fsqPoi.lng = fsqPoi.location.lng;
                            fsqPoi.updateLatlng();
                        }
                        fsqPoi.save();
                    } catch (Exception ex) {
                        Logger.warn("Exception while persisting %s | %s", fsqPoi, ex.toString());
                    }

                    dataList.add(fsqPoi);
                }
            }

            // TODO: calculate distance and sort!
        } catch (Exception ex) {

            Logger.error("exception : %s", ex.toString());
        }
    }

    return dataList;
}

From source file:jobs.FoursquareTrendingPoiJob.java

License:Apache License

@Override
public Object doJobWithResult() throws Exception {

    // https://developer.foursquare.com/docs/venues/trending
    // https://api.foursquare.com/v2/venues/trending
    WSRequest req = WS.url(baseUrl + trendingSearch + "?" + LocoUtils.buildUrlParams(params));
    Logger.info("req.url : %s", req.url);

    HttpResponse resp = req.get();//from   w w  w  .  ja v  a 2  s.co m
    LinkedList<Object> dataList = new LinkedList<Object>();

    try {
        Gson gson = new GsonBuilder().create();//new GsonBuilder().setPrettyPrinting().create();

        JsonObject jsonResp = resp.getJson().getAsJsonObject();
        //-Logger.info("jsonResp : %s", jsonResp);

        JsonObject respPart = jsonResp.getAsJsonObject("response");
        JsonArray venues = respPart.getAsJsonArray("venues");
        JsonObject venue;
        PoiModelFoursquare fsqPoi = null;
        for (int i = 0; i < venues.size(); i++) {
            venue = venues.get(i).getAsJsonObject();
            //-Logger.info("venue #%s : %s", i, venue);

            fsqPoi = gson.fromJson(venue, PoiModelFoursquare.class);
            if (fsqPoi != null)
                fsqPoi.updateCategoryIcons();
            Logger.info("fsqPoi #%s : %s", i, fsqPoi);

            if (venue.has("hereNow")) {
                fsqPoi.stats.herenowCount = venue.get("hereNow").getAsJsonObject().get("count").getAsInt();
            }

            fsqPoi.locType = BaseLocations.LocType.FSQ_TRENDING;

            if (fsqPoi != null && !StringUtils.isEmpty(fsqPoi.oid)) {
                try {
                    Cache.set(CACHE_KEYPREFIX_SINGLEPOI + fsqPoi.oid, fsqPoi, CACHE_TTL_SINGLEPOI);

                    // TODO: store only if it doesnt exists!
                    //if (fsqPoi!=null && fsqPoi.location!=null) {
                    if (fsqPoi.location != null) {
                        fsqPoi.lat = fsqPoi.location.lat;
                        fsqPoi.lng = fsqPoi.location.lng;
                        fsqPoi.updateLatlng();
                    }
                    fsqPoi.save();
                } catch (Exception ex) {
                    Logger.warn("Exception while persisting %s | %s", fsqPoi, ex.toString());
                }

                dataList.add(fsqPoi);
            }
        }
    } catch (Exception ex) {

        Logger.error("exception : %s", ex.toString());
    }

    return dataList;
}

From source file:jobs.NewsUpdateJob.java

@Override
public void doJob() throws Exception {
    Logger.info("Job started");

    //MorphiaFixtures.delete(Article.class);
    //GET http://api.feedzilla.com/v1/articles/search.json?q=bitcoin&order=date&since=2014-07-06&count=50

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, -1);//from   ww  w  .ja va  2  s .  c om
    String yesterday = dateFormat.format(cal.getTime());

    HttpResponse res = WS.url("http://api.feedzilla.com/v1/articles/search.json?q=bitcoin&order=date&since="
            + yesterday + "&count=50").get();
    JsonObject json = res.getJson().getAsJsonObject();
    JsonArray articles = json.getAsJsonArray("articles");
    for (JsonElement articleEle : articles) {
        JsonObject article = articleEle.getAsJsonObject();

        String title = article.get("title").getAsString();
        String summary = article.get("summary").getAsString();
        String source = article.get("source").getAsString();
        String sourceUrl = article.get("source_url").getAsString();
        String published = article.get("publish_date").getAsString();
        String author = null;
        if (article.get("author") != null) {
            author = article.get("author").getAsString();
        }
        String url = article.get("url").getAsString();

        int feedzillaId = 0;
        Pattern p = Pattern.compile("([0-9]+)");
        Matcher m = p.matcher(url);
        if (m.find()) {
            feedzillaId = Integer.parseInt(m.group(1));
        }

        //Just add the article if not already existing
        if (Article.find("feedzillaId", feedzillaId).first() == null) {
            Logger.info("New article: " + feedzillaId);
            Utils.emailAdmin("News: " + title, summary);
            new Article(title, published, source, sourceUrl, url, summary, author, feedzillaId).save();
            //TODO: Take the bitcoin value too
        } else {
            Logger.info("Article already exists: " + feedzillaId);
        }

    }
}