Example usage for com.google.gson JsonObject getAsJsonObject

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

Introduction

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

Prototype

public JsonObject getAsJsonObject() 

Source Link

Document

convenience method to get this element as a JsonObject .

Usage

From source file:com.smart.taxi.entities.User.java

public User deserializeUserObjectFromJSON(JsonObject userObject) {
    User user = new User();
    try {/*from   w w  w .j av  a2s . c o  m*/

        JsonObject rootObj = userObject.getAsJsonObject();

        user.setFirstName(JsonHelper.getString(rootObj, APIConstants.KEY_FIRST_NAME));
        user.setLastName(JsonHelper.getString(rootObj, APIConstants.KEY_LAST_NAME));
        user.setId(JsonHelper.getString(rootObj, APIConstants.KEY_ID));
        user.setGender(JsonHelper.getString(rootObj, APIConstants.KEY_GENDER));
        user.setGroupId(JsonHelper.getString(rootObj, APIConstants.KEY_GROUP_ID));
        user.setCreated(JsonHelper.getString(rootObj, APIConstants.KEY_CREATED));
        user.setPhone(JsonHelper.getString(rootObj, APIConstants.KEY_PHONE));
        user.setStatus(JsonHelper.getString(rootObj, APIConstants.KEY_STATUS));
        user.setCorporateId(JsonHelper.getInt(rootObj, APIConstants.KEY_CORPORATE_ID));
        user.setProfileImage(JsonHelper.getString(rootObj, APIConstants.KEY_USER_INFO_IMAGE_URL));
        user.setUserName(JsonHelper.getString(rootObj, APIConstants.KEY_USERNAME));
        user.setTip(JsonHelper.getString(rootObj, APIConstants.KEY_TIP));

    } catch (Exception e) {
        e.printStackTrace();
    }
    return user;
}

From source file:com.smarttaxi.driver.BAL.Driver.java

public static ArrayList<Cab> getCabs(JsonObject json, String activeCabID) {
    ArrayList<Cab> list = new ArrayList<Cab>();
    String cabNo, cab_provider_id, id;
    boolean status, isActive;

    try {/*from w w  w .  jav  a2  s . co  m*/

        for (Entry<String, JsonElement> entry : json.getAsJsonObject().entrySet()) {
            JsonElement jsonElement = entry.getValue();

            cabNo = JsonHelper.getString(jsonElement.getAsJsonObject(), APIConstants.KEY_CAB_NO);
            cab_provider_id = JsonHelper.getString(jsonElement.getAsJsonObject(),
                    APIConstants.KEY_CAB_PROVIDER_ID);
            id = JsonHelper.getString(jsonElement.getAsJsonObject(), APIConstants.KEY_ID);
            String _status = JsonHelper.getString(jsonElement.getAsJsonObject(), APIConstants.KEY_STATUS);
            String _isActive = JsonHelper.getString(jsonElement.getAsJsonObject(),
                    APIConstants.KEY_DRIVER_ASSIGNED);
            status = _status != null && _status.equalsIgnoreCase("active");
            isActive = _isActive != null && _isActive.equalsIgnoreCase("yes");
            Cab cab = new Cab();
            cab.setCabNo(cabNo);
            cab.setCabProviderId(cab_provider_id);
            cab.setID(id);
            cab.setStatus(status);
            // cab.isActive(isActive);
            cab.isActive(id.equalsIgnoreCase(activeCabID));
            list.add(cab);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    /*
     * JsonArray jsonArray = json.getAsJsonArray(); if(jsonArray == null)
     * return list;
     * 
     * for (int i = 0; i < jsonArray.size(); i++) { JsonElement obj =
     * jsonArray.get(i); String name =
     * JsonHelper.getString(obj.getAsJsonObject(), APIConstants.KEY_NAME);
     * Applog.Debug("Naame " + name); }
     */
    return list;
}

From source file:com.smarttaxi.driver.BAL.Driver.java

public static ArrayList<Journey> parseHistory(JsonObject json) {
    ArrayList<Journey> list = new ArrayList<Journey>();
    String firstName = "", lastName = "", corporateName = "", pickFromAddress = "", pickFromTime = "",
            dropToAddress = "", dropToTime = "";
    String paymentType = "", paymentAmout = "", tipGiven = "";
    boolean taxIncluded = false;

    try {// w  w w  .j  a  va2 s  . com
        /****** JOURNEYS ****/
        for (Entry<String, JsonElement> entry : json.getAsJsonObject().entrySet()) {
            JsonElement jsonElement = entry.getValue();
            JsonObject journeyUsersObject = JsonHelper.getJsonObject(jsonElement.getAsJsonObject(),
                    "journey_users");
            // Applog.Debug("journeyUsersObject " + journeyUsersObject);

            /** JOURNEY_USERS **/
            for (Entry<String, JsonElement> journey : journeyUsersObject.getAsJsonObject().entrySet()) {
                JsonElement jsonJourneyElement = journey.getValue();

                pickFromTime = JsonHelper.getString(jsonJourneyElement.getAsJsonObject(), "pickup_time");
                pickFromAddress = JsonHelper.getString(jsonJourneyElement.getAsJsonObject(),
                        "pickup_door_address");
                dropToAddress = JsonHelper.getString(jsonJourneyElement.getAsJsonObject(),
                        "dropOff_door_address");

                taxIncluded = Utils.isEmptyOrNull(
                        JsonHelper.getString(jsonJourneyElement.getAsJsonObject(), "extras")) ? false : true;
                dropToTime = JsonHelper.getString(jsonJourneyElement.getAsJsonObject(), "dropOff_time");
                tipGiven = JsonHelper.getString(jsonJourneyElement.getAsJsonObject(), "tip_given");
                Applog.Debug("TRIP : Pick From " + pickFromAddress);

                JsonObject usersObject = JsonHelper.getJsonObject(jsonJourneyElement.getAsJsonObject(),
                        "users");

                /******* USERS *******/
                for (Entry<String, JsonElement> users : usersObject.entrySet()) {
                    JsonElement usersJsonElement = users.getValue();
                    firstName = JsonHelper.getString(usersJsonElement.getAsJsonObject(),
                            APIConstants.KEY_FIRST_NAME);
                    lastName = JsonHelper.getString(usersJsonElement.getAsJsonObject(),
                            APIConstants.KEY_LAST_NAME);
                    Applog.Debug("TRIP : firstName " + firstName);
                    /******* Coparate Users *******/
                    try {
                        JsonObject coparteUsersObject = JsonHelper
                                .getJsonObject(usersJsonElement.getAsJsonObject(), "corporate_users");
                        corporateName = JsonHelper.getString(coparteUsersObject, APIConstants.KEY_NAME);
                        Applog.Debug("TRIP : coparteUsersObject " + corporateName);
                    } catch (Exception e) {
                        corporateName = "";
                    }

                }
                /***** USERS END ******/

                /******* PAYMENT *******/
                JsonObject paymentObject = JsonHelper.getJsonObject(jsonJourneyElement.getAsJsonObject(),
                        "Payment");
                for (Entry<String, JsonElement> paymentEntry : paymentObject.entrySet()) {
                    JsonElement paymentJsonElement = paymentEntry.getValue();
                    paymentAmout = JsonHelper.getString(paymentJsonElement.getAsJsonObject(), "amount");
                    paymentType = JsonHelper.getString(paymentJsonElement.getAsJsonObject(), "payment_type");
                    Applog.Debug("TRIP : paymentAMount " + paymentAmout);
                }
            }

            Journey journey = new Journey();
            journey.setCorporateName(corporateName);
            journey.setDropToAddress(dropToAddress);
            journey.setDropToTime(dropToTime);
            journey.setFirstName(firstName);
            journey.setLastName(lastName);
            journey.setPaymentAmout(paymentAmout);
            journey.setExtras(taxIncluded);
            journey.setPaymentType(paymentType);
            journey.setPickFromAddress(pickFromAddress);
            journey.setPickFromTime(pickFromTime);
            journey.setTipGiven(tipGiven);
            list.add(journey);

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

    return list;
}

From source file:com.smarttaxi.driver.entities.User.java

public User deserializeUserObjectFromJSON(JsonObject userObject) {
    User user = new User();
    try {//from  w w w  .j a va2  s. co m

        JsonObject rootObj = userObject.getAsJsonObject();

        user.setFirstName(JsonHelper.getString(rootObj, APIConstants.KEY_FIRST_NAME));
        user.setLastName(JsonHelper.getString(rootObj, APIConstants.KEY_LAST_NAME));

    } catch (Exception e) {
        e.printStackTrace();
    }
    return user;
}

From source file:com.zack6849.alphabot.api.Utils.java

License:Open Source License

public static String google(String s) {
    try {/* w  w  w  . j a  v a  2 s  .  com*/
        String temp = String.format("https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=%s",
                URLEncoder.encode(s, "UTF-8"));
        URL u = new URL(temp);
        URLConnection c = u.openConnection();
        c.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17");
        BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
        String json = "";
        String tmp;
        while ((tmp = in.readLine()) != null) {
            json += tmp + "\n";
        }
        in.close();
        JsonElement jelement = new JsonParser().parse(json);
        JsonObject output = jelement.getAsJsonObject();
        output = output.getAsJsonObject("responseData").getAsJsonArray("results").get(0).getAsJsonObject();

        String title = StringEscapeUtils.unescapeJava(StringEscapeUtils
                .unescapeHtml4(output.get("titleNoFormatting").toString().replaceAll("\"", "")));
        String content = StringEscapeUtils.unescapeJava(StringEscapeUtils.unescapeHtml4(output.get("content")
                .toString().replaceAll("\\s+", " ").replaceAll("\\<.*?>", "").replaceAll("\"", "")));
        String url = StringEscapeUtils.unescapeJava(output.get("url").toString().replaceAll("\"", ""));
        String result = String.format("Google: %s | %s | (%s)", title, content, url);
        if (result != null) {
            return result;
        } else {
            return "No results found for query " + s;
        }
    } catch (IOException ex) {
        Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:controllers.Rdio.java

License:Open Source License

public static ArrayList<Track> suggestsearchTrack(User user, String trackName) {

    ArrayList trackResults = null;
    // try {//from   w  w  w.j a  v  a2 s. c  om

    String url = endpoint;
    WSRequest sign;
    try {
        sign = getConnector(user).sign(user.rdioCreds, WS.url(url), "POST");
    } catch (Exception ex) {
        Logger.info(ex.toString());
        ex.printStackTrace();
        return null;
    }

    sign.setParameter("method", "searchSuggestions");
    sign.setParameter("domain", Play.configuration.getProperty("domain"));
    sign.setParameter("types", "Track,Album,Artist");

    sign.setParameter("query", trackName);
    sign.setParameter("never_or", true);
    sign.setHeader("Content-type", "application/json");
    JsonElement searchResult = sign.post().getJson();
    //Logger.info(searchResult.toString());
    com.google.gson.JsonObject asJsonObj = searchResult.getAsJsonObject();
    // JsonElement rawResult = asJsonObj.get("result").getAsJsonObject();

    com.google.gson.JsonArray resultArray = asJsonObj.getAsJsonObject().get("result").getAsJsonArray();

    trackResults = new ArrayList();
    for (JsonElement rdioTrackElement : resultArray) {
        JsonObject rdioTrack = rdioTrackElement.getAsJsonObject();

        if (rdioTrack.get("type").getAsString().contains("t")) { // Object's type
            Track track = Track.retrieveTrackByRadioId(rdioTrack.get("key").getAsString());
            if (track == null) {
                track = new Track();
                RdioHelper.parseNewTrack(user, track, rdioTrack, true);
                //                    YoutubeJob ty = new YoutubeJob(track);
                //                   ty.loadYoutubes();

            }

            track.uniformSave();

            if (track.canStream) {
                trackResults.add(track);
            }

        }
    }
    return trackResults;
}

From source file:de.behrfried.wikianalyzer.wawebapp.server.service.JsonWikiAccess.java

License:Apache License

@Override
public UserInfo getUserInfo(String userName) throws UserNotExistException {
    try {//  w  ww  .  j a v  a2  s.  c o m
        final int userid = this.getUserID(userName);

        if (userid == -1) {
            /* article does not exist */
            throw new UserNotExistException("Nutzer \"" + userid + "\" existiert nicht!");
        }

        final List<UserInfo.ArticleEdited> categoryEdited = new ArrayList<UserInfo.ArticleEdited>();

        boolean isBot = false;
        Date signInDate = null;
        int lastUserCommits = 0;

        final String response1 = this.requester
                .getResult(this.convertRequest("action=query&format=json&list=users&ususers=" + userName
                        + "&usprop=editcount|registration|blockinfo|groups"));

        final JsonObject root = this.parser.parse(response1).getAsJsonObject();
        final JsonObject user = root.getAsJsonObject("query").getAsJsonArray("users").get(0).getAsJsonObject();

        if (user.has("groups")) {
            final JsonArray groupsJsonArr = user.getAsJsonArray("groups");
            for (JsonElement jsonElement : groupsJsonArr) {
                if ("bot".equals(jsonElement.getAsJsonPrimitive().getAsString())) {
                    isBot = true;
                    break;
                }
            }
        }

        final int editcount = user.getAsJsonPrimitive("editcount").getAsInt();

        final boolean blocked = user.has("blockid");

        Map<Tuple2<Integer, String>, Tuple2<Integer, Integer>> comparableRevisions = new HashMap<Tuple2<Integer, String>, Tuple2<Integer, Integer>>();
        final Map<String, Integer> commitsPerCategory = new HashMap<String, Integer>();
        final List<ArticleEdited> articleEditeds = new ArrayList<UserInfo.ArticleEdited>();
        int numOfComments = 0;
        int numOfReverts = 0;
        int numOfUserDiscussion = 0;
        int numofSelfDiscussion = 0;

        final String userArticles = this.requester
                .getResult(this.convertRequest("action=query&format=json&list=usercontribs&ucdir=older&ucuser="
                        + userName + "&uclimit=500&ucprop=ids|sizediff|title|flags|comment|timestamp"));
        final JsonObject rootObj = this.parser.parse(userArticles).getAsJsonObject();

        final JsonArray articlesArticle = rootObj.getAsJsonObject("query").getAsJsonArray("usercontribs");
        lastUserCommits += articlesArticle.size();

        for (JsonElement elm : articlesArticle) {
            final JsonObject tmpObj = elm.getAsJsonObject();

            final Tuple2<Integer, String> key = Tuple.create(tmpObj.getAsJsonPrimitive("pageid").getAsInt(),
                    tmpObj.getAsJsonPrimitive("title").getAsString());

            if (key.getItem2().startsWith("Benutzer Diskussion:")) {
                if (key.getItem2().endsWith(userName)) {
                    numofSelfDiscussion++;
                } else {
                    numOfUserDiscussion++;
                }
            }

            final int sizediff = tmpObj.has("sizediff") ? tmpObj.getAsJsonPrimitive("sizediff").getAsInt() : 0;
            final String comment = tmpObj.has("comment") ? tmpObj.getAsJsonPrimitive("comment").getAsString()
                    : "";
            if (!comment.isEmpty()) {
                numOfComments++;
                if (this.isRevert(comment)) {
                    numOfReverts++;
                }
            }

            if (!comparableRevisions.containsKey(key)) {
                comparableRevisions.put(key, Tuple.create(0, 0));
            }
            comparableRevisions.put(key, Tuple.create(comparableRevisions.get(key).getItem1() + 1,
                    comparableRevisions.get(key).getItem2() + sizediff));
        }

        final Set<String> categorySet = new HashSet<String>();
        for (final Map.Entry<Tuple2<Integer, String>, Tuple2<Integer, Integer>> entry : comparableRevisions
                .entrySet()) {

            final String categories = this.getCategories(entry.getKey().getItem1());
            categoryEdited.add(new ArticleEdited(entry.getKey().getItem2(), entry.getValue().getItem1(),
                    entry.getValue().getItem2(), categories));

            final String[] catArr = categories.split(";");
            for (final String cat : catArr) {
                categorySet.add(cat.trim());

                if (!commitsPerCategory.containsKey(cat.trim())) {
                    commitsPerCategory.put(cat.trim(), entry.getValue().getItem1());
                } else {
                    commitsPerCategory.put(cat.trim(),
                            (commitsPerCategory.get(cat.trim()) + entry.getValue().getItem1()));
                }
            }
        }

        try {
            signInDate = this.formatter
                    .parse(user.getAsJsonPrimitive("registration").getAsString().replace('T', '_'));

        } catch (Exception e) {
            this.logger.warn(userName + " has no sign in date!");
            final String signInRsp = this.requester.getResult(
                    this.convertRequest("action=query&format=json&list=usercontribs&ucdir=newer&ucuser="
                            + userName + "&uclimit=1&ucprop=timestamp"));
            final JsonObject aa = this.parser.parse(userArticles).getAsJsonObject();
            final JsonArray aaa = aa.getAsJsonObject("query").getAsJsonArray("usercontribs");
            if (aaa.size() > 0) {
                // get the date of the first user contrib
                signInDate = this.formatter.parse(aaa.get(aaa.size() - 1).getAsJsonObject()
                        .getAsJsonPrimitive("timestamp").getAsString().replace('T', '_'));
            }
        }

        final StringBuilder categoriesStrBuilder = new StringBuilder();
        categoriesStrBuilder.append("(");
        categoriesStrBuilder.append(categorySet.size());
        categoriesStrBuilder.append(") = ");
        for (final String cat : categorySet) {
            categoriesStrBuilder.append(cat);
            categoriesStrBuilder.append("; ");
        }

        /*
         * get categories
         */
        final String categoryCommits = categoriesStrBuilder.toString().substring(0,
                categoriesStrBuilder.length() - 2);

        /*
         * get reputation
         */
        final Object[] reps = this.calcReputation(userName, lastUserCommits, blocked);
        final double reputation = (Double) reps[0];
        final String abuses = (String) reps[1];
        final int abuseCount = (Integer) reps[2];

        /*
         * user classes
         */
        String userclassNumOfCommits = "Gott";
        if (lastUserCommits < 100) {
            userclassNumOfCommits = "Rookie";
        } else if (lastUserCommits < 1000) {
            userclassNumOfCommits = "Fortgeschrittener";
        } else if (lastUserCommits < 10000) {
            userclassNumOfCommits = "Profi";
        } else if (lastUserCommits < 100000) {
            userclassNumOfCommits = "Master";
        }

        String userclassAvgCommits = "\"nicht bewertbar\"";
        double avgCommits = 0;
        if (signInDate != null) {
            avgCommits = editcount / ((System.currentTimeMillis() - signInDate.getTime()) / 86400000);
            if (avgCommits == 0.0) {
                userclassAvgCommits = "Schlafmtze";
            } else if (avgCommits < 1.0d) {
                userclassAvgCommits = "Gelegenheitssurfer";
            } else if (avgCommits < 5.0d) {
                userclassAvgCommits = "Durchschnittsuser";
            } else if (avgCommits < 15.0d) {
                userclassAvgCommits = "Vielschreiber";
            } else {
                userclassAvgCommits = "Dauergast";
            }
        }

        String userclassRevert = "\"nicht bewertbar\"";
        String userclassComment = "\"nicht bewertbar\"";

        if (lastUserCommits > 0) {
            final double revertCommitRelation = (double) numOfReverts / lastUserCommits;
            userclassRevert = "Spielverderber";
            if (revertCommitRelation < 0.01) {
                userclassRevert = "Ein-Auge-Zudrcker";
            } else if (revertCommitRelation < 0.1) {
                userclassRevert = "Gelegenheitsspieer";
            } else if (revertCommitRelation < 0.2) {
                userclassRevert = "Sturrkopf";
            } else if (revertCommitRelation < 0.5) {
                userclassRevert = "Kontrolleur";
            }

            final double commentCommitRelation = (double) numOfComments / lastUserCommits;
            userclassComment = "Saubermann";
            if (commentCommitRelation < 0.1) {
                userclassComment = "Dokuhasser";
            } else if (commentCommitRelation < 0.5) {
                userclassComment = "Ab und zu vergesslich";
            } else if (commentCommitRelation < 0.8) {
                userclassComment = "Ordnungshter";
            }
        }

        String userDiscussion = "Sehr oft";
        if (numOfUserDiscussion == 0) {
            userDiscussion = "Nie";
        } else if (numOfUserDiscussion < 3) {
            userDiscussion = "Selten";
        } else if (numOfUserDiscussion < 10) {
            userDiscussion = "Gelegentlich";
        } else if (numOfUserDiscussion < 20) {
            userDiscussion = "Oft";
        }

        String selfDiscussion = "Sehr oft";
        if (numofSelfDiscussion == 0) {
            selfDiscussion = "Nie";
        } else if (numofSelfDiscussion < 10) {
            selfDiscussion = "Selten";
        } else if (numofSelfDiscussion < 30) {
            selfDiscussion = "Gelegentlich";
        } else if (numofSelfDiscussion < 100) {
            selfDiscussion = "Oft";
        }

        return new UserInfo(userid, userName, editcount, categoryCommits, avgCommits, signInDate, reputation,
                categoryEdited, blocked, userclassNumOfCommits, userclassAvgCommits, userclassRevert,
                userclassComment, userDiscussion, selfDiscussion, commitsPerCategory, abuses, abuseCount,
                numOfReverts, numOfComments, numOfUserDiscussion, numofSelfDiscussion, isBot);
    } catch (Exception e) {
        this.logger.error(e.getMessage(), e);
    }
    return null;
}

From source file:de.craftolution.craftoplugin4.modules.bot.BotConnection.java

License:MIT License

private void parse(byte[] packet) {
    String string = new String(packet, Charset.forName("UTF8"));

    JsonObject root = gson.fromJson(string, JsonObject.class);

    String packetType = root.get("packetType").getAsString();
    String platform = root.get("platform").getAsString();
    int packetId = root.get("packetId").getAsInt();
    JsonObject content = root.getAsJsonObject("content").getAsJsonObject();

    if (packetType.equals("result")) {
        ResultPacket resultPacket = new ResultPacket(packetId, platform, packetType, content);
        Result result = Result.parse(resultPacket);
        ResultBotResponse response = new ResultBotResponse(result);

        this.module.craftobot.scheduleResponse(response);
    }// ww w .  j ava  2s  . c  o  m
}

From source file:edu.mit.media.funf.config.ConfigRewriteUtil.java

License:Open Source License

/**
 * Rewrites the filter array denoted by "@filters" to a "filters" member
 * with nested filters, in the order of their appearance in the array.
 * /*from  ww w .  j av  a  2  s.com*/
 * If the baseObj is not a CompositeDataSource, converts it into one, and
 * pushing the "@probe" annotation (if it exists) to the "source" field.
 * 
 * If the entire filter class name is not specified, it will be prefixed by
 * FILTER_PREFIX.
 * 
 * eg.
 * { "@probe": ".ActivityProbe",
 *   "sensorDelay": "FASTEST",
 *   "@filters": [{ "@type": ".KeyValueFilter", "matches": { "motionState": "Driving" } },
 *                { "@type": ".ProbabilityFilter", "probability": 0.5 } ] 
 * }
 * 
 * will be rewritten to
 * 
 * { "@type": "edu.mit.media.funf.datasource.CompositeDataSource",
 *   "source": { "@probe": ".ActivityProbe", "sensorDelay": "FASTEST" },
 *   "filters": { "@type": "edu.mit.media.funf.filter.KeyValueFilter", 
 *                "matches": { "motionState": "Driving" }
 *                "listener": { "@type": "edu.mit.media.funf.filter.ProbabilityFilter", 
 *                              "probability": 0.5 } }  
 * }
 * 
 * @param baseObj
 */
public static JsonObject rewriteFiltersAnnotation(JsonObject baseObj) {
    if (baseObj == null)
        return null;

    JsonElement filterEl = baseObj.remove(FILTER);
    JsonObject filterObj = null;
    if (filterEl.isJsonArray()) {
        for (JsonElement filterIter : filterEl.getAsJsonArray()) {
            if (filterIter.isJsonObject()) {
                // Add the filter class name prefix if not specified.
                addTypePrefix(filterIter.getAsJsonObject(), FILTER_PREFIX);
            }
        }
        filterObj = new JsonObject();
        filterObj.addProperty(TYPE, COMPOSITE_FILTER);
        filterObj.add("filters", filterEl.getAsJsonArray());
    } else {
        filterObj = filterEl.getAsJsonObject();
    }

    // Add the filter class name prefix if not specified.
    addTypePrefix(filterObj.getAsJsonObject(), FILTER_PREFIX);

    // Insert the filter object denoted by "@filter" to the existing
    // "filter" field.
    insertFilter(baseObj, filterObj);

    // If the baseObj is not a data source, convert it into CompositeDataSource.
    if (!isDataSourceObject(baseObj)) {
        JsonObject dataSourceObj = new JsonObject();
        dataSourceObj.addProperty(TYPE, COMPOSITE_DS);
        dataSourceObj.add(FILTER_FIELD_NAME, baseObj.remove(FILTER_FIELD_NAME));
        if (baseObj.has(ACTION)) {
            dataSourceObj.add(ACTION, baseObj.remove(ACTION));
        }

        // The remaining fields of baseObj should be "@probe" annotation and 
        // probe parameters.
        dataSourceObj.add(SOURCE_FIELD_NAME, baseObj);
        return dataSourceObj;
    } else {
        return baseObj;
    }
}

From source file:edu.ucla.cs.scai.swim.qa.ontology.dbpedia.DBpediaEntityLookup.java

public DBpediaNamedEntity getEntityByJson(String uri, JsonObject jsonObj) {

    DBpediaNamedEntity res = new DBpediaNamedEntity();
    res.setUri(uri);/* w  w  w  .  j a v  a2  s .  c om*/

    String uri2 = URI.create(uri).toASCIIString();
    System.out.println("uri: " + uri);
    System.out.println("uri2: " + uri2);
    JsonObject jo = jsonObj.getAsJsonObject().get(uri2).getAsJsonObject();

    for (Map.Entry<String, JsonElement> e : jsonObj.entrySet()) {
        String je = e.getKey();
        if (je.contains("http://dbpedia.org/resource")) {
            if (je.equals(uri)) {
                continue;
            }
            JsonObject o = e.getValue().getAsJsonObject();
            for (Map.Entry<String, JsonElement> v : o.entrySet()) {
                String attr = v.getKey();
                if (!attr.contains("http://dbpedia.org/ontology")) {
                    continue;
                }

                String value = o.get(attr).getAsJsonArray().get(0).getAsJsonObject().get("value").getAsString();
                if (value.equals(uri)) {
                    res.rangeOfAttributes.add(attr);
                }
            }
        }
    }

    try {
        JsonArray jda = jo.get("http://www.w3.org/2000/01/rdf-schema#comment").getAsJsonArray();
        for (JsonElement jde : jda) {
            JsonObject jdo = jde.getAsJsonObject();
            if (jdo.get("lang") != null && jdo.get("lang").getAsString().equals("en")) {
                res.setDescription(jdo.get("value").getAsString());
                break;
            }
        }
    } catch (Exception e) {
    }

    try {
        JsonArray jla = jo.get("http://www.w3.org/2000/01/rdf-schema#label").getAsJsonArray();
        for (JsonElement jle : jla) {
            JsonObject jlo = jle.getAsJsonObject();
            if (jlo.get("lang") != null && jlo.get("lang").getAsString().equals("en")) {
                res.setLabel(jlo.get("value").getAsString());
                break;
            }
        }
    } catch (Exception e) {
    }

    try {
        JsonArray jpa = jo.get("http://xmlns.com/foaf/0.1/isPrimaryTopicOf").getAsJsonArray();
        for (JsonElement jpe : jpa) {
            JsonObject jpo = jpe.getAsJsonObject();
            if (jpo.get("value") != null && jpo.get("value").getAsString().contains("en.wikipedia")) {
                res.setPageUrl(jpo.get("value").getAsString());
                break;
            }
        }
    } catch (Exception e) {
    }

    try {
        JsonArray jta = jo.get("http://dbpedia.org/ontology/thumbnail").getAsJsonArray();
        for (JsonElement jte : jta) {
            JsonObject jto = jte.getAsJsonObject();
            if (jto.get("value") != null) {
                res.setThumbUrl(jto.get("value").getAsString());
                break;
            }
        }
    } catch (Exception e) {
    }

    try {
        for (Map.Entry<String, JsonElement> e : jo.entrySet()) {
            String attr = e.getKey();
            if (attr.contains("http://dbpedia.org/ontology")) {
                res.domainOfAttributes.add(attr);
            }
        }

        HashSet<DBpediaCategory> categories = new HashSet<>();
        JsonArray jta = jo.get(DBpediaOntology.TYPE_ATTRIBUTE).getAsJsonArray();
        for (JsonElement jte : jta) {
            JsonObject jto = jte.getAsJsonObject();
            JsonElement jval = jto.get("value");
            if (jval != null) {
                String catUri = jval.getAsString();
                if (!catUri.contains("http://dbpedia.org/ontology")) {
                    continue;
                }
                DBpediaCategory cat = DBpediaOntology.getInstance().categoriesByUri.get(catUri);
                if (cat != null) {
                    //keep only the lowest subclasses categories
                    //if categories c contains a subclass of cat, then superclass c is removed
                    //if categories c contains a superclass of cat, then cat is not added
                    boolean addCat = true;
                    for (Iterator<DBpediaCategory> it = categories.iterator(); it.hasNext();) {
                        DBpediaCategory c = it.next();
                        if (cat.hasAncestor(c)) {
                            it.remove(); //don't break, there could be more than one ancestor
                        } else if (c.hasAncestor(cat)) {
                            addCat = false;
                            break;
                        }
                    }
                    if (addCat) {
                        categories.add(cat);
                    }
                }
            }
        }
        res.classes.addAll(categories);
    } catch (Exception e) {
    }
    if (res.classes.isEmpty()) {
        res.classes.add(DBpediaOntology.thingCategory());
    }
    return res;
}