Advertisement
Guest User

Untitled

a guest
Aug 8th, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.40 KB | None | 0 0
  1. package controllers;
  2.  
  3. import models.Customer;
  4. import models.CustomerUser;
  5. import play.data.Form;
  6. import play.data.FormFactory;
  7. import play.libs.concurrent.HttpExecutionContext;
  8. import play.mvc.Controller;
  9. import play.mvc.Result;
  10. import play.mvc.Results;
  11. import repository.CompanyRepository;
  12.  
  13. import repository.CustomerRepository;
  14. import repository.CustomerUserRepository;
  15.  
  16. import javax.inject.Inject;
  17. import javax.persistence.PersistenceException;
  18. import java.util.Map;
  19. import java.util.concurrent.CompletionStage;
  20.  
  21. /**
  22. * Manage a database of computers
  23. */
  24. public class UserController extends Controller {
  25.  
  26. private final CustomerUserRepository userRepository;
  27. private final CustomerRepository customerRepository;
  28. //private final CompanyRepository companyRepository;
  29. private final FormFactory formFactory;
  30. private final HttpExecutionContext httpExecutionContext;
  31.  
  32. @Inject
  33. public UserController(FormFactory formFactory,
  34. CustomerUserRepository userRepository,
  35.  
  36. CustomerRepository customerRepository,
  37. HttpExecutionContext httpExecutionContext) {
  38. this.userRepository = userRepository;
  39. this.formFactory = formFactory;
  40.  
  41. this.customerRepository = customerRepository;
  42. this.httpExecutionContext = httpExecutionContext;
  43. }
  44.  
  45. /**
  46. * This result directly redirect to application home.
  47. */
  48. private Result GO_HOME = Results.redirect(
  49. routes.UserController.list(0, "name", "asc", "")
  50. );
  51.  
  52. /**
  53. * Handle default path requests, redirect to computers list
  54. */
  55. public Result index() {
  56. return GO_HOME;
  57. }
  58.  
  59. /**
  60. * Display the paginated list of computers.
  61. *
  62. * @param page Current page number (starts from 0)
  63. * @param sortBy Column to be sorted
  64. * @param order Sort order (either asc or desc)
  65. * @param filter Filter applied on computer names
  66. */
  67. public CompletionStage<Result> list(int page, String sortBy, String order, String filter) {
  68. // Run a db operation in another thread (using DatabaseExecutionContext)
  69. return userRepository.page(page, 10, sortBy, order, filter).thenApplyAsync(list -> {
  70. // This is the HTTP rendering thread context
  71. return ok(views.html.listuser.render(list, sortBy, order, filter));
  72. }, httpExecutionContext.current());
  73. }
  74.  
  75. /**
  76. * Display the 'edit form' of a existing Computer.
  77. *
  78. * @param id Id of the computer to edit
  79. */
  80. public CompletionStage<Result> edit(Long id) {
  81.  
  82. // Run a db operation in another thread (using DatabaseExecutionContext)
  83. CompletionStage<Map<String, String>> customersFuture = customerRepository.options();
  84.  
  85. // Run the lookup also in another thread, then combine the results:
  86. return userRepository.lookup(id).thenCombineAsync(customersFuture, (userCustomerOptional, customers) -> {
  87. // This is the HTTP rendering thread context
  88. CustomerUser c = userCustomerOptional.get();
  89. Form<CustomerUser> userForm = formFactory.form(CustomerUser.class).fill(c);
  90. return ok(views.html.editFormUser.render(id, userForm, customers));
  91. }, httpExecutionContext.current());
  92. }
  93.  
  94. /**
  95. * Handle the 'edit form' submission
  96. *
  97. * @param id Id of the user to edit
  98. */
  99. public CompletionStage<Result> update(Long id) throws PersistenceException {
  100. Form<CustomerUser> userForm = formFactory.form(CustomerUser.class).bindFromRequest();
  101. if (userForm.hasErrors()) {
  102. // Run companies db operation and then render the failure case
  103. return customerRepository.options().thenApplyAsync(customers -> {
  104. // This is the HTTP rendering thread context
  105. return badRequest(views.html.editFormUser.render(id, userForm, customers));
  106. }, httpExecutionContext.current());
  107. } else {
  108. CustomerUser newUser = userForm.get();
  109. // Run update operation and then flash and then redirect
  110. return userRepository.update(id, newUser).thenApplyAsync(data -> {
  111. // This is the HTTP rendering thread context
  112. flash("success", "Data - " + newUser.name + " has been updated");
  113. return GO_HOME;
  114. }, httpExecutionContext.current());
  115. }
  116. }
  117.  
  118. /**
  119. * Display the 'new computer form'.
  120. */
  121. public CompletionStage<Result> create() {
  122. Form<CustomerUser> userForm = formFactory.form(CustomerUser.class);
  123. // Run companies db operation and then render the form
  124.  
  125. return customerRepository.options().thenApplyAsync((Map<String, String> customers) -> {
  126. // This is the HTTP rendering thread context
  127. return ok(views.html.createFormUser.render(userForm, customers));
  128. }, httpExecutionContext.current());
  129. }
  130.  
  131. /**
  132. * Handle the 'new computer form' submission
  133. */
  134. public CompletionStage<Result> save() {
  135. Form<CustomerUser> userForm = formFactory.form(CustomerUser.class).bindFromRequest();
  136. if (userForm.hasErrors()) {
  137. // Run companies db operation and then render the form
  138.  
  139.  
  140. return customerRepository.options().thenApplyAsync(customers -> {
  141. // This is the HTTP rendering thread context
  142. return badRequest(views.html.createFormUser.render(userForm, customers));
  143. }, httpExecutionContext.current());
  144. }
  145.  
  146. CustomerUser cust = userForm.get();
  147. // Run insert db operation, then redirect
  148. return userRepository.insert(cust).thenApplyAsync(data -> {
  149. // This is the HTTP rendering thread context
  150. flash("success", "Data - " + cust.name + " has been created");
  151. return GO_HOME;
  152. }, httpExecutionContext.current());
  153. }
  154.  
  155. /**
  156. * Handle computer deletion
  157. */
  158. //it works!!!
  159. public CompletionStage<Result> delete(Long id) {
  160. // Run delete db operation, then redirect
  161. return userRepository.delete(id).thenApplyAsync(v -> {
  162. // This is the HTTP rendering thread context
  163. flash("success", "User has been deleted");
  164. return GO_HOME;
  165. }, httpExecutionContext.current());
  166. }
  167.  
  168. }
  169.  
  170. package models;
  171.  
  172. import play.data.format.Formats;
  173. import play.data.validation.Constraints;
  174.  
  175. import javax.persistence.Entity;
  176. import javax.persistence.ManyToOne;
  177. import java.util.Date;
  178.  
  179. /**
  180. * Computer entity managed by Ebean
  181. */
  182.  
  183. @Entity
  184. public class CustomerUser extends BaseModel {
  185.  
  186. private static final long serialVersionUID = 1L;
  187.  
  188. @Constraints.Required
  189. public String name;
  190.  
  191. @Constraints.Required
  192. public String email;
  193.  
  194. @Constraints.Required
  195. public String password;
  196.  
  197. @Constraints.Required
  198. public String typeid;
  199.  
  200. @ManyToOne
  201. public Customer customer;
  202.  
  203. }
  204.  
  205. package repository;
  206.  
  207. import io.ebean.Ebean;
  208. import io.ebean.EbeanServer;
  209. import io.ebean.PagedList;
  210. import io.ebean.Transaction;
  211. import models.CustomerUser;
  212. import play.db.ebean.EbeanConfig;
  213.  
  214. import javax.inject.Inject;
  215. import java.util.Optional;
  216. import java.util.concurrent.CompletionStage;
  217.  
  218. import static java.util.concurrent.CompletableFuture.supplyAsync;
  219.  
  220. /**
  221. * A repository that executes database operations in a different
  222. * execution context.
  223. */
  224. public class CustomerUserRepository {
  225.  
  226. private final EbeanServer ebeanServer;
  227. private final DatabaseExecutionContext executionContext;
  228.  
  229. @Inject
  230. public CustomerUserRepository(EbeanConfig ebeanConfig, DatabaseExecutionContext executionContext) {
  231. this.ebeanServer = Ebean.getServer(ebeanConfig.defaultServer());
  232. this.executionContext = executionContext;
  233. }
  234.  
  235. /**
  236. * Return a paged list of computer
  237. *
  238. * @param page Page to display
  239. * @param pageSize Number of computers per page
  240. * @param sortBy CustomerUser property used for sorting
  241. * @param order Sort order (either or asc or desc)
  242. * @param filter Filter applied on the name column
  243. */
  244. public CompletionStage<PagedList<CustomerUser>> page(int page, int pageSize, String sortBy, String order, String filter) {
  245. return supplyAsync(() -> {
  246. return ebeanServer.find(CustomerUser.class).where()
  247. .ilike("name", "%" + filter + "%")
  248. .orderBy(sortBy + " " + order)
  249. .fetch("customer")
  250. .setFirstRow(page * pageSize)
  251. .setMaxRows(pageSize)
  252. .findPagedList();
  253. } , executionContext);
  254. }
  255.  
  256. public CompletionStage<Optional<CustomerUser>> lookup(Long id) {
  257. return supplyAsync(() -> {
  258. return Optional.ofNullable(ebeanServer.find(CustomerUser.class).setId(id).findUnique());
  259. }, executionContext);
  260. }
  261.  
  262. public CompletionStage<Optional<Long>> update(Long id, CustomerUser newUserData) {
  263. return supplyAsync(() -> {
  264. Transaction txn = ebeanServer.beginTransaction();
  265. Optional<Long> value = Optional.empty();
  266. try {
  267. CustomerUser savedUserCustomer = ebeanServer.find(CustomerUser.class).setId(id).findUnique();
  268. if (savedUserCustomer != null) {
  269. savedUserCustomer.customer = newUserData.customer;
  270. savedUserCustomer.typeid = newUserData.typeid;
  271. savedUserCustomer.password = newUserData.password;
  272. savedUserCustomer.email = newUserData.email;
  273. savedUserCustomer.name = newUserData.name;
  274.  
  275. savedUserCustomer.update();
  276. txn.commit();
  277. value = Optional.of(id);
  278. }
  279. } finally {
  280. txn.end();
  281. }
  282. return value;
  283. }, executionContext);
  284. }
  285.  
  286. public CompletionStage<Optional<Long>> delete(Long id) {
  287. return supplyAsync(() -> {
  288. try {
  289. final Optional<CustomerUser> userCustomerOptional = Optional.ofNullable(ebeanServer.find(CustomerUser.class).setId(id).findUnique());
  290. userCustomerOptional.ifPresent(c -> c.delete());
  291. return userCustomerOptional.map(c -> c.id);
  292. } catch (Exception e) {
  293. return Optional.empty();
  294. }
  295. }, executionContext);
  296. }
  297.  
  298. public CompletionStage<Long> insert(CustomerUser customerUser) {
  299. return supplyAsync(() -> {
  300. customerUser.id = System.currentTimeMillis(); // not ideal, but it works
  301. ebeanServer.insert(customerUser);
  302. return customerUser.id;
  303. }, executionContext);
  304. }
  305. }
  306.  
  307. @(id: Long, userForm: Form[CustomerUser], customers: Map[String, String])
  308.  
  309. @import helper._
  310.  
  311. @main {
  312.  
  313. <h1>Edit user</h1>
  314.  
  315. @form(routes.UserController.update(id)) {
  316.  
  317. <fieldset>
  318. @CSRF.formField
  319. @inputText(userForm("name"), '_label -> "User name", '_help -> "")
  320. @inputText(userForm("email"), '_label -> "E-mail", '_help -> "")
  321. @inputText(userForm("typeid"), '_label -> "Type Id", '_help -> "")
  322.  
  323. @select(
  324. userForm("customer.id"),
  325. options(customers),
  326. '_label -> "Customer", '_default -> "-- Choose a customer --",
  327. '_showConstraints -> false
  328. )
  329.  
  330. </fieldset>
  331.  
  332. <div class="actions">
  333. <input type="submit" value="Save this user" class="btn primary"> or
  334. <a href="@routes.UserController.list()" class="btn">Cancel</a>
  335. </div>
  336.  
  337. }
  338.  
  339. @form(routes.UserController.delete(id), 'class -> "topRight") {
  340. @CSRF.formField
  341. <input type="submit" value="Delete this user" class="btn danger">
  342. }
  343.  
  344. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement