Example usage for com.google.gson JsonElement getAsInt

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

Introduction

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

Prototype

public int getAsInt() 

Source Link

Document

convenience method to get this element as a primitive integer value.

Usage

From source file:com.remediatetheflag.global.actions.auth.user.GetGuacTokenForExerciseAction.java

License:Apache License

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

    JsonObject json = (JsonObject) request.getAttribute(Constants.REQUEST_JSON);
    JsonElement jsonElement = json.get(Constants.ACTION_PARAM_ID);
    Integer idExercise = jsonElement.getAsInt();

    ExerciseInstance exercise = hpc.getActiveExerciseInstanceForUserWithGuac(sessionUser.getIdUser(),
            idExercise);/*from w  w w.ja  v a 2 s .c  om*/

    String token = null;
    if (exercise.getGuac() != null) {
        token = guacHelper.getFreshToken(exercise.getGuac().getGateway(), exercise.getGuac().getUsername(),
                exercise.getGuac().getPassword());
    } else {
        logger.error("Could not find active ExerciseInstance " + idExercise + " for user: "
                + sessionUser.getIdUser());
        MessageGenerator.sendErrorMessage("NotFound", response);
        return;
    }

    if (null != token) {
        MessageGenerator.sendTokenMessage(exercise.getIdExerciseInstance(),
                exercise.getGuac().getGateway().getFqdn(), exercise.getGuac().getUsername(), token, 0,
                response);
    } else {
        logger.error("Could not get GuacToken for ExerciseInstance " + idExercise + " for user: "
                + sessionUser.getIdUser());
        MessageGenerator.sendErrorMessage("CouldNotRetrieveToken", response);
    }
}

From source file:com.remediatetheflag.global.actions.auth.user.GetHintForFlagQuestionAction.java

License:Apache License

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

    JsonObject json = (JsonObject) request.getAttribute(Constants.REQUEST_JSON);
    JsonElement idQuestionElement = json.get(Constants.ACTION_PARAM_ID);
    Integer idQuestion = idQuestionElement.getAsInt();
    JsonElement idExerciseInstanceElement = json.get(Constants.ACTION_PARAM_ID_EXERCISE_INSTANCE);
    Integer idExerciseInstance = idExerciseInstanceElement.getAsInt();
    Integer idFlag = hpc.getFlagIdFromQuestionId(idQuestion);
    if (null == idFlag) {
        User user = (User) request.getSession().getAttribute(Constants.ATTRIBUTE_SECURITY_CONTEXT);
        logger.error("Flag not found for questionId " + idQuestion + " for user " + user.getIdUser());
        MessageGenerator.sendErrorMessage("HintUnavailable", response);
        return;//from ww  w  .  j av  a  2  s .  com
    }
    Flag f = hpc.getFlagWithHints(idFlag);

    FlagQuestionHint hint = null;
    for (FlagQuestion fq : f.getFlagQuestionList()) {
        if (fq.getId().equals(idQuestion)) {
            hint = fq.getHint();
            break;
        }
    }
    if (null != hint) {
        ExerciseInstance ei = hpc.getExerciseInstanceWithHints(idExerciseInstance);
        if (null != ei && null != ei.getStatus() && !ei.getStatus().equals(ExerciseStatus.RUNNING)) {
            User user = (User) request.getSession().getAttribute(Constants.ATTRIBUTE_SECURITY_CONTEXT);
            logger.error("Refused to provide hint " + hint.getId() + " for ExerciseInstance "
                    + ei.getIdExerciseInstance() + " with status " + ei.getStatus().toString() + " for user "
                    + user.getIdUser());
            MessageGenerator.sendErrorMessage("HintUnavailable", response);
            return;
        }
        boolean alreadyIn = false;
        for (FlagQuestionHint fqh : ei.getUsedHints()) {
            if (fqh.getId().equals(hint.getId())) {
                alreadyIn = true;
                break;
            }
        }
        if (!alreadyIn) {
            ei.getUsedHints().add(hint);
            hpc.updateExerciseInstanceUsedHints(ei, hint);
        }
        MessageGenerator.sendHintMessage(hint, response);
    } else {
        User user = (User) request.getSession().getAttribute(Constants.ATTRIBUTE_SECURITY_CONTEXT);
        logger.error("Hint not found for questionId " + idQuestion + " for user " + user.getIdUser());
        MessageGenerator.sendErrorMessage("HintUnavailable", response);
    }
}

From source file:com.remediatetheflag.global.actions.auth.user.IsExerciseInChallengeAction.java

License:Apache License

@Override
public void doAction(HttpServletRequest request, HttpServletResponse response) throws Exception {
    JsonObject json = (JsonObject) request.getAttribute(Constants.REQUEST_JSON);
    JsonElement jsonElement = json.get(Constants.ACTION_PARAM_ID);
    Integer idExercise = jsonElement.getAsInt();
    User sessionUser = (User) request.getSession().getAttribute(Constants.ATTRIBUTE_SECURITY_CONTEXT);
    boolean isInChallenge = hpc.isExerciseInChallengeForUser(idExercise, sessionUser.getIdUser());
    MessageGenerator.sendIsExerciseInChallengeMessage(isInChallenge, response);
}

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;//from  www  . j av a2s.  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.remediatetheflag.global.actions.auth.user.LeaveFeedbackAction.java

License:Apache License

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

    JsonObject json = (JsonObject) request.getAttribute(Constants.REQUEST_JSON);
    JsonElement jsonElement = json.get(Constants.ACTION_PARAM_ID);
    Integer idExercise = jsonElement.getAsInt();
    JsonElement feedbackElement = json.get(Constants.ACTION_PARAM_FEEDBACK);
    String feedbackMessage = feedbackElement.getAsString();
    ExerciseInstance instance = hpc.getCompletedExerciseInstanceForUser(sessionUser.getIdUser(), idExercise);
    if (null != instance && instance.getFeedback() == null) {
        Feedback feedback = new Feedback();
        feedback.setFeedback(feedbackMessage);
        feedback.setInstance(instance);//from ww  w  . ja v a  2  s  .  c  o m
        feedback.setUser(sessionUser);
        feedback.setDate(new Date());
        hpc.addUserFeedback(feedback);
        instance.setFeedback(true);
        hpc.updateExerciseInstance(instance);
        notificationsHelper.newFeedbackReceived(sessionUser, instance);
        MessageGenerator.sendSuccessMessage(response);
    } else {
        logger.error("ExerciseInstance: " + idExercise + " not found for user " + sessionUser.getIdUser());
        MessageGenerator.sendErrorMessage("NotFound", response);
    }
}

From source file:com.remediatetheflag.global.actions.auth.user.MarkNotificationReadAction.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 jsonElement = json.get(Constants.ACTION_PARAM_ID);
    Integer idNotification = jsonElement.getAsInt();

    boolean markedRead = hpc.markNotificationAsRead(idNotification, user);
    if (markedRead) {
        List<Notification> notifications = hpc.getUnreadNotificationsForUser(user);
        MessageGenerator.sendNotificationsMessage(notifications, response);
    } else//  w  w w  .ja va  2s . c om
        MessageGenerator.sendErrorMessage("Error", response);

}

From source file:com.simiacryptus.mindseye.layers.aparapi.ConvolutionLayer.java

License:Apache License

/**
 * Instantiates a new Convolution key./*from w w w .java2 s . com*/
 *
 * @param json      the json
 * @param resources the resources
 */
protected ConvolutionLayer(@Nonnull final JsonObject json, Map<CharSequence, byte[]> resources) {
    super(json);
    kernel = Tensor.fromJson(json.get("filter"), resources);
    JsonElement paddingX = json.get("paddingX");
    if (null != paddingX && paddingX.isJsonPrimitive())
        this.setPaddingX((paddingX.getAsInt()));
    JsonElement paddingY = json.get("paddingY");
    if (null != paddingY && paddingY.isJsonPrimitive())
        this.setPaddingY((paddingY.getAsInt()));
}

From source file:com.simiacryptus.mindseye.layers.aparapi.ConvolutionLayer.java

License:Apache License

@Nonnull
@Override//from  w  w w .ja  va 2s  .  co m
public JsonObject getJson(Map<CharSequence, byte[]> resources, @Nonnull DataSerializer dataSerializer) {
    @Nonnull
    final JsonObject json = super.getJsonStub();
    json.add("filter", kernel.toJson(resources, dataSerializer));
    JsonElement paddingX = json.get("paddingX");
    if (null != paddingX && paddingX.isJsonPrimitive())
        this.setPaddingX((paddingX.getAsInt()));
    JsonElement paddingY = json.get("paddingY");
    if (null != paddingY && paddingY.isJsonPrimitive())
        this.setPaddingY((paddingY.getAsInt()));
    return json;
}

From source file:com.simiacryptus.mindseye.layers.cudnn.conv.ConvolutionLayer.java

License:Apache License

/**
 * Instantiates a new Convolution key./*ww  w. j  av a2  s .  com*/
 *
 * @param json      the json
 * @param resources the resources
 */
protected ConvolutionLayer(@Nonnull final JsonObject json, Map<CharSequence, byte[]> resources) {
    super(json);
    this.kernel = Tensor.fromJson(json.get("filter"), resources);
    assert getKernel().isValid();
    this.setBatchBands(json.get("batchBands").getAsInt());
    this.setStrideX(json.get("strideX").getAsInt());
    this.setStrideY(json.get("strideY").getAsInt());
    JsonElement paddingX = json.get("paddingX");
    if (null != paddingX && paddingX.isJsonPrimitive())
        this.setPaddingX((paddingX.getAsInt()));
    JsonElement paddingY = json.get("paddingY");
    if (null != paddingY && paddingY.isJsonPrimitive())
        this.setPaddingY((paddingY.getAsInt()));
    this.precision = Precision.valueOf(json.get("precision").getAsString());
    this.inputBands = json.get("inputBands").getAsInt();
    this.outputBands = json.get("outputBands").getAsInt();
}

From source file:com.simiacryptus.mindseye.layers.java.ImgConcatLayer.java

License:Apache License

/**
 * Instantiates a new Img eval key./*from  w ww.j  a va2  s.c  o m*/
 *
 * @param json the json
 */
protected ImgConcatLayer(@Nonnull final JsonObject json) {
    super(json);
    JsonElement maxBands = json.get("maxBands");
    if (null != maxBands)
        setMaxBands(maxBands.getAsInt());
}