Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package controllers;
- import models.Customer;
- import models.CustomerUser;
- import play.data.Form;
- import play.data.FormFactory;
- import play.libs.concurrent.HttpExecutionContext;
- import play.mvc.Controller;
- import play.mvc.Result;
- import play.mvc.Results;
- import repository.CompanyRepository;
- import repository.CustomerRepository;
- import repository.CustomerUserRepository;
- import javax.inject.Inject;
- import javax.persistence.PersistenceException;
- import java.util.Map;
- import java.util.concurrent.CompletionStage;
- /**
- * Manage a database of computers
- */
- public class UserController extends Controller {
- private final CustomerUserRepository userRepository;
- private final CustomerRepository customerRepository;
- //private final CompanyRepository companyRepository;
- private final FormFactory formFactory;
- private final HttpExecutionContext httpExecutionContext;
- @Inject
- public UserController(FormFactory formFactory,
- CustomerUserRepository userRepository,
- CustomerRepository customerRepository,
- HttpExecutionContext httpExecutionContext) {
- this.userRepository = userRepository;
- this.formFactory = formFactory;
- this.customerRepository = customerRepository;
- this.httpExecutionContext = httpExecutionContext;
- }
- /**
- * This result directly redirect to application home.
- */
- private Result GO_HOME = Results.redirect(
- routes.UserController.list(0, "name", "asc", "")
- );
- /**
- * Handle default path requests, redirect to computers list
- */
- public Result index() {
- return GO_HOME;
- }
- /**
- * Display the paginated list of computers.
- *
- * @param page Current page number (starts from 0)
- * @param sortBy Column to be sorted
- * @param order Sort order (either asc or desc)
- * @param filter Filter applied on computer names
- */
- public CompletionStage<Result> list(int page, String sortBy, String order, String filter) {
- // Run a db operation in another thread (using DatabaseExecutionContext)
- return userRepository.page(page, 10, sortBy, order, filter).thenApplyAsync(list -> {
- // This is the HTTP rendering thread context
- return ok(views.html.listuser.render(list, sortBy, order, filter));
- }, httpExecutionContext.current());
- }
- /**
- * Display the 'edit form' of a existing Computer.
- *
- * @param id Id of the computer to edit
- */
- public CompletionStage<Result> edit(Long id) {
- // Run a db operation in another thread (using DatabaseExecutionContext)
- CompletionStage<Map<String, String>> customersFuture = customerRepository.options();
- // Run the lookup also in another thread, then combine the results:
- return userRepository.lookup(id).thenCombineAsync(customersFuture, (userCustomerOptional, customers) -> {
- // This is the HTTP rendering thread context
- CustomerUser c = userCustomerOptional.get();
- Form<CustomerUser> userForm = formFactory.form(CustomerUser.class).fill(c);
- return ok(views.html.editFormUser.render(id, userForm, customers));
- }, httpExecutionContext.current());
- }
- /**
- * Handle the 'edit form' submission
- *
- * @param id Id of the user to edit
- */
- public CompletionStage<Result> update(Long id) throws PersistenceException {
- Form<CustomerUser> userForm = formFactory.form(CustomerUser.class).bindFromRequest();
- if (userForm.hasErrors()) {
- // Run companies db operation and then render the failure case
- return customerRepository.options().thenApplyAsync(customers -> {
- // This is the HTTP rendering thread context
- return badRequest(views.html.editFormUser.render(id, userForm, customers));
- }, httpExecutionContext.current());
- } else {
- CustomerUser newUser = userForm.get();
- // Run update operation and then flash and then redirect
- return userRepository.update(id, newUser).thenApplyAsync(data -> {
- // This is the HTTP rendering thread context
- flash("success", "Data - " + newUser.name + " has been updated");
- return GO_HOME;
- }, httpExecutionContext.current());
- }
- }
- /**
- * Display the 'new computer form'.
- */
- public CompletionStage<Result> create() {
- Form<CustomerUser> userForm = formFactory.form(CustomerUser.class);
- // Run companies db operation and then render the form
- return customerRepository.options().thenApplyAsync((Map<String, String> customers) -> {
- // This is the HTTP rendering thread context
- return ok(views.html.createFormUser.render(userForm, customers));
- }, httpExecutionContext.current());
- }
- /**
- * Handle the 'new computer form' submission
- */
- public CompletionStage<Result> save() {
- Form<CustomerUser> userForm = formFactory.form(CustomerUser.class).bindFromRequest();
- if (userForm.hasErrors()) {
- // Run companies db operation and then render the form
- return customerRepository.options().thenApplyAsync(customers -> {
- // This is the HTTP rendering thread context
- return badRequest(views.html.createFormUser.render(userForm, customers));
- }, httpExecutionContext.current());
- }
- CustomerUser cust = userForm.get();
- // Run insert db operation, then redirect
- return userRepository.insert(cust).thenApplyAsync(data -> {
- // This is the HTTP rendering thread context
- flash("success", "Data - " + cust.name + " has been created");
- return GO_HOME;
- }, httpExecutionContext.current());
- }
- /**
- * Handle computer deletion
- */
- //it works!!!
- public CompletionStage<Result> delete(Long id) {
- // Run delete db operation, then redirect
- return userRepository.delete(id).thenApplyAsync(v -> {
- // This is the HTTP rendering thread context
- flash("success", "User has been deleted");
- return GO_HOME;
- }, httpExecutionContext.current());
- }
- }
- package models;
- import play.data.format.Formats;
- import play.data.validation.Constraints;
- import javax.persistence.Entity;
- import javax.persistence.ManyToOne;
- import java.util.Date;
- /**
- * Computer entity managed by Ebean
- */
- @Entity
- public class CustomerUser extends BaseModel {
- private static final long serialVersionUID = 1L;
- @Constraints.Required
- public String name;
- @Constraints.Required
- public String email;
- @Constraints.Required
- public String password;
- @Constraints.Required
- public String typeid;
- @ManyToOne
- public Customer customer;
- }
- package repository;
- import io.ebean.Ebean;
- import io.ebean.EbeanServer;
- import io.ebean.PagedList;
- import io.ebean.Transaction;
- import models.CustomerUser;
- import play.db.ebean.EbeanConfig;
- import javax.inject.Inject;
- import java.util.Optional;
- import java.util.concurrent.CompletionStage;
- import static java.util.concurrent.CompletableFuture.supplyAsync;
- /**
- * A repository that executes database operations in a different
- * execution context.
- */
- public class CustomerUserRepository {
- private final EbeanServer ebeanServer;
- private final DatabaseExecutionContext executionContext;
- @Inject
- public CustomerUserRepository(EbeanConfig ebeanConfig, DatabaseExecutionContext executionContext) {
- this.ebeanServer = Ebean.getServer(ebeanConfig.defaultServer());
- this.executionContext = executionContext;
- }
- /**
- * Return a paged list of computer
- *
- * @param page Page to display
- * @param pageSize Number of computers per page
- * @param sortBy CustomerUser property used for sorting
- * @param order Sort order (either or asc or desc)
- * @param filter Filter applied on the name column
- */
- public CompletionStage<PagedList<CustomerUser>> page(int page, int pageSize, String sortBy, String order, String filter) {
- return supplyAsync(() -> {
- return ebeanServer.find(CustomerUser.class).where()
- .ilike("name", "%" + filter + "%")
- .orderBy(sortBy + " " + order)
- .fetch("customer")
- .setFirstRow(page * pageSize)
- .setMaxRows(pageSize)
- .findPagedList();
- } , executionContext);
- }
- public CompletionStage<Optional<CustomerUser>> lookup(Long id) {
- return supplyAsync(() -> {
- return Optional.ofNullable(ebeanServer.find(CustomerUser.class).setId(id).findUnique());
- }, executionContext);
- }
- public CompletionStage<Optional<Long>> update(Long id, CustomerUser newUserData) {
- return supplyAsync(() -> {
- Transaction txn = ebeanServer.beginTransaction();
- Optional<Long> value = Optional.empty();
- try {
- CustomerUser savedUserCustomer = ebeanServer.find(CustomerUser.class).setId(id).findUnique();
- if (savedUserCustomer != null) {
- savedUserCustomer.customer = newUserData.customer;
- savedUserCustomer.typeid = newUserData.typeid;
- savedUserCustomer.password = newUserData.password;
- savedUserCustomer.email = newUserData.email;
- savedUserCustomer.name = newUserData.name;
- savedUserCustomer.update();
- txn.commit();
- value = Optional.of(id);
- }
- } finally {
- txn.end();
- }
- return value;
- }, executionContext);
- }
- public CompletionStage<Optional<Long>> delete(Long id) {
- return supplyAsync(() -> {
- try {
- final Optional<CustomerUser> userCustomerOptional = Optional.ofNullable(ebeanServer.find(CustomerUser.class).setId(id).findUnique());
- userCustomerOptional.ifPresent(c -> c.delete());
- return userCustomerOptional.map(c -> c.id);
- } catch (Exception e) {
- return Optional.empty();
- }
- }, executionContext);
- }
- public CompletionStage<Long> insert(CustomerUser customerUser) {
- return supplyAsync(() -> {
- customerUser.id = System.currentTimeMillis(); // not ideal, but it works
- ebeanServer.insert(customerUser);
- return customerUser.id;
- }, executionContext);
- }
- }
- @(id: Long, userForm: Form[CustomerUser], customers: Map[String, String])
- @import helper._
- @main {
- <h1>Edit user</h1>
- @form(routes.UserController.update(id)) {
- <fieldset>
- @CSRF.formField
- @inputText(userForm("name"), '_label -> "User name", '_help -> "")
- @inputText(userForm("email"), '_label -> "E-mail", '_help -> "")
- @inputText(userForm("typeid"), '_label -> "Type Id", '_help -> "")
- @select(
- userForm("customer.id"),
- options(customers),
- '_label -> "Customer", '_default -> "-- Choose a customer --",
- '_showConstraints -> false
- )
- </fieldset>
- <div class="actions">
- <input type="submit" value="Save this user" class="btn primary"> or
- <a href="@routes.UserController.list()" class="btn">Cancel</a>
- </div>
- }
- @form(routes.UserController.delete(id), 'class -> "topRight") {
- @CSRF.formField
- <input type="submit" value="Delete this user" class="btn danger">
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement