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

The following examples show how to use play.data.Form#hasErrors() . 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: LocalAuthController.java    From gsn with GNU General Public License v3.0 6 votes vote down vote up
public static Result doAdduser() {
	com.feth.play.module.pa.controllers.Authenticate.noCache(response());
	final Form<GSNSignup> filledForm = GSNUsernamePasswordAuthProvider.SIGNUP_FORM
			.bindFromRequest();
	if (filledForm.hasErrors()) {
		return badRequest(adduser.render(filledForm));
	} else {
		GSNUsernamePasswordAuthUser guser = new GSNUsernamePasswordAuthUser(filledForm.get());
		final User u = User.findByUsernamePasswordIdentity(guser);
		if (u != null) {
			flash(LocalAuthController.FLASH_ERROR_KEY,
					Messages.get("playauthenticate.user.exists.message"));
			return badRequest(adduser.render(filledForm));
		}
		// The user either does not exist or is inactive - create a new one
		// manually created users are directly validated
		@SuppressWarnings("unused")
		final User newUser = User.create(guser);
		newUser.emailValidated = true;
		newUser.save();
		return ok(adduser.render(GSNUsernamePasswordAuthProvider.SIGNUP_FORM));
	}
}
 
Example 2
Source File: PortfolioController.java    From reactive-stock-trader with Apache License 2.0 6 votes vote down vote up
public CompletionStage<Result> openPortfolio() {
    Form<OpenPortfolioForm> form = openPortfolioForm.bindFromRequest();
    if (form.hasErrors()) {
        return CompletableFuture.completedFuture(badRequest(form.errorsAsJson()));
    } else {
        OpenPortfolioDetails openRequest = form.get().toRequest();
        return portfolioService
                .openPortfolio()
                .invoke(openRequest)
                .thenApply(portfolioId -> {
                    val jsonResult = Json.newObject()
                            .put("portfolioId", portfolioId.getId());
                    return Results.created(jsonResult);
                });
    }
}
 
Example 3
Source File: PortfolioController.java    From reactive-stock-trader with Apache License 2.0 6 votes vote down vote up
public CompletionStage<Result> placeOrder(String portfolioId) {
    Form<PlaceOrderForm> form = placeOrderForm.bindFromRequest();
    if (form.hasErrors()) {
        return CompletableFuture.completedFuture(badRequest(form.errorsAsJson()));
    } else {
        PlaceOrderForm orderForm = form.get();

        OrderDetails order = OrderDetails.builder()
                .tradeType(orderForm.getOrder().toTradeType())
                .symbol(orderForm.getSymbol())
                .shares(orderForm.getShares())
                .orderType(OrderType.Market.INSTANCE)
                .build();
        return portfolioService
                .placeOrder(new PortfolioId(portfolioId))
                .invoke(order)
                .thenApply(orderId -> {
                    val jsonResult = Json.newObject()
                            .put("orderId", orderId.getId());
                    return Results.status(Http.Status.ACCEPTED, jsonResult);
                });

    }
}
 
Example 4
Source File: Items.java    From pfe-samples with MIT License 6 votes vote down vote up
@DB
public Result create() {
    Form<CreateItem> submission = Form.form(CreateItem.class).bindFromRequest();
    if (submission.hasErrors()) {
        return render(
                version(MimeTypes.HTML, () -> badRequest(views.html.createForm.render(submission))),
                version(MimeTypes.JSON, () -> badRequest(submission.errorsAsJson()))
        );
    } else {
        CreateItem createItem = submission.get();
        Item item = service.shop.create(createItem.name, createItem.price);
        if (item != null) {
            return render(
                    version(MimeTypes.HTML, () -> redirect(routes.Items.details(item.id))),
                    version(MimeTypes.JSON, () -> ok(Json.toJson(item)))
            );
        } else {
            return internalServerError();
        }
    }
}
 
Example 5
Source File: GroupController.java    From htwplus with MIT License 6 votes vote down vote up
public Result createFolder(Long folderId) {
    Folder parentFolder = folderManager.findById(folderId);
    Group group = folderManager.findRoot(parentFolder).group;
    Folder folder = null;

    Form<Folder> filledForm = folderForm.bindFromRequest();

    if(filledForm.hasErrors()) {
        if(filledForm.data().get("name").isEmpty()) {
            flash("error", "Bitte einen Ordnernamen angeben.");
            return redirect(routes.GroupController.media(group.id, folderId));
        }
    }
    if(Secured.isMemberOfGroup(group, Component.currentAccount())) {
        folder = new Folder(filledForm.data().get("name"), Component.currentAccount(), parentFolder, null, null);
        folderManager.create(folder);
        return redirect(routes.GroupController.media(group.id, folder.id));
    }
    flash("error", messagesApi.get(Lang.defaultLang(), "post.join_group_first"));
    return redirect(routes.GroupController.media(group.id, folderId));
}
 
Example 6
Source File: Account.java    From gsn with GNU General Public License v3.0 6 votes vote down vote up
@SubjectPresent
public static Result doLink() {
	com.feth.play.module.pa.controllers.Authenticate.noCache(response());
	final AuthUser u = PlayAuthenticate.getLinkUser(session());
	if (u == null) {
		// account to link could not be found, silently redirect to login
		return redirect(routes.LocalAuthController.index());
	}

	final Form<Accept> filledForm = ACCEPT_FORM.bindFromRequest();
	if (filledForm.hasErrors()) {
		// User did not select whether to link or not link
		return badRequest(ask_link.render(filledForm, u));
	} else {
		// User made a choice :)
		final boolean link = filledForm.get().accept;
		if (link) {
			flash(LocalAuthController.FLASH_MESSAGE_KEY,
					Messages.get("playauthenticate.accounts.link.success"));
		}
		return PlayAuthenticate.link(ctx(), link);
	}
}
 
Example 7
Source File: Credential.java    From play-mpc with MIT License 5 votes vote down vote up
/**
 * Performs POST /login
 * @return an action result
 */
public static Result authenticate()
{
	Form<Login> loginForm = Form.form(Login.class).bindFromRequest();
	if (loginForm.hasErrors())
	{
		return unauthorized(login.render(loginForm));
	}
	else
	{
		session().clear();
		session("email", loginForm.get().email);
		return redirect(routes.Application.index());
	}
}
 
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: Items.java    From pfe-samples with MIT License 5 votes vote down vote up
@DB
public Result update(Long id) {
    Form<CreateItem> submission = Form.form(CreateItem.class).bindFromRequest();
    if (submission.hasErrors()) {
        return badRequest(submission.errorsAsJson());
    } else {
        CreateItem updateItem = submission.get();
        Item updated = service.shop.update(id, updateItem.name, updateItem.price);
        if (updated != null) {
            return ok(Json.toJson(updated));
        } else {
            return internalServerError();
        }
    }
}
 
Example 10
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 11
Source File: LocalAuthController.java    From gsn with GNU General Public License v3.0 5 votes vote down vote up
public static Result doSignup() {
	com.feth.play.module.pa.controllers.Authenticate.noCache(response());
	final Form<GSNSignup> filledForm = GSNUsernamePasswordAuthProvider.SIGNUP_FORM
			.bindFromRequest();
	if (filledForm.hasErrors()) {
		// User did not fill everything properly
		return badRequest(signup.render(filledForm));
	} else {
		// Everything was filled
		// do something with your part of the form before handling the user
		// signup
		return UsernamePasswordAuthProvider.handleSignup(ctx());
	}
}
 
Example 12
Source File: ProfileController.java    From htwplus with MIT License 5 votes vote down vote up
/**
 * Create the real avatar with the given dimensions
 *
 * @param id
 * @return
 */
public Result createAvatar(long id) {
    ObjectNode result = Json.newObject();

    Account account = accountManager.findById(id);

    if (account == null) {
        return notFound();
    }

    if (!Secured.editAccount(account)) {
        result.put("error", "Not allowed.");
        return forbidden(result);
    }

    Form<Avatar> form = formFactory.form(Avatar.class).bindFromRequest();

    if (form.hasErrors()) {
        result.set("error", form.errorsAsJson());
        return badRequest(result);
    }

    try {
        accountManager.saveAvatar(form.get(), account);
        result.put("success", "saved");
        return ok(result);
    } catch (FileOperationException e) {
        result.put("error", "Unexpected Error while saving avatar.");
        return internalServerError(result);
    }
}
 
Example 13
Source File: GroupController.java    From htwplus with MIT License 5 votes vote down vote up
/**
 * Create the real avatar with the given dimensions
 *
 * @param id
 * @return
 */
public Result createAvatar(long id) {
    ObjectNode result = Json.newObject();

    Group group = groupManager.findById(id);

    if (group == null) {
        return notFound();
    }

    if (!Secured.editGroup(group)) {
        result.put("error", "Not allowed.");
        return forbidden(result);
    }

    Form<Avatar> form = formFactory.form(Avatar.class).bindFromRequest();

    if (form.hasErrors()) {
        result.set("error", form.errorsAsJson());
        return badRequest(result);
    }

    try {
        groupManager.saveAvatar(form.get(), group);
        result.put("success", "saved");
        return ok(result);
    } catch (FileOperationException e) {
        result.put("error", "Unexpected Error while saving avatar.");
        return internalServerError(result);
    }
}
 
Example 14
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 15
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 16
Source File: TodoController.java    From play-rest-security with MIT License 5 votes vote down vote up
public Result createTodo() {
    Form<Todo> form = formFactory.form(Todo.class).bindFromRequest();
    if (form.hasErrors()) {
        return badRequest(form.errorsAsJson());
    }
    else {
        Todo todo = form.get();
        todo.user = SecurityController.getUser();
        todo.save();
        return ok(toJson(todo));
    }
}
 
Example 17
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 18
Source File: Signup.java    From gsn with GNU General Public License v3.0 4 votes vote down vote up
public static Result doForgotPassword() {
	com.feth.play.module.pa.controllers.Authenticate.noCache(response());
	final Form<GSNIdentity> filledForm = FORGOT_PASSWORD_FORM
			.bindFromRequest();
	if (filledForm.hasErrors()) {
		// User did not fill in his/her email
		return badRequest(password_forgot.render(filledForm));
	} else {
		// The email address given *BY AN UNKNWON PERSON* to the form - we
		// should find out if we actually have a user with this email
		// address and whether password login is enabled for him/her. Also
		// only send if the email address of the user has been verified.
		final String email = filledForm.get().email;

		// We don't want to expose whether a given email address is signed
		// up, so just say an email has been sent, even though it might not
		// be true - that's protecting our user privacy.
		flash(LocalAuthController.FLASH_MESSAGE_KEY,
				Messages.get(
						"playauthenticate.reset_password.message.instructions_sent",
						email));

		final User user = User.findByEmail(email);
		if (user != null) {
			// yep, we have a user with this email that is active - we do
			// not know if the user owning that account has requested this
			// reset, though.
			final GSNUsernamePasswordAuthProvider provider = GSNUsernamePasswordAuthProvider
					.getProvider();
			// User exists
			if (user.emailValidated) {
				provider.sendPasswordResetMailing(user, ctx());
				// In case you actually want to let (the unknown person)
				// know whether a user was found/an email was sent, use,
				// change the flash message
			} else {
				// We need to change the message here, otherwise the user
				// does not understand whats going on - we should not verify
				// with the password reset, as a "bad" user could then sign
				// up with a fake email via OAuth and get it verified by an
				// a unsuspecting user that clicks the link.
				flash(LocalAuthController.FLASH_MESSAGE_KEY,
						Messages.get("playauthenticate.reset_password.message.email_not_verified"));

				// You might want to re-send the verification email here...
				provider.sendVerifyEmailMailingAfterSignup(user, ctx());
			}
		}

		return redirect(routes.LocalAuthController.index());
	}
}
 
Example 19
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 20
Source File: Signup.java    From gsn with GNU General Public License v3.0 4 votes vote down vote up
public static Result doResetPassword() {
	com.feth.play.module.pa.controllers.Authenticate.noCache(response());
	final Form<PasswordReset> filledForm = PASSWORD_RESET_FORM
			.bindFromRequest();
	if (filledForm.hasErrors()) {
		return badRequest(password_reset.render(filledForm));
	} else {
		final String token = filledForm.get().token;
		final String newPassword = filledForm.get().password;

		final TokenAction ta = tokenIsValid(token, Type.PASSWORD_RESET);
		if (ta == null) {
			return badRequest(no_token_or_invalid.render());
		}
		final User u = ta.targetUser;
		try {
			// Pass true for the second parameter if you want to
			// automatically create a password and the exception never to
			// happen
			u.resetPassword(new GSNUsernamePasswordAuthUser(newPassword),
					false);
		} catch (final RuntimeException re) {
			flash(LocalAuthController.FLASH_MESSAGE_KEY,
					Messages.get("playauthenticate.reset_password.message.no_password_account"));
		}
		final boolean login = GSNUsernamePasswordAuthProvider.getProvider()
				.isLoginAfterPasswordReset();
		if (login) {
			// automatically log in
			flash(LocalAuthController.FLASH_MESSAGE_KEY,
					Messages.get("playauthenticate.reset_password.message.success.auto_login"));

			return PlayAuthenticate.loginAndRedirect(ctx(),
					new GSNLoginUsernamePasswordAuthUser(u.email));
		} else {
			// send the user to the login page
			flash(LocalAuthController.FLASH_MESSAGE_KEY,
					Messages.get("playauthenticate.reset_password.message.success.manual_login"));
		}
		return redirect(routes.LocalAuthController.login());
	}
}