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.redhat.thermostat.gateway.service.wp.JVMParser.java

License:Open Source License

void parse(String contentResponse, String sourceURL, List<VM> result) throws Exception {

    JsonParser parser = new JsonParser();
    JsonObject json = (JsonObject) parser.parse(contentResponse);
    JsonElement response = json.get("response");

    JsonArray allData = response.getAsJsonArray();
    for (JsonElement entry : allData) {

        json = (JsonObject) parser.parse(entry.toString());
        if (!json.has("vmId") || !json.has("agentId")) {
            continue;
        }//from   w  ww  . j a  va  2 s. c o  m

        String vmId = json.get("vmId").getAsString();
        String agentId = json.get("agentId").getAsString();

        result.add(new VM(vmId, agentId, sourceURL));
    }
}

From source file:com.remediatetheflag.global.actions.auth.management.rtfadmin.AddExerciseAction.java

License:Apache License

@Override
public void doAction(HttpServletRequest request, HttpServletResponse response) throws Exception {

    JsonObject json = (JsonObject) request.getAttribute(Constants.REQUEST_JSON);
    User sessionUser = (User) request.getSession().getAttribute(Constants.ATTRIBUTE_SECURITY_CONTEXT);

    JsonElement titleElement = json.get(Constants.ACTION_PARAM_TITLE);
    JsonElement topicsElement = json.get(Constants.ACTION_PARAM_TOPICS);
    JsonElement descriptionElement = json.get(Constants.ACTION_PARAM_DESCRIPTION);
    JsonElement difficultyElement = json.get(Constants.ACTION_PARAM_DIFFICULTY);
    JsonElement technologyElement = json.get(Constants.ACTION_PARAM_TECHNOLOGY);
    JsonElement durationElement = json.get(Constants.ACTION_PARAM_DURATION);
    JsonElement trophyTitleElement = json.get(Constants.ACTION_PARAM_TROPHY_TITLE);
    JsonElement trophyDescriptionElement = json.get(Constants.ACTION_PARAM_TROPHY_DESCRIPTION);
    JsonElement statusElement = json.get(Constants.ACTION_PARAM_STATUS);
    JsonElement typeElement = json.get(Constants.ACTION_PARAM_TYPE);
    JsonElement authorElement = json.get(Constants.ACTION_PARAM_AUTHOR);

    AvailableExercise exercise = new AvailableExercise();
    exercise.setDescription(descriptionElement.getAsString());
    exercise.setDifficulty(difficultyElement.getAsString());
    exercise.setDuration(durationElement.getAsInt());
    exercise.setTitle(titleElement.getAsString());
    exercise.setSubtitle(topicsElement.getAsString());
    exercise.setTechnology(technologyElement.getAsString());
    exercise.setStatus(AvailableExerciseStatus.getStatusFromStatusCode(statusElement.getAsInt()));
    exercise.setAuthor(authorElement.getAsString());
    exercise.setUuid(UUID.randomUUID().toString());
    exercise.setVersion(0);/*from   w  ww .jav a  2s. c o  m*/

    AvailableExerciseType validType = AvailableExerciseType.getStatusFromName(typeElement.getAsString());

    if (validType == null)
        validType = AvailableExerciseType.BOTH;
    exercise.setExerciseType(validType);

    Trophy trophy = new Trophy();
    trophy.setDescription(trophyDescriptionElement.getAsString());
    trophy.setName(trophyTitleElement.getAsString());
    trophy.setTechnology(exercise.getTechnology());
    exercise.setTrophy(trophy);

    JsonElement flags = json.get(Constants.ACTION_PARAM_FLAGS_LIST);
    JsonElement infos = json.get(Constants.ACTION_PARAM_INFO_LIST);
    JsonElement resources = json.get(Constants.ACTION_PARAM_RESOURCE_LIST);

    JsonElement referenceFile = json.get(Constants.ACTION_PARAM_REFERENCE_FILE);
    if (null != referenceFile) {
        JsonObject referenceFileObj = referenceFile.getAsJsonObject();
        String tmpReferenceFileString = referenceFileObj.get(Constants.ACTION_PARAM_DATA).getAsString();
        byte[] tmpReferenceFile = null;
        try {
            tmpReferenceFileString = tmpReferenceFileString.replaceFirst("(.*);base64,", "");
            tmpReferenceFile = Base64.decodeBase64(tmpReferenceFileString);
        } catch (Exception e) {
            logger.warn("ReferenceFile Parsing error for user " + sessionUser.getIdUser()
                    + " in adding exercise " + titleElement.getAsString() + " due to: " + e.getMessage(),
                    response);
        }
        if (null != tmpReferenceFile && tmpReferenceFile.length != 0) {
            AvailableExerciseReferenceFile refFile = new AvailableExerciseReferenceFile();
            refFile.setFile(tmpReferenceFile);
            refFile.setFilename(referenceFileObj.get(Constants.ACTION_PARAM_NAME).getAsString());
            exercise.setReferenceFile(refFile);
            exercise.setReferenceFileAvailable(true);
        } else {
            exercise.setReferenceFileAvailable(false);
        }
    } else {
        exercise.setReferenceFileAvailable(false);
    }

    JsonElement solutionFile = json.get(Constants.ACTION_PARAM_SOLUTION_FILE);
    JsonObject solutionFileObj = solutionFile.getAsJsonObject();
    String tmpSolutionFileString = solutionFileObj.get(Constants.ACTION_PARAM_DATA).getAsString();
    byte[] tmpSolutioneFile = null;
    try {
        tmpSolutionFileString = tmpSolutionFileString.replaceFirst("(.*);base64,", "");
        tmpSolutioneFile = Base64.decodeBase64(tmpSolutionFileString);
    } catch (Exception e) {
        MessageGenerator.sendErrorMessage("solutioneFileParsing", response);
        return;
    }
    if (null == tmpSolutioneFile || tmpSolutioneFile.length == 0) {
        MessageGenerator.sendErrorMessage("solutioneFileEmpty", response);
        return;
    }

    AvailableExerciseSolutionFile solFile = new AvailableExerciseSolutionFile();
    solFile.setFilename(solutionFileObj.get(Constants.ACTION_PARAM_NAME).getAsString());
    solFile.setFile(tmpSolutioneFile);
    exercise.setSolutionFile(solFile);

    Map<String, String> resourceMap = new HashMap<String, String>();
    for (JsonElement resourceElem : resources.getAsJsonArray()) {
        JsonObject tmpResource = resourceElem.getAsJsonObject();
        resourceMap.put(tmpResource.get(Constants.ACTION_PARAM_TITLE).getAsString(),
                tmpResource.get(Constants.ACTION_PARAM_URL).getAsString());
    }
    exercise.setResources(resourceMap);

    LinkedList<AvailableExerciseInfo> infoList = new LinkedList<AvailableExerciseInfo>();
    int n = 0;
    for (JsonElement infoElem : infos.getAsJsonArray()) {
        JsonObject tmpInfo = infoElem.getAsJsonObject();
        AvailableExerciseInfo tmpExInfo = new AvailableExerciseInfo();
        tmpExInfo.setTitle(tmpInfo.get(Constants.ACTION_PARAM_TITLE).getAsString());
        tmpExInfo.setDescription(tmpInfo.get(Constants.ACTION_PARAM_DESCRIPTION).getAsString());
        tmpExInfo.setInfoOrder(n);
        JsonObject tmpImage = tmpInfo.get(Constants.ACTION_PARAM_IMAGE).getAsJsonObject();
        String imageString = tmpImage.get(Constants.ACTION_PARAM_DATA).getAsString();
        byte[] tmpImageFile = null;
        try {
            imageString = imageString.replaceFirst("(.*);base64,", "");
            tmpImageFile = Base64.decodeBase64(imageString);
        } catch (Exception e) {
            MessageGenerator.sendErrorMessage("infoImageParsing", response);
            return;
        }
        tmpExInfo.setImage(tmpImageFile);
        infoList.add(tmpExInfo);
        n++;
    }
    exercise.setInfoList(infoList);
    if (infoList.isEmpty()) {
        MessageGenerator.sendErrorMessage("infoListEmpty", response);
        return;
    }

    Integer totalScore = 0;
    LinkedList<Flag> flagList = new LinkedList<Flag>();
    for (JsonElement flagElem : flags.getAsJsonArray()) {
        Flag flag = new Flag();

        JsonObject tmpFlag = flagElem.getAsJsonObject();
        JsonElement flagTitle = tmpFlag.get(Constants.ACTION_PARAM_TITLE);
        JsonElement flagCategory = tmpFlag.get(Constants.ACTION_PARAM_CATEGORY);
        JsonElement flagQuestions = tmpFlag.get(Constants.ACTION_PARAM_FLAG_QUESTIONS);

        flag.setCategory(flagCategory.getAsString());
        flag.setTitle(flagTitle.getAsString());
        LinkedList<FlagQuestion> questionList = new LinkedList<FlagQuestion>();

        for (JsonElement questionElem : flagQuestions.getAsJsonArray()) {
            FlagQuestion tmpQuestion = new FlagQuestion();
            JsonObject qEl = questionElem.getAsJsonObject();
            tmpQuestion.setType(qEl.get(Constants.ACTION_PARAM_TYPE).getAsString());
            tmpQuestion.setOptional(qEl.get(Constants.ACTION_PARAM_OPTIONAL).getAsBoolean());
            if (!tmpQuestion.getOptional()) {
                tmpQuestion.setMaxScore(qEl.get(Constants.ACTION_PARAM_MAX_SCORE).getAsInt());
                totalScore += tmpQuestion.getMaxScore();
            }
            tmpQuestion
                    .setSelfCheckAvailable(qEl.get(Constants.ACTION_PARAM_SELF_CHECK_AVAILABLE).getAsBoolean());
            if (tmpQuestion.getSelfCheckAvailable())
                tmpQuestion.setSelfCheckName(qEl.get(Constants.ACTION_PARAM_SELF_CHECK).getAsString());
            else
                tmpQuestion.setSelfCheckName(null);
            tmpQuestion.setInstructions(qEl.get(Constants.ACTION_PARAM_INSTRUCTIONS).getAsString());
            tmpQuestion.setHintAvailable(qEl.get(Constants.ACTION_PARAM_HINT_AVAILABLE).getAsBoolean());
            if (tmpQuestion.getHintAvailable()) {
                FlagQuestionHint tmpQuestionHint = new FlagQuestionHint();
                tmpQuestionHint.setType(tmpQuestion.getType());
                Gson gson = new Gson();
                FlagQuestionHint newHint = gson.fromJson(qEl.get(Constants.ACTION_PARAM_HINT).getAsJsonObject(),
                        FlagQuestionHint.class);
                if (null != newHint) {
                    tmpQuestionHint.setText(newHint.getText());
                    if (!tmpQuestion.getOptional())
                        tmpQuestionHint.setScoreReducePercentage(newHint.getScoreReducePercentage());
                    tmpQuestion.setHint(tmpQuestionHint);
                } else {
                    MessageGenerator.sendErrorMessage("hintEmpty", response);
                    return;
                }
            } else {
                tmpQuestion.setHint(null);
            }
            questionList.add(tmpQuestion);
        }
        flag.setFlagQuestionList(questionList);
        flagList.add(flag);
    }
    exercise.setFlags(flagList);
    if (flagList.isEmpty()) {
        MessageGenerator.sendErrorMessage("flagListEmpty", response);
        return;
    }
    exercise.setScore(totalScore);

    Integer id = hpc.addAvailableExercise(exercise);
    if (null != id)
        MessageGenerator.sendSuccessMessage(response);
    else
        MessageGenerator.sendErrorMessage("Error", response);
}

From source file:com.remediatetheflag.global.actions.auth.management.rtfadmin.UpdateExerciseAction.java

License:Apache License

@Override
public void doAction(HttpServletRequest request, HttpServletResponse response) throws Exception {
    User user = (User) request.getSession().getAttribute(Constants.ATTRIBUTE_SECURITY_CONTEXT);

    JsonObject json = (JsonObject) request.getAttribute(Constants.REQUEST_JSON);

    JsonElement idExerciseElement = json.get(Constants.ACTION_PARAM_ID);

    JsonElement titleElement = json.get(Constants.ACTION_PARAM_TITLE);
    JsonElement topicsElement = json.get(Constants.ACTION_PARAM_TOPICS);
    JsonElement descriptionElement = json.get(Constants.ACTION_PARAM_DESCRIPTION);
    JsonElement difficultyElement = json.get(Constants.ACTION_PARAM_DIFFICULTY);
    JsonElement technologyElement = json.get(Constants.ACTION_PARAM_TECHNOLOGY);
    JsonElement durationElement = json.get(Constants.ACTION_PARAM_DURATION);
    JsonElement trophyTitleElement = json.get(Constants.ACTION_PARAM_TROPHY_TITLE);
    JsonElement trophyDescriptionElement = json.get(Constants.ACTION_PARAM_TROPHY_DESCRIPTION);
    JsonElement statusElement = json.get(Constants.ACTION_PARAM_STATUS);
    JsonElement typeElement = json.get(Constants.ACTION_PARAM_TYPE);
    JsonElement authorElement = json.get(Constants.ACTION_PARAM_AUTHOR);

    AvailableExercise exercise = new AvailableExercise();
    AvailableExercise oldExercise = hpc.getAvailableExerciseComplete(idExerciseElement.getAsInt());
    if (null == oldExercise) {
        MessageGenerator.sendErrorMessage("NotFound", response);
        return;/* www. j a  v a  2s.  c  o  m*/
    }
    exercise.setDescription(descriptionElement.getAsString());
    exercise.setUuid(oldExercise.getUuid());
    exercise.setDifficulty(difficultyElement.getAsString());
    exercise.setDuration(durationElement.getAsInt());
    exercise.setTitle(titleElement.getAsString());
    exercise.setSubtitle(topicsElement.getAsString());
    exercise.setTechnology(technologyElement.getAsString());
    exercise.setStatus(AvailableExerciseStatus.getStatusFromStatusCode(statusElement.getAsInt()));
    exercise.setAuthor(authorElement.getAsString());
    Integer v = oldExercise.getVersion();
    if (v == null)
        v = 0;
    exercise.setVersion(v + 1);

    AvailableExerciseType validType = null;
    for (AvailableExerciseType t : AvailableExerciseType.values()) {
        if (t.toString().equals(typeElement.getAsString())) {
            validType = t;
            break;
        }
    }
    if (validType == null)
        validType = AvailableExerciseType.BOTH;
    exercise.setExerciseType(validType);

    Trophy trophy = new Trophy();
    trophy.setDescription(trophyDescriptionElement.getAsString());
    trophy.setName(trophyTitleElement.getAsString());
    trophy.setTechnology(exercise.getTechnology());
    exercise.setTrophy(trophy);

    JsonElement flags = json.get(Constants.ACTION_PARAM_FLAGS_LIST);
    JsonElement infos = json.get(Constants.ACTION_PARAM_INFO_LIST);
    JsonElement resources = json.get(Constants.ACTION_PARAM_RESOURCE_LIST);

    JsonElement referenceFile = json.get(Constants.ACTION_PARAM_REFERENCE_FILE);
    if (null != referenceFile) {
        JsonObject referenceFileObj = referenceFile.getAsJsonObject();
        String tmpReferenceFileString = referenceFileObj.get(Constants.ACTION_PARAM_DATA).getAsString();
        byte[] tmpReferenceFile = null;
        try {
            tmpReferenceFileString = tmpReferenceFileString.replaceFirst("(.*);base64,", "");
            tmpReferenceFile = Base64.decodeBase64(tmpReferenceFileString);
        } catch (Exception e) {
            logger.warn("ReferenceFile Parsing error for user " + user.getIdUser() + " in updating exercise "
                    + idExerciseElement.getAsInt() + " due to: " + e.getMessage(), response);
        }
        if (null != tmpReferenceFile && tmpReferenceFile.length != 0) {
            AvailableExerciseReferenceFile refFile = new AvailableExerciseReferenceFile();
            refFile.setFile(tmpReferenceFile);
            refFile.setFilename(referenceFileObj.get(Constants.ACTION_PARAM_NAME).getAsString());
            exercise.setReferenceFile(refFile);
            exercise.setReferenceFileAvailable(true);
        } else {
            exercise.setReferenceFileAvailable(false);
        }
    } else {
        exercise.setReferenceFileAvailable(false);
    }

    JsonElement solutionFile = json.get(Constants.ACTION_PARAM_SOLUTION_FILE);
    JsonObject solutionFileObj = solutionFile.getAsJsonObject();
    String tmpSolutionFileString = solutionFileObj.get(Constants.ACTION_PARAM_DATA).getAsString();
    byte[] tmpSolutioneFile = null;
    try {
        tmpSolutionFileString = tmpSolutionFileString.replaceFirst("(.*);base64,", "");
        tmpSolutioneFile = Base64.decodeBase64(tmpSolutionFileString);
    } catch (Exception e) {
        MessageGenerator.sendErrorMessage("solutioneFileParsing", response);
        return;
    }
    if (null == tmpSolutioneFile || tmpSolutioneFile.length == 0) {
        MessageGenerator.sendErrorMessage("solutioneFileEmpty", response);
        return;
    }
    AvailableExerciseSolutionFile solFile = new AvailableExerciseSolutionFile();

    solFile.setFilename(solutionFileObj.get(Constants.ACTION_PARAM_NAME).getAsString());
    solFile.setFile(tmpSolutioneFile);
    exercise.setSolutionFile(solFile);

    Map<String, String> resourceMap = new HashMap<String, String>();
    for (JsonElement resourceElem : resources.getAsJsonArray()) {
        JsonObject tmpResource = resourceElem.getAsJsonObject();
        resourceMap.put(tmpResource.get(Constants.ACTION_PARAM_TITLE).getAsString(),
                tmpResource.get(Constants.ACTION_PARAM_URL).getAsString());
    }
    exercise.setResources(resourceMap);

    LinkedList<AvailableExerciseInfo> infoList = new LinkedList<AvailableExerciseInfo>();
    int n = 0;
    for (JsonElement infoElem : infos.getAsJsonArray()) {
        JsonObject tmpInfo = infoElem.getAsJsonObject();
        AvailableExerciseInfo tmpExInfo = new AvailableExerciseInfo();
        tmpExInfo.setTitle(tmpInfo.get(Constants.ACTION_PARAM_TITLE).getAsString());
        tmpExInfo.setDescription(tmpInfo.get(Constants.ACTION_PARAM_DESCRIPTION).getAsString());
        tmpExInfo.setInfoOrder(n);
        JsonObject tmpImage = tmpInfo.get(Constants.ACTION_PARAM_IMAGE).getAsJsonObject();
        String imageString = tmpImage.get(Constants.ACTION_PARAM_DATA).getAsString();
        byte[] tmpImageFile = null;
        try {
            imageString = imageString.replaceFirst("(.*);base64,", "");
            tmpImageFile = Base64.decodeBase64(imageString);
        } catch (Exception e) {
            MessageGenerator.sendErrorMessage("infoImageParsing", response);
            return;
        }
        tmpExInfo.setImage(tmpImageFile);
        infoList.add(tmpExInfo);
        n++;
    }
    exercise.setInfoList(infoList);
    if (infoList.isEmpty()) {
        MessageGenerator.sendErrorMessage("infoListEmpty", response);
        return;
    }
    Integer totalScore = 0;
    LinkedList<Flag> flagList = new LinkedList<Flag>();
    for (JsonElement flagElem : flags.getAsJsonArray()) {
        Flag flag = new Flag();

        JsonObject tmpFlag = flagElem.getAsJsonObject();
        JsonElement flagTitle = tmpFlag.get(Constants.ACTION_PARAM_TITLE);
        JsonElement flagCategory = tmpFlag.get(Constants.ACTION_PARAM_CATEGORY);
        JsonElement flagQuestions = tmpFlag.get(Constants.ACTION_PARAM_FLAG_QUESTIONS);

        flag.setCategory(flagCategory.getAsString());
        flag.setTitle(flagTitle.getAsString());
        LinkedList<FlagQuestion> questionList = new LinkedList<FlagQuestion>();

        for (JsonElement questionElem : flagQuestions.getAsJsonArray()) {
            FlagQuestion tmpQuestion = new FlagQuestion();
            JsonObject qEl = questionElem.getAsJsonObject();
            tmpQuestion.setType(qEl.get(Constants.ACTION_PARAM_TYPE).getAsString());
            tmpQuestion.setOptional(qEl.get(Constants.ACTION_PARAM_OPTIONAL).getAsBoolean());
            if (!tmpQuestion.getOptional()) {
                tmpQuestion.setMaxScore(qEl.get(Constants.ACTION_PARAM_MAX_SCORE).getAsInt());
                totalScore += tmpQuestion.getMaxScore();
            }
            tmpQuestion
                    .setSelfCheckAvailable(qEl.get(Constants.ACTION_PARAM_SELF_CHECK_AVAILABLE).getAsBoolean());
            if (tmpQuestion.getSelfCheckAvailable())
                tmpQuestion.setSelfCheckName(qEl.get(Constants.ACTION_PARAM_SELF_CHECK).getAsString());
            else
                tmpQuestion.setSelfCheckName(null);
            tmpQuestion.setInstructions(qEl.get(Constants.ACTION_PARAM_INSTRUCTIONS).getAsString());
            tmpQuestion.setHintAvailable(qEl.get(Constants.ACTION_PARAM_HINT_AVAILABLE).getAsBoolean());
            if (tmpQuestion.getHintAvailable()) {
                FlagQuestionHint tmpQuestionHint = new FlagQuestionHint();
                tmpQuestionHint.setType(tmpQuestion.getType());
                Gson gson = new Gson();
                FlagQuestionHint newHint = gson.fromJson(qEl.get(Constants.ACTION_PARAM_HINT).getAsJsonObject(),
                        FlagQuestionHint.class);
                if (null != newHint) {
                    tmpQuestionHint.setText(newHint.getText());
                    if (!tmpQuestion.getOptional())
                        tmpQuestionHint.setScoreReducePercentage(newHint.getScoreReducePercentage());
                    tmpQuestion.setHint(tmpQuestionHint);
                } else {
                    MessageGenerator.sendErrorMessage("hintEmpty", response);
                    return;
                }
            } else {
                tmpQuestion.setHint(null);
            }
            questionList.add(tmpQuestion);
        }
        flag.setFlagQuestionList(questionList);
        flagList.add(flag);
    }
    exercise.setFlags(flagList);
    if (flagList.isEmpty()) {
        MessageGenerator.sendErrorMessage("flagListEmpty", response);
        return;
    }
    exercise.setScore(totalScore);

    Integer idNewExercise = hpc.addAvailableExercise(exercise);

    if (null != idNewExercise) {
        oldExercise.setStatus(AvailableExerciseStatus.SUPERSEDED);
        hpc.updateAvailableExercise(oldExercise);
        List<Organization> organizations = hpc.getAllOrganizations();
        oldExercise = hpc.getAvailableExerciseComplete(oldExercise.getId());
        AvailableExercise newExercise = hpc.getAvailableExerciseComplete(idNewExercise);
        for (Organization org : organizations) {
            if (hpc.isExerciseEnabledForOrganization(org.getId(), oldExercise.getId())) {
                hpc.addAvailableExerciseForOrganization(org, newExercise);
            }
        }
        hpc.updateAllTaskDefinitionsForExercise(oldExercise.getId(), idNewExercise);
        MessageGenerator.sendExerciseInfoMessageWithHints(newExercise, response);
    } else {
        MessageGenerator.sendErrorMessage("Error", response);
    }
}

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  ww.j a va  2s  .  co m
        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>.
 * //  w w  w. j  a  v  a 2s  . 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.
 * //from  ww w .  j a  va2 s  . co m
 * @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.memoryanalysis.traceparser.TraceAnalysisRunner.java

License:Open Source License

private FreeVariables buildFVMap(File dir) throws IOException {
    File fvFile = new File(dir, "freevars.json");
    FreeVariables res = new FreeVariables();
    if (fvFile.exists()) {
        JsonObject json = null;/*  w w  w.j  av  a2s .  co  m*/
        try {
            json = parser.parse(new BufferedReader(new FileReader(fvFile))).getAsJsonObject();// parser.parse(js.get());
        } catch (JsonParseException ex) {
            throw new IOException("Invalid free-variables map file: " + ex.getMessage());
        }

        for (Map.Entry<String, JsonElement> entry : json.entrySet()) {
            JsonElement o = entry.getValue();
            if (o.isJsonPrimitive() && o.getAsJsonPrimitive().isString())
                res.put(Integer.parseInt(entry.getKey()), FreeVariables.ANY);
            else {
                JsonArray a = o.getAsJsonArray();
                final Set<String> freeVars = HashSetFactory.make();
                for (int i = 0; i < a.size(); i++) {
                    final JsonElement jsonElement = a.get(i);
                    freeVars.add(jsonElement.getAsString());
                }
                res.put(Integer.parseInt(entry.getKey()), freeVars);
            }
        }
    }
    return res;
}

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);
                                    }//  w w  w.  jav a2 s . co  m
                                    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");
    }
}

From source file:com.sat.common.SDdetails.java

License:Open Source License

private static void prArray(JsonElement jelement) {
    //   System.out.println("------------------------Array---------------------------");

    JsonArray jarray = jelement.getAsJsonArray();
    for (JsonElement jobjecte : jarray) {
        if (jobjecte.isJsonObject()) {
            prObject(jobjecte);//w  w  w.  j  a  v a2s.c o m
        } else if (jobjecte.isJsonArray()) {
            prArray(jobjecte);
        } else {
            System.out.println("sathish");
        }

    }
}

From source file:com.savoirtech.json.processor.JsonComparisonProcessor.java

License:Apache License

/**
 * Walk the JSON and compare the actual JSON to the template JSON, applying rules as-needed.
 *
 * @param path        current path to the JSON elements given.
 * @param templateEle the template, or expected, JSON at this path.
 * @param actualEle   the actual JSON at this path.
 * @return result indicating whether there is a match, and providing a description when there is a
 * mismatch./*from  ww  w .  jav  a 2s  . c  om*/
 */
private JsonComparatorResult walkAndCompare(String path, JsonElement templateEle, JsonElement actualEle) {

    JsonComparatorResult result;

    // Find the rule that applies, if any
    JsonComparatorCompiledRule rule = this.ruleProcessor.findMatchingRule(path);

    if (rule != null) {
        result = rule.compare(path, templateEle, actualEle, this.childRuleComparator);
    } else {
        result = this.shallowCompareJsonElements(path, templateEle, actualEle);
    }

    // Make sure contents of objects and arrays are walked, as needed
    if ((result.isMatch()) && (!result.isDeep())) {
        if (actualEle.isJsonObject()) {
            result = this.walkJsonObjectFields(path, templateEle.getAsJsonObject(),
                    actualEle.getAsJsonObject());
        } else if (actualEle.isJsonArray()) {
            result = this.walkJsonArray(path, templateEle.getAsJsonArray(), actualEle.getAsJsonArray());
        }
    }

    return result;
}