@Security.Authenticated(Secured.class) public static Result newUser() { User user = getCurrentUser(); if (!user.isAdmin) return redirect(routes.Application.contacts()); Form<User> filledForm = userForm.bindFromRequest(); if (!filledForm.field("password").valueOr("").isEmpty()) { if (!filledForm .field("password") .valueOr("") .equals(filledForm.field("repeatPassword").value())) { filledForm.reject("repeatPassword", "Passwörter stimmen nicht überein"); } } if (!filledForm.hasErrors()) { if (userAlreadyExists(filledForm.get().email)) { filledForm.reject("email", "Diese Emailadresse ist bereits vergeben"); } } if (filledForm.hasErrors()) { flash("error", "Bitte korrigieren sie ihre Eingaben!"); return badRequest(views.html.addUser.render(filledForm, getCurrentUser(), User.find.all())); } else { User.create(filledForm.get()); flash("success", "Benutzer " + filledForm.get().email + " erstellt."); return redirect(routes.Application.contacts()); } }
/* * 사용자 가입 입력 폼 유효성 체크 */ private static void validate(Form<User> newUserForm) { // loginId가 빈 값이 들어오면 안된다. if (newUserForm.field("loginId").value().trim().isEmpty()) { newUserForm.reject("loginId", "user.wrongloginId.alert"); } if (newUserForm.field("loginId").value().contains(" ")) { newUserForm.reject("loginId", "user.wrongloginId.alert"); } // password가 빈 값이 들어오면 안된다. if (newUserForm.field("password").value().trim().isEmpty()) { newUserForm.reject("password", "user.wrongPassword.alert"); } // 중복된 loginId로 가입할 수 없다. if (User.isLoginIdExist(newUserForm.field("loginId").value())) { newUserForm.reject("loginId", "user.loginId.duplicate"); } // 중복된 email로 가입할 수 없다. if (User.isEmailExist(newUserForm.field("email").value())) { newUserForm.reject("email", "user.email.duplicate"); } }
/** * Validates fields from the registration form and either creates a new user or communicates any * validation errors. */ public static Result submit() { Form<User> filledForm = signupForm.bindFromRequest(); // Check accept conditions if (!"true".equals(filledForm.field("accept").value())) { filledForm.reject("accept", "You must accept the terms and conditions"); } // Check repeated password if (!filledForm.field("password").valueOr("").isEmpty()) { if (!filledForm .field("password") .valueOr("") .equals(filledForm.field("repeatPassword").value())) { filledForm.reject("repeatPassword", "Passwords do not match"); } } // Check if the username and email are valid if (!filledForm.hasErrors()) { String un = filledForm.get().username; String email = filledForm.get().email; if (un.equals("admin") || un.equals("guest")) { filledForm.reject("username", "This username is already taken"); } try { Logger.debug("Finding user " + email); User.findByEmail(email); filledForm.reject( "email", "There is already an account associated with this email address."); } catch (Exception e) { // continue - the user does not exist } } // Return validation results to user or save user if (filledForm.hasErrors()) { return badRequest(form.render(filledForm)); } else { User user = filledForm.get(); /* create an object from a form */ User svUser = new User(user.username, user.email, user.password); /* recreate to get save group info */ svUser.save(); return ok(summary.render(svUser)); } }
@Test public void fillForm() { // User needs a constructor. Give it one. class User extends javaguide.forms.u1.User { User(String email, String password) { this.email = email; this.password = password; } } Form<javaguide.forms.u1.User> userForm = Form.form(javaguide.forms.u1.User.class); // #fill userForm = userForm.fill(new User("*****@*****.**", "secret")); // #fill assertThat(userForm.field("email").value(), equalTo("*****@*****.**")); assertThat(userForm.field("password").value(), equalTo("secret")); }
/** Get a sub-field, with a key relative to the current field. */ public Field sub(String key) { String subKey; if (key.startsWith("[")) { subKey = name + key; } else { subKey = name + "." + key; } return form.field(subKey); }
public static Result update() { Form<User> userForm = new Form(User.class).bindFromRequest(); if (!userForm.field("password").valueOr("").isEmpty()) { if (!userForm .field("password") .valueOr("") .equals(userForm.field("repeatPassword").value())) { userForm.reject("repeatPassword", "Password don't match"); } } if (userForm.hasErrors()) { return badRequest(myAccount.render(userForm)); } userForm.get().update(Long.valueOf(session(Application.USER_KEY_ID))); flash("success", "User " + userForm.get().userName + " has been updated"); return redirect(routes.Application.index()); }
public static Result createNewUser() { Form<User> nu = userForm.bindFromRequest(); ObjectNode jsonData = Json.newObject(); String userName = null; try { userName = nu.field("firstName").value() + " " + (nu.field("middleInitial")).value() + " " + (nu.field("lastName")).value(); jsonData.put("userName", userName); jsonData.put("firstName", nu.get().getFirstName()); jsonData.put("middleInitial", nu.get().getMiddleInitial()); jsonData.put("lastName", nu.get().getLastName()); jsonData.put("password", nu.get().getPassword()); jsonData.put("affiliation", nu.get().getAffiliation()); jsonData.put("title", nu.get().getTitle()); jsonData.put("email", nu.get().getEmail()); jsonData.put("mailingAddress", nu.get().getMailingAddress()); jsonData.put("phoneNumber", nu.get().getPhoneNumber()); jsonData.put("faxNumber", nu.get().getFaxNumber()); jsonData.put("researchFields", nu.get().getResearchFields()); jsonData.put("highestDegree", nu.get().getHighestDegree()); JsonNode response = RESTfulCalls.postAPI( Constants.URL_HOST + Constants.CMU_BACKEND_PORT + Constants.ADD_USER, jsonData); // flash the response message Application.flashMsg(response); return redirect(routes.Application.createSuccess()); } catch (IllegalStateException e) { e.printStackTrace(); Application.flashMsg(RESTfulCalls.createResponse(ResponseType.CONVERSIONERROR)); } catch (Exception e) { e.printStackTrace(); Application.flashMsg(RESTfulCalls.createResponse(ResponseType.UNKNOWN)); } return ok(signup.render(nu)); }
private static Promise<Result> renderEditForm(final Form<DatasetForm> datasetForm) { // TODO final ActorSelection database = Akka.system().actorSelection(databaseRef); return from(database) .list(DataSource.class) .list(Category.class) .query( listSourceDatasets( datasetForm.field("dataSourceId").value(), datasetForm.field("categoryId").value())) // .query (listDatasetColumns (datasetForm.field ("id").value ())) .query( listSourceDatasetColumns( datasetForm.field("dataSourceId").value(), datasetForm.field("sourceDatasetId").value())) .execute( new Function4< Page<DataSource>, Page<Category>, Page<SourceDatasetStats>, List<Column>, Result>() { @Override public Result apply( Page<DataSource> dataSources, Page<Category> categories, final Page<SourceDatasetStats> sourceDatasets, final List<Column> columns) throws Throwable { Logger.debug( "Edit form: #datasources=" + dataSources.pageCount() + ", #categories=" + categories.pageCount() + ", #sourcedatasets=" + sourceDatasets.pageCount() + ", #columns: " + columns.size()); return ok( form.render( dataSources, categories, sourceDatasets, columns, datasetForm, false)); } }); }
public static Result actualizar() { Form<Economia> formREconomia = form(Economia.class).bindFromRequest(); String ids = formREconomia.field("id").value(); Long id = Long.parseLong(ids); formREconomia.get().update(id); flash("exito", "Solicitud actualizada con exito"); return Inicio; }
/** * Saves restaurant into the database. Collects all data from the form, checks if provided hotel * already contains a restaurant (according to project specifications, one hotel can contain only * one restaurant). * * @param hotelId * @return */ @Security.Authenticated(Authenticators.SellerFilter.class) public Result saveRestaurant(Integer hotelId) { // Checking if there is a restaurant with provided // hotel id in the database. if (!Restaurant.existsInDB(hotelId)) { Form<Restaurant> boundForm = restaurantForm.bindFromRequest(); Restaurant restaurant = new Restaurant(); Form<Restaurant> restaurantForm1 = restaurantForm.bindFromRequest(); // Collecting data from the form String name = restaurantForm1.field("name").value(); String restaurantType = restaurantForm1.field("restauranType").value(); Integer capacity = Integer.parseInt(restaurantForm1.field("capacity").value()); String description = restaurantForm1.field("description").value(); String open = restaurantForm1.field("restOpen").value(); String close = restaurantForm1.field("restClose").value(); String workingHours = open + " - " + close; restaurant.name = name; restaurant.restauranType = restaurantType; restaurant.capacity = capacity; restaurant.workingHours = workingHours; restaurant.description = description; // Finding hotel with provided hotel id Hotel hotel = Hotel.findHotelById(hotelId); // Checking if hotel with provided id exists if (hotel != null) { restaurant.hotel = hotel; } // Getting timestamp Calendar c = Calendar.getInstance(); restaurant.timestamp = c.getTime(); // Saving the restaurant into the database restaurant.save(); } else { flash("error", "There is already added restaurant for selected hotel."); return ok(createRestaurant.render(hotelId)); } if (session("userId") != null) { flash("create", "The restaurant was created!"); return redirect(routes.Hotels.showSellerHotels()); } else { return redirect(routes.Application.index()); } }
@Security.Authenticated(Secured.class) public static Result addNewMessageForm(Long id) { Form<MessageForm> mesForm = Form.form(MessageForm.class).bindFromRequest(); if (mesForm.hasErrors()) { return badRequest(postNewMessage.render(mesForm, id)); } else { Message m = new Message( mesForm.field("text").value().toString(), Student.find.byId(request().username())); Conversation c = null; c = Conversation.find.byId(id.toString()); c.messages.add(m); c.save(); return redirect(routes.Application.viewMyConversation(id)); } }
/** * Updates currently selected restaurant. Checks if room with selected id exists, if it does, * collects data from the form and updates the room. * * @param restaurantId * @return */ @Security.Authenticated(Authenticators.SellerFilter.class) public Result updateRestaurant(Integer restaurantId) { // Creating restaurant with provided restaurantId Restaurant restaurant = Restaurant.findRestaurantById(restaurantId); // Checking if such restaurant exists // If it does, collects its data and updates the restaurant. if (restaurant != null) { Form<Restaurant> restaurantForm1 = restaurantForm.bindFromRequest(); String name = restaurantForm1.field("name").value(); String restaurantType = restaurantForm1.field("restauranType").value(); Integer capacity = Integer.parseInt(restaurantForm1.field("capacity").value()); String description = restaurantForm1.field("description").value(); String open = restaurantForm1.field("restOpen").value(); String close = restaurantForm1.field("restClose").value(); String workingHours = open + " - " + close; restaurant.name = name; restaurant.restauranType = restaurantType; restaurant.capacity = capacity; restaurant.workingHours = workingHours; restaurant.description = description; // Adding images for the restaurant. Http.MultipartFormData body1 = request().body().asMultipartFormData(); List<Http.MultipartFormData.FilePart> fileParts = body1.getFiles(); if (fileParts != null) { for (Http.MultipartFormData.FilePart filePart1 : fileParts) { File file = filePart1.getFile(); Image image = Image.create(file, null, null, null, null, restaurantId); restaurant.images.add(image); } } restaurant.update(); } if (session("userId") != null) { flash("edit", "The restaurant was updated!"); return redirect(routes.Hotels.showSellerHotels()); } else { return redirect(routes.Application.index()); } }
/** * Save past race * * @return */ public static Result save() { Form<PastRaceForm> form = form(PastRaceForm.class).bindFromRequest(); // Is this an update or a creation? PastRace pastRace = null; boolean isnew = false; String raceId = form.field("id").value(); if (!StringUtils.isEmpty(raceId)) { try { pastRace = PastRace.find.byId(Long.valueOf(raceId)); } catch (NumberFormatException n) { } if (pastRace == null || !pastRace.user.equals(getConnectedUser())) { Logger.error("Past race save forbidden"); return forbidden(); } } else { isnew = true; pastRace = new PastRace(); pastRace.dateCreation = new Date(); } // Check date format Date date = null; if (form.error("date") == null) { DateFormat df = new SimpleDateFormat(Messages.get("general.dateformat")); try { date = df.parse(form.field("date").value()); } catch (ParseException p) { form.reject("date", "general.error.dateformat"); } } // Check time String hours = form.field("hours").value(); String minutes = form.field("minutes").value(); String seconds = form.field("seconds").value(); if (StringUtils.isEmpty(hours) || StringUtils.isEmpty(minutes) || StringUtils.isEmpty(seconds)) { form.reject("time", "general.error.multiple"); } int timeInSeconds = 0; try { timeInSeconds += Integer.parseInt(hours) * 3600; timeInSeconds += Integer.parseInt(minutes) * 60; timeInSeconds += Integer.parseInt(seconds); } catch (NumberFormatException n) { form.reject("time", "pastrace.error.time"); } if (form.hasErrors()) { return badRequest(views.html.user.pastRace.render(form, isnew)); } else { // Save past race pastRace.name = form.field("name").value(); pastRace.date = date; pastRace.user = Application.getConnectedUser(); pastRace.distance = form.field("distance").value(); pastRace.time = timeInSeconds; Ebean.save(pastRace); // Redirect to user homepage return redirect( controllers.user.routes.UserController.index(Application.getConnectedUser().username)); } }
@Test public void nestedContraints() { Form<JCustomer> customerForm = new Form<JCustomer>(JCustomer.class); // email constraints assertThat(customerForm.field("email").constraints().size()) .as("field(\"email\").constraints().size()") .isEqualTo(2); assertThat(customerForm.field("email").constraints().get(0)._1) .as("field(\"email\").constraints(0)") .isEqualTo("constraint.email"); assertThat(customerForm.field("email").constraints().get(1)._1) .as("field(\"email\").constraints(1)") .isEqualTo("constraint.required"); // orders[0].date constraints assertThat(customerForm.field("orders[0].date").constraints().size()) .as("field(\"orders[0].date\").constraints().size()") .isEqualTo(1); assertThat(customerForm.field("orders[0].date").constraints().get(0)._1) .as("field(\"orders[0].date\").constraints(0)") .isEqualTo("constraint.required"); // orders[0].date format assertThat(customerForm.field("orders[0].date").format()._1) .as("field(\"orders[0].date\").format()._1") .isEqualTo("format.date"); assertThat(customerForm.field("orders[0].date").format()._2.toString()) .as("field(\"orders[0].date\").format()._2") .isEqualTo("[yyyy-MM-dd]"); // orders[0].items[0].qty constraints assertThat(customerForm.field("orders[0].items[0].qty").constraints().size()) .as("field(\"orders[0].items[0].qty\").constraints().size()") .isEqualTo(2); assertThat(customerForm.field("orders[0].items[0].qty").constraints().get(0)._1) .as("field(\"orders[0].items[0].qty\").constraints(0)") .isEqualTo("constraint.min"); assertThat(customerForm.field("orders[0].items[0].qty").constraints().get(0)._2.toString()) .as("field(\"orders[0].items[0].qty\").constraints(0)._2") .isEqualTo("[1]"); assertThat(customerForm.field("orders[0].items[0].qty").constraints().get(1)._1) .as("field(\"orders[0].items[0].qty\").constraints(1)") .isEqualTo("constraint.required"); // orders[0].items[0].productCode constraints assertThat(customerForm.field("orders[0].items[0].productCode").constraints().size()) .as("field(\"orders[0].items[0].productCode\").constraints().size()") .isEqualTo(2); assertThat(customerForm.field("orders[0].items[0].productCode").constraints().get(0)._1) .as("field(\"orders[0].items[0].productCode\").constraints(0)") .isEqualTo("constraint.pattern"); assertThat(customerForm.field("orders[0].items[0].productCode").constraints().get(0)._2.size()) .as("field(\"orders[0].items[0].productCode\").constraints(0)") .isEqualTo(1); assertThat(customerForm.field("orders[0].items[0].productCode").constraints().get(0)._2.get(0)) .as("field(\"orders[0].items[0].productCode\").constraints(0)") .isEqualTo("[A-Z]{4}-[0-9]{3,}"); assertThat(customerForm.field("orders[0].items[0].productCode").constraints().get(1)._1) .as("field(\"orders[0].items[0].productCode\").constraints(1)") .isEqualTo("constraint.required"); // orders[0].items[0].deliveryDate constraints assertThat(customerForm.field("orders[0].items[0].deliveryDate").constraints().size()) .as("field(\"orders[0].items[0].deliveryDate\").constraints().size()") .isEqualTo(0); // orders[0].items[0].deliveryDate format assertThat(customerForm.field("orders[0].items[0].deliveryDate").format()._1) .as("field(\"orders[0].items[0].deliveryDate\").format()._1") .isEqualTo("format.date"); assertThat(customerForm.field("orders[0].items[0].deliveryDate").format()._2.toString()) .as("field(\"orders[0].items[0].deliveryDate\").format()._2") .isEqualTo("[yyyy-MM-dd]"); }
protected String extractEmail(Form<?> form) { return form.field(PasswordResetRequestData.EMAIL_FIELD).value(); }