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.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);//ww w.jav a 2 s . 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.AddExerciseInRegionAction.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 idExerciseElement = json.get(Constants.ACTION_PARAM_EXERCISE_ID);

    JsonElement taskDefinitionNameElement = json.get(Constants.ACTION_PARAM_TASK_DEFINITION_NAME);
    JsonElement containerNameElement = json.get(Constants.ACTION_PARAM_CONTAINER_NAME);
    JsonElement repositoryImageUrlElement = json.get(Constants.ACTION_PARAM_REPO_URL);
    JsonElement softMemoryLimitElement = json.get(Constants.ACTION_PARAM_SOFT_MEMORY);
    JsonElement regionElement = json.get(Constants.ACTION_PARAM_REGION);
    JsonElement hardMemoryLimitElement = json.get(Constants.ACTION_PARAM_HARD_MEMORY);
    JsonElement statusElement = json.get(Constants.ACTION_PARAM_STATUS);

    String taskDefinitionName = taskDefinitionNameElement.getAsString();
    String containerName = containerNameElement.getAsString();

    String repositoryImageUrl = repositoryImageUrlElement.getAsString();
    String region = regionElement.getAsString();
    Integer softMemoryLimit = softMemoryLimitElement.getAsInt();
    Integer hardMemoryLimit = hardMemoryLimitElement.getAsInt();

    Boolean active = statusElement.getAsBoolean();
    Integer idExercise = idExerciseElement.getAsInt();

    AvailableExercise exercise = hpc.getAvailableExercise(idExercise);
    if (null == exercise) {
        MessageGenerator.sendErrorMessage("ExerciseNotFound", response);
        logger.error("Exercise " + idExercise + " not found for user " + sessionUser.getIdUser());
        return;/*  www.j  a  va2  s.  c o  m*/
    }

    Regions awsRegion = null;
    try {
        awsRegion = Regions.valueOf(region);
    } catch (Exception e) {
        MessageGenerator.sendErrorMessage("RegionNotFound", response);
        logger.error("Region " + region + " not found for user " + sessionUser.getIdUser());
        return;
    }

    RTFECSTaskDefinition ecsTask = new RTFECSTaskDefinition();

    ecsTask.setRegion(awsRegion);
    ecsTask.setContainerName(containerName);
    ecsTask.setTaskDefinitionName(taskDefinitionName);
    ecsTask.setHardMemoryLimit(hardMemoryLimit);
    ecsTask.setSoftMemoryLimit(softMemoryLimit);
    ecsTask.setRepositoryImageUrl(repositoryImageUrl);
    ecsTask.setUpdateDate(new Date());

    AWSHelper awsHelper = new AWSHelper();
    String arn = awsHelper.createECSTaskDefinition(ecsTask, sessionUser);

    if (null != arn) {
        ecsTask.setTaskDefinitionArn(arn);
        String nameWithRevision = arn.split("/")[(arn.split("/").length) - 1];
        if (null != nameWithRevision && !nameWithRevision.equals(""))
            ecsTask.setTaskDefinitionName(nameWithRevision);
        RTFECSTaskDefinitionForExerciseInRegion ecsTaskForExercise = new RTFECSTaskDefinitionForExerciseInRegion();
        ecsTaskForExercise.setExercise(exercise);
        ecsTaskForExercise.setRegion(awsRegion);
        ecsTaskForExercise.setTaskDefinition(ecsTask);
        ecsTaskForExercise.setActive(active);
        Integer id = hpc.addECSTaskDefinitionForExerciseInRegion(ecsTaskForExercise);
        if (null == id) {
            MessageGenerator.sendErrorMessage("Error", response);
            logger.error("New ECSTaskDefinitionForExerciseInRegion could not be saved for user "
                    + sessionUser.getIdUser());
            return;
        }
        MessageGenerator.sendSuccessMessage(response);
        return;
    }
    MessageGenerator.sendErrorMessage("Error", response);
    logger.error(
            "New ECSTaskDefinitionForExerciseInRegion could not be saved for user " + sessionUser.getIdUser());
}

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

License:Apache License

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

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

    JsonElement idTaskDefElement = json.get(Constants.ACTION_PARAM_TASK_DEFINITION_ID);
    Integer idTaskDef = idTaskDefElement.getAsInt();
    JsonElement idExerciseElement = json.get(Constants.ACTION_PARAM_EXERCISE_ID);
    Integer idExecrcise = idExerciseElement.getAsInt();

    Boolean result = hpc.enableDisableTaskDefinitionInRegion(idExecrcise, idTaskDef, false);
    if (!result) {
        MessageGenerator.sendErrorMessage("Error", response);
        return;/*from w w w  .  j  a v a  2 s  .  c o  m*/
    }
    MessageGenerator.sendSuccessMessage(response);
}

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

License:Apache License

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

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

    JsonElement idTaskDefElement = json.get(Constants.ACTION_PARAM_TASK_DEFINITION_ID);
    Integer idTaskDef = idTaskDefElement.getAsInt();
    JsonElement idExerciseElement = json.get(Constants.ACTION_PARAM_EXERCISE_ID);
    Integer idExecrcise = idExerciseElement.getAsInt();

    Boolean result = hpc.enableDisableTaskDefinitionInRegion(idExecrcise, idTaskDef, true);
    if (!result) {
        MessageGenerator.sendErrorMessage("Error", response);
        return;/* ww w.  j  a v  a2 s.c o  m*/
    }
    MessageGenerator.sendSuccessMessage(response);
}

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

License:Apache License

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

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

    JsonElement idExerciseElement = json.get(Constants.ACTION_PARAM_EXERCISE_ID);
    Integer idExercise = idExerciseElement.getAsInt();

    Boolean result = hpc.removeAvailableExercise(idExercise);
    if (!result) {
        logger.warn("Could not remove exercise " + idExercise);
        MessageGenerator.sendErrorMessage("ExerciseRemoveFailed", response);
        return;/*  www . java 2  s  .com*/
    }
    MessageGenerator.sendSuccessMessage(response);
    return;
}

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

License:Apache License

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

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

    JsonElement idTaskDefElement = json.get(Constants.ACTION_PARAM_TASK_DEFINITION_ID);
    Integer idTaskDef = idTaskDefElement.getAsInt();
    JsonElement idExerciseElement = json.get(Constants.ACTION_PARAM_EXERCISE_ID);
    Integer idExercise = idExerciseElement.getAsInt();

    List<RTFECSTaskDefinitionForExerciseInRegion> list = hpc.getAllTaskDefinitionForExerciseInRegion(idTaskDef);
    for (RTFECSTaskDefinitionForExerciseInRegion taskDef : list) {
        if (taskDef.getActive()) {
            MessageGenerator.sendErrorMessage("TaskDefinitionActive", response);
            return;
        }//from ww  w . jav  a 2 s.  com
    }
    RTFECSTaskDefinitionForExerciseInRegion taskDefinitionForDeletion = hpc
            .getTaskDefinitionForExerciseInRegion(idExercise, idTaskDef);
    AWSHelper awsHelper = new AWSHelper();
    Boolean awsResult = awsHelper.removeTaskDefinitionInRegion(
            taskDefinitionForDeletion.getTaskDefinition().getTaskDefinitionArn(),
            taskDefinitionForDeletion.getRegion());
    if (!awsResult) {
        logger.warn("Could not deregister task definition " + idTaskDef + " from AWS region "
                + taskDefinitionForDeletion.getRegion().getName());
        MessageGenerator.sendErrorMessage("TaskDefinitionDeregisterFailed", response);
        return;
    }
    Boolean result = hpc.removeTaskDefinitionInRegion(idExercise, idTaskDef);
    if (!result) {
        logger.warn("Could not remove task definition " + idTaskDef);
        MessageGenerator.sendErrorMessage("TaskDefinitionRemoveFailed", response);
        return;
    }
    MessageGenerator.sendSuccessMessage(response);
    return;
}

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

License:Apache License

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

    JsonObject json = (JsonObject) request.getAttribute(Constants.REQUEST_JSON);
    JsonElement idElement = json.get(Constants.ACTION_PARAM_ID);
    Integer id = idElement.getAsInt();
    if (hpc.deleteGateway(id))
        MessageGenerator.sendSuccessMessage(response);
    else/*  w  w  w.j  av  a 2  s .com*/
        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 . java  2  s.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.remediatetheflag.global.actions.auth.management.rtfadmin.UpdateSatelliteGatewayAction.java

License:Apache License

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

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

    JsonElement idElement = json.get(Constants.ACTION_PARAM_ID);
    JsonElement nameElement = json.get(Constants.ACTION_PARAM_NAME);
    JsonElement fqdnElement = json.get(Constants.ACTION_PARAM_FQDN);
    JsonElement statusElement = json.get(Constants.ACTION_PARAM_STATUS);

    Integer id = idElement.getAsInt();
    String name = nameElement.getAsString();
    String fqdn = fqdnElement.getAsString();
    Boolean status = statusElement.getAsBoolean();

    RTFGateway g = new RTFGateway();
    g.setName(name);/*from w w w . j a va2s  .  c  o  m*/
    g.setFqdn(fqdn);
    g.setActive(status);

    if (hpc.updateGateway(id, g))
        MessageGenerator.sendSuccessMessage(response);
    else
        MessageGenerator.sendErrorMessage("Failed", response);
}

From source file:com.remediatetheflag.global.actions.auth.management.team.AddChallengeAction.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 nameElement = json.get(Constants.ACTION_PARAM_NAME);
    JsonElement detailsElement = json.get(Constants.ACTION_PARAM_DETAILS);
    JsonElement startElement = json.get(Constants.ACTION_PARAM_START_DATE);
    JsonElement endElement = json.get(Constants.ACTION_PARAM_END_DATE);
    JsonElement idOrgElement = json.get(Constants.ACTION_PARAM_ID_ORG);
    JsonElement scoringElement = json.get(Constants.ACTION_PARAM_SCORING_MODE);
    JsonElement firstPlaceElement = json.get(Constants.ACTION_PARAM_SCORING_FIRST_PLACE);
    JsonElement secondPlaceElement = json.get(Constants.ACTION_PARAM_SCORING_SECOND_PLACE);
    JsonElement thirdPlaceElement = json.get(Constants.ACTION_PARAM_SCORING_THIRD_PLACE);

    Type listIntegerType = new TypeToken<List<Integer>>() {
    }.getType();//from w  w w. j  a v a  2  s .  co m
    Type listStringType = new TypeToken<List<String>>() {
    }.getType();

    Gson gson = new Gson();
    Set<User> challengeUsers = new HashSet<User>();
    Set<AvailableExercise> challengeExercises = new HashSet<AvailableExercise>();

    Challenge existingChallenge = hpc.getChallengeFromName(nameElement.getAsString());
    if (existingChallenge != null) {
        MessageGenerator.sendErrorMessage("NameNotAvailable", response);
        return;
    }

    Organization org = hpc.getOrganizationById(idOrgElement.getAsInt());
    if (!user.getManagedOrganizations().contains(org)) {
        MessageGenerator.sendErrorMessage("NotAuthorized", response);
        return;
    }
    try {
        List<String> users = gson.fromJson(json.get(Constants.ACTION_PARAM_USERID_LIST), listStringType);
        for (String username : users) {
            User tmpUser = hpc.getUserFromUsername(username);
            if (null != tmpUser && tmpUser.getDefaultOrganization().equals(org))
                challengeUsers.add(tmpUser);
        }
        List<Integer> exercises = gson.fromJson(json.get(Constants.ACTION_PARAM_EXERCISE_LIST),
                listIntegerType);
        for (Integer idExercise : exercises) {
            AvailableExercise tmpExercise = hpc.getAvailableExercise(idExercise, org);
            if (null != tmpExercise)
                challengeExercises.add(tmpExercise);
        }
    } catch (Exception e) {
        MessageGenerator.sendErrorMessage("ListsParseError", response);
        return;
    }

    Challenge challenge = new Challenge();
    challenge.setCreatedBy(user.getIdUser());
    challenge.setCompletion(0.0);
    challenge.setRunExercises(new LinkedList<ExerciseInstance>());
    challenge.setDetails(detailsElement.getAsString());

    challenge.setFirstInFlag(firstPlaceElement.getAsInt());
    challenge.setSecondInFlag(secondPlaceElement.getAsInt());
    challenge.setThirdInFlag(thirdPlaceElement.getAsInt());

    SimpleDateFormat parser = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss zzz");
    challenge.setEndDate(parser.parse(endElement.getAsString()));
    challenge.setStartDate(parser.parse(startElement.getAsString()));

    if (challenge.getEndDate().before(challenge.getStartDate())) {
        MessageGenerator.sendErrorMessage("DatesError", response);
        return;
    }

    challenge.setExercises(challengeExercises);
    challenge.setLastActivity(new Date());
    challenge.setName(nameElement.getAsString());
    challenge.setOrganization(org);
    try {
        ExerciseScoringMode scoring = ExerciseScoringMode.getStatusFromStatusCode(scoringElement.getAsInt());
        challenge.setScoring(scoring);
    } catch (Exception e) {
        challenge.setScoring(ExerciseScoringMode.MANUAL_REVIEW);
    }
    challenge.setUsers(challengeUsers);

    if (challenge.getStartDate().before(new Date()))
        challenge.setStatus(ChallengeStatus.IN_PROGRESS);
    else
        challenge.setStatus(ChallengeStatus.NOT_STARTED);

    Integer id = hpc.addChallenge(challenge);
    if (null != id)
        MessageGenerator.sendSuccessMessage(response);
    else
        MessageGenerator.sendErrorMessage("ChallengeNotSaved", response);

}