Example usage for com.google.gson JsonObject getAsJsonArray

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

Introduction

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

Prototype

public JsonArray getAsJsonArray(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonArray.

Usage

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

License:Open Source License

public JsonArray extractVideoSessions(JsonDataSources sources) {
    videoSessionsById = new HashMap<String, JsonObject>();
    if (categoryToTagMap == null) {
        throw new IllegalStateException("You need to extract tags before attempting to extract video sessions");
    }/*ww  w. j a v  a2s . com*/
    if (speakersById == null) {
        throw new IllegalStateException(
                "You need to extract speakers before attempting to extract video sessions");
    }

    JsonArray result = new JsonArray();
    JsonDataSource source = sources.getSource(InputJsonKeys.VendorAPISource.MainTypes.topics.name());
    if (source != null) {
        for (JsonObject origin : source) {

            if (!isVideoSession(origin)) {
                continue;
            }
            if (isHiddenSession(origin)) {
                // Sessions with a "Hidden from schedule" flag should be ignored
                continue;
            }

            JsonObject dest = new JsonObject();

            JsonPrimitive vid = setVideoForVideoSession(origin, dest);

            JsonElement id = DataModelHelper.get(origin, InputJsonKeys.VendorAPISource.Topics.id);
            // video library id must be the Youtube video id
            DataModelHelper.set(vid, dest, OutputJsonKeys.VideoLibrary.id);
            DataModelHelper.set(origin, InputJsonKeys.VendorAPISource.Topics.title, dest,
                    OutputJsonKeys.VideoLibrary.title, obfuscate ? Converters.OBFUSCATE : null);
            DataModelHelper.set(origin, InputJsonKeys.VendorAPISource.Topics.description, dest,
                    OutputJsonKeys.VideoLibrary.desc, obfuscate ? Converters.OBFUSCATE : null);
            DataModelHelper.set(new JsonPrimitive(Config.CONFERENCE_YEAR), dest,
                    OutputJsonKeys.VideoLibrary.year);

            JsonElement videoTopic = null;
            JsonArray categories = origin
                    .getAsJsonArray(InputJsonKeys.VendorAPISource.Topics.categoryids.name());
            for (JsonElement category : categories) {
                JsonObject tag = categoryToTagMap.get(category.getAsString());
                if (tag != null) {
                    if (DataModelHelper.isHashtag(tag)) {
                        videoTopic = DataModelHelper.get(tag, OutputJsonKeys.Tags.name);
                        // by definition, the first tag that can be a hashtag (usually a TOPIC) is considered the video tag
                        break;
                    }
                }
            }
            if (videoTopic != null) {
                DataModelHelper.set(videoTopic, dest, OutputJsonKeys.VideoLibrary.topic);
            }

            // Concatenate speakers:
            JsonArray speakers = DataModelHelper.getAsArray(origin,
                    InputJsonKeys.VendorAPISource.Topics.speakerids);
            StringBuilder sb = new StringBuilder();
            if (speakers != null)
                for (int i = 0; i < speakers.size(); i++) {
                    String speakerId = speakers.get(i).getAsString();
                    usedSpeakers.add(speakerId);
                    JsonObject speaker = speakersById.get(speakerId);
                    if (speaker != null) {
                        sb.append(DataModelHelper.get(speaker, OutputJsonKeys.Speakers.name).getAsString());
                        if (i < speakers.size() - 1)
                            sb.append(", ");
                    }
                }
            DataModelHelper.set(new JsonPrimitive(sb.toString()), dest, OutputJsonKeys.VideoLibrary.speakers);
            videoSessionsById.put(id.getAsString(), dest);
            result.add(dest);
        }
    }
    return result;
}

From source file:com.remediatetheflag.global.actions.auth.user.LaunchExerciseInstanceAction.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_ATTRIBUTE_JSON);

    if (user.getCredits() == 0) {
        MessageGenerator.sendErrorMessage("CreditsLimit", response);
        logger.warn("No credits left for user " + user.getIdUser());
        return;//  w w w.j  a va  2  s .c  o  m
    }
    List<ExerciseInstance> activeInstances = hpc.getActiveExerciseInstanceForUser(user.getIdUser());
    if (activeInstances.size() > 0 && activeInstances.size() >= user.getInstanceLimit()) {
        MessageGenerator.sendErrorMessage("InstanceLimit", response);
        logger.warn("Instance limit reached for user " + user.getIdUser() + " current: "
                + activeInstances.size() + " limit:" + user.getInstanceLimit());
        return;
    }

    Integer exerciseId = json.get(Constants.ACTION_PARAM_ID).getAsInt();
    JsonElement challengeElement = json.get(Constants.ACTION_PARAM_CHALLENGE_ID);

    AvailableExercise exercise = hpc.getAvailableExercise(exerciseId, user.getDefaultOrganization());
    if (null == exercise || exercise.getStatus().equals(AvailableExerciseStatus.INACTIVE)
            || exercise.getStatus().equals(AvailableExerciseStatus.COMING_SOON)) {
        MessageGenerator.sendErrorMessage("ExerciseUnavailable", response);
        logger.error("User " + user.getIdUser() + " requested an unavailable exercise: " + exerciseId);
        return;
    }

    Integer validatedChallengeId = null;

    List<Challenge> userChallengesWithExercise = hpc.getChallengesForUserExercise(exercise.getId(),
            user.getIdUser());

    if (!userChallengesWithExercise.isEmpty()) {
        Boolean inChallenge = false;
        if (null != challengeElement && (challengeElement.getAsInt() != -1)) {
            Integer challengeId = challengeElement.getAsInt();
            Challenge c = hpc.getChallengeWithDetailsForUser(challengeId, user.getIdUser());
            if (null != c) {
                for (AvailableExercise avE : c.getExercises()) {
                    if (avE.getId().equals(exerciseId)) {
                        validatedChallengeId = c.getIdChallenge();
                        inChallenge = true;
                        break;
                    }
                }
            }
            if (!inChallenge) {
                logger.error("Exercise " + exerciseId + " is NOT in Challenge: " + challengeId
                        + ", but a challenge id was provided by user: " + user.getIdUser());
                validatedChallengeId = null;
            }
            for (ExerciseInstance e : c.getRunExercises()) {
                if (e.getUser().getIdUser().equals(user.getIdUser())
                        && e.getAvailableExercise().getId().equals(exerciseId)) {
                    logger.warn("Exercise " + exerciseId + " is in Challenge: " + challengeId + ", but user: "
                            + user.getIdUser() + " already run it");
                    validatedChallengeId = null;
                    break;
                }
            }
        } else {
            logger.warn("Exercise " + exerciseId
                    + " is in Challenge, but no challenge id was provided by user: " + user.getIdUser());
            Boolean run = false;
            for (Challenge dbChallenges : userChallengesWithExercise) {
                for (ExerciseInstance dbChallengeExercise : dbChallenges.getRunExercises()) {
                    if (dbChallengeExercise.getUser().getIdUser().equals(user.getIdUser())
                            && dbChallengeExercise.getAvailableExercise().getId().equals(exerciseId)) {
                        run = true;
                    }
                }
                if (!run) {
                    validatedChallengeId = userChallengesWithExercise.get(0).getIdChallenge();
                    break;
                }
            }
        }
    }

    JsonElement exerciseRegionsElement = json.getAsJsonArray(Constants.ACTION_PARAM_REGION);
    Type listType = new TypeToken<ArrayList<ExerciseRegion>>() {
    }.getType();
    List<ExerciseRegion> regList = null;
    try {
        regList = new Gson().fromJson(exerciseRegionsElement, listType);

    } catch (Exception e) {
        MessageGenerator.sendErrorMessage("NoRegionsPing", response);
        logger.error("User " + user.getIdUser() + " requested an exercise: " + exerciseId
                + " without supplying regions pings");
        return;
    }
    Collections.sort(regList, new Comparator<ExerciseRegion>() {
        public int compare(ExerciseRegion p1, ExerciseRegion p2) {
            return Integer.valueOf(p1.getPing()).compareTo(p2.getPing());
        }
    });
    AWSHelper awsHelper = new AWSHelper();
    RTFECSTaskDefinition taskDefinition = null;
    Regions awsRegion = null;

    Boolean satisfied = false;
    for (ExerciseRegion r : regList) {
        if (satisfied)
            break;
        try {
            awsRegion = Regions.valueOf(r.getName());
        } catch (Exception e) {
            logger.warn("Region " + r.getName() + " not found for user " + user.getIdUser()
                    + " for launching exercise: " + exerciseId);
            continue;
        }

        RTFGateway gw = hpc.getGatewayForRegion(awsRegion);
        if (null == gw || !gw.isActive()) {
            logger.warn("User " + user.getIdUser() + " requested an unavailable gateway for region: "
                    + awsRegion + " for launching exercise: " + exerciseId);
            continue;
        }
        GuacamoleHelper guacHelper = new GuacamoleHelper();
        if (!guacHelper.isGuacOnline(gw)) {
            logger.warn("User " + user.getIdUser()
                    + " could not launch instance as Guac is not available in region: " + awsRegion
                    + " for launching exercise: " + exerciseId);
            continue;
        }
        taskDefinition = hpc.getTaskDefinitionForExerciseInRegion(exerciseId, awsRegion);
        if (null == taskDefinition) {
            taskDefinition = hpc.getTaskDefinitionFromUUID(exercise.getUuid(), awsRegion);
        }
        if (null == taskDefinition || !resourcesAvailable(Region.getRegion(awsRegion))) {
            logger.warn("No resources for user " + user.getIdUser() + " launching exercise: " + exerciseId
                    + " in region " + awsRegion);
            continue;
        }
        satisfied = true;
    }

    if (!satisfied) {
        MessageGenerator.sendErrorMessage("Unavailable", response);
        logger.error("User " + user.getIdUser()
                + " could not launch instance as there is no available region/gateway/guac/task def for exercise id "
                + exerciseId);
        return;
    }

    String otp = UUID.randomUUID().toString().replaceAll("-", "");
    LaunchStrategy strategy = new AWSECSLaunchStrategy(user, exercise.getDuration(),
            RTFConfig.getExercisesCluster(), otp, taskDefinition, exercise, validatedChallengeId);
    RTFInstanceReservation reservation = awsHelper.createRTFInstance(strategy);
    if (!reservation.getError()) {
        logger.info("Reservation " + reservation.getId() + " for user " + user.getIdUser()
                + "  launching exercise: " + exerciseId + " in region " + awsRegion);
        if (user.getCredits() != -1) {
            user.setCredits(user.getCredits() - 1);
            hpc.updateUserInfo(user);
            request.getSession().setAttribute(Constants.ATTRIBUTE_SECURITY_CONTEXT, user);
            logger.info("Reducing 1 credit for user " + user.getIdUser() + " to: " + user.getCredits());
        }
        MessageGenerator.sendReservationMessage(reservation, response);
        return;
    } else {
        MessageGenerator.sendErrorMessage("InstanceUnavailable", response);
    }

}

From source file:com.replaymod.replaystudio.filter.RemoveMobsFilter.java

License:MIT License

@Override
public void init(Studio studio, JsonObject config) {
    filterTypes = EnumSet.noneOf(MobType.class);
    for (JsonElement e : config.getAsJsonArray("Types")) {
        filterTypes.add(MobType.valueOf(e.getAsString()));
    }/*  w  w w.jav a2  s  .com*/
}

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;//w  w w .  j av a 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.replaymod.replaystudio.replay.AbstractReplayFile.java

License:MIT License

@Override
public Optional<Set<UUID>> getInvisiblePlayers() throws IOException {
    Optional<InputStream> in = get(ENTRY_VISIBILITY);
    if (!in.isPresent()) {
        in = get(ENTRY_VISIBILITY_OLD);/*w  ww .  j  a  v  a 2s.  c  o  m*/
        if (!in.isPresent()) {
            return Optional.absent();
        }
    }
    Set<UUID> uuids = new HashSet<>();
    try (Reader is = new InputStreamReader(in.get())) {
        JsonObject json = new Gson().fromJson(is, JsonObject.class);
        for (JsonElement e : json.getAsJsonArray("hidden")) {
            uuids.add(UUID.fromString(e.getAsString()));
        }
    }
    return Optional.of(uuids);
}

From source file:com.ruesga.rview.misc.ContinuousIntegrationHelper.java

License:Apache License

@SuppressWarnings({ "ConstantConditions", "TryFinallyCanBeTryWithResources" })
private static List<ContinuousIntegrationInfo> obtainFromCQServer(Repository repository, String changeId,
        int revisionNumber) {
    List<ContinuousIntegrationInfo> statuses = new ArrayList<>();

    // NOTE: Do not fix "Redundant character escape" lint warning. Remove trailing '\'
    // will cause an PatternSyntaxException
    String url = repository.mCiStatusUrl.replaceFirst("\\{change\\}", changeId).replaceFirst("\\{revision\\}",
            String.valueOf(revisionNumber));

    try {/*from   w  w w  .j av  a 2 s  .  c om*/
        OkHttpClient okhttp = NetworkingHelper.createNetworkClient().build();
        Request request = new Request.Builder().url(url).build();

        Response response = okhttp.newCall(request).execute();
        try {
            String json = response.body().string();
            JsonObject root = new JsonParser().parse(json).getAsJsonObject();
            if (!root.has("builds")) {
                return statuses;
            }
            JsonArray o = root.getAsJsonArray("builds");
            int c1 = o.size();
            for (int i = 0; i < c1; i++) {
                JsonObject b = o.get(i).getAsJsonObject();
                try {
                    String status = b.get("status").getAsString();
                    String ciUrl = b.get("url").getAsString();
                    String ciName = null;
                    JsonArray tags = b.get("tags").getAsJsonArray();
                    int c2 = tags.size();
                    for (int j = 0; j < c2; j++) {
                        String tag = tags.get(j).getAsJsonPrimitive().getAsString();
                        if (tag.startsWith("builder:")) {
                            ciName = tag.substring(tag.indexOf(":") + 1);
                        }
                    }

                    if (!TextUtils.isEmpty(status) && !TextUtils.isEmpty(ciUrl) && !TextUtils.isEmpty(ciName)) {
                        BuildStatus buildStatus = BuildStatus.RUNNING;
                        if (status.equals("COMPLETED")) {
                            String result = b.get("result").getAsString();

                            switch (result) {
                            case "SUCCESS":
                                buildStatus = BuildStatus.SUCCESS;
                                break;
                            case "FAILURE":
                                buildStatus = BuildStatus.FAILURE;
                                break;
                            default:
                                buildStatus = BuildStatus.SKIPPED;
                                break;
                            }
                        }

                        ContinuousIntegrationInfo c = findContinuousIntegrationInfo(statuses, ciName);
                        // Attempts are sorted in reversed order, so we need the first one
                        if (c == null) {
                            statuses.add(new ContinuousIntegrationInfo(ciName, ciUrl, buildStatus));
                        }
                    }

                } catch (Exception ex) {
                    Log.w(TAG, "Failed to parse ci object" + b, ex);
                }

            }

        } finally {
            response.close();
        }

    } catch (Exception ex) {
        Log.w(TAG, "Failed to obtain ci status from " + url, ex);
    }

    return statuses;
}

From source file:com.samsung.sjs.FFILinkage.java

License:Apache License

public void includeLinkage(JsonObject linkage) {
    JsonArray decls = linkage.getAsJsonArray("globals");
    for (JsonElement d : decls) {
        parseDecl(d.getAsJsonObject());//ww w .j ava2  s.com
    }
    JsonArray tables = linkage.getAsJsonArray("indirections");
    for (JsonElement t : tables) {
        parseTable(t.getAsJsonObject());
    }
}

From source file:com.samsung.sjs.FFILinkage.java

License:Apache License

public void parseTable(JsonObject table) {
    String name = table.getAsJsonPrimitive("name").getAsString();
    JsonArray arr = table.getAsJsonArray("fields");
    LinkedList<String> l = new LinkedList<>();
    for (JsonElement fname : arr) {
        l.add(fname.getAsJsonPrimitive().getAsString());
    }/*from   w w w.  ja v a2  s . c o m*/
    tables_to_generate.put(name, l);
}

From source file:com.samsung.sjs.JSEnvironment.java

License:Apache License

public void parseIntrinsic(String name, JsonObject ty) {
    List<Property> props = new LinkedList<Property>();
    for (JsonElement e : ty.getAsJsonArray("operators")) {
        JsonObject eo = e.getAsJsonObject();
        props.add(parseProp(eo));//from  w w w.  j a v  a  2 s  . co m
    }
    assert (intrinsics.get(name) == null);
    intrinsics.put(name, props);
    // TODO: Verify it's an expected intrinsic
}

From source file:com.samsung.sjs.JSEnvironment.java

License:Apache License

public Type parseType(JsonObject ty) {
    assert (ty != null);
    String typefamily = ty.getAsJsonPrimitive("typefamily").getAsString();
    switch (typefamily) {
    case "string":
        return Types.mkString();
    case "int":
        return Types.mkInt();
    case "double":
        return Types.mkFloat();
    case "void":
        return Types.mkVoid();
    case "bool":
        return Types.mkBool();
    case "array":
        Type etype = parseType(ty.getAsJsonObject("elemtype"));
        return Types.mkArray(etype);
    case "map":
        Type mtype = parseType(ty.getAsJsonObject("elemtype"));
        return Types.mkMap(mtype);
    case "constructor":
    case "function":
    case "method":
        final Type ret = parseType(ty.getAsJsonObject("return"));
        final List<String> names = new LinkedList<String>();
        final List<Type> types = new LinkedList<Type>();
        for (JsonElement e : ty.getAsJsonArray("args")) {
            JsonObject eo = e.getAsJsonObject();
            names.add(eo.getAsJsonPrimitive("name").getAsString());
            types.add(parseType(eo.getAsJsonObject("type")));
        }/*w  ww .jav  a2 s  .  c o  m*/
        if (typefamily.equals("function")) {
            return Types.mkFunc(ret, types, names);
        } else if (typefamily.equals("constructor")) {
            return Types.mkCtor(types, names, ret, null);
        } else {
            // method
            assert (typefamily.equals("method"));
            return Types.mkMethod(Types.mkAny(), ret, names, types); // TODO: Why does AttachedMethodType have a receiver?
        }
    case "object":
        final List<Property> props = new LinkedList<Property>();
        for (JsonElement e : ty.getAsJsonArray("members")) {
            JsonObject eo = e.getAsJsonObject();
            props.add(parseProp(eo));
        }
        ObjectType o = Types.mkObject(props);
        if (ty.has("typename")) {
            namedTypes.put(ty.getAsJsonPrimitive("typename").getAsString(), o);
        }
        return o;

    case "intersection":
        List<Type> mems = new LinkedList<>();
        for (JsonElement e : ty.getAsJsonArray("members")) {
            JsonObject eo = e.getAsJsonObject();
            mems.add(parseType(eo));
        }
        return new IntersectionType(mems);
    case "typevariable":
        int x = ty.getAsJsonPrimitive("id").getAsInt();
        return new TypeVariable(x);
    case "name":
        String name = ty.getAsJsonPrimitive("name").getAsString();
        return new NamedObjectType(name, this);
    default:
        throw new IllegalArgumentException(typefamily);
    }
}