Example usage for com.google.gson JsonElement isJsonArray

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

Introduction

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

Prototype

public boolean isJsonArray() 

Source Link

Document

provides check for verifying if this element is an array or not.

Usage

From source file:com.qmetry.qaf.automation.gson.GsonObjectDeserializer.java

License:Open Source License

public static Object read(JsonElement in) {

    if (in.isJsonArray()) {
        List<Object> list = new ArrayList<Object>();
        JsonArray arr = in.getAsJsonArray();
        for (JsonElement anArr : arr) {
            list.add(read(anArr));/*from  w ww .jav a2  s  .  com*/
        }
        return list;
    } else if (in.isJsonObject()) {
        Map<String, Object> map = new LinkedTreeMap<String, Object>();
        JsonObject obj = in.getAsJsonObject();
        Set<Map.Entry<String, JsonElement>> entitySet = obj.entrySet();
        for (Map.Entry<String, JsonElement> entry : entitySet) {
            map.put(entry.getKey(), read(entry.getValue()));
        }
        return map;
    } else if (in.isJsonPrimitive()) {
        JsonPrimitive prim = in.getAsJsonPrimitive();
        if (prim.isBoolean()) {
            return prim.getAsBoolean();
        } else if (prim.isString()) {
            return prim.getAsString();
        } else if (prim.isNumber()) {
            if (prim.getAsString().contains("."))
                return prim.getAsDouble();
            else {
                return prim.getAsLong();
            }
        }
    }
    return null;
}

From source file:com.qmetry.qaf.automation.util.LocatorUtil.java

License:Open Source License

public static By getBy(String loc, PropertyUtil props) {
    Gson gson = new Gson();
    loc = props.getSubstitutor().replace(loc);
    loc = props.getString(loc, loc);//from   w  w w.ja v a 2s .  c  om
    JsonElement element = JSONUtil.getGsonElement(loc);
    if ((null != element) && element.isJsonObject()) {
        Object obj = gson.fromJson(element, Map.class).get("locator");

        loc = obj instanceof String ? (String) obj :

                gson.toJson(obj);
    }
    element = JSONUtil.getGsonElement(loc);
    if ((null != element) && element.isJsonArray()) {
        String[] locs = new Gson().fromJson(element, String[].class);
        return new ByAny(locs);
    }
    if (loc.startsWith("//")) {
        return By.xpath(loc);
    } else if (loc.indexOf("=") > 0) {
        String parts[] = loc.split("=", 2);
        if (parts[0].equalsIgnoreCase("key") || parts[0].equalsIgnoreCase("property")) {
            String val = props.getSubstitutor().replace(parts[1]);
            return getBy(props.getString(val, val), props);
        }
        if (parts[0].equalsIgnoreCase("jquery")) {
            return new ByJQuery(parts[1]);
        }
        if (parts[0].equalsIgnoreCase("name")) {
            return By.name(parts[1]);
        } else if (parts[0].equalsIgnoreCase("id")) {
            return By.id(parts[1]);
        } else if (parts[0].equalsIgnoreCase("xpath")) {
            return By.xpath(parts[1]);
        } else if (parts[0].equalsIgnoreCase("css")) {
            return By.cssSelector(parts[1]);
        } else if (parts[0].equalsIgnoreCase("link") || parts[0].equalsIgnoreCase("linkText")) {
            return By.linkText(parts[1]);
        } else if (parts[0].equalsIgnoreCase("partialLink") || parts[0].equalsIgnoreCase("partialLinkText")) {
            return By.partialLinkText(parts[1]);
        } else if (parts[0].equalsIgnoreCase("className")) {
            return By.className(parts[1]);
        } else if (parts[0].equalsIgnoreCase("tagName")) {
            return By.tagName(parts[1]);
        } else {
            return new ByCustom(parts[0], parts[1]);
        }
    } else {
        return By.xpath(String.format("//*[@name='%s' or @id='%s' or @value='%s']", loc, loc, loc));
    }
}

From source file:com.rackspacecloud.blueflood.inputs.handlers.HttpAggregatedMultiIngestionHandler.java

License:Apache License

public static List<AggregatedPayload> createBundleList(String json) {
    Gson gson = new Gson();
    JsonParser parser = new JsonParser();
    JsonElement element = parser.parse(json);

    if (!element.isJsonArray()) {
        throw new InvalidDataException("Invalid request body");
    }//from  w ww .j a v a2s.c om

    JsonArray jArray = element.getAsJsonArray();

    ArrayList<AggregatedPayload> bundleList = new ArrayList<AggregatedPayload>();

    for (JsonElement obj : jArray) {
        AggregatedPayload bundle = AggregatedPayload.create(obj);
        bundleList.add(bundle);
    }

    return bundleList;
}

From source file:com.razza.apps.iosched.server.schedule.model.DataExtractor.java

License:Open Source License

public JsonArray extractSessions(JsonDataSources sources) {
    if (videoSessionsById == null) {
        throw new IllegalStateException(
                "You need to extract video sessions before attempting to extract sessions");
    }//  w w  w.j a  v a  2 s.  c o  m
    if (categoryToTagMap == null) {
        throw new IllegalStateException("You need to extract tags before attempting to extract sessions");
    }

    JsonArray result = new JsonArray();
    JsonDataSource source = sources.getSource(InputJsonKeys.VendorAPISource.MainTypes.topics.name());
    if (source != null) {
        for (JsonObject origin : source) {
            if (isVideoSession(origin)) {
                // Sessions with the Video tag are processed as video library content
                continue;
            }
            if (isHiddenSession(origin)) {
                // Sessions with a "Hidden from schedule" flag should be ignored
                continue;
            }
            JsonElement title = DataModelHelper.get(origin, InputJsonKeys.VendorAPISource.Topics.title);
            // Since the CMS returns an empty keynote as a session, we need to ignore it
            if (title != null && title.isJsonPrimitive() && "keynote".equalsIgnoreCase(title.getAsString())) {
                continue;
            }
            JsonObject dest = new JsonObject();

            // Some sessions require a special ID, so we replace it here...
            if (title != null && title.isJsonPrimitive()
                    && "after hours".equalsIgnoreCase(title.getAsString())) {
                DataModelHelper.set(new JsonPrimitive("__afterhours__"), dest, OutputJsonKeys.Sessions.id);
            } else {
                DataModelHelper.set(origin, InputJsonKeys.VendorAPISource.Topics.id, dest,
                        OutputJsonKeys.Sessions.id);
            }
            DataModelHelper.set(origin, InputJsonKeys.VendorAPISource.Topics.id, dest,
                    OutputJsonKeys.Sessions.url, Converters.SESSION_URL);
            DataModelHelper.set(origin, InputJsonKeys.VendorAPISource.Topics.title, dest,
                    OutputJsonKeys.Sessions.title, obfuscate ? Converters.OBFUSCATE : null);
            DataModelHelper.set(origin, InputJsonKeys.VendorAPISource.Topics.description, dest,
                    OutputJsonKeys.Sessions.description, obfuscate ? Converters.OBFUSCATE : null);
            DataModelHelper.set(origin, InputJsonKeys.VendorAPISource.Topics.start, dest,
                    OutputJsonKeys.Sessions.startTimestamp, Converters.DATETIME);
            DataModelHelper.set(origin, InputJsonKeys.VendorAPISource.Topics.finish, dest,
                    OutputJsonKeys.Sessions.endTimestamp, Converters.DATETIME);
            DataModelHelper.set(new JsonPrimitive(isFeatured(origin)), dest,
                    OutputJsonKeys.Sessions.isFeatured);

            JsonElement documents = DataModelHelper.get(origin, InputJsonKeys.VendorAPISource.Topics.documents);
            if (documents != null && documents.isJsonArray() && documents.getAsJsonArray().size() > 0) {
                // Note that the input for SessionPhotoURL is the entity ID. We simply ignore the original
                // photo URL, because that will be processed by an offline cron script, resizing the
                // photos and saving them to a known location with the entity ID as its base name.
                DataModelHelper.set(origin, InputJsonKeys.VendorAPISource.Topics.id, dest,
                        OutputJsonKeys.Sessions.photoUrl, Converters.SESSION_PHOTO_URL);
            }

            setVideoPropertiesInSession(origin, dest);
            setRelatedContent(origin, dest);

            JsonElement mainTag = null;
            JsonElement hashtag = null;
            JsonElement mainTagColor = null;
            JsonArray categories = origin
                    .getAsJsonArray(InputJsonKeys.VendorAPISource.Topics.categoryids.name());
            JsonArray tags = new JsonArray();
            for (JsonElement category : categories) {
                JsonObject tag = categoryToTagMap.get(category.getAsString());
                if (tag != null) {
                    JsonElement tagName = DataModelHelper.get(tag, OutputJsonKeys.Tags.tag);
                    tags.add(tagName);
                    usedTags.add(tagName.getAsString());

                    if (mainTag == null) {
                        // check if the tag is from a "default" category. For example, if THEME is the default
                        // category, all sessions will have a "mainTag" property set to the first tag of type THEME
                        JsonElement tagCategory = DataModelHelper.get(tag, OutputJsonKeys.Tags.category); // THEME, TYPE or TOPIC
                        if (tagCategory.equals(mainCategory)) {
                            mainTag = tagName;
                            mainTagColor = DataModelHelper.get(tag, OutputJsonKeys.Tags.color);
                        }
                        if (hashtag == null && DataModelHelper.isHashtag(tag)) {
                            hashtag = DataModelHelper.get(tag, OutputJsonKeys.Tags.hashtag);
                            if (hashtag == null || hashtag.getAsString() == null
                                    || hashtag.getAsString().isEmpty()) {
                                // If no hashtag set in the tagsconf file, we will convert the tagname to find one:
                                hashtag = new JsonPrimitive(
                                        DataModelHelper.get(tag, OutputJsonKeys.Tags.name, Converters.TAG_NAME)
                                                .getAsString().toLowerCase());
                            }
                        }
                    }
                }
            }
            DataModelHelper.set(tags, dest, OutputJsonKeys.Sessions.tags);
            if (mainTag != null) {
                DataModelHelper.set(mainTag, dest, OutputJsonKeys.Sessions.mainTag);
            }
            if (mainTagColor != null) {
                DataModelHelper.set(mainTagColor, dest, OutputJsonKeys.Sessions.color);
            }
            if (hashtag != null) {
                DataModelHelper.set(hashtag, dest, OutputJsonKeys.Sessions.hashtag);
            }

            JsonArray speakers = DataModelHelper.getAsArray(origin,
                    InputJsonKeys.VendorAPISource.Topics.speakerids);
            if (speakers != null)
                for (JsonElement speaker : speakers) {
                    String speakerId = speaker.getAsString();
                    usedSpeakers.add(speakerId);
                }
            DataModelHelper.set(speakers, dest, OutputJsonKeys.Sessions.speakers);

            JsonArray sessions = origin.getAsJsonArray(InputJsonKeys.VendorAPISource.Topics.sessions.name());
            if (sessions != null && sessions.size() > 0) {
                String roomId = DataModelHelper
                        .get(sessions.get(0).getAsJsonObject(), InputJsonKeys.VendorAPISource.Sessions.roomid)
                        .getAsString();
                roomId = Config.ROOM_MAPPING.getRoomId(roomId);
                DataModelHelper.set(new JsonPrimitive(roomId), dest, OutputJsonKeys.Sessions.room);

                // captions URL is set based on the session room, so keep it here.
                String captionsURL = Config.ROOM_MAPPING.getCaptions(roomId);
                if (captionsURL != null) {
                    DataModelHelper.set(new JsonPrimitive(captionsURL), dest,
                            OutputJsonKeys.Sessions.captionsUrl);
                }
            }

            if (Config.DEBUG_FIX_DATA) {
                DebugDataExtractorHelper.changeSession(dest, usedTags);
            }
            result.add(dest);
        }
    }
    return result;
}

From source file:com.razza.apps.iosched.server.schedule.model.DataExtractor.java

License:Open Source License

@Deprecated
private void setRelatedVideos(JsonObject origin, JsonObject dest) {
    JsonArray related = DataModelHelper.getAsArray(origin, InputJsonKeys.VendorAPISource.Topics.related);
    if (related == null) {
        return;/*from  w  ww .j a  v a2  s  .  c  o  m*/
    }
    for (JsonElement el : related) {
        if (!el.isJsonObject()) {
            continue;
        }
        JsonObject obj = el.getAsJsonObject();
        if (!obj.has("name") || !obj.has("values")) {
            continue;
        }

        if (InputJsonKeys.VendorAPISource.Topics.RELATED_NAME_VIDEO
                .equals(obj.getAsJsonPrimitive("name").getAsString())) {

            JsonElement values = obj.get("values");
            if (!values.isJsonArray()) {
                continue;
            }

            // As per the data specification, related content is formatted as
            // "video1 title1\nvideo2 title2\n..."
            StringBuilder relatedContentStr = new StringBuilder();
            for (JsonElement value : values.getAsJsonArray()) {
                String relatedSessionId = value.getAsString();
                JsonObject relatedVideo = videoSessionsById.get(relatedSessionId);
                if (relatedVideo != null) {
                    JsonElement vid = DataModelHelper.get(relatedVideo, OutputJsonKeys.VideoLibrary.vid);
                    JsonElement title = DataModelHelper.get(relatedVideo, OutputJsonKeys.VideoLibrary.title);
                    if (vid != null && title != null) {
                        relatedContentStr.append(vid.getAsString()).append(" ").append(title.getAsString())
                                .append("\n");
                    }
                }
            }
            DataModelHelper.set(new JsonPrimitive(relatedContentStr.toString()), dest,
                    OutputJsonKeys.Sessions.relatedContent);
        }
    }
}

From source file:com.razza.apps.iosched.server.schedule.model.DataExtractor.java

License:Open Source License

private void setRelatedContent(JsonObject origin, JsonObject dest) {
    JsonArray related = DataModelHelper.getAsArray(origin, InputJsonKeys.VendorAPISource.Topics.related);
    JsonArray outputArray = new JsonArray();

    if (related == null) {
        return;//from w w w.j av  a2  s . c o  m
    }
    for (JsonElement el : related) {
        if (!el.isJsonObject()) {
            continue;
        }
        JsonObject obj = el.getAsJsonObject();
        if (!obj.has("name") || !obj.has("values")) {
            continue;
        }

        if (InputJsonKeys.VendorAPISource.Topics.RELATED_NAME_SESSIONS
                .equals(obj.getAsJsonPrimitive("name").getAsString())) {

            JsonElement values = obj.get("topics");
            if (!values.isJsonArray()) {
                continue;
            }

            // As per the data specification, related content is formatted as
            // "video1 title1\nvideo2 title2\n..."
            for (JsonElement topic : values.getAsJsonArray()) {
                if (!topic.isJsonObject()) {
                    continue;
                }

                JsonObject topicObj = topic.getAsJsonObject();

                String id = DataModelHelper.get(topicObj, InputJsonKeys.VendorAPISource.RelatedTopics.id)
                        .getAsString();
                String title = DataModelHelper.get(topicObj, InputJsonKeys.VendorAPISource.RelatedTopics.title)
                        .getAsString();

                if (id != null && title != null) {
                    JsonObject outputObj = new JsonObject();
                    DataModelHelper.set(new JsonPrimitive(id), outputObj, OutputJsonKeys.RelatedContent.id);
                    DataModelHelper.set(new JsonPrimitive(title), outputObj,
                            OutputJsonKeys.RelatedContent.title);
                    outputArray.add(outputObj);
                }
            }
            DataModelHelper.set(outputArray, dest, OutputJsonKeys.Sessions.relatedContent);
        }
    }
}

From source file:com.replaymod.replaystudio.launcher.Launcher.java

License:MIT License

public void parseConfig(Studio studio, JsonObject root) {
    JsonArray instructions = root.getAsJsonArray("Instructions");
    for (JsonElement e : instructions) {
        JsonObject o = e.getAsJsonObject();
        Instruction instruction;//from  w  w  w  .  java  2 s .  com
        switch (o.get("Name").getAsString().toLowerCase()) {
        case "split":
            if (o.get("at").isJsonArray()) {
                List<Long> at = new ArrayList<>();
                Iterables.addAll(at,
                        Iterables.transform(o.getAsJsonArray("at"), (e1) -> timeStampToMillis(e1.toString())));
                instruction = new SplitInstruction(Longs.toArray(at));
            } else {
                instruction = new SplitInstruction(timeStampToMillis(o.get("at").toString()));
            }
            break;
        case "append":
            instruction = new AppendInstruction();
            break;
        case "squash":
            instruction = new SquashInstruction(studio);
            break;
        case "copy":
            instruction = new CopyInstruction();
            break;
        case "filter":
            Filter filter = studio.loadFilter(o.get("Filter").toString());
            instruction = new FilterInstruction(studio, filter, o.getAsJsonObject("Config"));
            break;
        default:
            System.out.println("Warning: Unrecognized instruction in json config: " + o.get("Name"));
            continue;
        }

        JsonElement inputs = o.get("Inputs");
        if (inputs.isJsonArray()) {
            for (JsonElement e1 : inputs.getAsJsonArray()) {
                instruction.getInputs().add(e1.getAsString());
            }
        } else {
            instruction.getInputs().add(inputs.getAsString());
        }

        JsonElement outputs = o.get("Outputs");
        if (outputs.isJsonArray()) {
            for (JsonElement e1 : outputs.getAsJsonArray()) {
                instruction.getOutputs().add(e1.getAsString());
            }
        } else {
            instruction.getOutputs().add(outputs.getAsString());
        }

        this.instructions.add(instruction);
    }

    // Get all inputs
    JsonObject inputs = root.getAsJsonObject("Inputs");
    for (Map.Entry<String, JsonElement> e : inputs.entrySet()) {
        this.inputs.put(e.getKey(), e.getValue().getAsString());
    }

    // Get all outputs
    JsonObject outputs = root.getAsJsonObject("Outputs");
    for (Map.Entry<String, JsonElement> e : outputs.entrySet()) {
        this.outputs.put(e.getKey(), e.getValue().getAsString());
    }

    // Calculate all pipes
    for (Instruction instruction : this.instructions) {
        pipes.addAll(instruction.getInputs());
        pipes.addAll(instruction.getOutputs());
    }
    pipes.removeAll(this.inputs.keySet());
    pipes.removeAll(this.outputs.keySet());
}

From source file:com.rw.legion.input.JsonRecordReader.java

License:Apache License

/**
 * Recursively traverses all levels of a JSON object and adds their contents
 * to the <code>LegionRecord</code>.
 * //  ww w .  j  ava 2  s .co m
 * @param location  The JSON path leading up to the current depth level.
 * @param element  An element that appears at the current depth level.
 */
private void traverseJson(String location, JsonElement element) {
    if (element.isJsonNull()) {
        record.setField(location, "");
    } else if (element.isJsonPrimitive()) {
        record.setField(location, element.getAsString());
    } else if (element.isJsonObject()) {
        for (Map.Entry<String, JsonElement> entry : element.getAsJsonObject().entrySet()) {
            traverseJson(location + "." + entry.getKey(), entry.getValue());
        }
    } else if (element.isJsonArray()) {
        for (int i = 0; i < element.getAsJsonArray().size(); i++) {
            traverseJson(location + "[" + new Integer(i).toString() + "]", element.getAsJsonArray().get(i));
        }
    }
}

From source file:com.ryanantkowiak.jOptionsHouseAPI.JsonUtilities.java

License:Open Source License

/**
 * Recursively print the contents of a GSON JSON element.
 * //  w  w w .j  av  a2  s . com
 * @param element   the GSON JSON element to be printed
 * @param prefix   output will be prefixed with this string
 */
public static void printJson(JsonElement element, String prefix) {
    if (null == prefix || prefix.isEmpty()) {
        prefix = "";
    }

    if (null == element || element.isJsonNull()) {
        System.out.println(prefix + " [null]");
        return;
    }

    else if (element.isJsonPrimitive()) {
        JsonPrimitive p = element.getAsJsonPrimitive();
        if (p.isBoolean()) {
            System.out.println(prefix + " [bool=" + p.getAsBoolean() + "]");
        } else if (p.isString()) {
            System.out.println(prefix + " [string='" + p.getAsString() + "']");
        } else if (p.isNumber()) {
            System.out.println(prefix + " [number=" + p.getAsDouble() + "]");
        }
    }

    else if (element.isJsonArray()) {
        System.out.println(prefix + " [array]");
        for (int i = 0; i < element.getAsJsonArray().size(); ++i) {
            String newPrefix = prefix + "[" + i + "]";
            printJson(element.getAsJsonArray().get(i), newPrefix);
        }
    }

    else if (element.isJsonObject()) {
        JsonObject obj = element.getAsJsonObject();

        for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
            String key = entry.getKey();
            JsonElement value = entry.getValue();
            String newPrefix = prefix + "." + key;
            printJson(value, newPrefix);
        }
    }

}

From source file:com.samsung.sjs.constraintsolver.OperatorModel.java

License:Apache License

public OperatorModel() {
    Reader reader = new InputStreamReader(OperatorModel.class.getResourceAsStream("/operators.json"));

    JsonParser parser = new JsonParser();
    JsonElement element = parser.parse(reader);
    if (element.isJsonArray()) {
        JsonArray jsa = element.getAsJsonArray();
        for (Iterator<JsonElement> it = jsa.iterator(); it.hasNext();) {
            JsonElement operatorEntry = it.next();
            if (operatorEntry.isJsonObject()) {
                JsonObject jso = operatorEntry.getAsJsonObject();
                for (Entry<String, JsonElement> entry : jso.entrySet()) {
                    String operatorName = entry.getKey();
                    JsonElement value = entry.getValue();
                    if (value.isJsonArray()) {
                        JsonArray elements = value.getAsJsonArray();
                        for (Iterator<JsonElement> it2 = elements.iterator(); it2.hasNext();) {
                            JsonElement element2 = it2.next();
                            if (element2.isJsonObject()) {
                                JsonObject object = element2.getAsJsonObject();
                                JsonElement jsonElement = object.get("operand");
                                if (jsonElement != null) {
                                    String op = jsonElement.getAsString();
                                    String result = object.get("result").getAsString();
                                    String prefix = object.get("isprefix").getAsString();
                                    boolean isPrefix;
                                    if (prefix.equals("true")) {
                                        isPrefix = true;
                                    } else if (prefix.equals("false")) {
                                        isPrefix = false;
                                    } else {
                                        throw new Error(
                                                "unrecognized value for prefix status of unary operator: "
                                                        + prefix);
                                    }//from ww  w  .j  a  v  a  2 s .  com
                                    if (!unaryOperatorMap.containsKey(operatorName)) {
                                        unaryOperatorMap.put(operatorName, new ArrayList<UnOpTypeCase>());
                                    }
                                    List<UnOpTypeCase> cases = unaryOperatorMap.get(operatorName);
                                    cases.add(new UnOpTypeCase(toType(op), toType(result), isPrefix));
                                } else {
                                    String left = object.get("left").getAsString();
                                    String right = object.get("right").getAsString();
                                    String result = object.get("result").getAsString();
                                    if (!infixOperatorMap.containsKey(operatorName)) {
                                        infixOperatorMap.put(operatorName, new ArrayList<InfixOpTypeCase>());
                                    }
                                    List<InfixOpTypeCase> cases = infixOperatorMap.get(operatorName);
                                    cases.add(new InfixOpTypeCase(toType(left), toType(right), toType(result)));
                                }
                            }
                        }
                    }
                }
            } else {
                throw new Error("JsonObject expected");
            }
        }
    } else {
        throw new Error("JsonArray expected");
    }
}