diff --git a/pom.xml b/pom.xml index bbb2949..23cc34c 100644 --- a/pom.xml +++ b/pom.xml @@ -66,7 +66,8 @@ revaturelabs_rideshare-user-service revaturelabs-screenforce https://sonarcloud.io - com/revature/beans/*.java + src/main/java/com/revature/beans/**/*.java + src/main/java/com/revature/beans/**/*.java @@ -127,17 +128,17 @@ 2.9.2 - - com.googlecode.json-simple - json-simple - - - io.springfox springfox-swagger-ui 2.9.2 + + + com.googlecode.json-simple + json-simple + + com.h2database h2 diff --git a/src/main/java/com/revature/Driver.java b/src/main/java/com/revature/Driver.java index 8145998..2fc8591 100644 --- a/src/main/java/com/revature/Driver.java +++ b/src/main/java/com/revature/Driver.java @@ -10,7 +10,6 @@ import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; -import com.revature.services.DistanceService; /** diff --git a/src/main/java/com/revature/advice/HttpExceptionAdvice.java b/src/main/java/com/revature/advice/HttpExceptionAdvice.java new file mode 100644 index 0000000..a999dee --- /dev/null +++ b/src/main/java/com/revature/advice/HttpExceptionAdvice.java @@ -0,0 +1,19 @@ +package com.revature.advice; + +import org.jboss.logging.Logger; +import org.jboss.logging.Logger.Level; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.client.HttpClientErrorException; + +@RestControllerAdvice +public class HttpExceptionAdvice { + private static Logger logger = Logger.getLogger(HttpExceptionAdvice.class); + + @ExceptionHandler(HttpClientErrorException.class) + public HttpStatus handleClientError(HttpClientErrorException e) { + logger.log(Level.TRACE, e.getMessage(), e); + return e.getStatusCode(); + } +} diff --git a/src/main/java/com/revature/advice/package-info.java b/src/main/java/com/revature/advice/package-info.java new file mode 100644 index 0000000..18fd3fd --- /dev/null +++ b/src/main/java/com/revature/advice/package-info.java @@ -0,0 +1,5 @@ +/** + * Package that contains all advising classes + */ + +package com.revature.advice; \ No newline at end of file diff --git a/src/main/java/com/revature/beans/User.java b/src/main/java/com/revature/beans/User.java index 49f59a6..cbc80e7 100644 --- a/src/main/java/com/revature/beans/User.java +++ b/src/main/java/com/revature/beans/User.java @@ -20,7 +20,6 @@ import org.springframework.stereotype.Component; -import org.springframework.stereotype.Component; @Component @Entity diff --git a/src/main/java/com/revature/beans/dtos/UserCreationRequest.java b/src/main/java/com/revature/beans/dtos/UserCreationRequest.java new file mode 100644 index 0000000..c20e3de --- /dev/null +++ b/src/main/java/com/revature/beans/dtos/UserCreationRequest.java @@ -0,0 +1,359 @@ +package com.revature.beans.dtos; + +import javax.validation.Valid; +import javax.validation.constraints.Email; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; +import javax.validation.constraints.Size; + +import com.revature.beans.Batch; +import com.revature.beans.User; + +public class UserCreationRequest { + + @Valid + @NotBlank + @Size(min = 3, max = 12) + @Pattern(regexp = "^\\w+\\.?\\w+$") + private String userName; + + private Batch batch; + + @Valid + @NotBlank + @Size(max = 30) + @Pattern(regexp = "^[a-zA-Z\\u00C0-\\u017F]+[- ]?[a-zA-Z\\u00C0-\\u017F]+$") + private String firstName; + + @Valid + @NotBlank + @Size(max = 30) + @Pattern(regexp = "^[a-zA-Z\\u00C0-\\u017F]+[- ]?[a-zA-Z\\u00C0-\\u017F]+$") + private String lastName; + + @NotBlank + @Email + @Pattern(regexp = "^\\w+\\.?\\w+@\\w+\\.[a-zA-Z]{2,4}$") + private String email; + + @NotBlank + @Pattern(regexp = "^\\(?([0-9]{3})\\)?[-.\\s]?([0-9]{3})[-.\\s]?([0-9]{4})$") + private String phoneNumber; + + private boolean isDriver; + private boolean isActive; + private boolean isAcceptingRides; + + @NotBlank + private String hAddress; + + @NotBlank + private String hCity; + + @NotBlank + private String hZip; + + @NotBlank + private String hState; + + @NotBlank + private String wAddress; + + @NotBlank + private String wCity; + + @NotBlank + private String wZip; + + @NotBlank + private String wState; + + /** + * Produces a User Entity object from UserCreationRequest object + * + * @return + */ + public User toUser() { + User user = new User(); + user.setUserName(this.userName); + user.setBatch(this.batch); + user.setFirstName(this.firstName); + user.setLastName(this.lastName); + user.setEmail(this.email); + user.setPhoneNumber(this.phoneNumber); + user.setDriver(this.isDriver); + user.setActive(this.isActive); + user.setAcceptingRides(this.isAcceptingRides); + user.sethAddress(this.hAddress); + user.sethCity(this.hCity); + user.sethState(this.hState); + user.sethZip(this.hZip); + user.setwAddress(this.wAddress); + user.setwCity(this.wCity); + user.setwState(this.wState); + user.setwZip(this.wZip); + return user; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public Batch getBatch() { + return batch; + } + + public void setBatch(Batch batch) { + this.batch = batch; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getPhoneNumber() { + return phoneNumber; + } + + public void setPhoneNumber(String phoneNumber) { + this.phoneNumber = phoneNumber; + } + + public boolean isDriver() { + return isDriver; + } + + public void setDriver(boolean isDriver) { + this.isDriver = isDriver; + } + + public boolean isActive() { + return isActive; + } + + public void setActive(boolean isActive) { + this.isActive = isActive; + } + + public boolean isAcceptingRides() { + return isAcceptingRides; + } + + public void setAcceptingRides(boolean isAcceptingRides) { + this.isAcceptingRides = isAcceptingRides; + } + + public String gethAddress() { + return hAddress; + } + + public void sethAddress(String hAddress) { + this.hAddress = hAddress; + } + + public String gethCity() { + return hCity; + } + + public void sethCity(String hCity) { + this.hCity = hCity; + } + + public String gethZip() { + return hZip; + } + + public void sethZip(String hZip) { + this.hZip = hZip; + } + + public String gethState() { + return hState; + } + + public void sethState(String hState) { + this.hState = hState; + } + + public String getwAddress() { + return wAddress; + } + + public void setwAddress(String wAddress) { + this.wAddress = wAddress; + } + + public String getwCity() { + return wCity; + } + + public void setwCity(String wCity) { + this.wCity = wCity; + } + + public String getwZip() { + return wZip; + } + + public void setwZip(String wZip) { + this.wZip = wZip; + } + + public String getwState() { + return wState; + } + + public void setwState(String wState) { + this.wState = wState; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((batch == null) ? 0 : batch.hashCode()); + result = prime * result + ((email == null) ? 0 : email.hashCode()); + result = prime * result + ((firstName == null) ? 0 : firstName.hashCode()); + result = prime * result + ((hAddress == null) ? 0 : hAddress.hashCode()); + result = prime * result + ((hCity == null) ? 0 : hCity.hashCode()); + result = prime * result + ((hState == null) ? 0 : hState.hashCode()); + result = prime * result + ((hZip == null) ? 0 : hZip.hashCode()); + result = prime * result + (isAcceptingRides ? 1231 : 1237); + result = prime * result + (isActive ? 1231 : 1237); + result = prime * result + (isDriver ? 1231 : 1237); + result = prime * result + ((lastName == null) ? 0 : lastName.hashCode()); + result = prime * result + ((phoneNumber == null) ? 0 : phoneNumber.hashCode()); + result = prime * result + ((userName == null) ? 0 : userName.hashCode()); + result = prime * result + ((wAddress == null) ? 0 : wAddress.hashCode()); + result = prime * result + ((wCity == null) ? 0 : wCity.hashCode()); + result = prime * result + ((wState == null) ? 0 : wState.hashCode()); + result = prime * result + ((wZip == null) ? 0 : wZip.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + UserCreationRequest other = (UserCreationRequest) obj; + if (batch == null) { + if (other.batch != null) + return false; + } else if (!batch.equals(other.batch)) + return false; + if (email == null) { + if (other.email != null) + return false; + } else if (!email.equals(other.email)) + return false; + if (firstName == null) { + if (other.firstName != null) + return false; + } else if (!firstName.equals(other.firstName)) + return false; + if (hAddress == null) { + if (other.hAddress != null) + return false; + } else if (!hAddress.equals(other.hAddress)) + return false; + if (hCity == null) { + if (other.hCity != null) + return false; + } else if (!hCity.equals(other.hCity)) + return false; + if (hState == null) { + if (other.hState != null) + return false; + } else if (!hState.equals(other.hState)) + return false; + if (hZip == null) { + if (other.hZip != null) + return false; + } else if (!hZip.equals(other.hZip)) + return false; + if (isAcceptingRides != other.isAcceptingRides) + return false; + if (isActive != other.isActive) + return false; + if (isDriver != other.isDriver) + return false; + if (lastName == null) { + if (other.lastName != null) + return false; + } else if (!lastName.equals(other.lastName)) + return false; + if (phoneNumber == null) { + if (other.phoneNumber != null) + return false; + } else if (!phoneNumber.equals(other.phoneNumber)) + return false; + if (userName == null) { + if (other.userName != null) + return false; + } else if (!userName.equals(other.userName)) + return false; + if (wAddress == null) { + if (other.wAddress != null) + return false; + } else if (!wAddress.equals(other.wAddress)) + return false; + if (wCity == null) { + if (other.wCity != null) + return false; + } else if (!wCity.equals(other.wCity)) + return false; + if (wState == null) { + if (other.wState != null) + return false; + } else if (!wState.equals(other.wState)) + return false; + if (wZip == null) { + if (other.wZip != null) + return false; + } else if (!wZip.equals(other.wZip)) + return false; + return true; + } + + @Override + public String toString() { + return "UserCreationRequest [userName=" + userName + ", batch=" + batch + ", firstName=" + firstName + + ", lastName=" + lastName + ", email=" + email + ", phoneNumber=" + phoneNumber + ", isDriver=" + + isDriver + ", isActive=" + isActive + ", isAcceptingRides=" + isAcceptingRides + ", hAddress=" + + hAddress + ", hCity=" + hCity + ", hZip=" + hZip + ", hState=" + hState + ", wAddress=" + wAddress + + ", wCity=" + wCity + ", wZip=" + wZip + ", wState=" + wState + "]"; + } + + public UserCreationRequest() { + super(); + } + +} diff --git a/src/main/java/com/revature/beans/dtos/package-info.java b/src/main/java/com/revature/beans/dtos/package-info.java new file mode 100644 index 0000000..20753d2 --- /dev/null +++ b/src/main/java/com/revature/beans/dtos/package-info.java @@ -0,0 +1,5 @@ +/** + * Package that contains all DTOs. + */ + +package com.revature.beans.dtos; \ No newline at end of file diff --git a/src/main/java/com/revature/controllers/UserController.java b/src/main/java/com/revature/controllers/UserController.java index 138c063..c7eaa08 100644 --- a/src/main/java/com/revature/controllers/UserController.java +++ b/src/main/java/com/revature/controllers/UserController.java @@ -28,7 +28,7 @@ import com.google.maps.errors.ApiException; import com.revature.beans.User; -import com.revature.services.BatchService; +import com.revature.beans.dtos.UserCreationRequest; import com.revature.services.DistanceService; import com.revature.services.UserService; @@ -36,9 +36,10 @@ import io.swagger.annotations.ApiOperation; /** - * UserController takes care of handling our requests to /users. - * It provides methods that can perform tasks like all users, user by role (true or false), user by username, - * user by role and location, add user, update user and delete user by id. + * UserController takes care of handling our requests to /users. It provides + * methods that can perform tasks like all users, user by role (true or false), + * user by username, user by role and location, add user, update user and delete + * user by id. * * @author Adonis Cabreja * @@ -47,87 +48,72 @@ @RestController @RequestMapping("/users") @CrossOrigin -@Api(tags= {"User"}) +@Api(tags = { "User" }) public class UserController { - + @Autowired private UserService us; - - @Autowired - private BatchService bs; - + @Autowired private DistanceService ds; - + /** * HTTP GET method (/users) * * @param isDriver represents if the user is a driver or rider. * @param username represents the user's username. * @param location represents the batch's location. - * @return A list of all the users, users by is-driver, user by username and users by is-driver and location. + * @return A list of all the users, users by is-driver, user by username and + * users by is-driver and location. */ - - - /*@ApiOperation(value="Returns user drivers", tags= {"User"}) - @GetMapping - public List getActiveDrivers() { - return us.getActiveDrivers(); - }*/ - - - @ApiOperation(value="Returns user drivers", tags= {"User"}) + + /* + * @ApiOperation(value="Returns user drivers", tags= {"User"}) + * + * @GetMapping public List getActiveDrivers() { return + * us.getActiveDrivers(); } + */ + + @ApiOperation(value = "Returns user drivers", tags = { "User" }) @GetMapping("/driver/{address}") - public List getTopFiveDrivers(@PathVariable("address")String address) throws ApiException, InterruptedException, IOException { - //List aps = new ArrayList(); - System.out.println(address); + public List getTopFiveDrivers(@PathVariable("address") String address) + throws ApiException, InterruptedException, IOException { List destinationList = new ArrayList(); - String [] origins = {address}; -// - Map topfive = new HashMap(); -// - for(User d : us.getActiveDrivers()) { -// + String[] origins = { address }; + Map topfive = new HashMap(); + for (User d : us.getActiveDrivers()) { String add = d.gethAddress(); String city = d.gethCity(); String state = d.gethState(); - + String fullAdd = add + ", " + city + ", " + state; - + destinationList.add(fullAdd); -// topfive.put(fullAdd, d); -// - } -// -// System.out.println(destinationList); -// - String [] destinations = new String[destinationList.size()]; -//// - destinations = destinationList.toArray(destinations); -// - return ds.distanceMatrix(origins, destinations); -// -// - //return ds.distanceMatrix(); - + } + String[] destinations = new String[destinationList.size()]; + destinations = destinationList.toArray(destinations); + return ds.distanceMatrix(origins, destinations); + } - + /** * HTTP GET method (/users) * * @param isDriver represents if the user is a driver or rider. * @param username represents the user's username. * @param location represents the batch's location. - * @return A list of all the users, users by is-driver, user by username and users by is-driver and location. + * @return A list of all the users, users by is-driver, user by username and + * users by is-driver and location. */ - - @ApiOperation(value="Returns all users", tags= {"User"}, notes="Can also filter by is-driver, location and username") + + @ApiOperation(value = "Returns all users", tags = { + "User" }, notes = "Can also filter by is-driver, location and username") @GetMapping - public List getUsers(@RequestParam(name="is-driver",required=false)Boolean isDriver, - @RequestParam(name="username",required=false)String username, - @RequestParam(name="location", required=false)String location) { - + public List getUsers(@RequestParam(name = "is-driver", required = false) Boolean isDriver, + @RequestParam(name = "username", required = false) String username, + @RequestParam(name = "location", required = false) String location) { + if (isDriver != null && location != null) { return us.getUserByRoleAndLocation(isDriver.booleanValue(), location); } else if (isDriver != null) { @@ -135,162 +121,150 @@ public List getUsers(@RequestParam(name="is-driver",required=false)Boolean } else if (username != null) { return us.getUserByUsername(username); } - + return us.getUsers(); } - + /** * HTTP GET (users/{id}) * * @param id represents the user's id. * @return A user that matches the id. */ - - @ApiOperation(value="Returns user by id", tags= {"User"}) + @ApiOperation(value = "Returns user by id", tags = { "User" }) @GetMapping("/{id}") - public User getUserById(@PathVariable("id")int id) { - + public User getUserById(@PathVariable("id") int id) { + return us.getUserById(id); } - + /** * HTTP POST method (/users) * - * @param user represents the new User object being sent. + * @param userRequest represents the new User object being sent. * @return The newly created object with a 201 code. * - * Sends custom error messages when incorrect input is used + * Sends custom error messages when incorrect input is used */ - - @ApiOperation(value="Adds a new user", tags= {"User"}) + @ApiOperation(value = "Adds a new user", tags = { "User" }) @ResponseStatus(HttpStatus.CREATED) @PostMapping - public Map> addUser(@Valid @RequestBody User user, BindingResult result) { - - System.out.println(user.isDriver()); - Map> errors = new HashMap<>(); - - for (FieldError fieldError : result.getFieldErrors()) { - String code = fieldError.getCode(); - String field = fieldError.getField(); - if (code.equals("NotBlank") || code.equals("NotNull")) { -// - switch (field) { - case "userName": - errors.computeIfAbsent(field, key -> new HashSet<>()).add("Username field required"); - break; - case "firstName": - errors.computeIfAbsent(field, key -> new HashSet<>()).add("First name field required"); - break; - case "lastName": - errors.computeIfAbsent(field, key -> new HashSet<>()).add("Last name field required"); - break; - case "wAddress": - errors.computeIfAbsent(field, key -> new HashSet<>()).add("Work address field required"); - break; - case "wState": - case "hState": - errors.computeIfAbsent(field, key -> new HashSet<>()).add("State field required"); - break; - case "phoneNumber": - errors.computeIfAbsent(field, key -> new HashSet<>()).add("Phone number field required"); - break; - case "hAddress": - errors.computeIfAbsent(field, key -> new HashSet<>()).add("Home address field required"); - break; - case "hZip": - case "wZip": - errors.computeIfAbsent(field, key -> new HashSet<>()).add("Zip code field required"); - break; - case "hCity": - case "wCity": - errors.computeIfAbsent(field, key -> new HashSet<>()).add("City field required"); - break; - default: - errors.computeIfAbsent(field, key -> new HashSet<>()).add(field+" required"); - } - } - //username custom error message - else if (code.equals("Size") && field.equals("userName")) { - errors.computeIfAbsent(field, key -> new HashSet<>()).add("Username must be between 3 and 12 characters in length"); - } - else if (code.equals("Pattern") && field.equals("userName")) { - errors.computeIfAbsent(field, key -> new HashSet<>()).add("Username may not have any illegal characters such as $@-"); - } - else if (code.equals("Valid") && field.equals("userName")) { - errors.computeIfAbsent(field, key -> new HashSet<>()).add("Invalid username"); - } - //first name custom error message - else if (code.equals("Size") && field.equals("firstName")) { - errors.computeIfAbsent(field, key -> new HashSet<>()).add("First name cannot be more than 30 characters in length"); - } - else if (code.equals("Pattern") && field.equals("firstName")) { - errors.computeIfAbsent(field, key -> new HashSet<>()).add("First name allows only 1 space or hyphen and no illegal characters"); - } - else if (code.equals("Valid") && field.equals("firstName")) { - errors.computeIfAbsent(field, key -> new HashSet<>()).add("Invalid first name"); - } - //last name custom error message - else if (code.equals("Size") && field.equals("lastName")) { - errors.computeIfAbsent(field, key -> new HashSet<>()).add("Last name cannot be more than 30 characters in length"); - } - else if (code.equals("Pattern") && field.equals("lastName")) { - errors.computeIfAbsent(field, key -> new HashSet<>()).add("Last name allows only 1 space or hyphen and no illegal characters"); - } - else if (code.equals("Valid") && field.equals("lastName")) { - errors.computeIfAbsent(field, key -> new HashSet<>()).add("Invalid last name"); - } - //email custom error messages - else if (code.equals("Email") && field.equals("email")) { - errors.computeIfAbsent(field, key -> new HashSet<>()).add("Invalid Email"); - } - else if (code.equals("Pattern") && field.equals("email")) { - errors.computeIfAbsent(field, key -> new HashSet<>()).add("Invalid Email"); - } - //phone number custom error messages - else if (code.equals("Pattern") && field.equals("phoneNumber")) { - errors.computeIfAbsent(field, key -> new HashSet<>()).add("Invalid Phone Number"); - } - } + public Map> addUser(@Valid @RequestBody UserCreationRequest userRequest, BindingResult result) { + + System.out.println(userRequest.isDriver()); + Map> errors = new HashMap<>(); - if (errors.isEmpty()) { - - user.setBatch(bs.getBatchByNumber(user.getBatch().getBatchNumber())); - us.addUser(user); - + for (FieldError fieldError : result.getFieldErrors()) { + String code = fieldError.getCode(); + String field = fieldError.getField(); + if (code.equals("NotBlank") || code.equals("NotNull")) { + switch (field) { + case "userName": + errors.computeIfAbsent(field, key -> new HashSet<>()).add("Username field required"); + break; + case "firstName": + errors.computeIfAbsent(field, key -> new HashSet<>()).add("First name field required"); + break; + case "lastName": + errors.computeIfAbsent(field, key -> new HashSet<>()).add("Last name field required"); + break; + case "wAddress": + errors.computeIfAbsent(field, key -> new HashSet<>()).add("Work address field required"); + break; + case "wState": + case "hState": + errors.computeIfAbsent(field, key -> new HashSet<>()).add("State field required"); + break; + case "phoneNumber": + errors.computeIfAbsent(field, key -> new HashSet<>()).add("Phone number field required"); + break; + case "hAddress": + errors.computeIfAbsent(field, key -> new HashSet<>()).add("Home address field required"); + break; + case "hZip": + case "wZip": + errors.computeIfAbsent(field, key -> new HashSet<>()).add("Zip code field required"); + break; + case "hCity": + case "wCity": + errors.computeIfAbsent(field, key -> new HashSet<>()).add("City field required"); + break; + default: + errors.computeIfAbsent(field, key -> new HashSet<>()).add(field + " required"); + } + } + // username custom error message + else if (code.equals("Size") && field.equals("userName")) { + errors.computeIfAbsent(field, key -> new HashSet<>()) + .add("Username must be between 3 and 12 characters in length"); + } else if (code.equals("Pattern") && field.equals("userName")) { + errors.computeIfAbsent(field, key -> new HashSet<>()) + .add("Username may not have any illegal characters such as $@-"); + } else if (code.equals("Valid") && field.equals("userName")) { + errors.computeIfAbsent(field, key -> new HashSet<>()).add("Invalid username"); + } + // first name custom error message + else if (code.equals("Size") && field.equals("firstName")) { + errors.computeIfAbsent(field, key -> new HashSet<>()) + .add("First name cannot be more than 30 characters in length"); + } else if (code.equals("Pattern") && field.equals("firstName")) { + errors.computeIfAbsent(field, key -> new HashSet<>()) + .add("First name allows only 1 space or hyphen and no illegal characters"); + } else if (code.equals("Valid") && field.equals("firstName")) { + errors.computeIfAbsent(field, key -> new HashSet<>()).add("Invalid first name"); + } + // last name custom error message + else if (code.equals("Size") && field.equals("lastName")) { + errors.computeIfAbsent(field, key -> new HashSet<>()) + .add("Last name cannot be more than 30 characters in length"); + } else if (code.equals("Pattern") && field.equals("lastName")) { + errors.computeIfAbsent(field, key -> new HashSet<>()) + .add("Last name allows only 1 space or hyphen and no illegal characters"); + } else if (code.equals("Valid") && field.equals("lastName")) { + errors.computeIfAbsent(field, key -> new HashSet<>()).add("Invalid last name"); + } + // email custom error messages + else if (code.equals("Email") && field.equals("email")) { + errors.computeIfAbsent(field, key -> new HashSet<>()).add("Invalid Email"); + } else if (code.equals("Pattern") && field.equals("email")) { + errors.computeIfAbsent(field, key -> new HashSet<>()).add("Invalid Email"); + } + // phone number custom error messages + else if (code.equals("Pattern") && field.equals("phoneNumber")) { + errors.computeIfAbsent(field, key -> new HashSet<>()).add("Invalid Phone Number"); + } + } + + if (errors.isEmpty()) { + us.addUser(userRequest); + } + return errors; - } - return errors; - } - + /** * HTTP PUT method (/users) * * @param user represents the updated User object being sent. * @return The newly updated object. */ - - @ApiOperation(value="Updates user by id", tags= {"User"}) + @ApiOperation(value = "Updates user by id", tags = { "User" }) @PutMapping public User updateUser(@Valid @RequestBody User user) { - //System.out.println(user); return us.updateUser(user); } - + /** * HTTP DELETE method (/users) * * @param id represents the user's id. * @return A string that says which user was deleted. */ - - @ApiOperation(value="Deletes user by id", tags= {"User"}) + @ApiOperation(value = "Deletes user by id", tags = { "User" }) @DeleteMapping("/{id}") - public String deleteUserById(@PathVariable("id")int id) { - + public String deleteUserById(@PathVariable("id") int id) { + return us.deleteUserById(id); } - - + } diff --git a/src/main/java/com/revature/services/JSONReaderService.java b/src/main/java/com/revature/services/JSONReaderService.java index 3b3ee62..e239745 100644 --- a/src/main/java/com/revature/services/JSONReaderService.java +++ b/src/main/java/com/revature/services/JSONReaderService.java @@ -7,6 +7,8 @@ import java.util.HashMap; import java.util.Map; +import org.jboss.logging.Logger; +import org.jboss.logging.Logger.Level; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; @@ -14,8 +16,9 @@ public class JSONReaderService { + private static Logger logger = Logger.getLogger(JSONReaderService.class); + // Method under construction - @SuppressWarnings("unchecked") public static Map dataMapper() { JSONParser jsonParser = new JSONParser(); FileReader dataReady = null; @@ -23,9 +26,8 @@ public static Map dataMapper() { // Local Data for DEV ---> Same format as API json try { dataReady = new FileReader("src/main/resources/users_address.json"); - - } catch (FileNotFoundException e) { - e.printStackTrace(); + } catch (FileNotFoundException e) { + logger.log(Level.ERROR, e.getMessage(), e); } Object obj = null; @@ -33,10 +35,10 @@ public static Map dataMapper() { obj = jsonParser.parse(dataReady); } catch (IOException | ParseException e) { - e.printStackTrace(); + logger.log(Level.ERROR, e.getMessage(), e); } // Declare Map for loop - Map idAndStreets = new HashMap(); + Map idAndStreets = new HashMap(); JSONArray addressList = (JSONArray) obj; // System.out.println("\n... Reading in From addresses.json ..."); @@ -48,23 +50,19 @@ public static Map dataMapper() { Long user_id = (Long) user.get("user_id"); long u=user_id; int intUser=(int)u; - System.out.println(intUser); - // Concatetate street & zip + // Concatenate street & zip String street = (String) user.get("h_address"); String h_zip = (String) user.get("h_zip"); String addrConcat = street + " "+ h_zip; - System.out.println(addrConcat); // Make Hash of userId/addresses PRE-distanceMatrix idAndStreets.put(intUser, addrConcat); // make map of id/streets } - System.out.println(idAndStreets); return idAndStreets; } - @SuppressWarnings("unchecked") public static ArrayList dataCleaner() { // JSON parser object to parse read file @@ -75,46 +73,39 @@ public static ArrayList dataCleaner() { try { dataReady = new FileReader("src/main/resources/users_address.json"); - } catch (FileNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - - } catch (NullPointerException e) { - e.printStackTrace(); + } catch (FileNotFoundException | NullPointerException e) { + logger.log(Level.ERROR, e.getMessage(), e); } Object obj = null; try { obj = jsonParser.parse(dataReady); - } catch (IOException e) { - e.printStackTrace(); - - } catch (ParseException e) { - e.printStackTrace(); + } catch (IOException | ParseException e) { + logger.log(Level.ERROR, e.getMessage(), e); } - ArrayList streets = new ArrayList(); - ArrayList newList = new ArrayList(); + + ArrayList streets = new ArrayList(); + ArrayList newList = new ArrayList(); JSONArray addressList = (JSONArray) obj; - System.out.println("\n... Reading in From addresses.json ..."); - System.out.println(addressList); - System.out.println("\n Objects: "); + logger.info("Reading in From addresses.json"); + logger.info("\n Objects: "); for (Object o : addressList) { JSONObject user = (JSONObject) o; Long user_id = (Long) user.get("user_id"); - System.out.println(user_id); + logger.info(user_id); String first_name = (String) user.get("first_name"); String last_name = (String) user.get("last_name"); String fullName = first_name + " " + last_name; - System.out.println(fullName); + logger.info(fullName); String street = (String) user.get("h_address"); String h_zip = (String) user.get("h_zip"); String addrConcat = street + " "+ h_zip; - System.out.println(addrConcat); + logger.info(addrConcat); streets.add(addrConcat); // make array of streets newList.add(o); diff --git a/src/main/java/com/revature/services/UserService.java b/src/main/java/com/revature/services/UserService.java index b2589e9..2d86f72 100644 --- a/src/main/java/com/revature/services/UserService.java +++ b/src/main/java/com/revature/services/UserService.java @@ -3,6 +3,7 @@ import java.util.List; import com.revature.beans.User; +import com.revature.beans.dtos.UserCreationRequest; public interface UserService { @@ -11,7 +12,7 @@ public interface UserService { public List getUserByUsername(String username); public List getUserByRole(boolean isDriver); public List getUserByRoleAndLocation(boolean isDriver, String location); - public User addUser(User user); + public User addUser(UserCreationRequest userCreationRequest); public User updateUser(User user); public String deleteUserById(int id); public List getActiveDrivers(); diff --git a/src/main/java/com/revature/services/impl/AdminServiceImpl.java b/src/main/java/com/revature/services/impl/AdminServiceImpl.java index 929d2fb..a664dcd 100644 --- a/src/main/java/com/revature/services/impl/AdminServiceImpl.java +++ b/src/main/java/com/revature/services/impl/AdminServiceImpl.java @@ -3,7 +3,9 @@ import java.util.List; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; +import org.springframework.web.client.HttpClientErrorException; import com.revature.beans.Admin; import com.revature.repositories.AdminRepository; @@ -43,7 +45,7 @@ public List getAdmins() { @Override public Admin getAdminById(int id) { - return ar.findById(id).get(); + return ar.findById(id).orElseThrow(() -> new HttpClientErrorException(HttpStatus.NOT_FOUND)); } /** diff --git a/src/main/java/com/revature/services/impl/BatchServiceImpl.java b/src/main/java/com/revature/services/impl/BatchServiceImpl.java index 45b6d6c..1b2373e 100644 --- a/src/main/java/com/revature/services/impl/BatchServiceImpl.java +++ b/src/main/java/com/revature/services/impl/BatchServiceImpl.java @@ -3,7 +3,9 @@ import java.util.List; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; +import org.springframework.web.client.HttpClientErrorException; import com.revature.beans.Batch; import com.revature.repositories.BatchRepository; @@ -43,7 +45,7 @@ public List getBatches() { @Override public Batch getBatchByNumber(int id) { - return br.findById(id).get(); + return br.findById(id).orElseThrow(() -> new HttpClientErrorException(HttpStatus.NOT_FOUND)); } /** diff --git a/src/main/java/com/revature/services/impl/CarServiceImpl.java b/src/main/java/com/revature/services/impl/CarServiceImpl.java index 4724468..d842905 100644 --- a/src/main/java/com/revature/services/impl/CarServiceImpl.java +++ b/src/main/java/com/revature/services/impl/CarServiceImpl.java @@ -3,7 +3,9 @@ import java.util.List; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; +import org.springframework.web.client.HttpClientErrorException; import com.revature.beans.Car; import com.revature.repositories.CarRepository; @@ -43,7 +45,7 @@ public List getCars() { @Override public Car getCarById(int id) { - return cr.findById(id).get(); + return cr.findById(id).orElseThrow(() -> new HttpClientErrorException(HttpStatus.NOT_FOUND)); } /** diff --git a/src/main/java/com/revature/services/impl/DistanceServiceImpl.java b/src/main/java/com/revature/services/impl/DistanceServiceImpl.java index 3c134db..152ac86 100644 --- a/src/main/java/com/revature/services/impl/DistanceServiceImpl.java +++ b/src/main/java/com/revature/services/impl/DistanceServiceImpl.java @@ -23,136 +23,110 @@ @Service public class DistanceServiceImpl implements DistanceService { - + @Autowired private UserService us; @Override - public List distanceMatrix(String[] origins, String[] destinations) throws ApiException, InterruptedException, IOException { - + public List distanceMatrix(String[] origins, final String[] destinations) + throws ApiException, InterruptedException, IOException { + Map userDestMap = new HashMap(); - + List destinationList = new ArrayList(); - - for(User d : us.getActiveDrivers()) { - + + for (User d : us.getActiveDrivers()) { + String add = d.gethAddress(); String city = d.gethCity(); String state = d.gethState(); - + String fullAdd = add + ", " + city + ", " + state; - + destinationList.add(fullAdd); - + userDestMap.put(fullAdd, d); - + } - - //System.out.println(destinationList); - - destinations = new String[destinationList.size()]; -// - destinations = destinationList.toArray(destinations); - - + + String[] mappedDestinations = destinationList.stream().toArray(String[]::new); + GeoApiContext context = new GeoApiContext.Builder().apiKey(getGoogleMAPKey()).build(); List arrlist = new ArrayList(); DistanceMatrixApiRequest req = DistanceMatrixApi.newRequest(context); - DistanceMatrix t = req.origins(origins).destinations(destinations).mode(TravelMode.DRIVING).units(Unit.IMPERIAL) - .await(); - - Map< Double, String> unsortMap = new HashMap<>(); + DistanceMatrix t = req.origins(origins).destinations(mappedDestinations).mode(TravelMode.DRIVING) + .units(Unit.IMPERIAL).await(); + + Map unsortMap = new HashMap<>(); for (int i = 0; i < origins.length; i++) { - for (int j = 0; j < destinations.length; j++) { + for (int j = 0; j < mappedDestinations.length; j++) { try { - System.out.println((j+1) + "): " + t.rows[i].elements[j].distance.inMeters + " meters"); + System.out.println((j + 1) + "): " + t.rows[i].elements[j].distance.inMeters + " meters"); arrlist.add((double) t.rows[i].elements[j].distance.inMeters); - - unsortMap.put((double) t.rows[i].elements[j].distance.inMeters, destinations[j]); - + + unsortMap.put((double) t.rows[i].elements[j].distance.inMeters, mappedDestinations[j]); + System.out.println((double) t.rows[i].elements[j].distance.inMeters); - - + } catch (Exception e) { - System.out.println("invalid address"); + System.out.println("invalid address"); } } } - - + // LinkedHashMap sortedMap = new LinkedHashMap<>(); // unsortMap.entrySet().stream().sorted(Map.Entry.comparingByValue()) // .forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue())); // - - - - + System.out.println("-"); - - + Collections.sort(arrlist); - + System.out.println(arrlist); List destList = new ArrayList(); - - arrlist.removeIf(r ->(arrlist.indexOf(r)>4)); - - - Double [] arrArray = new Double[arrlist.size()]; - - arrArray = arrlist.toArray(arrArray); - - System.out.println(arrArray); - - - for(int c=0; c< arrArray.length; c++) { - String destination = unsortMap.get(arrArray[c]); - destList.add(destination); - } - - System.out.println(destList); - - - - - - - - - String [] destArray = new String[destList.size()]; - + + arrlist.removeIf(r -> (arrlist.indexOf(r) > 4)); + + Double[] arrArray = new Double[arrlist.size()]; + + arrArray = arrlist.toArray(arrArray); + + System.out.println(arrArray); + + for (int c = 0; c < arrArray.length; c++) { + String destination = unsortMap.get(arrArray[c]); + destList.add(destination); + } + + System.out.println(destList); + + String[] destArray = new String[destList.size()]; + destArray = destList.toArray(destArray); - + List userList = new ArrayList(); - - - for(int x=0; x< destArray.length; x++) { + + for (int x = 0; x < destArray.length; x++) { User a = userDestMap.get(destArray[x]); System.out.println(a); userList.add(a); System.out.println(userList); } - - - return userList; - + return userList; } - + public String getGoogleMAPKey() { - Map env = System.getenv(); - for (Map.Entry entry: env.entrySet()) { - if(entry.getKey().equals("googleMapAPIKey")) { - return entry.getValue(); - } - } - return null; - } - - - + Map env = System.getenv(); + for (Map.Entry entry : env.entrySet()) { + if (entry.getKey().equals("googleMapAPIKey")) { + return entry.getValue(); + } + } + return null; + } } \ No newline at end of file diff --git a/src/main/java/com/revature/services/impl/UserServiceImpl.java b/src/main/java/com/revature/services/impl/UserServiceImpl.java index 784e4cd..2e1a754 100644 --- a/src/main/java/com/revature/services/impl/UserServiceImpl.java +++ b/src/main/java/com/revature/services/impl/UserServiceImpl.java @@ -3,10 +3,14 @@ import java.util.List; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; +import org.springframework.web.client.HttpClientErrorException; import com.revature.beans.User; +import com.revature.beans.dtos.UserCreationRequest; import com.revature.repositories.UserRepository; +import com.revature.services.BatchService; import com.revature.services.UserService; /** @@ -23,6 +27,9 @@ public class UserServiceImpl implements UserService { @Autowired private UserRepository ur; + @Autowired + private BatchService batchService; + @Override public List getActiveDrivers() { return ur.getActiveDrivers(); @@ -48,7 +55,7 @@ public List getUsers() { @Override public User getUserById(int id) { - return ur.findById(id).get(); + return ur.findById(id).orElseThrow(() -> new HttpClientErrorException(HttpStatus.NOT_FOUND)); } /** @@ -96,7 +103,9 @@ public List getUserByRoleAndLocation(boolean isDriver, String location) { */ @Override - public User addUser(User user) { + public User addUser(UserCreationRequest userRequest) { + User user = userRequest.toUser(); + user.setBatch(batchService.getBatchByNumber(userRequest.getBatch().getBatchNumber())); return ur.save(user); } diff --git a/src/test/java/com/revature/controllers/UserControllerTest.java b/src/test/java/com/revature/controllers/UserControllerTest.java index c739ed5..6cb4afc 100644 --- a/src/test/java/com/revature/controllers/UserControllerTest.java +++ b/src/test/java/com/revature/controllers/UserControllerTest.java @@ -30,7 +30,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.revature.beans.Batch; import com.revature.beans.User; -import com.revature.services.BatchService; +import com.revature.beans.dtos.UserCreationRequest; import com.revature.services.DistanceService; import com.revature.services.UserService; @@ -47,9 +47,6 @@ public class UserControllerTest { @MockBean private UserService us; - @MockBean - private BatchService bs; - @MockBean private DistanceService ds; @@ -128,7 +125,13 @@ public void testGettingUserByRoleAndLocation() throws Exception { public void testAddingUser() throws Exception { Batch batch = new Batch(111, "address"); - User user = new User(1, "userName", batch, "adonis", "cabreja", "adonis@gmail.com", "123-456-7891"); + UserCreationRequest user = new UserCreationRequest(); + user.setUserName("userName"); + user.setBatch(batch); + user.setFirstName("adonis"); + user.setLastName("cabreja"); + user.setEmail("adonis@gmail.com"); + user.setPhoneNumber("123-456-7891"); user.setDriver(true); user.setActive(true); user.setAcceptingRides(true); @@ -142,16 +145,17 @@ public void testAddingUser() throws Exception { user.setwState("FL"); user.setwAddress("456 USF Ave"); + User expected = user.toUser(); + Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); - Set> violations = validator.validate(user); + Set> violations = validator.validate(user); System.out.println(violations); - when(us.addUser(user)).thenReturn(user); + when(us.addUser(user)).thenReturn(expected); mvc.perform(post("/users").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsString(user))) .andExpect(status().isCreated()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)); -// .andExpect(jsonPath("$.userName").value("userName")); } @Test diff --git a/src/test/java/com/revature/services/impl/UserServiceImplTest.java b/src/test/java/com/revature/services/impl/UserServiceImplTest.java index 34bde80..83184b6 100644 --- a/src/test/java/com/revature/services/impl/UserServiceImplTest.java +++ b/src/test/java/com/revature/services/impl/UserServiceImplTest.java @@ -11,11 +11,14 @@ import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.Mockito; import org.springframework.test.context.junit4.SpringRunner; import com.revature.beans.Batch; import com.revature.beans.User; +import com.revature.beans.dtos.UserCreationRequest; import com.revature.repositories.UserRepository; +import com.revature.services.BatchService; @RunWith(SpringRunner.class) public class UserServiceImplTest { @@ -26,6 +29,9 @@ public class UserServiceImplTest { @Mock private UserRepository ur; + @Mock + private BatchService bs; + @Test public void testGettingUsers() { @@ -83,9 +89,13 @@ public void testGettingUserByRoleAndLocation() { @Test public void testAddingUser() { - User expected = new User(1, "userName", new Batch(), "adonis", "cabreja", "adonis@gmail.com", "123-456-789"); - when(ur.save(expected)).thenReturn(expected); - User actual = usi.addUser(expected); + UserCreationRequest userRequest = new UserCreationRequest(); + User expected = userRequest.toUser(); + userRequest.setBatch(new Batch(1, "USF")); + + when(bs.getBatchByNumber(userRequest.getBatch().getBatchNumber())).thenReturn(userRequest.getBatch()); + when(ur.save(Mockito.any(User.class))).thenReturn(expected); + User actual = usi.addUser(userRequest); assertEquals(expected, actual); }