From 5bbfc562be6a68117b6913badef5a80443168a92 Mon Sep 17 00:00:00 2001 From: Tarah Date: Mon, 19 Apr 2021 23:08:24 -0400 Subject: [PATCH 1/2] MVP --- .../zoos/services/ZooServiceImpl.html | 8 +- schools/pom.xml | 23 ++- .../schools/SchoolsApplication.java | 46 ++++- .../schools/config/H2ServerConfiguration.java | 16 +- .../schools/config/Swagger2Config.java | 54 +++++ .../controllers/OtherApisController.java | 125 ++++++++++++ .../exceptions/CustomErrorDetails.java | 42 ++++ .../exceptions/ResourceFoundException.java | 9 + .../exceptions/ResourceNotFoundException.java | 8 + .../handlers/RestExceptionHandler.java | 185 ++++++++++++++++++ .../schools/models/ErrorDetail.java | 74 +++++++ .../schools/models/Instructor.java | 2 + .../schools/models/IssPosition.java | 26 +++ .../schools/models/IssPositionReturnData.java | 37 ++++ .../schools/models/SlipReturnData.java | 24 +++ .../schools/models/Translation.java | 19 ++ .../schools/models/TranslationContents.java | 19 ++ .../schools/models/ValidationError.java | 30 +++ .../com/lambdaschool/schools/models/slip.java | 31 +++ .../schools/services/CoursesServiceImpl.java | 12 +- .../schools/services/HelperFunctions.java | 10 + .../schools/services/HelperFunctionsImpl.java | 49 +++++ .../schools/services/InstructorService.java | 17 ++ .../services/InstuctorServiceImpl.java | 71 +++++++ .../schools/services/StudentServiceImpl.java | 9 +- .../src/main/resources/application.properties | 7 + 26 files changed, 927 insertions(+), 26 deletions(-) create mode 100644 schools/src/main/java/com/lambdaschool/schools/config/Swagger2Config.java create mode 100644 schools/src/main/java/com/lambdaschool/schools/controllers/OtherApisController.java create mode 100644 schools/src/main/java/com/lambdaschool/schools/exceptions/CustomErrorDetails.java create mode 100644 schools/src/main/java/com/lambdaschool/schools/exceptions/ResourceFoundException.java create mode 100644 schools/src/main/java/com/lambdaschool/schools/exceptions/ResourceNotFoundException.java create mode 100644 schools/src/main/java/com/lambdaschool/schools/handlers/RestExceptionHandler.java create mode 100644 schools/src/main/java/com/lambdaschool/schools/models/ErrorDetail.java create mode 100644 schools/src/main/java/com/lambdaschool/schools/models/IssPosition.java create mode 100644 schools/src/main/java/com/lambdaschool/schools/models/IssPositionReturnData.java create mode 100644 schools/src/main/java/com/lambdaschool/schools/models/SlipReturnData.java create mode 100644 schools/src/main/java/com/lambdaschool/schools/models/Translation.java create mode 100644 schools/src/main/java/com/lambdaschool/schools/models/TranslationContents.java create mode 100644 schools/src/main/java/com/lambdaschool/schools/models/ValidationError.java create mode 100644 schools/src/main/java/com/lambdaschool/schools/models/slip.java create mode 100644 schools/src/main/java/com/lambdaschool/schools/services/HelperFunctions.java create mode 100644 schools/src/main/java/com/lambdaschool/schools/services/HelperFunctionsImpl.java create mode 100644 schools/src/main/java/com/lambdaschool/schools/services/InstructorService.java create mode 100644 schools/src/main/java/com/lambdaschool/schools/services/InstuctorServiceImpl.java diff --git a/schools/javadocs/com/lambdaschool/zoos/services/ZooServiceImpl.html b/schools/javadocs/com/lambdaschool/zoos/services/ZooServiceImpl.html index 10bef294..845a2d71 100644 --- a/schools/javadocs/com/lambdaschool/zoos/services/ZooServiceImpl.html +++ b/schools/javadocs/com/lambdaschool/zoos/services/ZooServiceImpl.html @@ -376,7 +376,7 @@

update

delete

@Transactional
 public void delete​(long id)
-            throws javax.persistence.EntityNotFoundException
+ throws javax.persistence.ResourceNotFoundException
Description copied from interface: ZooService
Deletes the course record, it student course combinations, and its telephone items from the database based off of the provided primary key
@@ -385,7 +385,7 @@

delete

Parameters:
id - id The primary key (long) of the course you seek.
Throws:
-
javax.persistence.EntityNotFoundException
+
javax.persistence.ResourceNotFoundException
@@ -438,7 +438,7 @@

saveZooAnimalCombo

  • findZooByLikeName

    public java.util.ArrayList<Zoo> findZooByLikeName​(java.lang.String name)
    -                                           throws javax.persistence.EntityNotFoundException
    + throws javax.persistence.ResourceNotFoundException
    Description copied from interface: ZooService
    A list of all zoos whose name contains the given substring A Stretch Goal
    @@ -450,7 +450,7 @@

    findZooByLikeName

    Returns:
    List of zoos whose name contains the given substring
    Throws:
    -
    javax.persistence.EntityNotFoundException
    +
    javax.persistence.ResourceNotFoundException
  • diff --git a/schools/pom.xml b/schools/pom.xml index e68d108f..5b797589 100644 --- a/schools/pom.xml +++ b/schools/pom.xml @@ -15,7 +15,7 @@ Demo project for Spring Boot - 11 + 14 @@ -43,6 +43,27 @@ spring-boot-starter-test test + + + + io.springfox + springfox-swagger2 + 2.9.2 + + + + + io.springfox + springfox-swagger-ui + 2.9.2 + + + + io.springfox + springfox-bean-validators + 2.9.2 + + diff --git a/schools/src/main/java/com/lambdaschool/schools/SchoolsApplication.java b/schools/src/main/java/com/lambdaschool/schools/SchoolsApplication.java index ae94d2dc..f2d56537 100644 --- a/schools/src/main/java/com/lambdaschool/schools/SchoolsApplication.java +++ b/schools/src/main/java/com/lambdaschool/schools/SchoolsApplication.java @@ -1,8 +1,15 @@ package com.lambdaschool.schools; +import com.lambdaschool.schools.models.slip; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.core.ParameterizedTypeReference; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; +import org.springframework.http.*; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.web.client.RestTemplate; + +import java.util.Collections; /** * Main class to start the application. @@ -17,10 +24,43 @@ public class SchoolsApplication * * @param args Not used in this application. */ - public static void main(String[] args) - { + public static void main(String[] args){ + /* + * Creates the object that is needed to do a client side Rest API call. + * We are the client getting data from a remote API. + */ + RestTemplate restTemplate = new RestTemplate(); + + // we need to tell our RestTemplate what format to expect + MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); + // a couple of common formats + // converter.setSupportedMediaTypes(Collections.singletonList(MediaType.TEXT_HTML)); + // converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON)); + // or we can accept all formats! Easiest but least secure + converter.setSupportedMediaTypes(Collections.singletonList(MediaType.ALL)); + restTemplate.getMessageConverters().add(converter); + + String requestURL = "https://api.adviceslip.com/advice"; + ParameterizedTypeReference responseType = new ParameterizedTypeReference<>() + { + }; + + // create the response entity. do the get and get back information + ResponseEntity responseEntity = restTemplate.exchange(requestURL, + HttpMethod.GET, + null, + responseType); + + try{ + System.out.println(System.getenv("PATH").toUpperCase()); + } catch (Exception e){ + System.out.println("No Such Environment Variable"); + } finally{ + // now that we have our data, let's print it to the console! + slip ourSlip = responseEntity.getBody(); + System.out.println(ourSlip); SpringApplication.run(SchoolsApplication.class, args); + } } - } diff --git a/schools/src/main/java/com/lambdaschool/schools/config/H2ServerConfiguration.java b/schools/src/main/java/com/lambdaschool/schools/config/H2ServerConfiguration.java index 981a4568..236c1d7a 100644 --- a/schools/src/main/java/com/lambdaschool/schools/config/H2ServerConfiguration.java +++ b/schools/src/main/java/com/lambdaschool/schools/config/H2ServerConfiguration.java @@ -44,10 +44,10 @@ public Server h2TcpServer() throws SQLException { return Server.createTcpServer("-tcp", - "-tcpAllowOthers", - "-tcpPort", - h2TcpPort) - .start(); + "-tcpAllowOthers", + "-tcpPort", + h2TcpPort) + .start(); } /** @@ -64,9 +64,9 @@ public Server h2WebServer() throws SQLException { return Server.createWebServer("-web", - "-webAllowOthers", - "-webPort", - h2WebPort) - .start(); + "-webAllowOthers", + "-webPort", + h2WebPort) + .start(); } } \ No newline at end of file diff --git a/schools/src/main/java/com/lambdaschool/schools/config/Swagger2Config.java b/schools/src/main/java/com/lambdaschool/schools/config/Swagger2Config.java new file mode 100644 index 00000000..fbff8690 --- /dev/null +++ b/schools/src/main/java/com/lambdaschool/schools/config/Swagger2Config.java @@ -0,0 +1,54 @@ +package com.lambdaschool.schools.config; + +import org.springframework.context.annotation.*; +import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration; +import springfox.documentation.builders.*; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.service.Contact; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +/** + * Configures the default Swagger Documentation + */ +@Configuration +@EnableSwagger2 +@Import(BeanValidatorPluginsConfiguration.class) +public class Swagger2Config +{ + /** + * Configures what to document using Swagger + * + * @return A Docket which is the primary interface for Swagger configuration + */ + @Bean + public Docket api() + { + return new Docket(DocumentationType.SWAGGER_2) + .select() + .apis(RequestHandlerSelectors + .basePackage("com.lambdaschool.schools")) + .paths(PathSelectors.regex("/.*")) + .build() + .apiInfo(apiEndPointsInfo()); + } + + /** + * Configures some information related to the Application for Swagger + * + * @return ApiInfo a Swagger object containing identification information for this application + */ + private ApiInfo apiEndPointsInfo() + { + return new ApiInfoBuilder().title("School Example") + .description("User Model Example") + .contact(new Contact("John Mitchell", + "http://www.lambdaschool.com", + "john@lambdaschool.com")) + .license("MIT") + .licenseUrl("https://github.com/LambdaSchool/java-school/blob/master/LICENSE") + .version("1.0.0") + .build(); + } +} \ No newline at end of file diff --git a/schools/src/main/java/com/lambdaschool/schools/controllers/OtherApisController.java b/schools/src/main/java/com/lambdaschool/schools/controllers/OtherApisController.java new file mode 100644 index 00000000..365f1179 --- /dev/null +++ b/schools/src/main/java/com/lambdaschool/schools/controllers/OtherApisController.java @@ -0,0 +1,125 @@ +package com.lambdaschool.schools.controllers; + +import com.lambdaschool.schools.models.*; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.*; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.client.RestTemplate; + +import java.util.Collections; + +@RestController +@RequestMapping("/otherapis") // optional +public class OtherApisController +{ + /* + * Creates the object that is needed to do a client side Rest API call. + * We are the client getting data from a remote API. + * We can share this template among endpoints + */ + private RestTemplate restTemplate = new RestTemplate(); + + @GetMapping(value = "/isspositions") + public ResponseEntity listIssPositions() + { + // we need to tell our RestTemplate what format to expect + MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); + // a couple of common formats + // converter.setSupportedMediaTypes(Collections.singletonList(MediaType.TEXT_HTML)); + // converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON)); + // or we can accept all formats! Easiest but least secure + converter.setSupportedMediaTypes(Collections.singletonList(MediaType.ALL)); + restTemplate.getMessageConverters().add(converter); + + // create the url to access the API + String requestURL = "http://api.open-notify.org/iss-now.json"; + // create the responseType expected. Notice the IssPositionReturnData is the data type we are expecting back from the API! + ParameterizedTypeReference responseType = new ParameterizedTypeReference<>() + { + }; + + // create the response entity. do the get and get back information + ResponseEntity responseEntity = restTemplate.exchange(requestURL, + HttpMethod.GET, + null, + responseType); + // we want to return the Iss_position data. From the data that gets returned in the body, + // get the Iss_position data only and return it. + // putting the data into its own object first, prevents the data from being reported to client inside of + // an embedded. So the response will look more like our clients are use to! + IssPosition ourIssPosition = responseEntity.getBody().getIss_position(); + return new ResponseEntity<>(ourIssPosition, + HttpStatus.OK); + } + + @GetMapping(value = "/advice") + public ResponseEntity listSlipAdvice() + { + // we need to tell our RestTemplate what format to expect + MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); + // a couple of common formats + // converter.setSupportedMediaTypes(Collections.singletonList(MediaType.TEXT_HTML)); + // converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON)); + // or we can accept all formats! Easiest but least secure + converter.setSupportedMediaTypes(Collections.singletonList(MediaType.ALL)); + restTemplate.getMessageConverters().add(converter); + + // create the url to access the API + String requestURL = "https://api.adviceslip.com/advice"; + // create the responseType expected. Notice the IssPositionReturnData is the data type we are expecting back from the API! + ParameterizedTypeReference responseType = new ParameterizedTypeReference<>() + { + }; + + // create the response entity. do the get and get back information + ResponseEntity responseEntity = restTemplate.exchange(requestURL, + HttpMethod.GET, + null, + responseType); + // we want to return the Iss_position data. From the data that gets returned in the body, + // get the Iss_position data only and return it. + // putting the data into its own object first, prevents the data from being reported to client inside of + // an embedded. So the response will look more like our clients are use to! + slip ourSlipPosition = responseEntity.getBody().getSlip_position(); + return new ResponseEntity<>(ourSlipPosition, + HttpStatus.OK); + } + + @GetMapping(value = "/shakespeare/{englishText}") + public ResponseEntity getTranslation( + @PathVariable + String englishText) + { + // we need to tell our RestTemplate what format to expect + MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); + // a couple of common formats + // converter.setSupportedMediaTypes(Collections.singletonList(MediaType.TEXT_HTML)); + // converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON)); + // or we can accept all formats! Easiest but least secure + converter.setSupportedMediaTypes(Collections.singletonList(MediaType.ALL)); + restTemplate.getMessageConverters() + .add(converter); + + // create the url to access the API including adding the path variable + String requestURL = "https://api.funtranslations.com/translate/shakespeare.json?text=" + englishText; + // create the responseType expected. Notice the Translation is the data type we are expecting back from the API! + ParameterizedTypeReference responseType = new ParameterizedTypeReference<>() + { + }; + + // create the response entity. do the get and get back information + ResponseEntity responseEntity = restTemplate.exchange(requestURL, + HttpMethod.GET, + null, + responseType); + // we want to return the contents of the translation data. From the data that gets returned in the body, + // get the contents data only and return it. + // putting the data into its own object first, prevents the data from being reported to client inside of + // an embedded. So the response will look more like our clients are use to! + TranslationContents ourTranslation = responseEntity.getBody() + .getContents(); + return new ResponseEntity<>(ourTranslation, + HttpStatus.OK); + } +} \ No newline at end of file diff --git a/schools/src/main/java/com/lambdaschool/schools/exceptions/CustomErrorDetails.java b/schools/src/main/java/com/lambdaschool/schools/exceptions/CustomErrorDetails.java new file mode 100644 index 00000000..3836fec4 --- /dev/null +++ b/schools/src/main/java/com/lambdaschool/schools/exceptions/CustomErrorDetails.java @@ -0,0 +1,42 @@ +package com.lambdaschool.schools.exceptions; + +import com.lambdaschool.schools.services.HelperFunctions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.web.servlet.error.DefaultErrorAttributes; +import org.springframework.stereotype.Component; +import org.springframework.web.context.request.WebRequest; + +import java.text.SimpleDateFormat; +import java.util.*; + +@Component +public class CustomErrorDetails extends DefaultErrorAttributes { + + @Autowired + private HelperFunctions helperFunctions; + + /* + title + status + detail + timestamp + developerMessage + */ + + SimpleDateFormat dateFormat = new SimpleDateFormat("E, MMM dd,yyyy | HH:mm:ss"); + Date date = new Date(); + @Override + public Map getErrorAttributes(WebRequest webRequest, boolean includeStackTrace){ + Map errorAttributes = super.getErrorAttributes(webRequest, includeStackTrace); + + Map rtnAttributes = new LinkedHashMap<>(); + rtnAttributes.put("title", errorAttributes.get("error")); + rtnAttributes.put("status", errorAttributes.get("status")); + rtnAttributes.put("details", errorAttributes.get("message")); + rtnAttributes.put("timestamp", dateFormat.format(date)); + rtnAttributes.put("developerMessage", "path: " + errorAttributes.get("path")); + rtnAttributes.put("errors", helperFunctions.getValidationErrors(this.getError(webRequest))); + + return rtnAttributes; + } +} diff --git a/schools/src/main/java/com/lambdaschool/schools/exceptions/ResourceFoundException.java b/schools/src/main/java/com/lambdaschool/schools/exceptions/ResourceFoundException.java new file mode 100644 index 00000000..d4c45f0e --- /dev/null +++ b/schools/src/main/java/com/lambdaschool/schools/exceptions/ResourceFoundException.java @@ -0,0 +1,9 @@ +package com.lambdaschool.schools.exceptions; + +import javax.persistence.EntityExistsException; + +public class ResourceFoundException extends EntityExistsException { + public ResourceFoundException(String message) { + super("Found an issue with School: " + message); + } +} diff --git a/schools/src/main/java/com/lambdaschool/schools/exceptions/ResourceNotFoundException.java b/schools/src/main/java/com/lambdaschool/schools/exceptions/ResourceNotFoundException.java new file mode 100644 index 00000000..8da2fef2 --- /dev/null +++ b/schools/src/main/java/com/lambdaschool/schools/exceptions/ResourceNotFoundException.java @@ -0,0 +1,8 @@ +package com.lambdaschool.schools.exceptions; + +public class ResourceNotFoundException extends RuntimeException { + + public ResourceNotFoundException(String message) { + super("Found an issue with School: " + message); + } +} \ No newline at end of file diff --git a/schools/src/main/java/com/lambdaschool/schools/handlers/RestExceptionHandler.java b/schools/src/main/java/com/lambdaschool/schools/handlers/RestExceptionHandler.java new file mode 100644 index 00000000..6dc6431b --- /dev/null +++ b/schools/src/main/java/com/lambdaschool/schools/handlers/RestExceptionHandler.java @@ -0,0 +1,185 @@ +package com.lambdaschool.schools.handlers; + +import com.lambdaschool.schools.exceptions.ResourceFoundException; +import com.lambdaschool.schools.exceptions.ResourceNotFoundException; +import com.lambdaschool.schools.models.ErrorDetail; +import com.lambdaschool.schools.services.HelperFunctions; +import org.springframework.beans.TypeMismatchException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.http.*; +import org.springframework.web.HttpRequestMethodNotSupportedException; +import org.springframework.web.bind.*; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.context.request.WebRequest; +import org.springframework.web.servlet.NoHandlerFoundException; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; + +import java.text.SimpleDateFormat; +import java.util.Date; + +@RestControllerAdvice +@Order(Ordered.HIGHEST_PRECEDENCE) +public class RestExceptionHandler extends ResponseEntityExceptionHandler { + + @Autowired + private HelperFunctions helperFunctions; + + SimpleDateFormat dateFormat = new SimpleDateFormat("E, MMM dd,yyyy || HH:mm:ss"); + Date date = new Date(); + + @ExceptionHandler(ResourceNotFoundException.class) + public ResponseEntity handleResourceNotFoundException(ResourceNotFoundException rnfe) { + + ErrorDetail errorDetail = new ErrorDetail(); + + errorDetail.setTitle("Resource Not Found!"); + errorDetail.setStatus(HttpStatus.NOT_FOUND.value()); + errorDetail.setDetail(rnfe.getMessage()); + errorDetail.setTimestamp(dateFormat.format(date)); + errorDetail.setDeveloperMessage(rnfe.getClass().getName()); + errorDetail.setErrors(helperFunctions.getValidationErrors(rnfe)); + return new ResponseEntity<>(errorDetail, null, HttpStatus.NOT_FOUND); + } + + @ExceptionHandler(ResourceFoundException.class) + public ResponseEntity handleResourceFoundException(ResourceFoundException rsfe) { + + ErrorDetail confirmDetail = new ErrorDetail(); + + confirmDetail.setTitle("Resource Found!"); + confirmDetail.setStatus(HttpStatus.FOUND.value()); + confirmDetail.setDetail(rsfe.getMessage()); + confirmDetail.setTimestamp(dateFormat.format(date)); + confirmDetail.setDeveloperMessage("Found an issue with School: " + rsfe.getClass().getName()); + confirmDetail.setErrors(helperFunctions.getValidationErrors(rsfe)); + return new ResponseEntity<>(confirmDetail, null, HttpStatus.FOUND); + } + + @Override + protected ResponseEntity handleExceptionInternal(Exception ex, Object body, + HttpHeaders headers, HttpStatus status, + WebRequest request) { + + ErrorDetail errorDetail = new ErrorDetail(); + + errorDetail.setTitle("Rest Internal Exception"); + errorDetail.setStatus(status.value()); + errorDetail.setDetail(ex.getMessage()); + errorDetail.setTimestamp(dateFormat.format(date)); + errorDetail.setDeveloperMessage("Found an issue with School: " + ex.getClass().getName()); + errorDetail.setErrors(helperFunctions.getValidationErrors(ex)); + return new ResponseEntity<>(errorDetail, null, status); + } + + @Override + protected ResponseEntity handleHttpRequestMethodNotSupported( + HttpRequestMethodNotSupportedException ex, + HttpHeaders headers, + HttpStatus status, + WebRequest request) { + + ErrorDetail errorDetail = new ErrorDetail(); + + errorDetail.setTitle("Rest Internal Exception"); + errorDetail.setStatus(status.value()); + errorDetail.setDetail(ex.getMessage()); + errorDetail.setTimestamp(dateFormat.format(date)); + errorDetail.setDeveloperMessage("Found an issue with School: " + ex.getClass().getName()); + errorDetail.setErrors(helperFunctions.getValidationErrors(ex)); + return new ResponseEntity<>(errorDetail, null, status); + } + + @Override + protected ResponseEntity handleMissingServletRequestParameter( + MissingServletRequestParameterException ex, + HttpHeaders headers, + HttpStatus status, + WebRequest request) { + + ErrorDetail errorDetail = new ErrorDetail(); + + errorDetail.setTitle("Rest Internal Exception"); + errorDetail.setStatus(status.value()); + errorDetail.setDetail("Found an issue with School: " + ex.getMessage()); + errorDetail.setTimestamp(dateFormat.format(date)); + errorDetail.setDeveloperMessage(ex.getClass().getName()); + errorDetail.setErrors(helperFunctions.getValidationErrors(ex)); + return new ResponseEntity<>(errorDetail, null, status); + } + + @Override + protected ResponseEntity handleNoHandlerFoundException( + NoHandlerFoundException ex, + HttpHeaders headers, + HttpStatus status, + WebRequest request) { + + ErrorDetail errorDetail = new ErrorDetail(); + + errorDetail.setTitle("Rest Internal Exception"); + errorDetail.setStatus(status.value()); + errorDetail.setDetail("Found an issue with School: " + ex.getMessage()); + errorDetail.setTimestamp(dateFormat.format(date)); + errorDetail.setDeveloperMessage(ex.getClass() + .getName()); + errorDetail.setErrors(helperFunctions.getValidationErrors(ex)); + return new ResponseEntity<>(errorDetail, status); + } + + @Override + protected ResponseEntity handleMethodArgumentNotValid( + MethodArgumentNotValidException ex, + HttpHeaders headers, + HttpStatus status, + WebRequest request) { + ErrorDetail errorDetail = new ErrorDetail(); + + errorDetail.setTitle("Rest Internal Exception"); + errorDetail.setStatus(status.value()); + errorDetail.setDetail("Found an issue with School: " + ex.getMessage()); + errorDetail.setTimestamp(dateFormat.format(date)); + errorDetail.setDeveloperMessage(ex.getClass() + .getName()); + errorDetail.setErrors(helperFunctions.getValidationErrors(ex)); + return new ResponseEntity<>(errorDetail, status); + } + + @Override + protected ResponseEntity handleTypeMismatch( + TypeMismatchException ex, + HttpHeaders headers, + HttpStatus status, + WebRequest request) { + ErrorDetail errorDetail = new ErrorDetail(); + + errorDetail.setTitle("Rest Internal Exception"); + errorDetail.setStatus(status.value()); + errorDetail.setDetail("Found an issue with School: " + ex.getMessage()); + errorDetail.setTimestamp(dateFormat.format(date)); + errorDetail.setDeveloperMessage(ex.getClass() + .getName()); + errorDetail.setErrors(helperFunctions.getValidationErrors(ex)); + return new ResponseEntity<>(errorDetail, status); + } + + @Override + protected ResponseEntity handleMissingPathVariable( + MissingPathVariableException ex, + HttpHeaders headers, + HttpStatus status, + WebRequest request) { + ErrorDetail errorDetail = new ErrorDetail(); + + errorDetail.setTitle("Rest Internal Exception"); + errorDetail.setStatus(status.value()); + errorDetail.setDetail("Found an issue with School: " + ex.getMessage()); + errorDetail.setTimestamp(dateFormat.format(date)); + errorDetail.setDeveloperMessage(ex.getClass() + .getName()); + errorDetail.setErrors(helperFunctions.getValidationErrors(ex)); + return new ResponseEntity<>(errorDetail, status); + } +} \ No newline at end of file diff --git a/schools/src/main/java/com/lambdaschool/schools/models/ErrorDetail.java b/schools/src/main/java/com/lambdaschool/schools/models/ErrorDetail.java new file mode 100644 index 00000000..dc47324a --- /dev/null +++ b/schools/src/main/java/com/lambdaschool/schools/models/ErrorDetail.java @@ -0,0 +1,74 @@ +package com.lambdaschool.schools.models; + +import java.util.ArrayList; +import java.util.List; + +public class ErrorDetail { + private String title; + private int status; + private String detail; +// private Date timestamp; + private String timestamp; + private String developerMessage; + private List errors = new ArrayList<>(); + + public ErrorDetail() { + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public int getStatus() { + return status; + } + + public void setStatus(int status) { + this.status = status; + } + + public String getDetail() { + return detail; + } + + public void setDetail(String detail) { + this.detail = detail; + } + +// public Date getTimestamp() { +// return timestamp; +// } +// +// public void setTimestamp(Date timestamp) { +// this.timestamp = timestamp; +// } + + + public String getTimestamp() { + return timestamp; + } + + public void setTimestamp(String timestamp) { + this.timestamp = timestamp; + } + + public String getDeveloperMessage() { + return developerMessage; + } + + public void setDeveloperMessage(String developerMessage) { + this.developerMessage = developerMessage; + } + + public List getErrors() { + return errors; + } + + public void setErrors(List errors) { + this.errors = errors; + } +} \ No newline at end of file diff --git a/schools/src/main/java/com/lambdaschool/schools/models/Instructor.java b/schools/src/main/java/com/lambdaschool/schools/models/Instructor.java index 19da1bd9..2694da98 100644 --- a/schools/src/main/java/com/lambdaschool/schools/models/Instructor.java +++ b/schools/src/main/java/com/lambdaschool/schools/models/Instructor.java @@ -27,6 +27,8 @@ public class Instructor @Column(nullable = false) private String name; + @Transient + private String advice; /** * List of courses associated with this instructor. Does not get saved in the database directly. * Forms a one to many relationship with courses. One instructor to many courses. diff --git a/schools/src/main/java/com/lambdaschool/schools/models/IssPosition.java b/schools/src/main/java/com/lambdaschool/schools/models/IssPosition.java new file mode 100644 index 00000000..e22d46c9 --- /dev/null +++ b/schools/src/main/java/com/lambdaschool/schools/models/IssPosition.java @@ -0,0 +1,26 @@ +package com.lambdaschool.schools.models; + +public class IssPosition { + private String latitude; + private String longitude; + + public String getLatitude() + { + return latitude; + } + + public void setLatitude(String latitude) + { + this.latitude = latitude; + } + + public String getLongitude() + { + return longitude; + } + + public void setLongitude(String longitude) + { + this.longitude = longitude; + } +} diff --git a/schools/src/main/java/com/lambdaschool/schools/models/IssPositionReturnData.java b/schools/src/main/java/com/lambdaschool/schools/models/IssPositionReturnData.java new file mode 100644 index 00000000..828ed962 --- /dev/null +++ b/schools/src/main/java/com/lambdaschool/schools/models/IssPositionReturnData.java @@ -0,0 +1,37 @@ +package com.lambdaschool.schools.models; + +public class IssPositionReturnData { + private String message; + private IssPosition iss_position; + private long timestamp; + + public String getMessage() + { + return message; + } + + public void setMessage(String message) + { + this.message = message; + } + + public IssPosition getIss_position() + { + return iss_position; + } + + public void setIss_position(IssPosition iss_position) + { + this.iss_position = iss_position; + } + + public long getTimestamp() + { + return timestamp; + } + + public void setTimestamp(long timestamp) + { + this.timestamp = timestamp; + } +} diff --git a/schools/src/main/java/com/lambdaschool/schools/models/SlipReturnData.java b/schools/src/main/java/com/lambdaschool/schools/models/SlipReturnData.java new file mode 100644 index 00000000..31d6c08d --- /dev/null +++ b/schools/src/main/java/com/lambdaschool/schools/models/SlipReturnData.java @@ -0,0 +1,24 @@ +package com.lambdaschool.schools.models; + +public class SlipReturnData { +// private String message; + private slip slip_position; +// private long timestamp; + +// public String getMessage() { +// return message; +// } +// +// public void setMessage(String message) { +// this.message = message; +// } + + public slip getSlip_position() { + return slip_position; + } + + public void setSlip_position(slip slip_position) { + this.slip_position = slip_position; + } + +} diff --git a/schools/src/main/java/com/lambdaschool/schools/models/Translation.java b/schools/src/main/java/com/lambdaschool/schools/models/Translation.java new file mode 100644 index 00000000..d36a1642 --- /dev/null +++ b/schools/src/main/java/com/lambdaschool/schools/models/Translation.java @@ -0,0 +1,19 @@ +package com.lambdaschool.schools.models; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class Translation +{ + private TranslationContents contents; + + public TranslationContents getContents() + { + return contents; + } + + public void setContents(TranslationContents contents) + { + this.contents = contents; + } +} \ No newline at end of file diff --git a/schools/src/main/java/com/lambdaschool/schools/models/TranslationContents.java b/schools/src/main/java/com/lambdaschool/schools/models/TranslationContents.java new file mode 100644 index 00000000..33a2c69c --- /dev/null +++ b/schools/src/main/java/com/lambdaschool/schools/models/TranslationContents.java @@ -0,0 +1,19 @@ +package com.lambdaschool.schools.models; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class TranslationContents +{ + private String translated; + + public String getTranslated() + { + return translated; + } + + public void setTranslated(String translated) + { + this.translated = translated; + } +} \ No newline at end of file diff --git a/schools/src/main/java/com/lambdaschool/schools/models/ValidationError.java b/schools/src/main/java/com/lambdaschool/schools/models/ValidationError.java new file mode 100644 index 00000000..2de22709 --- /dev/null +++ b/schools/src/main/java/com/lambdaschool/schools/models/ValidationError.java @@ -0,0 +1,30 @@ +package com.lambdaschool.schools.models; + +public class ValidationError { + private String fieldname; + private String message; + + public ValidationError() { + } + + public ValidationError(String fieldname, String message) { + this.fieldname = fieldname; + this.message = message; + } + + public String getFieldname() { + return fieldname; + } + + public void setFieldname(String fieldname) { + this.fieldname = fieldname; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} \ No newline at end of file diff --git a/schools/src/main/java/com/lambdaschool/schools/models/slip.java b/schools/src/main/java/com/lambdaschool/schools/models/slip.java new file mode 100644 index 00000000..950ceec0 --- /dev/null +++ b/schools/src/main/java/com/lambdaschool/schools/models/slip.java @@ -0,0 +1,31 @@ +package com.lambdaschool.schools.models; + +public class slip { + + private long id; + private String advice; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getAdvice() { + return advice; + } + + public void setAdvice(String advice) { + this.advice = advice; + } + + @Override + public String toString() { + return System.class.getName().toLowerCase() +"{\n" + + "id':" + this.id +",\n"+ + "advice':" + this.getAdvice() + "\n" + + '}'+ "\n"; + } +} diff --git a/schools/src/main/java/com/lambdaschool/schools/services/CoursesServiceImpl.java b/schools/src/main/java/com/lambdaschool/schools/services/CoursesServiceImpl.java index 77861321..5682d2a5 100644 --- a/schools/src/main/java/com/lambdaschool/schools/services/CoursesServiceImpl.java +++ b/schools/src/main/java/com/lambdaschool/schools/services/CoursesServiceImpl.java @@ -1,5 +1,6 @@ package com.lambdaschool.schools.services; +import com.lambdaschool.schools.exceptions.ResourceNotFoundException; import com.lambdaschool.schools.models.Course; import com.lambdaschool.schools.models.Instructor; import com.lambdaschool.schools.models.StudCourses; @@ -11,7 +12,6 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import javax.persistence.EntityNotFoundException; import java.util.ArrayList; import java.util.List; @@ -58,7 +58,7 @@ public List findAll() public Course findCourseById(long id) { return courserepos.findById(id) - .orElseThrow(() -> new EntityNotFoundException("Course id " + id + " not found!")); + .orElseThrow(() -> new ResourceNotFoundException("Course id " + id + " not found!")); } @Transactional @@ -66,7 +66,7 @@ public Course findCourseById(long id) public void delete(long id) { courserepos.findById(id) - .orElseThrow(() -> new EntityNotFoundException("Course id " + id + " not found!")); + .orElseThrow(() -> new ResourceNotFoundException("Course id " + id + " not found!")); courserepos.deleteById(id); } @@ -79,7 +79,7 @@ public Course save(Course course) if (course.getCourseid() != 0) { Course oldCourse = courserepos.findById(course.getCourseid()) - .orElseThrow(() -> new EntityNotFoundException("Course id " + course.getCourseid() + " not found!")); + .orElseThrow(() -> new ResourceNotFoundException("Course id " + course.getCourseid() + " not found!")); newCourse.setCourseid(course.getCourseid()); } @@ -87,7 +87,7 @@ public Course save(Course course) newCourse.setCoursename(course.getCoursename()); Instructor newInstructor = instructorrepos.findById(course.getInstructor() .getInstructorid()) - .orElseThrow(() -> new EntityNotFoundException("Instructor id " + course.getInstructor() + .orElseThrow(() -> new ResourceNotFoundException("Instructor id " + course.getInstructor() .getInstructorid() + " not found!")); newCourse.setInstructor(newInstructor); @@ -97,7 +97,7 @@ public Course save(Course course) { Student newStudent = studentrepos.findById(sc.getStudent() .getStudentid()) - .orElseThrow(() -> new EntityNotFoundException("Instructor id " + sc.getStudent() + .orElseThrow(() -> new ResourceNotFoundException("Instructor id " + sc.getStudent() .getStudentid() + " not found!")); newCourse.getStudents() diff --git a/schools/src/main/java/com/lambdaschool/schools/services/HelperFunctions.java b/schools/src/main/java/com/lambdaschool/schools/services/HelperFunctions.java new file mode 100644 index 00000000..fe76ef97 --- /dev/null +++ b/schools/src/main/java/com/lambdaschool/schools/services/HelperFunctions.java @@ -0,0 +1,10 @@ +package com.lambdaschool.schools.services; + +import com.lambdaschool.schools.models.ValidationError; + +import java.util.List; + +public interface HelperFunctions { + List getValidationErrors(Throwable cause); + +} diff --git a/schools/src/main/java/com/lambdaschool/schools/services/HelperFunctionsImpl.java b/schools/src/main/java/com/lambdaschool/schools/services/HelperFunctionsImpl.java new file mode 100644 index 00000000..2f8548ea --- /dev/null +++ b/schools/src/main/java/com/lambdaschool/schools/services/HelperFunctionsImpl.java @@ -0,0 +1,49 @@ +package com.lambdaschool.schools.services; + +import com.lambdaschool.schools.models.ValidationError; +import org.hibernate.exception.ConstraintViolationException; +import org.springframework.stereotype.Service; +import org.springframework.validation.FieldError; +import org.springframework.web.bind.MethodArgumentNotValidException; + +import java.util.ArrayList; +import java.util.List; + +@Service(value = "helperFunctions") +public class HelperFunctionsImpl implements HelperFunctions{ + @Override + public List getValidationErrors(Throwable cause) { + List validationErrorList = new ArrayList<>(); + + while (cause != null && !(cause instanceof ConstraintViolationException || + cause instanceof MethodArgumentNotValidException)){ + System.out.println(cause.getClass() + .toString()); + cause = cause.getCause(); + } + + if (cause != null) { + if (cause instanceof ConstraintViolationException) { + ConstraintViolationException ex = (ConstraintViolationException)cause; + + ValidationError newVE = new ValidationError(); + newVE.setMessage(ex.getConstraintName()); + newVE.setFieldname(ex.getMessage()); + + validationErrorList.add(newVE); + } + else { + MethodArgumentNotValidException ex = (MethodArgumentNotValidException)cause; + List fieldErrors = ex.getBindingResult().getFieldErrors(); + + for (FieldError fe : fieldErrors) { + ValidationError newVE = new ValidationError(); + newVE.setFieldname(fe.getField()); + newVE.setMessage(fe.getDefaultMessage()); + validationErrorList.add(newVE); + } + } + } + return validationErrorList; + } +} diff --git a/schools/src/main/java/com/lambdaschool/schools/services/InstructorService.java b/schools/src/main/java/com/lambdaschool/schools/services/InstructorService.java new file mode 100644 index 00000000..dcc422a7 --- /dev/null +++ b/schools/src/main/java/com/lambdaschool/schools/services/InstructorService.java @@ -0,0 +1,17 @@ +package com.lambdaschool.schools.services; + +import com.lambdaschool.schools.models.Instructor; + +import java.util.List; + +public interface InstructorService { + List findAll(); + + Instructor findInstructorById(long id); + + void delete(long id); + + Instructor save(Instructor instructor); + + Instructor addAdvice(Instructor instructor, long id); +} diff --git a/schools/src/main/java/com/lambdaschool/schools/services/InstuctorServiceImpl.java b/schools/src/main/java/com/lambdaschool/schools/services/InstuctorServiceImpl.java new file mode 100644 index 00000000..cc2bc861 --- /dev/null +++ b/schools/src/main/java/com/lambdaschool/schools/services/InstuctorServiceImpl.java @@ -0,0 +1,71 @@ +package com.lambdaschool.schools.services; + +import com.lambdaschool.schools.exceptions.ResourceNotFoundException; +import com.lambdaschool.schools.models.Instructor; +import com.lambdaschool.schools.models.StudCourses; +import com.lambdaschool.schools.repositories.InstructorRepository; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.ArrayList; +import java.util.List; + + +public class InstuctorServiceImpl implements InstructorService{ + + @Autowired + private InstructorRepository instructorrepos; + + @Override + public List findAll() { + List list = new ArrayList<>(); + instructorrepos.findAll() + .iterator() + .forEachRemaining(list::add); + return list; + } + + @Override + public Instructor findInstructorById(long id) { + + return instructorrepos.findById(id) + .orElseThrow(()->new ResourceNotFoundException( + "Instructor id " + id + " not found!")); + } + + @Override + public void delete(long id) { + instructorrepos.findById(id) + .orElseThrow(()->new ResourceNotFoundException( + "Instructor id " + id + " not found!")); + instructorrepos.deleteById(id); + } + + @Override + public Instructor save(Instructor instructor) { + Instructor newInstructor = new Instructor(); + + if (instructor.getInstructorid() != 0){ + Instructor oldInstructor = instructorrepos.findById( + instructor.getInstructorid()).orElseThrow(()->new + ResourceNotFoundException("Instructor id " + instructor.getInstructorid() + + " not found!")); + + newInstructor.setInstructorid(instructor.getInstructorid()); + } + + newInstructor.setName(instructor.getName()); + newInstructor.setCourses(instructor.getCourses()); + return instructorrepos.save(newInstructor); + } + + @Override + public Instructor addAdvice(Instructor instructor, long id) { + Instructor newAdvice = new Instructor(); + instructorrepos.findById(id) + .orElseThrow(()->new ResourceNotFoundException( + "Instructor id " + id + " not found!")); + + newAdvice.setInstructorid(instructor.getInstructorid()); + return instructorrepos.save(newAdvice); + } +} diff --git a/schools/src/main/java/com/lambdaschool/schools/services/StudentServiceImpl.java b/schools/src/main/java/com/lambdaschool/schools/services/StudentServiceImpl.java index 1ad495cd..731bc88a 100644 --- a/schools/src/main/java/com/lambdaschool/schools/services/StudentServiceImpl.java +++ b/schools/src/main/java/com/lambdaschool/schools/services/StudentServiceImpl.java @@ -1,5 +1,6 @@ package com.lambdaschool.schools.services; +import com.lambdaschool.schools.exceptions.ResourceNotFoundException; import com.lambdaschool.schools.models.Course; import com.lambdaschool.schools.models.StudCourses; import com.lambdaschool.schools.models.Student; @@ -8,7 +9,6 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import javax.persistence.EntityNotFoundException; import java.util.ArrayList; import java.util.List; @@ -49,7 +49,7 @@ public List findAll() public Student findStudentById(long id) { return studentrepos.findById(id) - .orElseThrow(() -> new EntityNotFoundException("Student id " + id + " not found!")); + .orElseThrow(() -> new ResourceNotFoundException("Student id " + id + " not found!")); } @Transactional @@ -57,7 +57,7 @@ public Student findStudentById(long id) public void delete(long id) { studentrepos.findById(id) - .orElseThrow(() -> new EntityNotFoundException("Student id " + id + " not found!")); + .orElseThrow(() -> new ResourceNotFoundException("Student id " + id + " not found!")); studentrepos.deleteById(id); } @@ -70,7 +70,8 @@ public Student save(Student student) if (student.getStudentid() != 0) { Student oldStudent = studentrepos.findById(student.getStudentid()) - .orElseThrow(() -> new EntityNotFoundException("Student id " + student.getStudentid() + " not found!")); + .orElseThrow(() -> new ResourceNotFoundException("Student id " + student.getStudentid() + + " not found!")); newStudent.setStudentid(student.getStudentid()); } diff --git a/schools/src/main/resources/application.properties b/schools/src/main/resources/application.properties index 9758fe0c..b5d91bfc 100644 --- a/schools/src/main/resources/application.properties +++ b/schools/src/main/resources/application.properties @@ -23,3 +23,10 @@ spring.datasource.initialization-mode=always # spring.jpa.hibernate.ddl-auto=update # since we have our data in SeedData, do not also load it from data.sql # spring.datasource.initialization-mode=never +server.error.whitelabel.enabled=false +# +spring.mvc.throw-exception-if-no-handler-found=true +# +spring.resources.add-mappings=true +# +spring.mvc.static-path-pattern=/static \ No newline at end of file From 15aab3c123604eec67aadf29da9738c4d468c8a4 Mon Sep 17 00:00:00 2001 From: Tarah Date: Tue, 20 Apr 2021 00:04:56 -0400 Subject: [PATCH 2/2] MVP --- .../schools/SchoolsApplication.java | 28 ------------ .../controllers/OtherApisController.java | 45 +++++++++++++++++-- .../schools/models/SlipReturnData.java | 25 +++++++---- .../com/lambdaschool/schools/models/slip.java | 7 ++- 4 files changed, 62 insertions(+), 43 deletions(-) diff --git a/schools/src/main/java/com/lambdaschool/schools/SchoolsApplication.java b/schools/src/main/java/com/lambdaschool/schools/SchoolsApplication.java index f2d56537..f959a9ed 100644 --- a/schools/src/main/java/com/lambdaschool/schools/SchoolsApplication.java +++ b/schools/src/main/java/com/lambdaschool/schools/SchoolsApplication.java @@ -25,40 +25,12 @@ public class SchoolsApplication * @param args Not used in this application. */ public static void main(String[] args){ - /* - * Creates the object that is needed to do a client side Rest API call. - * We are the client getting data from a remote API. - */ - RestTemplate restTemplate = new RestTemplate(); - - // we need to tell our RestTemplate what format to expect - MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); - // a couple of common formats - // converter.setSupportedMediaTypes(Collections.singletonList(MediaType.TEXT_HTML)); - // converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON)); - // or we can accept all formats! Easiest but least secure - converter.setSupportedMediaTypes(Collections.singletonList(MediaType.ALL)); - restTemplate.getMessageConverters().add(converter); - - String requestURL = "https://api.adviceslip.com/advice"; - ParameterizedTypeReference responseType = new ParameterizedTypeReference<>() - { - }; - - // create the response entity. do the get and get back information - ResponseEntity responseEntity = restTemplate.exchange(requestURL, - HttpMethod.GET, - null, - responseType); try{ System.out.println(System.getenv("PATH").toUpperCase()); } catch (Exception e){ System.out.println("No Such Environment Variable"); } finally{ - // now that we have our data, let's print it to the console! - slip ourSlip = responseEntity.getBody(); - System.out.println(ourSlip); SpringApplication.run(SchoolsApplication.class, args); } diff --git a/schools/src/main/java/com/lambdaschool/schools/controllers/OtherApisController.java b/schools/src/main/java/com/lambdaschool/schools/controllers/OtherApisController.java index 365f1179..1f0d7fec 100644 --- a/schools/src/main/java/com/lambdaschool/schools/controllers/OtherApisController.java +++ b/schools/src/main/java/com/lambdaschool/schools/controllers/OtherApisController.java @@ -53,6 +53,43 @@ public ResponseEntity listIssPositions() HttpStatus.OK); } + @GetMapping(value = "/shakespeare/{englishText}") + public ResponseEntity getTranslation( + @PathVariable + String englishText) + { + // we need to tell our RestTemplate what format to expect + MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); + // a couple of common formats + // converter.setSupportedMediaTypes(Collections.singletonList(MediaType.TEXT_HTML)); + // converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON)); + // or we can accept all formats! Easiest but least secure + converter.setSupportedMediaTypes(Collections.singletonList(MediaType.ALL)); + restTemplate.getMessageConverters() + .add(converter); + + // create the url to access the API including adding the path variable + String requestURL = "https://api.funtranslations.com/translate/shakespeare.json?text=" + englishText; + // create the responseType expected. Notice the Translation is the data type we are expecting back from the API! + ParameterizedTypeReference responseType = new ParameterizedTypeReference<>() + { + }; + + // create the response entity. do the get and get back information + ResponseEntity responseEntity = restTemplate.exchange(requestURL, + HttpMethod.GET, + null, + responseType); + // we want to return the contents of the translation data. From the data that gets returned in the body, + // get the contents data only and return it. + // putting the data into its own object first, prevents the data from being reported to client inside of + // an embedded. So the response will look more like our clients are use to! + TranslationContents ourTranslation = responseEntity.getBody() + .getContents(); + return new ResponseEntity<>(ourTranslation, + HttpStatus.OK); + } + @GetMapping(value = "/advice") public ResponseEntity listSlipAdvice() { @@ -86,10 +123,10 @@ public ResponseEntity listSlipAdvice() HttpStatus.OK); } - @GetMapping(value = "/shakespeare/{englishText}") - public ResponseEntity getTranslation( + @GetMapping(value = "/advice/{id}") + public ResponseEntity getAdviceTranslation( @PathVariable - String englishText) + int id) { // we need to tell our RestTemplate what format to expect MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); @@ -102,7 +139,7 @@ public ResponseEntity getTranslation( .add(converter); // create the url to access the API including adding the path variable - String requestURL = "https://api.funtranslations.com/translate/shakespeare.json?text=" + englishText; + String requestURL = "https://api.adviceslip.com/advice?text=" + id; // create the responseType expected. Notice the Translation is the data type we are expecting back from the API! ParameterizedTypeReference responseType = new ParameterizedTypeReference<>() { diff --git a/schools/src/main/java/com/lambdaschool/schools/models/SlipReturnData.java b/schools/src/main/java/com/lambdaschool/schools/models/SlipReturnData.java index 31d6c08d..28a0750e 100644 --- a/schools/src/main/java/com/lambdaschool/schools/models/SlipReturnData.java +++ b/schools/src/main/java/com/lambdaschool/schools/models/SlipReturnData.java @@ -1,17 +1,17 @@ package com.lambdaschool.schools.models; public class SlipReturnData { -// private String message; + private String message; private slip slip_position; -// private long timestamp; + private long timestamp; -// public String getMessage() { -// return message; -// } -// -// public void setMessage(String message) { -// this.message = message; -// } + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } public slip getSlip_position() { return slip_position; @@ -21,4 +21,11 @@ public void setSlip_position(slip slip_position) { this.slip_position = slip_position; } + public long getTimestamp() { + return timestamp; + } + + public void setTimestamp(long timestamp) { + this.timestamp = timestamp; + } } diff --git a/schools/src/main/java/com/lambdaschool/schools/models/slip.java b/schools/src/main/java/com/lambdaschool/schools/models/slip.java index 950ceec0..600d4226 100644 --- a/schools/src/main/java/com/lambdaschool/schools/models/slip.java +++ b/schools/src/main/java/com/lambdaschool/schools/models/slip.java @@ -1,15 +1,18 @@ package com.lambdaschool.schools.models; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) public class slip { - private long id; + private int id; private String advice; public long getId() { return id; } - public void setId(long id) { + public void setId(int id) { this.id = id; }