Java Code Examples for play.data.Form#reject()

The following examples show how to use play.data.Form#reject() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LessonController.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
@Transactional
@RequireCSRFCheck
public Result postEditLesson(long lessonId) throws LessonNotFoundException {
    Lesson lesson = lessonService.findLessonById(lessonId);

    if (!LessonControllerUtils.isAllowedToUpdateLesson(lessonService, lesson)) {
        return notFound();
    }

    Form<LessonEditForm> lessonEditForm = Form.form(LessonEditForm.class).bindFromRequest();

    if (formHasErrors(lessonEditForm)) {
        return showEditLesson(lessonEditForm, lesson);
    }

    if (!lesson.getSlug().equals(lessonEditForm.get().slug) && lessonService.lessonExistsBySlug(lessonEditForm.get().slug)) {
        lessonEditForm.reject("slug", Messages.get("error.lesson.slugExists"));
    }

    LessonEditForm lessonEditData = lessonEditForm.get();
    lessonService.updateLesson(lesson.getJid(), lessonEditData.slug, lessonEditData.additionalNote, IdentityUtils.getUserJid(), IdentityUtils.getIpAddress());

    return redirect(routes.LessonController.viewLesson(lesson.getId()));
}
 
Example 2
Source File: ProblemController.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
@Transactional
@RequireCSRFCheck
public Result postCreateProblem() {
    Form<ProblemCreateForm> problemCreateForm = Form.form(ProblemCreateForm.class).bindFromRequest();

    if (formHasErrors(problemCreateForm)) {
        return showCreateProblem(problemCreateForm);
    }

    if (problemService.problemExistsBySlug(problemCreateForm.get().slug)) {
        problemCreateForm.reject("slug", Messages.get("error.problem.slugExists"));
    }

    ProblemCreateForm problemCreateData = problemCreateForm.get();
    ProblemControllerUtils.setJustCreatedProblem(problemCreateData.slug, problemCreateData.additionalNote, problemCreateData.initLanguageCode);

    if (problemCreateData.type.equals(ProblemType.PROGRAMMING.name())) {
        return redirect(org.iatoki.judgels.sandalphon.problem.programming.routes.ProgrammingProblemController.createProgrammingProblem());
    } else if (problemCreateData.type.equals(ProblemType.BUNDLE.name())) {
        return redirect(org.iatoki.judgels.sandalphon.problem.bundle.routes.BundleProblemController.createBundleProblem());
    }

    return internalServerError();
}
 
Example 3
Source File: ProblemController.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
@Transactional
@RequireCSRFCheck
public Result postEditProblem(long problemId) throws ProblemNotFoundException {
    Problem problem = problemService.findProblemById(problemId);

    if (!ProblemControllerUtils.isAllowedToUpdateProblem(problemService, problem)) {
        return notFound();
    }

    Form<ProblemEditForm> problemEditForm = Form.form(ProblemEditForm.class).bindFromRequest();

    if (formHasErrors(problemEditForm)) {
        return showEditProblem(problemEditForm, problem);
    }

    if (!problem.getSlug().equals(problemEditForm.get().slug) && problemService.problemExistsBySlug(problemEditForm.get().slug)) {
        problemEditForm.reject("slug", Messages.get("error.problem.slugExists"));
    }

    ProblemEditForm problemEditData = problemEditForm.get();
    problemService.updateProblem(problem.getJid(), problemEditData.slug, problemEditData.additionalNote, IdentityUtils.getUserJid(), IdentityUtils.getIpAddress());

    return redirect(routes.ProblemController.viewProblem(problem.getId()));
}
 
Example 4
Source File: AdminController.java    From htwplus with MIT License 5 votes vote down vote up
@Transactional
public Result createAccount() {
    Form<Account> filledForm = accountForm.bindFromRequest();
    Logger.info(filledForm.errors().toString());

    filledForm.errors().remove("role");

    if (filledForm.data().get("email").isEmpty()) {
        filledForm.reject("email", "Bitte gib hier etwas ein!");
    }

    if (!(accountManager.findByEmail(filledForm.data().get("email")) == null)) {
        filledForm.reject("email", "Diese Email-Adresse wird bereits verwendet!");
    }

    if (!filledForm.data().get("password").equals(filledForm.data().get("repeatPassword"))) {
        filledForm.reject("repeatPassword", "Passwörter stimmen nicht überein");
    }

    if (filledForm.data().get("password").length() < 6) {
        filledForm.reject("password", "Das Passwort muss mindestens 6 Zeichen haben.");
    }

    if (filledForm.hasErrors()) {
        return badRequest(createAccount.render(filledForm));
    }
    Account account = new Account();
    account.firstname = filledForm.data().get("firstname");
    account.lastname = filledForm.data().get("lastname");
    account.email = filledForm.data().get("email");
    account.password = Component.md5(filledForm.data().get("password"));
    account.avatar = "1";
    account.role = AccountRole.values()[Integer.parseInt(filledForm.data().get("role"))];
    accountManager.create(account);

    flash("success", "User angelegt");
    return ok(createAccount.render(accountForm));

}
 
Example 5
Source File: LessonController.java    From judgels with GNU General Public License v2.0 5 votes vote down vote up
@Transactional
@RequireCSRFCheck
public Result postCreateLesson() {
    Form<LessonCreateForm> lessonCreateForm = Form.form(LessonCreateForm.class).bindFromRequest();

    if (formHasErrors(lessonCreateForm)) {
        return showCreateLesson(lessonCreateForm);
    }

    if (lessonService.lessonExistsBySlug(lessonCreateForm.get().slug)) {
        lessonCreateForm.reject("slug", Messages.get("error.lesson.slugExists"));
    }

    LessonCreateForm lessonCreateData = lessonCreateForm.get();

    Lesson lesson;
    try {
        lesson = lessonService.createLesson(lessonCreateData.slug, lessonCreateData.additionalNote, lessonCreateData.initLanguageCode, IdentityUtils.getUserJid(), IdentityUtils.getIpAddress());
        lessonService.updateStatement(null, lesson.getJid(), lessonCreateData.initLanguageCode, new LessonStatement(ProblemStatementUtils.getDefaultTitle(lessonCreateData.initLanguageCode), LessonStatementUtils.getDefaultText(lessonCreateData.initLanguageCode)));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    lessonService.initRepository(IdentityUtils.getUserJid(), lesson.getJid());

    LessonControllerUtils.setCurrentStatementLanguage(lessonCreateData.initLanguageCode);

    return redirect(routes.LessonController.index());
}
 
Example 6
Source File: ProgrammingProblemGradingController.java    From judgels with GNU General Public License v2.0 5 votes vote down vote up
@Transactional
@RequireCSRFCheck
public Result postEditLanguageRestriction(long problemId) throws ProblemNotFoundException {
    Problem problem = problemService.findProblemById(problemId);

    if (!ProgrammingProblemControllerUtils.isAllowedToManageGrading(problemService, problem)) {
        return notFound();
    }

    Form<LanguageRestrictionEditForm> languageRestrictionEditForm = Form.form(LanguageRestrictionEditForm.class).bindFromRequest(request());

    if (formHasErrors(languageRestrictionEditForm)) {
        return showEditLanguageRestriction(languageRestrictionEditForm, problem);
    }

    problemService.createUserCloneIfNotExists(IdentityUtils.getUserJid(), problem.getJid());

    LanguageRestrictionEditForm data = languageRestrictionEditForm.get();
    LanguageRestriction languageRestriction = LanguageRestrictionAdapter.createLanguageRestrictionFromForm(data.allowedLanguageNames, data.isAllowedAll);

    try {
        programmingProblemService.updateLanguageRestriction(IdentityUtils.getUserJid(), problem.getJid(), languageRestriction);
    } catch (IOException e) {
        languageRestrictionEditForm.reject("problem.programming.language.error.cantUpdate");
        return showEditLanguageRestriction(languageRestrictionEditForm, problem);
    }

    return redirect(routes.ProgrammingProblemGradingController.editLanguageRestriction(problem.getId()));
}
 
Example 7
Source File: ProgrammingProblemController.java    From judgels with GNU General Public License v2.0 5 votes vote down vote up
@Transactional
@RequireCSRFCheck
public Result postCreateProgrammingProblem() {
    if (!ProblemControllerUtils.wasProblemJustCreated()) {
        return badRequest();
    }

    Form<ProgrammingProblemCreateForm> programmingProblemCreateForm = Form.form(ProgrammingProblemCreateForm.class).bindFromRequest();

    if (formHasErrors(programmingProblemCreateForm)) {
        return showCreateProgrammingProblem(programmingProblemCreateForm);
    }

    String slug = ProblemControllerUtils.getJustCreatedProblemSlug();
    String additionalNote = ProblemControllerUtils.getJustCreatedProblemAdditionalNote();
    String languageCode = ProblemControllerUtils.getJustCreatedProblemInitLanguageCode();

    ProgrammingProblemCreateForm programmingProblemCreateData = programmingProblemCreateForm.get();

    Problem problem;
    try {
        problem = problemService.createProblem(ProblemType.PROGRAMMING, slug, additionalNote, languageCode, IdentityUtils.getUserJid(), IdentityUtils.getIpAddress());
        ProblemStatement statement = new ProblemStatement.Builder()
                .title(ProblemStatementUtils.getDefaultTitle(languageCode))
                .text(ProgrammingProblemStatementUtils.getDefaultText(languageCode))
                .build();
        problemService.updateStatement(null, problem.getJid(), languageCode, statement);
        programmingProblemService.initProgrammingProblem(problem.getJid(), programmingProblemCreateData.gradingEngineName);
    } catch (IOException e) {
        programmingProblemCreateForm.reject("problem.programming.error.cantCreate");
        return showCreateProgrammingProblem(programmingProblemCreateForm);
    }

    problemService.initRepository(IdentityUtils.getUserJid(), problem.getJid());

    ProblemControllerUtils.setCurrentStatementLanguage(ProblemControllerUtils.getJustCreatedProblemInitLanguageCode());
    ProblemControllerUtils.removeJustCreatedProblem();

    return redirect(org.iatoki.judgels.sandalphon.problem.base.routes.ProblemController.enterProblem(problem.getId()));
}
 
Example 8
Source File: JophielClientController.java    From judgels with GNU General Public License v2.0 5 votes vote down vote up
@RequireCSRFCheck
@Transactional
public Result postLogin() {
    Form<LoginForm> form = Form.form(LoginForm.class).bindFromRequest();
    if (form.hasErrors()) {
        return showLogin(form);
    }

    LoginForm data = form.get();

    PlaySession session;
    try {
        session = sessionService.logIn(Credentials.of(data.username, data.password));
    } catch (RemoteException e) {
        if (e.getError().errorName().equals(PlaySessionErrors.ROLE_NOT_ALLOWED.name())) {
            form.reject("User role not allowed to log in.");
        } else if (e.getStatus() == 403) {
            form.reject("Username or password incorrect.");
        }
        return showLogin(form);
    }

    session("version", JophielSessionUtils.getSessionVersion());
    session("token", session.getToken());
    session("userJid", session.getUserJid());
    session("username", session.getUsername());
    session("role", session.getRole());
    session("avatar", getUserAvatarUrl(session.getUserJid()));

    return redirect(getServiceLoginUrl(session.getAuthCode(), getRootUrl(Http.Context.current().request())));
}
 
Example 9
Source File: ItemShortAnswerConfAdapter.java    From judgels with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Form bindFormFromRequest(Http.Request request) {
    Form form = Form.form(ItemShortAnswerConfForm.class).bindFromRequest();
    if (!(form.hasErrors() || form.hasGlobalErrors())) {
        ItemShortAnswerConfForm confForm = ((Form<ItemShortAnswerConfForm>) form).get();
        if (!isRegexValid(confForm.inputValidationRegex)) {
            form.reject(Messages.get("error.problem.bundle.item.shortAnswer.invalidInputValidationRegex"));
        }
        if (!confForm.gradingRegex.isEmpty() && !isRegexValid(confForm.gradingRegex)) {
            form.reject(Messages.get("error.problem.bundle.item.shortAnswer.invalidGradingRegex"));
        }
    }
    return form;
}
 
Example 10
Source File: ItemMultipleChoiceConfAdapter.java    From judgels with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Form bindFormFromRequest(Http.Request request) {
    Form form = Form.form(ItemMultipleChoiceConfForm.class).bindFromRequest();
    if (!(form.hasErrors() || form.hasGlobalErrors())) {
        ItemMultipleChoiceConfForm confForm = ((Form<ItemMultipleChoiceConfForm>) form).get();
        Set<String> uniqueChoiceAliases = Sets.newHashSet(confForm.choiceAliases);
        if (uniqueChoiceAliases.size() != confForm.choiceAliases.size()) {
            form.reject(Messages.get("error.problem.bundle.item.multipleChoice.duplicateAlias"));
        }
    }
    return form;
}
 
Example 11
Source File: SunriseCheckoutPaymentController.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
@Override
public CompletionStage<Form<? extends CheckoutPaymentFormData>> validateForm(final PaymentMethodsWithCart paymentMethodsWithCart, final Form<? extends CheckoutPaymentFormData> filledForm) {
    final String selectedPaymentMethod = filledForm.field("payment").valueOr("");
    if (!selectedPaymentMethod.isEmpty() && !isValidPaymentMethod(paymentMethodsWithCart, selectedPaymentMethod)) {
        filledForm.reject("Invalid payment error"); // TODO get from i18n
    }
    return completedFuture(filledForm);
}
 
Example 12
Source File: BundleProblemPartnerController.java    From judgels with GNU General Public License v2.0 4 votes vote down vote up
@Transactional
@RequireCSRFCheck
public Result postAddPartner(long problemId) throws ProblemNotFoundException {
    Problem problem = problemService.findProblemById(problemId);

    if (!ProblemControllerUtils.isAuthorOrAbove(problem)) {
        return notFound();
    }

    Form<ProblemPartnerUsernameForm> usernameForm = Form.form(ProblemPartnerUsernameForm.class).bindFromRequest();
    Form<ProblemPartnerUpsertForm> problemForm = Form.form(ProblemPartnerUpsertForm.class).bindFromRequest();
    Form<BundlePartnerUpsertForm> bundleForm = Form.form(BundlePartnerUpsertForm.class).bindFromRequest();

    if (formHasErrors(usernameForm) || formHasErrors(problemForm) || formHasErrors(bundleForm)) {
        return showAddPartner(usernameForm, problemForm, bundleForm, problem);
    }

    String username = usernameForm.get().username;
    ProblemPartnerUpsertForm problemData = problemForm.get();
    BundlePartnerUpsertForm bundleData = bundleForm.get();

    Map<String, String> usernameToJidMap = userSearchService.translateUsernamesToJids(ImmutableSet.of(username));

    if (!usernameToJidMap.containsKey(username)) {
        usernameForm.reject("username", Messages.get("problem.partner.usernameNotFound"));
        return showAddPartner(usernameForm, problemForm, bundleForm, problem);
    }

    String userJid = usernameToJidMap.get(username);

    JidCacheServiceImpl.getInstance().putDisplayName(userJid, JudgelsPlayUtils.getUserDisplayName(username), IdentityUtils.getUserJid(), IdentityUtils.getIpAddress());

    if (problemService.isUserPartnerForProblem(problem.getJid(), userJid)) {
        usernameForm.reject("username", Messages.get("problem.partner.already"));
        return showAddPartner(usernameForm, problemForm, bundleForm, problem);
    }

    ProblemPartnerConfig problemConfig = new ProblemPartnerConfigBuilder()
          .setIsAllowedToUpdateProblem(problemData.isAllowedToUpdateProblem)
          .setIsAllowedToUpdateStatement(problemData.isAllowedToUpdateStatement)
          .setIsAllowedToUploadStatementResources(problemData.isAllowedToUploadStatementResources)
          .setAllowedStatementLanguagesToView(PartnerControllerUtils.splitByComma(problemData.allowedStatementLanguagesToView))
          .setAllowedStatementLanguagesToUpdate(PartnerControllerUtils.splitByComma(problemData.allowedStatementLanguagesToUpdate))
          .setIsAllowedToManageStatementLanguages(problemData.isAllowedToManageStatementLanguages)
          .setIsAllowedToViewVersionHistory(problemData.isAllowedToViewVersionHistory)
          .setIsAllowedToRestoreVersionHistory(problemData.isAllowedToRestoreVersionHistory)
          .setIsAllowedToManageProblemClients(problemData.isAllowedToManageProblemClients)
          .build();

    BundleProblemPartnerConfig bundleConfig = new BundleProblemPartnerConfig(bundleData.isAllowedToSubmit, bundleData.isAllowedToManageItems);

    problemService.createProblemPartner(problem.getJid(), userJid, problemConfig, bundleConfig, IdentityUtils.getUserJid(), IdentityUtils.getIpAddress());

    return redirect(org.iatoki.judgels.sandalphon.problem.base.partner.routes.ProblemPartnerController.viewPartners(problem.getId()));
}
 
Example 13
Source File: ProfileController.java    From htwplus with MIT License 4 votes vote down vote up
public Result update(Long id) {
    // Get regarding Object
    Account account = accountManager.findById(id);
    if (account == null) {
        flash("info", "Diese Person gibt es nicht.");
        return redirect(controllers.routes.Application.index());
    }

    // Check Access
    if (!Secured.editAccount(account)) {
        return redirect(controllers.routes.Application.index());
    }

    // Get the data from the request
    Form<Account> filledForm = accountForm.bindFromRequest();

    Navigation.set(Level.PROFILE, "Editieren");

    // Remove expected errors
    filledForm.errors().remove("password");
    filledForm.errors().remove("studycourse");
    filledForm.errors().remove("firstname");
    filledForm.errors().remove("lastname");

    // Custom Validations
    Account exisitingAccount = accountManager.findByEmail(filledForm.field("email").value());
    if (exisitingAccount != null && !exisitingAccount.equals(account)) {
        filledForm.reject("email", "Diese Mail wird bereits verwendet!");
        return badRequest(edit.render(account, filledForm, loginForm, studycourseManager.getAll()));
    }

    // Perform JPA Validation
    if (filledForm.hasErrors()) {
        return badRequest(edit.render(account, filledForm, loginForm, studycourseManager.getAll()));
    } else {

        // Fill an and update the model manually
        // because the its just a partial form
        if (!filledForm.field("email").value().isEmpty()) {
            account.email = filledForm.field("email").value();
        } else {
            account.email = null;
            account.emailNotifications = EmailNotifications.NONE;
            account.dailyEmailNotificationHour = null;
        }

        if (filledForm.data().containsKey("degree")) {
            if (filledForm.field("degree").value().equals("null")) {
                account.degree = null;
            } else {
                account.degree = filledForm.field("degree").value();
            }
        }

        if (filledForm.data().containsKey("semester")) {
            if (filledForm.field("semester").value().equals("0")) {
                account.semester = null;
            } else {
                account.semester = Integer.parseInt(filledForm.field("semester").value());
            }
        }

        if (filledForm.data().containsKey("emailNotifications") && (account.email != null && !account.email.isEmpty())) {
            account.emailNotifications = EmailNotifications.valueOf(filledForm.field("emailNotifications").value());
            if (account.emailNotifications.equals(EmailNotifications.COLLECTED_DAILY)
                    && filledForm.data().containsKey("dailyEmailNotificationHour")) {
                account.dailyEmailNotificationHour = Integer.valueOf(
                        filledForm.field("dailyEmailNotificationHour").value()
                );
            }
        }

        Long studycourseId = Long.parseLong(filledForm.field("studycourse").value());
        Studycourse studycourse;
        if (studycourseId != 0) {
            studycourse = studycourseManager.findById(studycourseId);
        } else {
            studycourse = null;
        }
        account.studycourse = studycourse;

        if (!filledForm.field("about").value().isEmpty()) {
            account.about = filledForm.field("about").value();
        } else {
            account.about = null;
        }

        if (!filledForm.field("homepage").value().isEmpty()) {
            account.homepage = filledForm.field("homepage").value();
        } else {
            account.homepage = null;
        }

        accountManager.update(account);

        flash("success", "Profil erfolgreich gespeichert.");
        return redirect(controllers.routes.ProfileController.me());
    }
}
 
Example 14
Source File: ProfileController.java    From htwplus with MIT License 4 votes vote down vote up
public Result saveConvert(Long id) {
    // Get regarding Object
    Account account = accountManager.findById(id);
    if (account == null) {
        flash("info", "Diese Person gibt es nicht.");
        return redirect(controllers.routes.Application.index());
    }

    // Create error switch
    Boolean error = false;

    // Check Access
    if (!Secured.isAdmin()) {
        return redirect(controllers.routes.Application.index());
    }

    // Get data from request
    Form<Account> filledForm = accountForm.bindFromRequest();


    // Remove all unnecessary fields
    filledForm.errors().remove("firstname");
    filledForm.errors().remove("lastname");

    // Store old and new password for validation
    String email = filledForm.field("email").value();
    String password = filledForm.field("password").value();
    String repeatPassword = filledForm.field("repeatPassword").value();

    // Perform JPA Validation
    if (filledForm.hasErrors()) {
        error = true;
    }

    if (email.isEmpty()) {
        filledForm.reject("email", "Für einen lokalen Account ist eine EMail nötig!");
        error = true;
    }
    if (password.length() < 6) {
        filledForm.reject("password", "Das Passwort muss mindestens 6 Zeichen haben.");
        error = true;
    }

    if (!password.equals(repeatPassword)) {
        filledForm.reject("repeatPassword", "Die Passwörter stimmen nicht überein.");
        error = true;
    }

    if (error) {
        return badRequest(convert.render(account, filledForm));
    } else {
        account.password = Component.md5(password);
        account.email = email;
        accountManager.update(account);
        flash("success", "Account erfolgreich konvertiert.");
    }
    return redirect(controllers.routes.ProfileController.view(id));
}
 
Example 15
Source File: GroupController.java    From htwplus with MIT License 4 votes vote down vote up
public Result add() {
    Navigation.set(Level.GROUPS, "Erstellen");

    // Get data from request
    Form<Group> filledForm = groupForm.bindFromRequest();

    // Perform JPA Validation
    if (filledForm.hasErrors()) {
        return badRequest(create.render(filledForm));
    } else {
        Group group = filledForm.get();
        int groupType;
        try {
            groupType = Integer.parseInt(filledForm.data().get("type"));
        } catch (NumberFormatException ex) {
            filledForm.reject("type", "Bitte eine Sichtbarkeit wählen!");
            return ok(create.render(filledForm));
        }

        String successMsg;
        switch (groupType) {

            case 0:
                group.groupType = GroupType.open;
                successMsg = "Öffentliche Gruppe";
                break;

            case 1:
                group.groupType = GroupType.close;
                successMsg = "Geschlossene Gruppe";
                break;

            case 2:
                group.groupType = GroupType.course;
                successMsg = "Kurs";
                String token = filledForm.data().get("token");
                if (!Group.validateToken(token)) {
                    filledForm.reject("token", "Bitte einen Token zwischen 4 und 45 Zeichen eingeben!");
                    return ok(create.render(filledForm));
                }

                if (!Secured.createCourse()) {
                    flash("error", "Du darfst leider keinen Kurs erstellen");
                    return badRequest(create.render(filledForm));
                }
                break;

            default:
                filledForm.reject("Nicht möglich!");
                return ok(create.render(filledForm));
        }

        groupManager.createWithGroupAccount(group, Component.currentAccount());
        flash("success", successMsg + " erstellt!");
        return redirect(controllers.routes.GroupController.stream(group.id, PAGE, false));
    }
}
 
Example 16
Source File: WithFormFlow.java    From commercetools-sunrise-java with Apache License 2.0 4 votes vote down vote up
default void saveUnexpectedFormError(final Form<? extends F> form, final Throwable throwable) {
    form.reject("Something went wrong, please try again"); // TODO i18n
    getLogger().error("The CTP request raised an unexpected exception", throwable);
}
 
Example 17
Source File: WithFormFlow.java    From commercetools-sunrise-java with Apache License 2.0 4 votes vote down vote up
default void saveFormError(final Form<? extends F> form, final String message) {
    form.reject(message);
}
 
Example 18
Source File: ProgrammingProblemPartnerController.java    From judgels with GNU General Public License v2.0 4 votes vote down vote up
@Transactional
@RequireCSRFCheck
public Result postAddPartner(long problemId) throws ProblemNotFoundException {
    Problem problem = problemService.findProblemById(problemId);

    if (!ProblemControllerUtils.isAuthorOrAbove(problem)) {
        return notFound();
    }

    Form<ProblemPartnerUsernameForm> usernameForm = Form.form(ProblemPartnerUsernameForm.class).bindFromRequest();
    Form<ProblemPartnerUpsertForm> problemForm = Form.form(ProblemPartnerUpsertForm.class).bindFromRequest();
    Form<ProgrammingPartnerUpsertForm> programmingForm = Form.form(ProgrammingPartnerUpsertForm.class).bindFromRequest();

    if (formHasErrors(usernameForm) || formHasErrors(problemForm) || formHasErrors(programmingForm)) {
        return showAddPartner(usernameForm, problemForm, programmingForm, problem);
    }

    String username = usernameForm.get().username;
    ProblemPartnerUpsertForm problemData = problemForm.get();
    ProgrammingPartnerUpsertForm programmingData = programmingForm.get();

    Map<String, String> usernameToJidMap = userSearchService.translateUsernamesToJids(ImmutableSet.of(username));

    if (!usernameToJidMap.containsKey(username)) {
        usernameForm.reject("username", Messages.get("problem.partner.usernameNotFound"));
        return showAddPartner(usernameForm, problemForm, programmingForm, problem);
    }

    String userJid = usernameToJidMap.get(username);

    JidCacheServiceImpl.getInstance().putDisplayName(userJid, JudgelsPlayUtils.getUserDisplayName(username), IdentityUtils.getUserJid(), IdentityUtils.getIpAddress());

    if (problemService.isUserPartnerForProblem(problem.getJid(), userJid)) {
        usernameForm.reject("username", Messages.get("problem.partner.already"));
        return showAddPartner(usernameForm, problemForm, programmingForm, problem);
    }

    ProblemPartnerConfig problemConfig = new ProblemPartnerConfigBuilder()
          .setIsAllowedToUpdateProblem(problemData.isAllowedToUpdateProblem)
          .setIsAllowedToUpdateStatement(problemData.isAllowedToUpdateStatement)
          .setIsAllowedToUploadStatementResources(problemData.isAllowedToUploadStatementResources)
          .setAllowedStatementLanguagesToView(PartnerControllerUtils.splitByComma(problemData.allowedStatementLanguagesToView))
          .setAllowedStatementLanguagesToUpdate(PartnerControllerUtils.splitByComma(problemData.allowedStatementLanguagesToUpdate))
          .setIsAllowedToManageStatementLanguages(problemData.isAllowedToManageStatementLanguages)
          .setIsAllowedToViewVersionHistory(problemData.isAllowedToViewVersionHistory)
          .setIsAllowedToRestoreVersionHistory(problemData.isAllowedToRestoreVersionHistory)
          .setIsAllowedToManageProblemClients(problemData.isAllowedToManageProblemClients)
          .build();

    ProgrammingProblemPartnerConfig programmingConfig = new ProgrammingProblemPartnerConfigBuilder()
          .setIsAllowedToSubmit(programmingData.isAllowedToSubmit)
          .setIsAllowedToManageGrading(programmingData.isAllowedToManageGrading)
          .build();

    problemService.createProblemPartner(problem.getJid(), userJid, problemConfig, programmingConfig, IdentityUtils.getUserJid(), IdentityUtils.getIpAddress());

    return redirect(org.iatoki.judgels.sandalphon.problem.base.partner.routes.ProblemPartnerController.viewPartners(problem.getId()));
}
 
Example 19
Source File: LessonPartnerController.java    From judgels with GNU General Public License v2.0 4 votes vote down vote up
@Transactional
@RequireCSRFCheck
public Result postAddPartner(long lessonId) throws LessonNotFoundException {
    Lesson lesson = lessonService.findLessonById(lessonId);

    if (!LessonControllerUtils.isAuthorOrAbove(lesson)) {
        return notFound();
    }

    Form<LessonPartnerUsernameForm> usernameForm = Form.form(LessonPartnerUsernameForm.class).bindFromRequest();
    Form<LessonPartnerUpsertForm> lessonForm = Form.form(LessonPartnerUpsertForm.class).bindFromRequest();

    if (formHasErrors(usernameForm) || formHasErrors(lessonForm)) {
        return showAddPartner(usernameForm, lessonForm, lesson);
    }

    String username = usernameForm.get().username;
    LessonPartnerUpsertForm lessonData = lessonForm.get();

    Map<String, String> usernameToJidMap = userSearchService.translateUsernamesToJids(ImmutableSet.of(username));

    if (!usernameToJidMap.containsKey(username)) {
        usernameForm.reject("username", Messages.get("lesson.partner.usernameNotFound"));
        return showAddPartner(usernameForm, lessonForm, lesson);
    }

    String userJid = usernameToJidMap.get(username);

    JidCacheServiceImpl.getInstance().putDisplayName(userJid, JudgelsPlayUtils.getUserDisplayName(username), IdentityUtils.getUserJid(), IdentityUtils.getIpAddress());

    if (lessonService.isUserPartnerForLesson(lesson.getJid(), userJid)) {
        usernameForm.reject("username", Messages.get("lesson.partner.already"));
        return showAddPartner(usernameForm, lessonForm, lesson);
    }

    LessonPartnerConfig partnerConfig = new LessonPartnerConfigBuilder()
          .setIsAllowedToUpdateLesson(lessonData.isAllowedToUpdateLesson)
          .setIsAllowedToUpdateStatement(lessonData.isAllowedToUpdateStatement)
          .setIsAllowedToUploadStatementResources(lessonData.isAllowedToUploadStatementResources)
          .setAllowedStatementLanguagesToView(PartnerControllerUtils.splitByComma(lessonData.allowedStatementLanguagesToView))
          .setAllowedStatementLanguagesToUpdate(PartnerControllerUtils.splitByComma(lessonData.allowedStatementLanguagesToUpdate))
          .setIsAllowedToManageStatementLanguages(lessonData.isAllowedToManageStatementLanguages)
          .setIsAllowedToViewVersionHistory(lessonData.isAllowedToViewVersionHistory)
          .setIsAllowedToRestoreVersionHistory(lessonData.isAllowedToRestoreVersionHistory)
          .setIsAllowedToManageLessonClients(lessonData.isAllowedToManageLessonClients)
          .build();

    lessonService.createLessonPartner(lesson.getJid(), userJid, partnerConfig, IdentityUtils.getUserJid(), IdentityUtils.getIpAddress());

    return redirect(routes.LessonPartnerController.viewPartners(lesson.getId()));
}