Example usage for com.google.gson JsonElement getAsJsonArray

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

Introduction

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

Prototype

public JsonArray getAsJsonArray() 

Source Link

Document

convenience method to get this element as a JsonArray .

Usage

From source file:com.nextdoor.bender.operation.json.key.KeyNameReplacementOperation.java

License:Apache License

protected void perform(JsonObject obj) {
    Set<Entry<String, JsonElement>> entries = obj.entrySet();
    Set<Entry<String, JsonElement>> orgEntries = new HashSet<Entry<String, JsonElement>>(entries);

    for (Entry<String, JsonElement> entry : orgEntries) {
        JsonElement val = entry.getValue();

        /*/*ww w.  ja  v a  2s  . c  o m*/
         * See if key matches. If it does then drop or rename. Otherwise keep recursing.
         */
        Matcher m = this.pattern.matcher(entry.getKey());
        boolean found = m.find();
        if (found) {
            /*
             * If instructed to drop then remove and continue. Otherwise remove and later rename;
             */
            obj.remove(entry.getKey());
            if (this.drop) {
                continue;
            }

            /*
             * Rename
             */
            if (val.isJsonPrimitive()) {
                obj.add(m.replaceAll(this.replacement), val);
            } else if (val.isJsonObject()) {
                obj.add(m.replaceAll(this.replacement), val);
                perform(val.getAsJsonObject());
            } else if (val.isJsonArray()) {
                JsonArray arr = val.getAsJsonArray();

                arr.forEach(item -> {
                    performOnArray(item);
                });
                obj.add(m.replaceAll(this.replacement), val);
            }
            continue;
        }

        /*
         * Keep recursing
         */
        if (val.isJsonObject()) {
            perform(val.getAsJsonObject());
        } else if (val.isJsonArray()) {
            JsonArray arr = val.getAsJsonArray();
            arr.forEach(item -> {
                performOnArray(item);
            });
        }

    }
}

From source file:com.nextdoor.bender.operation.json.key.LowerCaseKeyOperation.java

License:Apache License

protected void perform(JsonObject obj) {
    Set<Entry<String, JsonElement>> entries = obj.entrySet();
    Set<Entry<String, JsonElement>> orgEntries = new HashSet<Entry<String, JsonElement>>(entries);

    for (Entry<String, JsonElement> entry : orgEntries) {

        JsonElement val = entry.getValue();
        obj.remove(entry.getKey());/* w ww . j av a 2s  . c  o  m*/
        String key = entry.getKey().toLowerCase();

        if (val.isJsonPrimitive()) {
            obj.add(key, val);
        } else if (val.isJsonObject()) {
            obj.add(key, val);
            perform(val.getAsJsonObject());
        } else if (val.isJsonArray()) {
            obj.add(key, val);

            val.getAsJsonArray().forEach(elm -> {
                if (elm.isJsonObject()) {
                    perform((JsonObject) elm);
                }
            });
        }
    }
}

From source file:com.orange.homenap.gson.ActionListAdapter.java

License:Open Source License

@Override
public List<Action> deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context)
        throws JsonParseException {
    JsonArray array = jsonElement.getAsJsonArray();
    List<Action> actionList = new ArrayList<Action>();

    for (int i = 0; i < array.size(); i++) {
        JsonElement element = array.get(i);
        JsonObject jsonObject = element.getAsJsonObject();

        Action action = context.deserialize(jsonObject, Action.class);
        action.setProperties(new HashMap<String, Object>());

        if (!jsonObject.get("properties").toString().equals("{}")) {
            //System.out.println(jsonObject.get("properties").toString());

            JsonObject properties = jsonObject.get("properties").getAsJsonObject();

            /*List<String> resources;
            JsonArray resourcesArray = properties.get("resources").getAsJsonArray();
                    /* www. ja  v  a2 s  .  c  o m*/
            for(int j = 0; j < resourcesArray.size(); j++)
            resources.add(context.deserialize())
            resources.add(resourcesArray.get(j).));
            */
            List<String> resources = context.deserialize(properties.get("resources").getAsJsonArray(),
                    (new TypeToken<List<String>>() {
                    }).getType());

            action.getProperties().put("resources", resources);

            List<Component> components = context.deserialize(properties.get("components"),
                    (new TypeToken<List<Component>>() {
                    }).getType());

            action.getProperties().put("components", components);

            List<Architecture> architectures = context.deserialize(properties.get("architectures"),
                    (new TypeToken<List<Architecture>>() {
                    }).getType());

            action.getProperties().put("architectures", architectures);

            List<Device> devices = context.deserialize(properties.get("devices"),
                    (new TypeToken<List<Device>>() {
                    }).getType());

            action.getProperties().put("devices", devices);
        }

        actionList.add(action);
    }

    return actionList;
}

From source file:com.parallax.client.cloudsession.CloudSessionAuthenticationTokenService.java

/**
 *
 * @param idUser//from   www. jav a  2s.c o m
 * @param browser
 * @param ipAddress
 * @return
 * @throws ServerException
 */
public List<String> getTokens(Long idUser, String browser, String ipAddress) throws ServerException {

    LOG.debug("Contacting endpoint '/authtoken/tokens");

    try {
        Map<String, String> data = new HashMap<>();
        data.put("browser", browser);
        data.put("ipAddress", ipAddress);

        HttpRequest request = HttpRequest.post(getUrl("/authtoken/tokens/" + idUser)).header("server", SERVER)
                .form(data);

        if (request.ok()) {
            String response = request.body();
            JsonElement jelement = new JsonParser().parse(response);
            JsonArray jsonTokens = jelement.getAsJsonArray();
            List<String> tokens = new ArrayList<>();

            for (JsonElement token : jsonTokens) {
                tokens.add(token.getAsString());
            }

            return tokens;
        }
    } catch (HttpRequest.HttpRequestException hre) {
        LOG.error("Inter service error", hre);
        throw new ServerException(hre);
    } catch (JsonSyntaxException jse) {
        LOG.error("Json syntax error: {}", jse.getMessage());
        throw new ServerException(jse);
    }

    return null;
}

From source file:com.pearson.pdn.learningstudio.content.ContentService.java

License:Apache License

/**
 * Get links details from a specific item for a course with
 * Get /courses/{courseId}/items/{itemId}
 * using OAuth2 as a student, teacher or teaching assistant
 * //  w w w .j a va  2 s  .c  o m
 * Example JSON structure: (Multimedia item)
 * 
 * { 
 *   "details": { 
 *     "access": {...}, 
 *     "schedule": {...}, 
 *     "self": {...},
 *     "selfType": "textMultimedias"
 *   }
 * }
 * 
 * @param courseId   ID of the course
 * @param itemId   ID of the item
 * @return   Response object with details of status and content
 * @throws IOException
 */
public Response getItemLinkDetails(String courseId, String itemId) throws IOException {
    Response response = getItem(courseId, itemId);
    if (response.isError()) {
        return response;
    }

    // should only be one item here, but it is returned in an array for some reason
    String courseItemsJson = response.getContent();
    JsonObject json = this.jsonParser.parse(courseItemsJson).getAsJsonObject();
    JsonArray items = json.get("items").getAsJsonArray();
    JsonObject detail = new JsonObject();

    // again, only one element expected here...
    Iterator<JsonElement> itemIterator = items.iterator();
    if (itemIterator.hasNext()) {
        JsonObject item = itemIterator.next().getAsJsonObject();
        JsonArray links = item.get("links").getAsJsonArray();

        for (Iterator<JsonElement> linkIter = links.iterator(); linkIter.hasNext();) {
            JsonObject link = linkIter.next().getAsJsonObject();
            String relativeUrl = this.getRelativePath(link.get("href").getAsString());

            response = doMethod(HttpMethod.GET, relativeUrl, NO_CONTENT);
            if (response.isError()) {
                return response;
            }

            JsonElement linkElement = this.jsonParser.parse(response.getContent());

            JsonElement title = link.get("title");
            // rel on link varies, so identify self by missing title
            if (title == null) {
                Map.Entry<String, JsonElement> self = linkElement.getAsJsonObject().entrySet().iterator()
                        .next();

                linkElement = self.getValue();
                // content items like to return a single resource in an array sometimes
                if (linkElement.isJsonArray()) {
                    linkElement = linkElement.getAsJsonArray().get(0);
                }

                detail.add("self", linkElement);
                detail.addProperty("selfType", self.getKey());
            } else {
                // remove the first layer wrapper. it's just repetitive
                linkElement = linkElement.getAsJsonObject().get(title.getAsString());
                detail.add(title.getAsString(), linkElement);
            }
        }

        JsonObject detailWrapper = new JsonObject();
        detailWrapper.add("details", detail);

        response.setContent(this.gson.toJson(detailWrapper));
    } else {
        // this should never happen, but it should be detected if it does
        throw new RuntimeException("Unexpected condition in library: No items");
    }

    return response;
}

From source file:com.photon.phresco.framework.impl.CIManagerImpl.java

License:Apache License

private JsonArray getBuildsArray(CIJob job) throws PhrescoException {
    try {// ww w  .  j av a 2 s  .c  o m
        String jenkinsUrl = "http://" + job.getJenkinsUrl() + ":" + job.getJenkinsPort() + "/ci/";
        String jobNameUtf8 = job.getName().replace(" ", "%20");
        String buildsJsonUrl = jenkinsUrl + "job/" + jobNameUtf8 + "/api/json";
        String jsonResponse = getJsonResponse(buildsJsonUrl);

        JsonParser parser = new JsonParser();
        JsonElement jsonElement = parser.parse(jsonResponse);
        JsonObject jsonObject = jsonElement.getAsJsonObject();
        JsonElement element = jsonObject.get(FrameworkConstants.CI_JOB_JSON_BUILDS);

        JsonArray jsonArray = element.getAsJsonArray();

        return jsonArray;
    } catch (Exception e) {
        throw new PhrescoException(e);

    }
}

From source file:com.photon.phresco.impl.HtmlApplicationProcessor.java

License:Apache License

private List<Configuration> getConfiguration(File jsonFile, String envName, String componentName)
        throws PhrescoException {
    FileReader reader = null;/*from  w  w w. j a  va  2  s .c o  m*/
    try {
        reader = new FileReader(jsonFile);
        JsonParser parser = new JsonParser();
        Object obj = parser.parse(reader);
        JsonObject jsonObject = (JsonObject) obj;
        List<Configuration> configurations = new ArrayList<Configuration>();
        Configuration configuration = new Configuration();
        Properties properties = new Properties();
        Set<Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
        for (Entry<String, JsonElement> entry : entrySet) {
            JsonElement value = entry.getValue();
            JsonArray jsonArray = value.getAsJsonArray();
            for (JsonElement jsonElement : jsonArray) {
                JsonObject asJsonObject = jsonElement.getAsJsonObject();
                JsonElement name = asJsonObject.get(Constants.NAME);
                if (name.getAsString().equals(envName)) {
                    JsonElement components = asJsonObject.get(Constants.COMPONENTS);
                    JsonObject asJsonObj = components.getAsJsonObject();
                    Set<Entry<String, JsonElement>> parentEntrySet = asJsonObj.entrySet();
                    for (Entry<String, JsonElement> entry1 : parentEntrySet) {
                        String key = entry1.getKey();
                        if (key.equalsIgnoreCase(componentName)) {
                            JsonObject valueJsonObj = entry1.getValue().getAsJsonObject();
                            Set<Entry<String, JsonElement>> valueEntrySet = valueJsonObj.entrySet();
                            for (Entry<String, JsonElement> valueEntry : valueEntrySet) {
                                String key1 = valueEntry.getKey();
                                JsonElement value1 = valueEntry.getValue();
                                properties.setProperty(key1, value1.getAsString());
                            }
                        }
                    }
                    configuration.setProperties(properties);
                    configurations.add(configuration);
                    return configurations;
                }
            }
        }
    } catch (Exception e) {
        throw new PhrescoException(e);
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (IOException e) {
            throw new PhrescoException(e);
        }
    }

    return null;
}

From source file:com.plnyyanks.frcnotebook.database.DatabaseHandler.java

License:Open Source License

public void importDatabase(JsonObject data) {
    if (data == null || data.equals(new JsonObject()))
        return;//from  www  .  j av a  2  s  .  com
    JsonElement e;

    e = data.get(TABLE_EVENTS);
    if (e != null)
        importEvents(e.getAsJsonArray());

    e = data.get(TABLE_MATCHES);
    if (e != null)
        importMatches(e.getAsJsonArray());

    e = data.get(TABLE_TEAMS);
    if (e != null)
        importTeams(e.getAsJsonArray());

    e = data.get(TABLE_NOTES);
    if (e != null)
        importNotes(e.getAsJsonArray());

    if (tableExists(TABLE_PREDEF_NOTES)) {
        try {
            e = data.get(TABLE_PREDEF_NOTES);
            if (e != null)
                importDefNotes(e.getAsJsonArray());
        } catch (Exception ex) {

        }
    }
}

From source file:com.podio.sdk.push.FayePushClient.java

License:Open Source License

private HashMap<String, ArrayList<Event>> parseEventData(String json) {
    HashMap<String, ArrayList<Event>> result = new HashMap<String, ArrayList<Event>>();

    if (Utils.isEmpty(json)) {
        return result;
    }// www. j  av a2  s .c  om

    // Parse the root json element.
    JsonParser jsonParser = new JsonParser();
    JsonElement root = jsonParser.parse(json);
    JsonArray jsonElements;

    // Make sure we're always operating on an array of objects.
    if (root.isJsonArray()) {
        jsonElements = root.getAsJsonArray();
    } else if (root.isJsonObject()) {
        jsonElements = new JsonArray();
        jsonElements.add(root.getAsJsonObject());
    } else {
        return result;
    }

    JsonObject jsonObject;
    Gson gson = new Gson();

    // Search for all data bearing event objects.
    for (JsonElement jsonElement : jsonElements) {
        if (jsonElement.isJsonObject()) {
            jsonObject = jsonElement.getAsJsonObject();

            if (jsonObject.has("channel") && jsonObject.has("data")) {
                JsonObject fayeData = getJsonObject(jsonObject, "data");
                JsonObject podioData = getJsonObject(fayeData, "data");

                String key = getString(jsonObject, "channel");
                String type = getString(podioData, "event");

                if (Utils.notAnyEmpty(key, type)) {
                    try {
                        Event.Type eventType = Event.Type.valueOf(type);
                        Event event = gson.fromJson(podioData, eventType.getClassObject());

                        if (result.containsKey(key)) {
                            result.get(key).add(event);
                        } else {
                            ArrayList<Event> events = new ArrayList<Event>();
                            events.add(event);
                            result.put(key, events);
                        }
                    } catch (NullPointerException e) {
                        callbackManager.deliverError(e);
                    } catch (IllegalArgumentException e) {
                        callbackManager.deliverError(e);
                    } catch (JsonSyntaxException e) {
                        callbackManager.deliverError(e);
                    }
                }
            }
        }
    }

    return result;
}

From source file:com.podio.sdk.push.PushRequest.java

License:Open Source License

private static Status parseStatus(String json) {
    if (Utils.isEmpty(json)) {
        status = new Status(); // Defaults to "unknown error" status.
        return status;
    }// www  . j a  va 2s . c  o  m

    // Parse the json string into an object tree.
    JsonParser jsonParser = new JsonParser();
    JsonElement jsonElement = jsonParser.parse(json);
    JsonArray jsonArray;

    // Make a general data structure (a JsonArray) to search for the
    // first available status object (sometimes the API delivers the
    // Status object on its own, and sometimes in an array).
    if (jsonElement.isJsonArray()) {
        jsonArray = jsonElement.getAsJsonArray();
    } else {
        jsonArray = new JsonArray();
        jsonArray.add(jsonElement);
    }

    // Now try to find the first available Status JsonObject which
    // meets our minimum criteria.
    int size = jsonArray.size();

    for (int i = 0; i < size; i++) {
        jsonElement = jsonArray.get(i);

        if (jsonElement.isJsonObject()) {
            JsonObject jsonObject = jsonElement.getAsJsonObject();

            if (jsonObject.has("clientId") && jsonObject.has("channel") && jsonObject.has("successful")) {
                status = (new Gson()).fromJson(jsonObject, Status.class);

                if (status.hasAdvice()) {
                    advice = status.advice();
                }

                break;
            }
        }
    }

    return status;
}