diff --git a/.gitignore b/.gitignore index 1de5659..794c788 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ -target \ No newline at end of file +target +HELP.md \ No newline at end of file diff --git a/Week 02/Lecture 03/Assignment 05/ListToMap.java b/Week 02/Lecture 03/Assignment 05/ListToMap.java index 686f587..de47030 100644 --- a/Week 02/Lecture 03/Assignment 05/ListToMap.java +++ b/Week 02/Lecture 03/Assignment 05/ListToMap.java @@ -1,7 +1,7 @@ import java.util.Arrays; import java.util.List; import java.util.Map; -import java.util.stream.Collectors; +import java.util.TreeMap; // Assume Employee class with fields: int employeeID, String name, String department class Employee { @@ -46,11 +46,15 @@ public static void main(String[] args) { new Employee(3, "Charlie", "Finance") ); - // Convert List to Map using employeeID as key - Map employeeMap = employees.stream() - .collect(Collectors.toMap(Employee::getEmployeeID, emp -> emp)); + // Creating employeeMap using TreeMap + Map employeesMap = new TreeMap<>(); + + // Convert List to Map + for (Employee emp : employees){ + employeesMap.put(emp.getEmployeeID(), emp.getName()); + } // Print the resulting Map - employeeMap.forEach((id, emp) -> System.out.println("Employee ID: " + id + ", Employee: " + emp)); + employeesMap.forEach((id, emp) -> System.out.println("Employee ID: " + id + ", Employee: " + emp)); } } \ No newline at end of file diff --git a/Week 02/Lecture 03/Assignment 05/README.md b/Week 02/Lecture 03/Assignment 05/README.md index 6769ca7..55b8de1 100644 --- a/Week 02/Lecture 03/Assignment 05/README.md +++ b/Week 02/Lecture 03/Assignment 05/README.md @@ -80,7 +80,7 @@ To remove duplicate lines from a file: 4. **Writing Unique Lines**: Write only those lines to a new file that haven't been seen before (not in the `HashSet`). #### πŸ“‹ Case CSV Content -In this program, i use CSV file [`input.csv`](/Week%2002%20-%20Jun%2017-21/Lecture%2003/Assignment%205/data/input.csv) with content like this. +In this program, i use CSV file [`input.csv`](/Week%2002/Lecture%2003/Assignment%2005/RemoveDuplicates.java) with content like this. ```csv employeeID,name,department 1,Alice,HR @@ -106,6 +106,16 @@ Detail implementation is written on [this code](/Week%2002%20-%20Jun%2017-21/Lec The output of the program shows on this [`output.csv`](/Week%2002%20-%20Jun%2017-21/Lecture%2003/Assignment%205/data/output.csv) +Here is how to run the updated code of program +```bash +$ java RemoveDuplicates +``` + +for example. +```bash +java RemoveDuplicates data/input.csv data/output.csv 0 +``` +
### πŸ–¨οΈ Task 4 - Get a Shallow Copy of a `HashMap` @@ -166,7 +176,7 @@ Here i implement class `BankAccount` and `BankAccountDemo`. 3. **Use Java Streams for Transformation**: Utilize Java Streams API to transform the `List` into a `Map`. 4. **Collect into Map**: Use the `Collectors.toMap()` method to collect elements of the `List` into a `Map` using the specified key and value mappings. -Detail implementation is written on [this code](/Week%2002%20-%20Jun%2017-21/Lecture%2003/Assignment%205/ListToMap.java), and the output of the program shows like this. +Detail implementation is written on [this code](/Week%2002/Lecture%2003/Assignment%2005/ListToMap.java), and the output of the program shows like this (updated based on comment). ![Screenshot](img/Task5.png) diff --git a/Week 02/Lecture 03/Assignment 05/RemoveDuplicates.java b/Week 02/Lecture 03/Assignment 05/RemoveDuplicates.java index f364dd0..19287f7 100644 --- a/Week 02/Lecture 03/Assignment 05/RemoveDuplicates.java +++ b/Week 02/Lecture 03/Assignment 05/RemoveDuplicates.java @@ -3,29 +3,42 @@ import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; +import java.util.ArrayList; import java.util.HashSet; +import java.util.List; import java.util.Set; public class RemoveDuplicates { public static void main(String[] args) { - String inputFileName = "data/input.csv"; - String outputFileName = "data/output.csv"; - String delimiter = ","; // Parse CSV format - - // Set to store unique keys (employeeID in this case) + if (args.length < 3) { + System.out.println("Usage: java RemoveDuplicates "); + return; + } + + String inputFileName = args[0]; + String outputFileName = args[1]; + int keyFieldIndex; + try { + keyFieldIndex = Integer.parseInt(args[2]); + } catch (NumberFormatException e) { + System.out.println("Invalid keyFieldIndex. It must be an integer."); + return; + } + + // Set to store unique keys Set seenKeys = new HashSet<>(); - + try (BufferedReader reader = new BufferedReader(new FileReader(inputFileName)); PrintWriter writer = new PrintWriter(new FileWriter(outputFileName))) { String line; while ((line = reader.readLine()) != null) { - // Split the line into fields - String[] fields = line.split(delimiter); - - // Ensure there are enough fields and key field is valid - if (fields.length > 1) { - String key = fields[0]; // Assuming employeeID is the first field + // Properly split the line respecting quoted commas + String[] fields = parseCsvLine(line); + + // Ensure key field index is valid + if (fields.length > keyFieldIndex) { + String key = fields[keyFieldIndex]; if (!seenKeys.contains(key)) { seenKeys.add(key); // Add the key to set (marks as seen) writer.println(line); // Write the line to output @@ -36,7 +49,36 @@ public static void main(String[] args) { System.out.println("Duplicates removed successfully. Output written to " + outputFileName); } catch (IOException e) { - System.out.println("I/O Error occured:" + e); + System.out.println("I/O Error occurred: " + e); } } -} + + // Function to parse CSV line while handling commas within quotes + private static String[] parseCsvLine(String line) { + boolean inQuotes = false; + StringBuilder field = new StringBuilder(); + List fields = new ArrayList<>(); + + for (char c : line.toCharArray()) { + switch (c) { + case '"': + inQuotes = !inQuotes; // Toggle the inQuotes flag + break; + case ',': + if (inQuotes) { + field.append(c); // Inside quotes, include comma + } else { + fields.add(field.toString()); + field.setLength(0); // Reset the field buffer + } + break; + default: + field.append(c); // Add character to field buffer + break; + } + } + fields.add(field.toString()); // Add last field + + return fields.toArray(new String[0]); + } +} \ No newline at end of file diff --git a/Week 02/Lecture 03/Assignment 05/img/Task5.png b/Week 02/Lecture 03/Assignment 05/img/Task5.png index ec754bd..620f659 100644 Binary files a/Week 02/Lecture 03/Assignment 05/img/Task5.png and b/Week 02/Lecture 03/Assignment 05/img/Task5.png differ diff --git a/Week 02/Lecture 04/Assignment 06/README.md b/Week 02/Lecture 04/Assignment 06/README.md index 7a36c3c..26cad3a 100644 --- a/Week 02/Lecture 04/Assignment 06/README.md +++ b/Week 02/Lecture 04/Assignment 06/README.md @@ -119,11 +119,22 @@ Here’s a detailed process on how to remove duplicate lines from files based on 4. **Write the Output**: Write the processed, duplicate-free data to a new file. #### πŸ‘¨πŸ»β€πŸ’» Implementation -Detail implementation is written on [this code](/Week%2002%20-%20Jun%2017-21/Lecture%2004/Assignment%206/RemoveDuplicatesCSV.java). Here’s what the program actually done. -1. **Read All Lines**: `Files.readAllLines(Paths.get(inputFilePath))` reads the CSV file into a list of strings. -2. **Extract Header**: The first line is treated as the header to determine the key field's index. -3. **Stream Processing**: The stream skips the header, then collects lines into a map using the key field (`id`). If a duplicate key is found, the first occurrence is retained. -4. **Write Results**: The header is re-added, and the list is written to the new file. +Detail implementation is written on [this code](/Week%2002/Lecture%2004/Assignment%2006/RemoveDuplicatesCSV.java). Here’s what the program actually done (updated based on comment). +1. **Initialize Readers and Writers** + - `BufferedReader` is used to read the input CSV file line by line. + - `BufferedWriter` is used to write the unique lines to the output CSV file. +2. **Extract and Write Header** + - The first line, which is the header, is read using `reader.readLine()`. + - This header is written immediately to the output file using `writer.write(header)`. +3. **Determine Key Field Index** + - The header is split to determine the index of the key field (`id`). + - This is done by iterating through the headers to find the matching field. +4. **Stream Processing and Duplicate Removal** + - A `Set` is used to keep track of the keys that have already been processed. + - For each subsequent line, the key field's value is checked against the `Set`. If the key is unique, the line is written to the output file. +5. **Read and Write Lines** + - The program continues to read each line from the input file, splits it to get the key field, and checks the key against the `Set`. + - If the key is not in the `Set`, the line is written to the output file and the key is added to the `Set`. **Best Practices Highlighted** 1. **`BufferedReader` for Large Files**: Using `BufferedReader` with `lines()` streams data efficiently. diff --git a/Week 02/Lecture 04/Assignment 06/RemoveDuplicatesCSV.java b/Week 02/Lecture 04/Assignment 06/RemoveDuplicatesCSV.java index 77d29de..01e728e 100644 --- a/Week 02/Lecture 04/Assignment 06/RemoveDuplicatesCSV.java +++ b/Week 02/Lecture 04/Assignment 06/RemoveDuplicatesCSV.java @@ -1,10 +1,10 @@ import java.io.BufferedReader; +import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; +import java.util.HashSet; +import java.util.Set; public class RemoveDuplicatesCSV { public static void main(String[] args) { @@ -12,35 +12,44 @@ public static void main(String[] args) { String outputFilePath = "data/unique.csv"; String keyFieldName = "id"; - try (BufferedReader reader = Files.newBufferedReader(Paths.get(inputFilePath))) { - List lines = reader.lines().collect(Collectors.toList()); - if (lines.isEmpty()) return; + try (BufferedReader reader = Files.newBufferedReader(Paths.get(inputFilePath)); + BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputFilePath))) { + + String header = reader.readLine(); + if (header == null) return; - // Extract header and determine the key field index - String header = lines.get(0); - List headers = Arrays.asList(header.split(",")); - int keyIndex = headers.indexOf(keyFieldName); - if (keyIndex == -1) throw new IllegalArgumentException("Invalid key field name"); + // Write header to the output file + writer.write(header); + writer.newLine(); - // Process lines and remove duplicates based on the key field - List uniqueLines = lines.stream() - .skip(1) // Skip header - .collect(Collectors.toMap( - line -> line.split(",")[keyIndex], // Use the key field - line -> line, // Use the line as value - (existing, replacement) -> existing // Keep the first occurrence - )) - .values() - .stream() - .collect(Collectors.toList()); + // Determine the key field index + String[] headers = header.split(","); + int keyIndex = -1; + for (int i = 0; i < headers.length; i++) { + if (headers[i].trim().equals(keyFieldName)) { + keyIndex = i; + break; + } + } + if (keyIndex == -1) throw new IllegalArgumentException("Invalid key field name"); - // Add header back to the list - uniqueLines.add(0, header); + // Use a Set to track unique keys + Set seenKeys = new HashSet<>(); - // Write the results to a new file - Files.write(Paths.get(outputFilePath), uniqueLines); + // Read and process each line + String line; + while ((line = reader.readLine()) != null) { + String[] fields = line.split(","); + if (fields.length > keyIndex) { + String key = fields[keyIndex]; + if (seenKeys.add(key)) { // Add returns false if the key was already present + writer.write(line); + writer.newLine(); + } + } + } } catch (IOException e) { - System.out.println("I/O Error occured:" + e); + System.out.println("I/O Error occurred: " + e); } } -} +} \ No newline at end of file diff --git a/Week 08/Lecture 13/Assignment 01/README.md b/Week 08/Lecture 13/Assignment 01/README.md new file mode 100644 index 0000000..7868ac9 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 01/README.md @@ -0,0 +1,111 @@ +# πŸ‘¨πŸ»β€πŸ« Lecture 13 - Spring Advance Feature: Filter and Spring Interceptor +> This repository is created as a part of assignment for Lecture 13 - Spring Advance Feature: Filter and Spring Interceptor + +## πŸ” Assignment 01 - Research about `onceperrequestfilter` + +### 🧐 Detailed Overview + +#### **What is a Filter?** +In the context of a Java web application, a filter is a component that performs tasks before or after a request is processed by a servlet. Filters can modify request and response objects, and they are useful for cross-cutting concerns like logging, authentication, and response modification. + +#### **Purpose of `OncePerRequestFilter`** +The `OncePerRequestFilter` class is designed to handle cases where filters might be executed multiple times for a single request due to forwarding or including requests. This ensures that a filter’s logic is only executed once per request, preventing redundant processing and potential performance issues. + +#### **How `OncePerRequestFilter` Works** + +1. **Filter Lifecycle** + + Filters in a web application are managed by the servlet container (e.g., Tomcat). The `OncePerRequestFilter` ensures that the `doFilterInternal` method is called only once per request. + +2. **Request Wrapping** + + When a request is forwarded or included, it might be wrapped in additional `ServletRequest` objects. `OncePerRequestFilter` ensures that the filtering logic is applied only once, even if the request has been wrapped multiple times. + +3. **Thread Safety** + + The `OncePerRequestFilter` class is designed to be thread-safe, meaning that its instance can be safely used across multiple threads handling different requests. + +### πŸ‘¨πŸ»β€πŸ’» **Advanced Example: Authentication Filter** + +Let’s create an advanced example of a filter that checks for a specific header in requests to enforce custom authentication. This example will include detailed aspects, such as handling exceptions and configuring the filter in a Spring Boot application. + +#### **Authentication Filter Example** + +1. **Create the Filter Class** + + ```java + import org.springframework.web.filter.OncePerRequestFilter; + + import javax.servlet.FilterChain; + import javax.servlet.FilterConfig; + import javax.servlet.ServletException; + import javax.servlet.ServletRequest; + import javax.servlet.ServletResponse; + import javax.servlet.http.HttpServletRequest; + import javax.servlet.http.HttpServletResponse; + import java.io.IOException; + + public class CustomAuthenticationFilter extends OncePerRequestFilter { + + private static final String AUTH_HEADER = "X-Custom-Auth"; + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) + throws ServletException, IOException { + // Check for the custom authentication header + String authHeader = request.getHeader(AUTH_HEADER); + if (authHeader == null || !authHeader.equals("expectedValue")) { + // If the header is missing or incorrect, respond with an unauthorized status + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); + return; + } + + // Continue the request-response chain if authentication is successful + filterChain.doFilter(request, response); + } + } + ``` + +2. **Register the Filter in Spring Boot Configuration** + + In Spring Boot, we can configure the filter either by using `FilterRegistrationBean` or by annotating a configuration class. + + ```java + import org.springframework.boot.web.servlet.FilterRegistrationBean; + import org.springframework.context.annotation.Bean; + import org.springframework.context.annotation.Configuration; + + @Configuration + public class FilterConfig { + + @Bean + public FilterRegistrationBean customAuthenticationFilter() { + FilterRegistrationBean registrationBean = new FilterRegistrationBean<>(); + registrationBean.setFilter(new CustomAuthenticationFilter()); + registrationBean.addUrlPatterns("/api/*"); // Apply filter to specific URL patterns + return registrationBean; + } + } + ``` + +### πŸš€ **Explanation** +Here is the explanation on what i already made on the previous segment. + +1. **Filter Logic (`doFilterInternal` Method)** + - **Header Check**: The filter checks if the custom header `X-Custom-Auth` is present and has the expected value. + - **Unauthorized Response**: If the header is missing or incorrect, it sends a `401 Unauthorized` response and halts further processing. + - **Continue Chain**: If the header is valid, the request is passed down the filter chain. + +2. **Filter Registration** + - **FilterRegistrationBean**: This bean registers the filter with the Spring context. + - **addUrlPatterns("/api/*")**: Specifies that the filter should be applied to URLs that start with `/api/`. + +### πŸ”‘ **Key Points** + +1. **Execution Control**: `OncePerRequestFilter` ensures the filter logic is applied once per request even if the request is forwarded or included multiple times. + +2. **Thread Safety**: You should be cautious about mutable state within your filter. Since filters are often accessed by multiple threads, any mutable state should be handled carefully. + +3. **Exception Handling**: It’s essential to handle exceptions gracefully within filters, especially when dealing with authentication or authorization, to avoid exposing sensitive information. + +4. **Configuration**: Filters can be configured to apply to specific URL patterns or to all requests, depending on your needs. \ No newline at end of file diff --git a/Week 08/Lecture 13/Assignment 02/README.md b/Week 08/Lecture 13/Assignment 02/README.md new file mode 100644 index 0000000..9aff75d --- /dev/null +++ b/Week 08/Lecture 13/Assignment 02/README.md @@ -0,0 +1,275 @@ +# πŸ‘¨πŸ»β€πŸ« Lecture 13 - Spring Advance Feature: Filter and Spring Interceptor +> This repository is created as a part of assignment for Lecture 13 - Spring Advance Feature: Filter and Spring Interceptor + +## πŸ” Assignment 02 - Simple Filter + +### 🧐 Detailed Overview + +To complete the assignment, we need to add the following functionalities to the existing CRUD project: +1. **Store API key in the database**: Ensure we have a table to store the API key. +2. **Verify requests**: Filter to check for the "api-key" header in incoming requests. +3. **Include header in all responses**: Filter to add the "source" header to all responses. + +Here’s a step-by-step guide: + +### πŸ“¦ Storing API Key in the Database + +**Idea**: Create a table to store the API key. We can have a single record in this table that holds the API key. + +**Table Schema** +See the detail [here](/Week%2008/Lecture%2013/Assignment%2002/lecture_13/src/main/resources/data.sql). +```sql +-- Create `APIKey` table +CREATE TABLE APIKey ( + ID BIGINT AUTO_INCREMENT PRIMARY KEY, + api_key VARCHAR(255) NOT NULL, + description VARCHAR(255), -- Description or label for the API key + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, -- Timestamp of creation + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- Timestamp of last update + active BOOLEAN DEFAULT TRUE -- Status to enable or disable the API key +); +``` + +**Java Entity** +See the detail [here](/Week%2008/Lecture%2013/Assignment%2002/lecture_13/src/main/java/com/example/lecture_13/data/model/APIKey.java). +```java +@Data +@NoArgsConstructor +@AllArgsConstructor +@Entity +@Table(name = "APIKey") +public class APIKey { + + @Id + @Column(name = "ID", columnDefinition = "BIGINT", updatable = false, nullable = false) + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + private String apiKey; + private String description; + private LocalDateTime createdAt; + private LocalDateTime updatedAt; + private boolean active; +} +``` + +**Repository** +See the detail [here](/Week%2008/Lecture%2013/Assignment%2002/lecture_13/src/main/java/com/example/lecture_13/data/repository/APIKeyRepository.java). +```java +@Repository +public interface APIKeyRepository extends JpaRepository { + + // Get the first API key, order by ID + Optional findFirstByOrderById(); + + // Find the first active API key + Optional findFirstByActiveTrueOrderById(); +} +``` + +### πŸ”½ Filter for API Key Verification + +**Idea**: Create a filter that intercepts incoming requests, checks for the "api-key" header, and verifies it against the stored API key in the database. Use it also to add the "source" header to all responses. + +**Filter Implementation** +See the detail [here](/Week%2008/Lecture%2013/Assignment%2002/lecture_13/src/main/java/com/example/lecture_13/config/filter/APIKeyFilter.java). +```java +@Component +public class APIKeyFilter extends OncePerRequestFilter { + + @Autowired + private APIKeyRepository apiKeyRepository; + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) + throws ServletException, IOException { + String requestApiKey = request.getHeader("api-key"); + + Optional apiKeyOpt = apiKeyRepository.findFirstByActiveTrueOrderById(); + response.addHeader("source", "fpt-software"); + if (apiKeyOpt.isPresent()) { + String storedApiKey = apiKeyOpt.get().getApiKey(); + + if (storedApiKey.equals(requestApiKey)) { + filterChain.doFilter(request, response); + } else { + response.setStatus(HttpStatus.FORBIDDEN.value()); + response.setContentType("application/json"); + response.getWriter().write("{\"error\": \"Invalid API Key\"}"); + } + } else { + response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.setContentType("application/json"); + response.getWriter().write("{\"error\": \"API Key not configured or inactive\"}"); + } + } +} +``` + +### βœ”οΈ Register Filters +**Configuration** +See the detail [here](/Week%2008/Lecture%2013/Assignment%2002/lecture_13/src/main/java/com/example/lecture_13/config/FilterConfig.java). +```java +@Configuration +public class FilterConfig { + + @Bean + public FilterRegistrationBean apiKeyFilter(APIKeyFilter apiKeyFilter) { + FilterRegistrationBean registrationBean = new FilterRegistrationBean<>(); + registrationBean.setFilter(apiKeyFilter); + registrationBean.addUrlPatterns("/api/v1/*"); // All Customer API + return registrationBean; + } +} +``` + +--- + +### 🌳 Project Structure +```bash +lecture_13 +β”œβ”€β”€ .mvn/wrapper/ +β”‚ └── maven-wrapper.properties +β”œβ”€β”€ src/main/ +β”‚ β”œβ”€β”€ java/com/example/lecture_13/ +β”‚ β”‚ β”œβ”€β”€ config/ +β”‚ β”‚ β”‚ β”œβ”€β”€ filter/ +β”‚ β”‚ β”‚ β”‚ └── APIKeyFilter.java +β”‚ β”‚ β”‚ β”œβ”€β”€ FilterConfig.java +β”‚ β”‚ β”‚ └── WebConfig.java +β”‚ β”‚ β”œβ”€β”€ controller/ +β”‚ β”‚ β”‚ └── CustomerController.java +β”‚ β”‚ β”œβ”€β”€ data/ +β”‚ β”‚ β”‚ β”œβ”€β”€ model/ +β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ APIKey.java +β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ Customer.java +β”‚ β”‚ β”‚ β”‚ └── Status.java +β”‚ β”‚ β”‚ └── repository/ +β”‚ β”‚ β”‚ β”œβ”€β”€ APIKeyRepository.java +β”‚ β”‚ β”‚ └── CustomerRepository.java +β”‚ β”‚ β”œβ”€β”€ dto/ +β”‚ β”‚ β”‚ β”œβ”€β”€ CustomerDTO.java +β”‚ β”‚ β”‚ β”œβ”€β”€ CustomerSaveDTO.java +β”‚ β”‚ β”‚ └── CustomerShowDTO.java +β”‚ β”‚ β”œβ”€β”€ exception/ +β”‚ β”‚ β”‚ β”œβ”€β”€ BadRequestException.java +β”‚ β”‚ β”‚ β”œβ”€β”€ DuplicateStatusException.java +β”‚ β”‚ β”‚ β”œβ”€β”€ GlobalExceptionHandler.java +β”‚ β”‚ β”‚ └── ResourceNotFound.java +β”‚ β”‚ β”œβ”€β”€ mapper/ +β”‚ β”‚ β”‚ └── CustomerMapper.java +β”‚ β”‚ β”œβ”€β”€ service/ +β”‚ β”‚ β”‚ β”œβ”€β”€ impl/ +β”‚ β”‚ β”‚ β”‚ └── CustomerServiceImpl.java +β”‚ β”‚ β”‚ └── CustomerService.java +β”‚ β”‚ └── Lecture13Application.java +β”‚ └── resources/ +β”‚ β”œβ”€β”€ application.properties +β”‚ └── data.sql +β”œβ”€β”€ .gitignore +β”œβ”€β”€ env.properties +β”œβ”€β”€ mvnw +β”œβ”€β”€ mvnw.cmd +β”œβ”€β”€ pom.xml +β”œβ”€β”€ run.bat +└── run.sh +``` + +### 🧩 SQL Query Data +Here is the SQL query to create the database, table, and instantiate some data. +```sql +-- Create the database +CREATE DATABASE week8_lecture13; + +-- Use the database +USE week8_lecture13; + +-- Initialize table with DDL +-- Create `Customer` table +CREATE TABLE Customer ( + ID BINARY(16) PRIMARY KEY, + name VARCHAR(255) NOT NULL, + phoneNumber VARCHAR(255), + status ENUM('Active', 'Deactivate') NOT NULL, + createdAt DATETIME, + updatedAt DATETIME +); + +-- Create `APIKey` table +CREATE TABLE APIKey ( + ID BIGINT AUTO_INCREMENT PRIMARY KEY, + api_key VARCHAR(255) NOT NULL, + description VARCHAR(255), -- Description or label for the API key + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, -- Timestamp of creation + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- Timestamp of last update + active BOOLEAN DEFAULT TRUE -- Status to enable or disable the API key +); +``` + +There are also query to insert some generated dummy data. All the MySQL queries is available on [this file](/Week%2008/Lecture%2013/Assignment%2002/lecture_13/src/main/resources/data.sql). Here is the query to drop the database. +```sql +-- Drop the database +DROP DATABASE IF EXISTS week8_lecture13; +``` + +Don't forget to add this to re-update the SQL DDL queries. +```java +spring.jpa.hibernate.ddl-auto=update +``` + +finally, don't forget to add this for hibernate SQL logging. +```java +spring.jpa.show-sql=true +spring.jpa.properties.hibernate.format_sql=true +logging.level.org.hibernate.SQL=DEBUG +logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE +``` + +### βš™οΈ How to run the program +1. Go to the `lecture_13` directory by using this command + ```bash + $ cd lecture_13 + ``` +2. Make sure you have maven installed on my computer, use `mvn -v` to check the version. +3. Setup your credential. You can configure it by creating file `env.properties` on the **root of the project** (aligned with [pom.xml](/Week%2008/Lecture%2013/Assignment%2002/lecture_13/pom.xml)), then fill it with this format. + ```java + DB_DATABASE= + DB_USER= + DB_PASSWORD=M + PORT= + ``` +4. If you are using windows, you can run the program by using this command. + ```bash + $ ./run.bat + ``` + And if you are using Linux, you can run the program by using this command. + ```bash + $ chmod +x run.sh + $ ./run.sh + ``` + +If all the instruction is well executed, Open [localhost:8080](http://localhost:8080) to see that the REST APIs is now works. + +### πŸ”‘ List of Endpoints +| Endpoints | Method | Description | +|--------------------------------------------------------------------------------------------|:------:|-------------------------------------------------------------------------------------------------| +| /api/v1/customers | GET | Retrieve all customers with default pagination (page 1 with size 20 elements/page). Consider only active customers. | +| /api/v1/customers?page={X}&size={Y} | GET | Retrieve all customers with custom pagination (page X (0-based index) with size Y elements/page). Consider only active customers. | +| /api/v1/customers | POST | Create a new customer. Validate POST request format. | +| /api/v1/customers/{id} | PUT | Update an existing customer by customer ID. Make sure the customer ID exists. | +| /api/v1/customers/active/{id} | PUT | Activate the existing customer by their customer ID. Make sure the customer ID exists and is currently inactive. | +| /api/v1/customers/deactive/{id} | PUT | Deactivate the existing customer by their customer ID. Make sure the customer ID exists and is currently active. | +| /api/v1/customers/{id} | DELETE | Delete an existing customer by customer ID. Make sure the customer ID exists. | + + +### πŸš€ Demonstration +![Screenshots](/Week%2008/Lecture%2013/Assignment%2002/img/demo1.png) + +Result if API Key not exists or not configured on the header. + +![Screenshots](/Week%2008/Lecture%2013/Assignment%2002/img/demo2.png) + +Result if API Key well-configured on the header. + +![Screenshots](/Week%2008/Lecture%2013/Assignment%2002/img/demo3.png) + +Result header returning source from fpt-software. \ No newline at end of file diff --git a/Week 08/Lecture 13/Assignment 02/img/demo1.png b/Week 08/Lecture 13/Assignment 02/img/demo1.png new file mode 100644 index 0000000..087f503 Binary files /dev/null and b/Week 08/Lecture 13/Assignment 02/img/demo1.png differ diff --git a/Week 08/Lecture 13/Assignment 02/img/demo2.png b/Week 08/Lecture 13/Assignment 02/img/demo2.png new file mode 100644 index 0000000..6977fbe Binary files /dev/null and b/Week 08/Lecture 13/Assignment 02/img/demo2.png differ diff --git a/Week 08/Lecture 13/Assignment 02/img/demo3.png b/Week 08/Lecture 13/Assignment 02/img/demo3.png new file mode 100644 index 0000000..0fcdb99 Binary files /dev/null and b/Week 08/Lecture 13/Assignment 02/img/demo3.png differ diff --git a/Week 08/Lecture 13/Assignment 02/lecture_13/.gitignore b/Week 08/Lecture 13/Assignment 02/lecture_13/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/Week 08/Lecture 13/Assignment 02/lecture_13/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/Week 08/Lecture 13/Assignment 02/lecture_13/.mvn/wrapper/maven-wrapper.properties b/Week 08/Lecture 13/Assignment 02/lecture_13/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..8f96f52 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 02/lecture_13/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.7/apache-maven-3.9.7-bin.zip diff --git a/Week 08/Lecture 13/Assignment 02/lecture_13/env.properties b/Week 08/Lecture 13/Assignment 02/lecture_13/env.properties new file mode 100644 index 0000000..4a1afe3 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 02/lecture_13/env.properties @@ -0,0 +1,4 @@ +DB_DATABASE=jdbc:mysql://localhost:3308/week8_lecture13?allowPublicKeyRetrieval=true&useSSL=false +DB_USER=root +DB_PASSWORD=Michaeleon16606_ +PORT=8080 \ No newline at end of file diff --git a/Week 08/Lecture 13/Assignment 02/lecture_13/mvnw b/Week 08/Lecture 13/Assignment 02/lecture_13/mvnw new file mode 100644 index 0000000..d7c358e --- /dev/null +++ b/Week 08/Lecture 13/Assignment 02/lecture_13/mvnw @@ -0,0 +1,259 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.2 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/Week 08/Lecture 13/Assignment 02/lecture_13/mvnw.cmd b/Week 08/Lecture 13/Assignment 02/lecture_13/mvnw.cmd new file mode 100644 index 0000000..6f779cf --- /dev/null +++ b/Week 08/Lecture 13/Assignment 02/lecture_13/mvnw.cmd @@ -0,0 +1,149 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.2 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' +$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/Week 08/Lecture 13/Assignment 02/lecture_13/pom.xml b/Week 08/Lecture 13/Assignment 02/lecture_13/pom.xml new file mode 100644 index 0000000..7db908d --- /dev/null +++ b/Week 08/Lecture 13/Assignment 02/lecture_13/pom.xml @@ -0,0 +1,124 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.3.2 + + + com.example + lecture_13 + 1.0-SNAPSHOT + lecture_13 + Demo project for Spring Boot + + + + + + + + + + + + + + + 21 + + + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter-web-services + + + org.springframework.boot + spring-boot-devtools + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java + 8.0.33 + runtime + + + + + org.projectlombok + lombok + + + + + org.springframework.boot + spring-boot-starter-validation + + + org.hibernate.validator + hibernate-validator + 8.0.0.Final + + + javax.validation + validation-api + 2.0.1.Final + + + + + org.mapstruct + mapstruct + 1.5.3.Final + + + org.mapstruct + mapstruct-processor + 1.5.3.Final + provided + + + + + javax.servlet + javax.servlet-api + 4.0.1 + provided + + + + + org.springdoc + springdoc-openapi-starter-webmvc-ui + 2.2.0 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/Week 08/Lecture 13/Assignment 02/lecture_13/run.bat b/Week 08/Lecture 13/Assignment 02/lecture_13/run.bat new file mode 100644 index 0000000..7f578be --- /dev/null +++ b/Week 08/Lecture 13/Assignment 02/lecture_13/run.bat @@ -0,0 +1,3 @@ +@echo off +echo Building and running the project with Maven... +mvn clean install && java -jar target/lecture_13-1.0-SNAPSHOT.jar \ No newline at end of file diff --git a/Week 08/Lecture 13/Assignment 02/lecture_13/run.sh b/Week 08/Lecture 13/Assignment 02/lecture_13/run.sh new file mode 100644 index 0000000..1596d33 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 02/lecture_13/run.sh @@ -0,0 +1,3 @@ +#!/bin/bash +echo Building the project with Maven... +mvn clean install && java -jar target/lecture_13-1.0-SNAPSHOT.jar \ No newline at end of file diff --git a/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/Lecture13Application.java b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/Lecture13Application.java new file mode 100644 index 0000000..e77dfa4 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/Lecture13Application.java @@ -0,0 +1,12 @@ +package com.example.lecture_13; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Lecture13Application { + + public static void main(String[] args) { + SpringApplication.run(Lecture13Application.class, args); + } +} diff --git a/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/config/FilterConfig.java b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/config/FilterConfig.java new file mode 100644 index 0000000..83dc148 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/config/FilterConfig.java @@ -0,0 +1,19 @@ +package com.example.lecture_13.config; + +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.example.lecture_13.config.filter.APIKeyFilter; + +@Configuration +public class FilterConfig { + + @Bean + public FilterRegistrationBean apiKeyFilter(APIKeyFilter apiKeyFilter) { + FilterRegistrationBean registrationBean = new FilterRegistrationBean<>(); + registrationBean.setFilter(apiKeyFilter); + registrationBean.addUrlPatterns("/api/v1/*"); // All Customer API + return registrationBean; + } +} \ No newline at end of file diff --git a/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/config/WebConfig.java b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/config/WebConfig.java new file mode 100644 index 0000000..9e643f3 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/config/WebConfig.java @@ -0,0 +1,9 @@ +package com.example.lecture_13.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.data.web.config.EnableSpringDataWebSupport; + +@Configuration +@EnableSpringDataWebSupport(pageSerializationMode = EnableSpringDataWebSupport.PageSerializationMode.VIA_DTO) +public class WebConfig { +} diff --git a/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/config/filter/APIKeyFilter.java b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/config/filter/APIKeyFilter.java new file mode 100644 index 0000000..2535b63 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/config/filter/APIKeyFilter.java @@ -0,0 +1,48 @@ +package com.example.lecture_13.config.filter; + +import java.io.IOException; +import java.util.Optional; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import com.example.lecture_13.data.model.APIKey; +import com.example.lecture_13.data.repository.APIKeyRepository; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +@Component +public class APIKeyFilter extends OncePerRequestFilter { + + @Autowired + private APIKeyRepository apiKeyRepository; + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) + throws ServletException, IOException { + String requestApiKey = request.getHeader("api-key"); + + Optional apiKeyOpt = apiKeyRepository.findFirstByActiveTrueOrderById(); + response.addHeader("source", "fpt-software"); + if (apiKeyOpt.isPresent()) { + String storedApiKey = apiKeyOpt.get().getApiKey(); + + if (storedApiKey.equals(requestApiKey)) { + filterChain.doFilter(request, response); + } else { + response.setStatus(HttpStatus.FORBIDDEN.value()); + response.setContentType("application/json"); + response.getWriter().write("{\"error\": \"Invalid API Key\"}"); + } + } else { + response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.setContentType("application/json"); + response.getWriter().write("{\"error\": \"API Key not configured or inactive\"}"); + } + } +} diff --git a/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/controller/CustomerController.java b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/controller/CustomerController.java new file mode 100644 index 0000000..3ba54e7 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/controller/CustomerController.java @@ -0,0 +1,154 @@ +package com.example.lecture_13.controller; + +import java.util.UUID; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import com.example.lecture_13.data.model.Status; +import com.example.lecture_13.dto.CustomerDTO; +import com.example.lecture_13.dto.CustomerSaveDTO; +import com.example.lecture_13.dto.CustomerShowDTO; +import com.example.lecture_13.service.CustomerService; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import jakarta.validation.Valid; + +@RestController +@RequestMapping("/api/v1/customers") +@Validated +public class CustomerController { + + @Autowired + private CustomerService customerService; + + /** + * Retrieves all customers from the database. + * + * @param page The index of the page to retrieve. Defaults to 0. + * @param size The number of customers to retrieve per page. Defaults to 20. + * @return A {@link ResponseEntity} containing a {@link Page} of {@link CustomerShowDTO} objects representing the customers on the specified page. + * @apiNote If no customers are found, a {@link ResponseEntity} with status status code 204 (No Content) is returned. + */ + @Operation(summary = "Retrieve all Active Customers.") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Customers retrieved successfully"), + @ApiResponse(responseCode = "204", description = "Customers not found") + }) + @GetMapping + public ResponseEntity> getAllCustomer(@RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "20") int size) { + Pageable pageable = PageRequest.of(page, size); + Page customerPage = customerService.findAllActiveCustomer(pageable); + + if (customerPage.isEmpty()) { + return ResponseEntity.status(HttpStatus.NO_CONTENT).build(); + } + + return ResponseEntity.status(HttpStatus.OK).body(customerPage); + } + + /** + * Creates a new Customer. + * + * @param customerSaveDTO The CustomerSaveDTO object containing the details of the new customer to be created. + * @return A ResponseEntity containing the newly created CustomerDTO object and an HTTP status code of 201 (Created) upon successful creation. + */ + @Operation(summary = "Create a new Customer.") + @ApiResponses(value = { + @ApiResponse(responseCode = "201", description = "Customer created successfully") + }) + @PostMapping + public ResponseEntity createCustomer(@Valid @RequestBody CustomerSaveDTO customerSaveDTO) { + CustomerDTO customer = customerService.createCustomer(customerSaveDTO); + return ResponseEntity.status(HttpStatus.CREATED).body(customer); + } + + /** + * Updates an existing Customer with the provided CustomerSaveDTO object. + * + * @param id The unique identifier of the customer to be updated. + * @param customerSaveDTO The CustomerSaveDTO object containing the details of the updated customer. + * @return A ResponseEntity containing the updated CustomerDTO object and an HTTP status code of 200 (OK) upon successful update. + * @apiNote If the Customer with the given ID is not found, a ResponseEntity with status code 204 (No Content) is returned. + */ + @Operation(summary = "Update existing Customer.") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Customer updated successfully"), + @ApiResponse(responseCode = "204", description = "Customer not found") + }) + @PutMapping(value = "/{id}") + public ResponseEntity updateCustomer(@PathVariable("id") UUID id, @Valid @RequestBody CustomerSaveDTO customerSaveDTO) { + CustomerDTO customer = customerService.updateCustomer(id, customerSaveDTO); + return ResponseEntity.status(HttpStatus.OK).body(customer); + } + + /** + * Updates an existing Customer's status from Deactive to Active. + * + * @param id The unique identifier of the Customer to be updated. + * @return A ResponseEntity containing the updated CustomerDTO object and an HTTP status code of 200 (OK) upon successful update. + * @apiNote If the Customer with the given ID is not found, a ResponseEntity with status code 204 (No Content) is returned. + */ + @Operation(summary = "Update existing Customer status from Deactive to Active.") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Customer successfully activated"), + @ApiResponse(responseCode = "204", description = "Customer not found") + }) + @PutMapping(value = "/active/{id}") + public ResponseEntity updateCustomerStatusActive(@PathVariable("id") UUID id) { + CustomerDTO customer = customerService.updateCustomerStatus(id, Status.Active); + return ResponseEntity.status(HttpStatus.OK).body(customer); + } + + /** + * Updates an existing Customer's status from Active to Deactive. + * + * @param id The unique identifier of the Customer to be updated. + * @return A ResponseEntity containing the updated CustomerDTO object and an HTTP status code of 200 (OK) upon successful update. + * @apiNote If the Customer with the given ID is not found, a ResponseEntity with status code 204 (No Content) is returned. + */ + @Operation(summary = "Update existing Customer status from Active to Deactive.") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Customer successfully deactivated"), + @ApiResponse(responseCode = "204", description = "Customer not found") + }) + @PutMapping(value = "/deactive/{id}") + public ResponseEntity updateCustomerStatusDeactive(@PathVariable("id") UUID id) { + CustomerDTO customer = customerService.updateCustomerStatus(id, Status.Deactive); + return ResponseEntity.status(HttpStatus.OK).body(customer); + } + + /** + * Deletes an existing Customer. + * + * @param id The unique identifier of the Customer to be deleted. + * @return A ResponseEntity with status code 200 (OK) upon successful deletion. + * @apiNote If the Customer with the given ID is not found, a ResponseEntity with status code 204 (No Content) is returned. + */ + @Operation(summary = "Delete an existing Customer.") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Customer deleted successfully"), + @ApiResponse(responseCode = "204", description = "Customer not found") + }) + @DeleteMapping(value = "/{id}") + public ResponseEntity deleteCustomer(@PathVariable("id") UUID id) { + customerService.deleteCustomer(id); + return ResponseEntity.status(HttpStatus.OK).build(); + } +} \ No newline at end of file diff --git a/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/data/model/APIKey.java b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/data/model/APIKey.java new file mode 100644 index 0000000..8461e80 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/data/model/APIKey.java @@ -0,0 +1,31 @@ +package com.example.lecture_13.data.model; + +import java.time.LocalDateTime; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Entity +@Table(name = "APIKey") +public class APIKey { + + @Id + @Column(name = "ID", columnDefinition = "BIGINT", updatable = false, nullable = false) + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + private String apiKey; + private String description; + private LocalDateTime createdAt; + private LocalDateTime updatedAt; + private boolean active; +} diff --git a/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/data/model/Customer.java b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/data/model/Customer.java new file mode 100644 index 0000000..9068525 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/data/model/Customer.java @@ -0,0 +1,51 @@ +package com.example.lecture_13.data.model; + +import java.util.Date; +import java.util.UUID; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Pattern; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Entity +@Table(name = "Customer") +public class Customer { + + @Id + @Column(name = "ID", columnDefinition = "BINARY(16)", updatable = false, nullable = false) + @GeneratedValue(strategy = GenerationType.UUID) + private UUID id; + + @NotBlank(message = "Name is mandatory") + @Pattern(regexp = "^[a-zA-Z\\s]+$", message = "Name can only contain letters and spaces") + @Column(name = "name", nullable = false) + private String name; + + @NotBlank(message = "Phone is mandatory") + @Pattern(regexp = "^\\+62[0-9]{9,13}$", message = "Phone number must start with +62 and contain 9 to 13 digits") + @Column(name = "phoneNumber", nullable = false) + private String phoneNumber; + + @Enumerated(EnumType.STRING) + @Column(name = "status", nullable = false) + private Status status = Status.Active; + + @Column(name = "createdAt", nullable = false) + private Date createdAt; + + @Column(name = "updatedAt", nullable = false) + private Date updatedAt; +} \ No newline at end of file diff --git a/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/data/model/Status.java b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/data/model/Status.java new file mode 100644 index 0000000..0fe8cb5 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/data/model/Status.java @@ -0,0 +1,6 @@ +package com.example.lecture_13.data.model; + +public enum Status { + Active, + Deactive +} diff --git a/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/data/repository/APIKeyRepository.java b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/data/repository/APIKeyRepository.java new file mode 100644 index 0000000..e50c68b --- /dev/null +++ b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/data/repository/APIKeyRepository.java @@ -0,0 +1,18 @@ +package com.example.lecture_13.data.repository; + +import java.util.Optional; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import com.example.lecture_13.data.model.APIKey; + +@Repository +public interface APIKeyRepository extends JpaRepository { + + // Get the first API key, order by ID + Optional findFirstByOrderById(); + + // Find the first active API key + Optional findFirstByActiveTrueOrderById(); +} \ No newline at end of file diff --git a/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/data/repository/CustomerRepository.java b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/data/repository/CustomerRepository.java new file mode 100644 index 0000000..54f6310 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/data/repository/CustomerRepository.java @@ -0,0 +1,18 @@ +package com.example.lecture_13.data.repository; + +import java.util.UUID; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import com.example.lecture_13.data.model.Customer; +import com.example.lecture_13.data.model.Status; + +@Repository +public interface CustomerRepository extends JpaRepository { + + // Find customer data by considering the status. + Page findByStatus(Status status, Pageable pageable); +} diff --git a/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/dto/CustomerDTO.java b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/dto/CustomerDTO.java new file mode 100644 index 0000000..a3081d5 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/dto/CustomerDTO.java @@ -0,0 +1,19 @@ +package com.example.lecture_13.dto; + +import com.example.lecture_13.data.model.Status; + +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.AllArgsConstructor; + +import java.util.UUID; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class CustomerDTO { + private UUID Id; + private String name; + private String phoneNumber; + private Status status; +} diff --git a/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/dto/CustomerSaveDTO.java b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/dto/CustomerSaveDTO.java new file mode 100644 index 0000000..276693f --- /dev/null +++ b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/dto/CustomerSaveDTO.java @@ -0,0 +1,27 @@ +package com.example.lecture_13.dto; + +import lombok.Data; +import lombok.NoArgsConstructor; +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; +import lombok.AllArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class CustomerSaveDTO { + + @NotBlank(message = "Name is mandatory") + @NotNull(message = "Name can't be NULL") + @Pattern(regexp = "^[a-zA-Z\\s]+$", message = "Name can only contain letters and spaces") + @Schema(example = "Your Name") + private String name; + + @NotBlank(message = "Phone is mandatory") + @NotNull(message = "Phone can't be NULL") + @Pattern(regexp = "^\\+62[0-9]{9,13}$", message = "Phone number must start with +62 and contain 9 to 13 digits") + @Schema(example = "+62xxxxxxxxxxxxx") + private String phoneNumber; +} diff --git a/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/dto/CustomerShowDTO.java b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/dto/CustomerShowDTO.java new file mode 100644 index 0000000..1f4cb67 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/dto/CustomerShowDTO.java @@ -0,0 +1,16 @@ +package com.example.lecture_13.dto; + +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.AllArgsConstructor; + +import java.util.UUID; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class CustomerShowDTO { + private UUID Id; + private String name; + private String phoneNumber; +} diff --git a/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/exception/BadRequestException.java b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/exception/BadRequestException.java new file mode 100644 index 0000000..645c68e --- /dev/null +++ b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/exception/BadRequestException.java @@ -0,0 +1,7 @@ +package com.example.lecture_13.exception; + +public class BadRequestException extends RuntimeException { + public BadRequestException(String message) { + super(message); + } +} diff --git a/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/exception/DuplicateStatusException.java b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/exception/DuplicateStatusException.java new file mode 100644 index 0000000..5f3f806 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/exception/DuplicateStatusException.java @@ -0,0 +1,7 @@ +package com.example.lecture_13.exception; + +public class DuplicateStatusException extends RuntimeException { + public DuplicateStatusException(String message) { + super(message); + } +} diff --git a/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/exception/GlobalExceptionHandler.java b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..b1fc0b4 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/exception/GlobalExceptionHandler.java @@ -0,0 +1,77 @@ +package com.example.lecture_13.exception; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.FieldError; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +@RestControllerAdvice +public class GlobalExceptionHandler { + + // Handle validation errors from @Valid annotated methods + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity>> handleValidationErrors(MethodArgumentNotValidException ex) { + List errors = ex.getBindingResult().getFieldErrors() + .stream().map(FieldError::getDefaultMessage).collect(Collectors.toList()); + return new ResponseEntity<>(getErrorsMap(errors), HttpStatus.BAD_REQUEST); + } + + private Map> getErrorsMap(List errors) { + Map> errorResponse = new HashMap<>(); + errorResponse.put("errors", errors); + return errorResponse; + } + + /** + * Handles generic exceptions by creating a response entity containing an error message. + * + * @param e the exception to handle + * @return a response entity containing a map with an error message + */ + @ExceptionHandler(Exception.class) + @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) + public ResponseEntity> handleException(Exception e) { + Map errorResponse = new HashMap<>(); + errorResponse.put("error", e.getMessage()); + return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR); + } + + // Custom exceptions + /** + * Handles {@link ResourceNotFoundException} by creating a response entity containing an error message. + * + * @param e the {@link ResourceNotFoundException} to handle + * @return a {@link ResponseEntity} containing a map with an error message + * @throws ResourceNotFoundException if the specified resource is not found + */ + @ExceptionHandler(ResourceNotFoundException.class) + @ResponseStatus(HttpStatus.NOT_FOUND) + public ResponseEntity> handleResourceNotFoundException(ResourceNotFoundException e) { + Map errorResponse = new HashMap<>(); + errorResponse.put("error", e.getMessage()); + return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND); + } + + /** + * Handles {@link BadRequestException} by creating a response entity containing an error message. + * + * @param e the {@link BadRequestException} to handle + * @return a {@link ResponseEntity} containing a map with an error message + */ + @ExceptionHandler(BadRequestException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public ResponseEntity> handleBadRequestException(BadRequestException e) { + Map errorResponse = new HashMap<>(); + errorResponse.put("error", e.getMessage()); + return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST); + } +} + diff --git a/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/exception/ResourceNotFoundException.java b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/exception/ResourceNotFoundException.java new file mode 100644 index 0000000..ad0e756 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/exception/ResourceNotFoundException.java @@ -0,0 +1,7 @@ +package com.example.lecture_13.exception; + +public class ResourceNotFoundException extends RuntimeException { + public ResourceNotFoundException(String message) { + super(message); + } +} diff --git a/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/mapper/CustomerMapper.java b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/mapper/CustomerMapper.java new file mode 100644 index 0000000..6ddfa82 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/mapper/CustomerMapper.java @@ -0,0 +1,40 @@ +package com.example.lecture_13.mapper; + +import com.example.lecture_13.data.model.Customer; +import com.example.lecture_13.dto.CustomerDTO; +import com.example.lecture_13.dto.CustomerShowDTO; +import com.example.lecture_13.dto.CustomerSaveDTO; + +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper(componentModel = "spring") +public interface CustomerMapper { + + CustomerMapper INSTANCE = Mappers.getMapper(CustomerMapper.class); + + // Customer - CustomerDTO + CustomerDTO toCustomerDTO(Customer customer); + + @Mapping(target = "createdAt", ignore = true) + @Mapping(target = "updatedAt", ignore = true) + Customer toCustomer(CustomerDTO customerDTO); + + // Customer - CustomerShowDTO + CustomerShowDTO toCustomerShowDTO(Customer customer); + + @Mapping(target = "status", ignore = true) + @Mapping(target = "createdAt", ignore = true) + @Mapping(target = "updatedAt", ignore = true) + Customer toCustomer(CustomerShowDTO customerShowDTO); + + // Customer - CustomerSaveDTO + CustomerSaveDTO toCustomerSaveDTO(Customer customer); + + @Mapping(target = "id", ignore = true) + @Mapping(target = "status", ignore = true) + @Mapping(target = "createdAt", ignore = true) + @Mapping(target = "updatedAt", ignore = true) + Customer toCustomer(CustomerSaveDTO customerSaveDTO); +} diff --git a/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/service/CustomerService.java b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/service/CustomerService.java new file mode 100644 index 0000000..d57b77e --- /dev/null +++ b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/service/CustomerService.java @@ -0,0 +1,35 @@ +package com.example.lecture_13.service; + +import java.util.UUID; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + +import com.example.lecture_13.data.model.Customer; +import com.example.lecture_13.data.model.Status; +import com.example.lecture_13.dto.CustomerDTO; +import com.example.lecture_13.dto.CustomerSaveDTO; +import com.example.lecture_13.dto.CustomerShowDTO; + +import jakarta.validation.Valid; + +public interface CustomerService { + + // Retrieves a paginated list of all customers. + Page findAllActiveCustomer(Pageable pageable); + + // Creating a new customer. + CustomerDTO createCustomer(@Valid CustomerSaveDTO customerSaveDTO); + + // Updates an existing customer with the provided customer details. + CustomerDTO updateCustomer(UUID id, @Valid CustomerSaveDTO customerSaveDTO); + + // Updates the status of an existing customer. + CustomerDTO updateCustomerStatus(UUID id, Status status); + + // Find customer by its id. + Customer findById(UUID id); + + // Deletes a customer from the repository. + void deleteCustomer(UUID id); +} \ No newline at end of file diff --git a/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/service/impl/CustomerServiceImpl.java b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/service/impl/CustomerServiceImpl.java new file mode 100644 index 0000000..a4ccaf7 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/java/com/example/lecture_13/service/impl/CustomerServiceImpl.java @@ -0,0 +1,129 @@ +package com.example.lecture_13.service.impl; + +import java.util.Date; +import java.util.UUID; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.validation.annotation.Validated; + +import com.example.lecture_13.data.model.Customer; +import com.example.lecture_13.data.model.Status; +import com.example.lecture_13.data.repository.CustomerRepository; +import com.example.lecture_13.dto.CustomerDTO; +import com.example.lecture_13.dto.CustomerSaveDTO; +import com.example.lecture_13.dto.CustomerShowDTO; +import com.example.lecture_13.exception.DuplicateStatusException; +import com.example.lecture_13.exception.ResourceNotFoundException; +import com.example.lecture_13.mapper.CustomerMapper; +import com.example.lecture_13.service.CustomerService; + +import jakarta.validation.Valid; + +@Service +@Validated +public class CustomerServiceImpl implements CustomerService { + + @Autowired + private CustomerMapper customerMapper; + + @Autowired + private CustomerRepository customerRepository; + + /** + * Retrieves a paginated list of all active customers from the repository. + * + * @param pageable The pagination parameters, including the page number and size. + * @return A Page object containing a list of {@link CustomerShowDTO} objects representing the customers on the specified page. + */ + @Override + public Page findAllActiveCustomer(Pageable pageable) { + return customerRepository.findByStatus(Status.Active, pageable).map(customerMapper::toCustomerShowDTO); + } + + /** + * Retrieves a customer from the repository based on the provided unique identifier. + * + * @param customerId The unique identifier of the customer to be retrieved. + * @return A {@link Customer} object representing the customer with the given ID. + * @throws ResourceNotFoundException if no customer is found with the given ID. + */ + @Override + public Customer findById(UUID customerId) { + return customerRepository.findById(customerId).orElseThrow(() -> new ResourceNotFoundException("Customer not found")); + } + + /** + * Creates a new customer in the repository and returns the corresponding {@link CustomerDTO} object. + * + * @param customerSaveDTO The {@link CustomerSaveDTO} object containing the details of the new customer to be created. + * @return A {@link CustomerDTO} object representing the newly created customer. + */ + @Override + public CustomerDTO createCustomer(@Valid CustomerSaveDTO customerSaveDTO) { + Customer customer = customerMapper.toCustomer(customerSaveDTO); + customer.setCreatedAt(new Date()); + customer.setUpdatedAt(new Date()); + Customer savedCustomer = customerRepository.save(customer); + return customerMapper.toCustomerDTO(savedCustomer); + } + + /** + * Updates an existing customer in the repository with the provided details from the {@link CustomerSaveDTO} object. + * + * @param id The unique identifier of the customer to be updated. + * @param customerSaveDTO The {@link CustomerSaveDTO} object containing the details of the customer to be updated. + * @return A {@link CustomerDTO} object representing the updated customer. + * @throws ResourceNotFoundException if the customer with the given ID is not found. + */ + @Override + public CustomerDTO updateCustomer(UUID id, @Valid CustomerSaveDTO customerSaveDTO) { + Customer customer = customerRepository.findById(id) + .orElseThrow(() -> new ResourceNotFoundException("Customer not found")); + + customer.setName(customerSaveDTO.getName()); + customer.setPhoneNumber(customerSaveDTO.getPhoneNumber()); + customer.setUpdatedAt(new Date()); + Customer updatedCustomer = customerRepository.save(customer); + return customerMapper.toCustomerDTO(updatedCustomer); + } + + /** + * Updates the status of an existing customer in the repository. + * + * @param id The unique identifier of the customer whose status is to be updated. + * @param status The new status to be assigned to the customer. + * @return A {@link CustomerDTO} object representing the updated customer. + * @throws ResourceNotFoundException if the customer with the given ID is not found. + * @throws DuplicateStatusException if the customer already has the specified status. + */ + @Override + public CustomerDTO updateCustomerStatus(UUID id, Status status) { + Customer customer = customerRepository.findById(id) + .orElseThrow(() -> new ResourceNotFoundException("Customer not found")); + + if (customer.getStatus() == status) { + throw new DuplicateStatusException("Customer status is already " + status); + } + + customer.setStatus(status); + customer.setUpdatedAt(new Date()); + Customer updatedCustomer = customerRepository.save(customer); + return customerMapper.toCustomerDTO(updatedCustomer); + } + + /** + * Deletes a customer from the repository based on the provided unique identifier. + * + * @param id The unique identifier of the customer to be deleted. + * @throws ResourceNotFoundException if no customer is found with the given ID. + */ + @Override + public void deleteCustomer(UUID id) { + Customer customer = customerRepository.findById(id) + .orElseThrow(() -> new ResourceNotFoundException("Customer not found")); + customerRepository.delete(customer); + } +} \ No newline at end of file diff --git a/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/resources/application.properties b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/resources/application.properties new file mode 100644 index 0000000..1aa55bc --- /dev/null +++ b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/resources/application.properties @@ -0,0 +1,31 @@ +spring.application.name=lecture_13 + +# Datasorce connection data +spring.config.import=file:env.properties +spring.datasource.url=${DB_DATABASE} +spring.datasource.username=${DB_USER} +spring.datasource.password=${DB_PASSWORD} +spring.datasource.driver-class-name=com.mysql.jdbc.Driver +spring.jpa.hibernate.ddl-auto=update + +# Enable SQL logging and show the statements and params + formatting +spring.jpa.show-sql=true +spring.jpa.properties.hibernate.format_sql=true +logging.level.org.hibernate.SQL=DEBUG +logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE + +# Swagger API documentation docs path +springdoc.api-docs.path=/api-docs + +# Enable the restart feature but exclude certain paths from triggering a restart +spring.devtools.restart.additional-paths=src/main/java +spring.devtools.restart.exclude=static/**,public/** + +# Enable the LiveReload feature +spring.devtools.livereload.enabled=true + +# Overriding bean +spring.main.allow-bean-definition-overriding=true + +# Port +server.port=${PORT} \ No newline at end of file diff --git a/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/resources/data.sql b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/resources/data.sql new file mode 100644 index 0000000..3cfacc2 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 02/lecture_13/src/main/resources/data.sql @@ -0,0 +1,55 @@ +-- Create the database +CREATE DATABASE week8_lecture13; + +-- Use the database +USE week8_lecture13; + +-- Initialize table with DDL +-- Create `Customer` table +CREATE TABLE Customer ( + ID BINARY(16) PRIMARY KEY, + name VARCHAR(255) NOT NULL, + phoneNumber VARCHAR(255), + status ENUM('Active', 'Deactivate') NOT NULL, + createdAt DATETIME, + updatedAt DATETIME +); + +-- Create `APIKey` table +CREATE TABLE APIKey ( + ID BIGINT AUTO_INCREMENT PRIMARY KEY, + api_key VARCHAR(255) NOT NULL, + description VARCHAR(255), -- Description or label for the API key + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, -- Timestamp of creation + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- Timestamp of last update + active BOOLEAN DEFAULT TRUE -- Status to enable or disable the API key +); + +-- Initialize data on table with DML +-- Insert 20 customers +INSERT INTO Customer (ID, name, phone_number, status, created_at, updated_at) VALUES +(UUID_TO_BIN(UUID()), 'Alice Smith', '1234567890', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Bob Johnson', '0987654321', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Charlie Brown', '1122334455', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'David Wilson', '5566778899', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Eva Davis', '2233445566', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Frank Miller', '6677889900', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Grace Lee', '9988776655', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Hank Moore', '4455667788', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Ivy Taylor', '3344556677', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Jack Anderson', '7788990011', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Kara Thomas', '9988771122', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Leo Harris', '4455662233', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Mona Clark', '5566773344', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Nate Lewis', '3344558899', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Olivia Hall', '1122336677', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Paul Young', '8899001122', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Quinn Walker', '2233447788', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Rachel Allen', '6677883344', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Sam King', '9988773344', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Tina Scott', '5566778899', 'Active', NOW(), NOW()); + +-- Prepare API Keys +INSERT INTO APIKey (api_key, description, created_at, updated_at, active) VALUES +('12345-ABCDE', 'Primary API Key for System Access', NOW(), NOW(), TRUE), +('67890-FGHIJ', 'Secondary API Key for Testing', NOW(), NOW(), FALSE); \ No newline at end of file diff --git a/Week 08/Lecture 13/Assignment 02/lecture_13/src/test/java/com/example/lecture_13/Lecture13ApplicationTests.java b/Week 08/Lecture 13/Assignment 02/lecture_13/src/test/java/com/example/lecture_13/Lecture13ApplicationTests.java new file mode 100644 index 0000000..14fdbea --- /dev/null +++ b/Week 08/Lecture 13/Assignment 02/lecture_13/src/test/java/com/example/lecture_13/Lecture13ApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.lecture_13; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class Lecture13ApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/Week 08/Lecture 13/Assignment 03/README.md b/Week 08/Lecture 13/Assignment 03/README.md new file mode 100644 index 0000000..bc7ce35 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 03/README.md @@ -0,0 +1,369 @@ +# πŸ‘¨πŸ»β€πŸ« Lecture 13 - Spring Advance Feature: Filter and Spring Interceptor +> This repository is created as a part of assignment for Lecture 13 - Spring Advance Feature: Filter and Spring Interceptor + +## πŸ‘€ Assignment 03 - Simple Interceptor + +### 🧐 Detailed Overview + +1. **Store Username for Each API Key**: Add a username field to the `ApiKey` entity and include this in the response headers. +2. **Add Timestamp Header**: Add a `timestamp` header with the current time to all responses. +3. **Store Last Used Time**: Update the `ApiKey` entity to store the last time it was used. +4. **Print Username in Controller**: Implement a method in the controller to print the username associated with the API key. + +### πŸ› οΈ Modify the `ApiKey` Entity + +**Idea**: Update the `ApiKey` entity to include a username field and a last used time field. + +**Java Entity** +See the detail [here](/Week%2008/Lecture%2013/Assignment%2003/lecture_13/src/main/java/com/example/lecture_13/data/model/APIKey.java). +```java +@Data +@NoArgsConstructor +@AllArgsConstructor +@Entity +@Table(name = "APIKey") +public class APIKey { + + @Id + @Column(name = "ID", columnDefinition = "BIGINT", updatable = false, nullable = false) + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + private String apiKey; + private String username; // Added username field + private String description; + private LocalDateTime createdAt; + private LocalDateTime updatedAt; + private boolean active; + private LocalDateTime lastUsedAt; // Added last used field +} +``` + +### πŸ—„οΈ Update the Repository + +**Idea**: Add a method to update the last used time. + +**Repository** +See the detail [here](/Week%2008/Lecture%2013/Assignment%2003/lecture_13/src/main/java/com/example/lecture_13/data/repository/APIKeyRepository.java). +```java +@Repository +public interface APIKeyRepository extends JpaRepository { + + // Get the first API key, order by ID + Optional findFirstByOrderById(); + + // Find the first active API key + Optional findFirstByActiveTrueOrderById(); + + // Find the first active API key with a specific API key + Optional findFirstByApiKeyAndActiveTrue(String apiKey); +} +``` + +### 🌐 Create Interceptor + +**Idea**: Create an interceptor that intercepts incoming requests, checks for the "api-key-username" header, send it to header, and also setup "timestamp" header to all responses. + +**Interceptor Implementation** +See the detail [here](/Week%2008/Lecture%2013/Assignment%2003/lecture_13/src/main/java/com/example/lecture_13/config/interceptor/APIKeyInterceptor.java). +```java +@Component +public class APIKeyInterceptor implements HandlerInterceptor { + + private final APIKeyRepository apiKeyRepository; + private final static Logger logger = LoggerFactory.getLogger(APIKeyInterceptor.class); + + @Autowired + public APIKeyInterceptor(APIKeyRepository apiKeyRepository) { + this.apiKeyRepository = apiKeyRepository; + logger.info("APIKeyRepository injected: {}", (this.apiKeyRepository != null)); + } + + // Request is intercepted by this method before reaching the Controller + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + // Pre-processing logic here + // Apply timestamp + response.addHeader("timestamp", LocalDateTime.now().toString()); + logger.info("[PreHandle] Timestamp applied."); + logger.info("[PreHandle][" + request + "]" + "[" + request.getMethod()+ "] " + request.getRequestURI()); + return true; // Continue with the request + } + + // Response is intercepted by this method before reaching the client + @Override + public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { + // Post-handle logic here + logger.info("[PostHandle][" + request + "]" + "[" + request.getMethod()+ "] " + request.getRequestURI()); + } + + // This method is called after request & response HTTP communication is done. + @Override + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { + logger.info("[AfterCompletion][" + request + "]" + "[" + request.getMethod()+ "] " + request.getRequestURI()); + + String username = request.getHeader("api-key-username"); + if (username != null) { + response.addHeader("username", username); + logger.info("[AfterCompletion] Username detected : {}", username); + } + + // Update lastUsedAt in the database + String requestApiKey = request.getHeader("api-key"); + logger.info("[AfterCompletion] API Key : {}", requestApiKey); + Optional apiKeyOpt = apiKeyRepository.findFirstByApiKeyAndActiveTrue(requestApiKey); + if (apiKeyOpt.isPresent()) { + APIKey apiKey = apiKeyOpt.get(); + apiKey.setUsername(username); + apiKey.setLastUsedAt(LocalDateTime.now()); + apiKeyRepository.save(apiKey); + logger.info("[AfterCompletion] API Key data updated : {}", apiKey); + } + + logger.info("[AfterCompletion] Execution done."); + } +} +``` + +### βœ”οΈ Register Interceptor +**Interceptor Configuration** +See the detail [here](/Week%2008/Lecture%2013/Assignment%2003/lecture_13/src/main/java/com/example/lecture_13/config/InterceptorConfig.java). +```java +@Configuration +public class InterceptorConfig implements WebMvcConfigurer { + // Register an interceptor with the registry + private final APIKeyInterceptor apiKeyInterceptor; + + @Autowired + public InterceptorConfig(APIKeyInterceptor apiKeyInterceptor) { + this.apiKeyInterceptor = apiKeyInterceptor; + } + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(apiKeyInterceptor); + } +} +``` + +#### Response Header Filter + +Update the response header filter to include the `timestamp` header. + +### πŸ†• Add a Controller Method to Print Username + +**Idea**: Add a method to your controller to print the username associated with the API key. + +**Customer Controller** +See the detail [here](/Week%2008/Lecture%2013/Assignment%2003/lecture_13/src/main/java/com/example/lecture_13/controller/CustomerController.java). + +```java +@RestController +@RequestMapping("/api/v1/customers") +@Validated +public class CustomerController { + + ..... + + /** + * Retrieves the username of the current API User. + * + * @param apiKey The API key provided in the request header. + * @return The username of the current API User if the provided API key is valid, otherwise returns "Invalid API Key". + */ + @Operation(summary = "Get the username of current API User.") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Username retrieved successfully"), + }) + @GetMapping("/username") + public String printUsername(@RequestHeader("api-key") String apiKey) { + Optional apiKeyOpt = apiKeyRepository.findFirstByActiveTrueOrderById(); + if (apiKeyOpt.isPresent() && apiKeyOpt.get().getApiKey().equals(apiKey)) { + return "Username: " + apiKeyOpt.get().getUsername(); + } + return "Invalid API Key"; + } +} +``` + +--- + +### 🌳 Project Structure +```bash +lecture_13 +β”œβ”€β”€ .mvn/wrapper/ +β”‚ └── maven-wrapper.properties +β”œβ”€β”€ src/main/ +β”‚ β”œβ”€β”€ java/com/example/lecture_13/ +β”‚ β”‚ β”œβ”€β”€ config/ +β”‚ β”‚ β”‚ β”œβ”€β”€ filter/ +β”‚ β”‚ β”‚ β”‚ └── APIKeyFilter.java +β”‚ β”‚ β”‚ β”œβ”€β”€ interceptor/ +β”‚ β”‚ β”‚ β”‚ └── APIKeyInterceptor.java +β”‚ β”‚ β”‚ β”œβ”€β”€ FilterConfig.java +β”‚ β”‚ β”‚ β”œβ”€β”€ InterceptorConfig.java +β”‚ β”‚ β”‚ └── WebConfig.java +β”‚ β”‚ β”œβ”€β”€ controller/ +β”‚ β”‚ β”‚ └── CustomerController.java +β”‚ β”‚ β”œβ”€β”€ data/ +β”‚ β”‚ β”‚ β”œβ”€β”€ model/ +β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ APIKey.java +β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ Customer.java +β”‚ β”‚ β”‚ β”‚ └── Status.java +β”‚ β”‚ β”‚ └── repository/ +β”‚ β”‚ β”‚ β”œβ”€β”€ APIKeyRepository.java +β”‚ β”‚ β”‚ └── CustomerRepository.java +β”‚ β”‚ β”œβ”€β”€ dto/ +β”‚ β”‚ β”‚ β”œβ”€β”€ CustomerDTO.java +β”‚ β”‚ β”‚ β”œβ”€β”€ CustomerSaveDTO.java +β”‚ β”‚ β”‚ └── CustomerShowDTO.java +β”‚ β”‚ β”œβ”€β”€ exception/ +β”‚ β”‚ β”‚ β”œβ”€β”€ BadRequestException.java +β”‚ β”‚ β”‚ β”œβ”€β”€ DuplicateStatusException.java +β”‚ β”‚ β”‚ β”œβ”€β”€ GlobalExceptionHandler.java +β”‚ β”‚ β”‚ └── ResourceNotFound.java +β”‚ β”‚ β”œβ”€β”€ mapper/ +β”‚ β”‚ β”‚ └── CustomerMapper.java +β”‚ β”‚ β”œβ”€β”€ service/ +β”‚ β”‚ β”‚ β”œβ”€β”€ impl/ +β”‚ β”‚ β”‚ β”‚ └── CustomerServiceImpl.java +β”‚ β”‚ β”‚ └── CustomerService.java +β”‚ β”‚ └── Lecture13Application.java +β”‚ └── resources/ +β”‚ β”œβ”€β”€ application.properties +β”‚ └── data.sql +β”œβ”€β”€ .gitignore +β”œβ”€β”€ env.properties +β”œβ”€β”€ mvnw +β”œβ”€β”€ mvnw.cmd +β”œβ”€β”€ pom.xml +β”œβ”€β”€ run.bat +└── run.sh +``` + +### 🧩 SQL Query Data +Here is the SQL query to create the database, table, and instantiate some data. +```sql +-- Create the database +CREATE DATABASE week8_lecture13; + +-- Use the database +USE week8_lecture13; + +-- Initialize table with DDL +-- Create `Customer` table +CREATE TABLE Customer ( + ID BINARY(16) PRIMARY KEY, + name VARCHAR(255) NOT NULL, + phoneNumber VARCHAR(255), + status ENUM('Active', 'Deactivate') NOT NULL, + createdAt DATETIME, + updatedAt DATETIME +); + +-- Create `APIKey` table +CREATE TABLE APIKey ( + ID BIGINT AUTO_INCREMENT PRIMARY KEY, + api_key VARCHAR(255) NOT NULL, + description VARCHAR(255), -- Description or label for the API key + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, -- Timestamp of creation + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- Timestamp of last update + active BOOLEAN DEFAULT TRUE, -- Status to enable or disable the API key + last_used_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, -- Last time the API key was used + username VARCHAR(255) -- Username associated with the API key +); +``` + +There are also query to insert some generated dummy data. All the MySQL queries is available on [this file](/Week%2008/Lecture%2013/Assignment%2002/lecture_13/src/main/resources/data.sql). Here is the query to drop the database. +```sql +-- Drop the database +DROP DATABASE IF EXISTS week8_lecture13; +``` + +Don't forget to add this to re-update the SQL DDL queries. +```java +spring.jpa.hibernate.ddl-auto=update +``` + +finally, don't forget to add this for hibernate SQL logging. +```java +spring.jpa.show-sql=true +spring.jpa.properties.hibernate.format_sql=true +logging.level.org.hibernate.SQL=DEBUG +logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE +``` + +### βš™οΈ How to run the program +1. Go to the `lecture_13` directory by using this command + ```bash + $ cd lecture_13 + ``` +2. Make sure you have maven installed on my computer, use `mvn -v` to check the version. +3. Setup your credential. You can configure it by creating file `env.properties` on the **root of the project** (aligned with [pom.xml](/Week%2008/Lecture%2013/Assignment%2002/lecture_13/pom.xml)), then fill it with this format. + ```java + DB_DATABASE= + DB_USER= + DB_PASSWORD=M + PORT= + ``` +4. If you are using windows, you can run the program by using this command. + ```bash + $ ./run.bat + ``` + And if you are using Linux, you can run the program by using this command. + ```bash + $ chmod +x run.sh + $ ./run.sh + ``` + +If all the instruction is well executed, Open [localhost:8080](http://localhost:8080) to see that the REST APIs is now works. + +### πŸ”‘ List of Endpoints +| Endpoints | Method | Description | +|--------------------------------------------------------------------------------------------|:------:|-------------------------------------------------------------------------------------------------| +| /api/v1/customers | GET | Retrieve all customers with default pagination (page 1 with size 20 elements/page). Consider only active customers. | +| /api/v1/customers?page={X}&size={Y} | GET | Retrieve all customers with custom pagination (page X (0-based index) with size Y elements/page). Consider only active customers. | +| /api/v1/customers | POST | Create a new customer. Validate POST request format. | +| /api/v1/customers/{id} | PUT | Update an existing customer by customer ID. Make sure the customer ID exists. | +| /api/v1/customers/active/{id} | PUT | Activate the existing customer by their customer ID. Make sure the customer ID exists and is currently inactive. | +| /api/v1/customers/deactive/{id} | PUT | Deactivate the existing customer by their customer ID. Make sure the customer ID exists and is currently active. | +| /api/v1/customers/{id} | DELETE | Delete an existing customer by customer ID. Make sure the customer ID exists. | +| /api/v1/customers/username | GET | Get the current username of Customer API user. | + + +### πŸš€ Demonstration +#### Screenshots +![Screenshots](/Week%2008/Lecture%2013/Assignment%2003/img/demo1.png) + +The request headers used and the response headers returned. + +![Screenshots](/Week%2008/Lecture%2013/Assignment%2003/img/demo2.png) + +Data stored on APIKey table from database. + +![Screenshots](/Week%2008/Lecture%2013/Assignment%2003/img/demo3.png) + +The current Customer API username. + +#### Swagger Documentation +I use swagger for documentation, you can access it [here](http://localhost:8080/swagger-ui/index.html) + +![Screenshots](/Week%2008/Lecture%2013/Assignment%2003/img/swagger.png) + +#### Logs +Here is the log printed from the console (excluding the SQL Hibernate log) when `GET` request to `/api/v1/customers` is called with the defined headers. +```java +[Filter][org.apache.catalina.connector.RequestFacade@73cd94a6][GET] /api/v1/customers +[Filter] doFilter starts. +[PreHandle][org.apache.catalina.connector.RequestFacade@73cd94a6][GET] /api/v1/customers +[PreHandle] Timestamp applied. +[PreHandle] preHandle done. +[PostHandle][org.apache.catalina.connector.RequestFacade@73cd94a6][GET] /api/v1/customers +[PostHandle] postHandle done. +[AfterCompletion][org.apache.catalina.connector.RequestFacade@73cd94a6][GET] /api/v1/customers +[AfterCompletion] Username detected : Leon +[AfterCompletion] API Key : 12345-ABCDE +[AfterCompletion] API Key data updated : APIKey(id=1, apiKey=12345-ABCDE, username=Leon, description=Primary API Key for System Access, createdAt=2024-07-29T15:12:25, updatedAt=2024-07-29T15:12:25, active=true, lastUsedAt=2024-07-30T10:53:09.157716200) +[AfterCompletion] afterCompletion done. +[Filter] doFilter done. +[Filter] Logging Response : 200 +``` \ No newline at end of file diff --git a/Week 08/Lecture 13/Assignment 03/img/demo1.png b/Week 08/Lecture 13/Assignment 03/img/demo1.png new file mode 100644 index 0000000..678a5f3 Binary files /dev/null and b/Week 08/Lecture 13/Assignment 03/img/demo1.png differ diff --git a/Week 08/Lecture 13/Assignment 03/img/demo2.png b/Week 08/Lecture 13/Assignment 03/img/demo2.png new file mode 100644 index 0000000..8a365a2 Binary files /dev/null and b/Week 08/Lecture 13/Assignment 03/img/demo2.png differ diff --git a/Week 08/Lecture 13/Assignment 03/img/demo3.png b/Week 08/Lecture 13/Assignment 03/img/demo3.png new file mode 100644 index 0000000..42d0534 Binary files /dev/null and b/Week 08/Lecture 13/Assignment 03/img/demo3.png differ diff --git a/Week 08/Lecture 13/Assignment 03/img/swagger.png b/Week 08/Lecture 13/Assignment 03/img/swagger.png new file mode 100644 index 0000000..260be2d Binary files /dev/null and b/Week 08/Lecture 13/Assignment 03/img/swagger.png differ diff --git a/Week 08/Lecture 13/Assignment 03/lecture_13/.gitignore b/Week 08/Lecture 13/Assignment 03/lecture_13/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/Week 08/Lecture 13/Assignment 03/lecture_13/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/Week 08/Lecture 13/Assignment 03/lecture_13/.mvn/wrapper/maven-wrapper.properties b/Week 08/Lecture 13/Assignment 03/lecture_13/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..8f96f52 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 03/lecture_13/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.7/apache-maven-3.9.7-bin.zip diff --git a/Week 08/Lecture 13/Assignment 03/lecture_13/env.properties b/Week 08/Lecture 13/Assignment 03/lecture_13/env.properties new file mode 100644 index 0000000..4a1afe3 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 03/lecture_13/env.properties @@ -0,0 +1,4 @@ +DB_DATABASE=jdbc:mysql://localhost:3308/week8_lecture13?allowPublicKeyRetrieval=true&useSSL=false +DB_USER=root +DB_PASSWORD=Michaeleon16606_ +PORT=8080 \ No newline at end of file diff --git a/Week 08/Lecture 13/Assignment 03/lecture_13/mvnw b/Week 08/Lecture 13/Assignment 03/lecture_13/mvnw new file mode 100644 index 0000000..d7c358e --- /dev/null +++ b/Week 08/Lecture 13/Assignment 03/lecture_13/mvnw @@ -0,0 +1,259 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.2 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/Week 08/Lecture 13/Assignment 03/lecture_13/mvnw.cmd b/Week 08/Lecture 13/Assignment 03/lecture_13/mvnw.cmd new file mode 100644 index 0000000..6f779cf --- /dev/null +++ b/Week 08/Lecture 13/Assignment 03/lecture_13/mvnw.cmd @@ -0,0 +1,149 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.2 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' +$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/Week 08/Lecture 13/Assignment 03/lecture_13/pom.xml b/Week 08/Lecture 13/Assignment 03/lecture_13/pom.xml new file mode 100644 index 0000000..decd417 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 03/lecture_13/pom.xml @@ -0,0 +1,128 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.3.2 + + + com.example + lecture_13 + 1.0-SNAPSHOT + lecture_13 + Demo project for Spring Boot + + + + + + + + + + + + + + + 21 + + + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter-web-services + + + org.springframework.boot + spring-boot-devtools + + + org.springframework + spring-webmvc + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java + 8.0.33 + runtime + + + + + org.projectlombok + lombok + + + + + org.springframework.boot + spring-boot-starter-validation + + + org.hibernate.validator + hibernate-validator + 8.0.0.Final + + + javax.validation + validation-api + 2.0.1.Final + + + + + org.mapstruct + mapstruct + 1.5.3.Final + + + org.mapstruct + mapstruct-processor + 1.5.3.Final + provided + + + + + javax.servlet + javax.servlet-api + 4.0.1 + provided + + + + + org.springdoc + springdoc-openapi-starter-webmvc-ui + 2.2.0 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/Week 08/Lecture 13/Assignment 03/lecture_13/run.bat b/Week 08/Lecture 13/Assignment 03/lecture_13/run.bat new file mode 100644 index 0000000..7f578be --- /dev/null +++ b/Week 08/Lecture 13/Assignment 03/lecture_13/run.bat @@ -0,0 +1,3 @@ +@echo off +echo Building and running the project with Maven... +mvn clean install && java -jar target/lecture_13-1.0-SNAPSHOT.jar \ No newline at end of file diff --git a/Week 08/Lecture 13/Assignment 03/lecture_13/run.sh b/Week 08/Lecture 13/Assignment 03/lecture_13/run.sh new file mode 100644 index 0000000..1596d33 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 03/lecture_13/run.sh @@ -0,0 +1,3 @@ +#!/bin/bash +echo Building the project with Maven... +mvn clean install && java -jar target/lecture_13-1.0-SNAPSHOT.jar \ No newline at end of file diff --git a/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/Lecture13Application.java b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/Lecture13Application.java new file mode 100644 index 0000000..e77dfa4 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/Lecture13Application.java @@ -0,0 +1,12 @@ +package com.example.lecture_13; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Lecture13Application { + + public static void main(String[] args) { + SpringApplication.run(Lecture13Application.class, args); + } +} diff --git a/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/config/FilterConfig.java b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/config/FilterConfig.java new file mode 100644 index 0000000..9c2fed8 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/config/FilterConfig.java @@ -0,0 +1,19 @@ +package com.example.lecture_13.config; + +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.example.lecture_13.config.filter.APIKeyFilter; + +@Configuration +public class FilterConfig { + + @Bean + public FilterRegistrationBean apiKeyFilter(APIKeyFilter apiKeyFilter) { + FilterRegistrationBean registrationBean = new FilterRegistrationBean<>(); + registrationBean.setFilter(apiKeyFilter); + registrationBean.addUrlPatterns("/api/*"); // All Customer API + return registrationBean; + } +} \ No newline at end of file diff --git a/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/config/InterceptorConfig.java b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/config/InterceptorConfig.java new file mode 100644 index 0000000..7f5fbfd --- /dev/null +++ b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/config/InterceptorConfig.java @@ -0,0 +1,24 @@ +package com.example.lecture_13.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +import com.example.lecture_13.config.interceptor.APIKeyInterceptor; + +@Configuration +public class InterceptorConfig implements WebMvcConfigurer { + // Register an interceptor with the registry + private final APIKeyInterceptor apiKeyInterceptor; + + @Autowired + public InterceptorConfig(APIKeyInterceptor apiKeyInterceptor) { + this.apiKeyInterceptor = apiKeyInterceptor; + } + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(apiKeyInterceptor); + } +} diff --git a/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/config/WebConfig.java b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/config/WebConfig.java new file mode 100644 index 0000000..9e643f3 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/config/WebConfig.java @@ -0,0 +1,9 @@ +package com.example.lecture_13.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.data.web.config.EnableSpringDataWebSupport; + +@Configuration +@EnableSpringDataWebSupport(pageSerializationMode = EnableSpringDataWebSupport.PageSerializationMode.VIA_DTO) +public class WebConfig { +} diff --git a/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/config/filter/APIKeyFilter.java b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/config/filter/APIKeyFilter.java new file mode 100644 index 0000000..f133e22 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/config/filter/APIKeyFilter.java @@ -0,0 +1,58 @@ +package com.example.lecture_13.config.filter; + +import java.io.IOException; +import java.util.Optional; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import com.example.lecture_13.data.model.APIKey; +import com.example.lecture_13.data.repository.APIKeyRepository; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +@Component +public class APIKeyFilter extends OncePerRequestFilter { + + @Autowired + private APIKeyRepository apiKeyRepository; + + private final static Logger logger = LoggerFactory.getLogger(APIKeyFilter.class); + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) + throws ServletException, IOException { + + logger.info("[Filter][" + request + "]" + "[" + request.getMethod()+ "] " + request.getRequestURI()); + String requestApiKey = request.getHeader("api-key"); + + Optional apiKeyOpt = apiKeyRepository.findFirstByActiveTrueOrderById(); + response.addHeader("source", "fpt-software"); + if (apiKeyOpt.isPresent()) { + String storedApiKey = apiKeyOpt.get().getApiKey(); + + if (storedApiKey.equals(requestApiKey)) { + logger.info("[Filter] doFilter starts."); + filterChain.doFilter(request, response); + logger.info("[Filter] doFilter done."); + } else { + response.setStatus(HttpStatus.FORBIDDEN.value()); + response.setContentType("application/json"); + response.getWriter().write("{\"error\": \"Invalid API Key\"}"); + } + } else { + response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.setContentType("application/json"); + response.getWriter().write("{\"error\": \"API Key not configured or inactive\"}"); + } + + logger.info("[Filter] Logging Response : {}", response.getStatus()); + } +} diff --git a/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/config/interceptor/APIKeyInterceptor.java b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/config/interceptor/APIKeyInterceptor.java new file mode 100644 index 0000000..61bab43 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/config/interceptor/APIKeyInterceptor.java @@ -0,0 +1,76 @@ +package com.example.lecture_13.config.interceptor; + +import java.time.LocalDateTime; +import java.util.Optional; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.HandlerInterceptor; +import org.springframework.web.servlet.ModelAndView; + +import com.example.lecture_13.data.model.APIKey; +import com.example.lecture_13.data.repository.APIKeyRepository; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +@Component +public class APIKeyInterceptor implements HandlerInterceptor { + + private final APIKeyRepository apiKeyRepository; + private final static Logger logger = LoggerFactory.getLogger(APIKeyInterceptor.class); + + @Autowired + public APIKeyInterceptor(APIKeyRepository apiKeyRepository) { + this.apiKeyRepository = apiKeyRepository; + logger.info("APIKeyRepository injected: {}", (this.apiKeyRepository != null)); + } + + // Request is intercepted by this method before reaching the Controller + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + // Pre-processing logic here + logger.info("[PreHandle][" + request + "]" + "[" + request.getMethod()+ "] " + request.getRequestURI()); + // Apply timestamp + response.addHeader("timestamp", LocalDateTime.now().toString()); + logger.info("[PreHandle] Timestamp applied."); + logger.info("[PreHandle] preHandle done."); + return true; // Continue with the request + } + + // Response is intercepted by this method before reaching the client + @Override + public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { + // Post-handle logic here + logger.info("[PostHandle][" + request + "]" + "[" + request.getMethod()+ "] " + request.getRequestURI()); + logger.info("[PostHandle] postHandle done."); + } + + // This method is called after request & response HTTP communication is done. + @Override + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { + logger.info("[AfterCompletion][" + request + "]" + "[" + request.getMethod()+ "] " + request.getRequestURI()); + + String username = request.getHeader("api-key-username"); + if (username != null) { + response.addHeader("username", username); + logger.info("[AfterCompletion] Username detected : {}", username); + } + + // Update lastUsedAt in the database + String requestApiKey = request.getHeader("api-key"); + logger.info("[AfterCompletion] API Key : {}", requestApiKey); + Optional apiKeyOpt = apiKeyRepository.findFirstByApiKeyAndActiveTrue(requestApiKey); + if (apiKeyOpt.isPresent()) { + APIKey apiKey = apiKeyOpt.get(); + apiKey.setUsername(username); + apiKey.setLastUsedAt(LocalDateTime.now()); + apiKeyRepository.save(apiKey); + logger.info("[AfterCompletion] API Key data updated : {}", apiKey); + } + + logger.info("[AfterCompletion] afterCompletion done."); + } +} diff --git a/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/controller/CustomerController.java b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/controller/CustomerController.java new file mode 100644 index 0000000..73c563d --- /dev/null +++ b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/controller/CustomerController.java @@ -0,0 +1,180 @@ +package com.example.lecture_13.controller; + +import java.util.Optional; +import java.util.UUID; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import com.example.lecture_13.data.model.APIKey; +import com.example.lecture_13.data.model.Status; +import com.example.lecture_13.data.repository.APIKeyRepository; +import com.example.lecture_13.dto.CustomerDTO; +import com.example.lecture_13.dto.CustomerSaveDTO; +import com.example.lecture_13.dto.CustomerShowDTO; +import com.example.lecture_13.service.CustomerService; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import jakarta.validation.Valid; + +@RestController +@RequestMapping("/api/v1/customers") +@Validated +public class CustomerController { + + @Autowired + private CustomerService customerService; + + @Autowired + private APIKeyRepository apiKeyRepository; + + /** + * Retrieves all customers from the database. + * + * @param page The index of the page to retrieve. Defaults to 0. + * @param size The number of customers to retrieve per page. Defaults to 20. + * @return A {@link ResponseEntity} containing a {@link Page} of {@link CustomerShowDTO} objects representing the customers on the specified page. + * @apiNote If no customers are found, a {@link ResponseEntity} with status status code 204 (No Content) is returned. + */ + @Operation(summary = "Retrieve all Active Customers.") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Customers retrieved successfully"), + @ApiResponse(responseCode = "204", description = "Customers not found") + }) + @GetMapping + public ResponseEntity> getAllCustomer(@RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "20") int size) { + Pageable pageable = PageRequest.of(page, size); + Page customerPage = customerService.findAllActiveCustomer(pageable); + + if (customerPage.isEmpty()) { + return ResponseEntity.status(HttpStatus.NO_CONTENT).build(); + } + + return ResponseEntity.status(HttpStatus.OK).body(customerPage); + } + + /** + * Creates a new Customer. + * + * @param customerSaveDTO The CustomerSaveDTO object containing the details of the new customer to be created. + * @return A ResponseEntity containing the newly created CustomerDTO object and an HTTP status code of 201 (Created) upon successful creation. + */ + @Operation(summary = "Create a new Customer.") + @ApiResponses(value = { + @ApiResponse(responseCode = "201", description = "Customer created successfully") + }) + @PostMapping + public ResponseEntity createCustomer(@Valid @RequestBody CustomerSaveDTO customerSaveDTO) { + CustomerDTO customer = customerService.createCustomer(customerSaveDTO); + return ResponseEntity.status(HttpStatus.CREATED).body(customer); + } + + /** + * Updates an existing Customer with the provided CustomerSaveDTO object. + * + * @param id The unique identifier of the customer to be updated. + * @param customerSaveDTO The CustomerSaveDTO object containing the details of the updated customer. + * @return A ResponseEntity containing the updated CustomerDTO object and an HTTP status code of 200 (OK) upon successful update. + * @apiNote If the Customer with the given ID is not found, a ResponseEntity with status code 204 (No Content) is returned. + */ + @Operation(summary = "Update existing Customer.") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Customer updated successfully"), + @ApiResponse(responseCode = "204", description = "Customer not found") + }) + @PutMapping(value = "/{id}") + public ResponseEntity updateCustomer(@PathVariable("id") UUID id, @Valid @RequestBody CustomerSaveDTO customerSaveDTO) { + CustomerDTO customer = customerService.updateCustomer(id, customerSaveDTO); + return ResponseEntity.status(HttpStatus.OK).body(customer); + } + + /** + * Updates an existing Customer's status from Deactive to Active. + * + * @param id The unique identifier of the Customer to be updated. + * @return A ResponseEntity containing the updated CustomerDTO object and an HTTP status code of 200 (OK) upon successful update. + * @apiNote If the Customer with the given ID is not found, a ResponseEntity with status code 204 (No Content) is returned. + */ + @Operation(summary = "Update existing Customer status from Deactive to Active.") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Customer successfully activated"), + @ApiResponse(responseCode = "204", description = "Customer not found") + }) + @PutMapping(value = "/active/{id}") + public ResponseEntity updateCustomerStatusActive(@PathVariable("id") UUID id) { + CustomerDTO customer = customerService.updateCustomerStatus(id, Status.Active); + return ResponseEntity.status(HttpStatus.OK).body(customer); + } + + /** + * Updates an existing Customer's status from Active to Deactive. + * + * @param id The unique identifier of the Customer to be updated. + * @return A ResponseEntity containing the updated CustomerDTO object and an HTTP status code of 200 (OK) upon successful update. + * @apiNote If the Customer with the given ID is not found, a ResponseEntity with status code 204 (No Content) is returned. + */ + @Operation(summary = "Update existing Customer status from Active to Deactive.") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Customer successfully deactivated"), + @ApiResponse(responseCode = "204", description = "Customer not found") + }) + @PutMapping(value = "/deactive/{id}") + public ResponseEntity updateCustomerStatusDeactive(@PathVariable("id") UUID id) { + CustomerDTO customer = customerService.updateCustomerStatus(id, Status.Deactive); + return ResponseEntity.status(HttpStatus.OK).body(customer); + } + + /** + * Deletes an existing Customer. + * + * @param id The unique identifier of the Customer to be deleted. + * @return A ResponseEntity with status code 200 (OK) upon successful deletion. + * @apiNote If the Customer with the given ID is not found, a ResponseEntity with status code 204 (No Content) is returned. + */ + @Operation(summary = "Delete an existing Customer.") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Customer deleted successfully"), + @ApiResponse(responseCode = "204", description = "Customer not found") + }) + @DeleteMapping(value = "/{id}") + public ResponseEntity deleteCustomer(@PathVariable("id") UUID id) { + customerService.deleteCustomer(id); + return ResponseEntity.status(HttpStatus.OK).build(); + } + + /** + * Retrieves the username of the current API User. + * + * @param apiKey The API key provided in the request header. + * @return The username of the current API User if the provided API key is valid, otherwise returns "Invalid API Key". + */ + @Operation(summary = "Get the username of current API User.") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Username retrieved successfully"), + }) + @GetMapping("/username") + public String printUsername(@RequestHeader("api-key") String apiKey) { + Optional apiKeyOpt = apiKeyRepository.findFirstByActiveTrueOrderById(); + if (apiKeyOpt.isPresent() && apiKeyOpt.get().getApiKey().equals(apiKey)) { + return "Username: " + apiKeyOpt.get().getUsername(); + } + return "Invalid API Key"; + } +} \ No newline at end of file diff --git a/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/data/model/APIKey.java b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/data/model/APIKey.java new file mode 100644 index 0000000..2c5b664 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/data/model/APIKey.java @@ -0,0 +1,33 @@ +package com.example.lecture_13.data.model; + +import java.time.LocalDateTime; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Entity +@Table(name = "APIKey") +public class APIKey { + + @Id + @Column(name = "ID", columnDefinition = "BIGINT", updatable = false, nullable = false) + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + private String apiKey; + private String username; // Added username field + private String description; + private LocalDateTime createdAt; + private LocalDateTime updatedAt; + private boolean active; + private LocalDateTime lastUsedAt; // Added last used field +} diff --git a/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/data/model/Customer.java b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/data/model/Customer.java new file mode 100644 index 0000000..9068525 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/data/model/Customer.java @@ -0,0 +1,51 @@ +package com.example.lecture_13.data.model; + +import java.util.Date; +import java.util.UUID; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Pattern; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Entity +@Table(name = "Customer") +public class Customer { + + @Id + @Column(name = "ID", columnDefinition = "BINARY(16)", updatable = false, nullable = false) + @GeneratedValue(strategy = GenerationType.UUID) + private UUID id; + + @NotBlank(message = "Name is mandatory") + @Pattern(regexp = "^[a-zA-Z\\s]+$", message = "Name can only contain letters and spaces") + @Column(name = "name", nullable = false) + private String name; + + @NotBlank(message = "Phone is mandatory") + @Pattern(regexp = "^\\+62[0-9]{9,13}$", message = "Phone number must start with +62 and contain 9 to 13 digits") + @Column(name = "phoneNumber", nullable = false) + private String phoneNumber; + + @Enumerated(EnumType.STRING) + @Column(name = "status", nullable = false) + private Status status = Status.Active; + + @Column(name = "createdAt", nullable = false) + private Date createdAt; + + @Column(name = "updatedAt", nullable = false) + private Date updatedAt; +} \ No newline at end of file diff --git a/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/data/model/Status.java b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/data/model/Status.java new file mode 100644 index 0000000..0fe8cb5 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/data/model/Status.java @@ -0,0 +1,6 @@ +package com.example.lecture_13.data.model; + +public enum Status { + Active, + Deactive +} diff --git a/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/data/repository/APIKeyRepository.java b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/data/repository/APIKeyRepository.java new file mode 100644 index 0000000..11b1163 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/data/repository/APIKeyRepository.java @@ -0,0 +1,21 @@ +package com.example.lecture_13.data.repository; + +import java.util.Optional; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import com.example.lecture_13.data.model.APIKey; + +@Repository +public interface APIKeyRepository extends JpaRepository { + + // Get the first API key, order by ID + Optional findFirstByOrderById(); + + // Find the first active API key + Optional findFirstByActiveTrueOrderById(); + + // Find the first active API key with a specific API key + Optional findFirstByApiKeyAndActiveTrue(String apiKey); +} \ No newline at end of file diff --git a/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/data/repository/CustomerRepository.java b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/data/repository/CustomerRepository.java new file mode 100644 index 0000000..54f6310 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/data/repository/CustomerRepository.java @@ -0,0 +1,18 @@ +package com.example.lecture_13.data.repository; + +import java.util.UUID; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import com.example.lecture_13.data.model.Customer; +import com.example.lecture_13.data.model.Status; + +@Repository +public interface CustomerRepository extends JpaRepository { + + // Find customer data by considering the status. + Page findByStatus(Status status, Pageable pageable); +} diff --git a/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/dto/CustomerDTO.java b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/dto/CustomerDTO.java new file mode 100644 index 0000000..a3081d5 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/dto/CustomerDTO.java @@ -0,0 +1,19 @@ +package com.example.lecture_13.dto; + +import com.example.lecture_13.data.model.Status; + +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.AllArgsConstructor; + +import java.util.UUID; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class CustomerDTO { + private UUID Id; + private String name; + private String phoneNumber; + private Status status; +} diff --git a/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/dto/CustomerSaveDTO.java b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/dto/CustomerSaveDTO.java new file mode 100644 index 0000000..276693f --- /dev/null +++ b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/dto/CustomerSaveDTO.java @@ -0,0 +1,27 @@ +package com.example.lecture_13.dto; + +import lombok.Data; +import lombok.NoArgsConstructor; +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; +import lombok.AllArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class CustomerSaveDTO { + + @NotBlank(message = "Name is mandatory") + @NotNull(message = "Name can't be NULL") + @Pattern(regexp = "^[a-zA-Z\\s]+$", message = "Name can only contain letters and spaces") + @Schema(example = "Your Name") + private String name; + + @NotBlank(message = "Phone is mandatory") + @NotNull(message = "Phone can't be NULL") + @Pattern(regexp = "^\\+62[0-9]{9,13}$", message = "Phone number must start with +62 and contain 9 to 13 digits") + @Schema(example = "+62xxxxxxxxxxxxx") + private String phoneNumber; +} diff --git a/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/dto/CustomerShowDTO.java b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/dto/CustomerShowDTO.java new file mode 100644 index 0000000..1f4cb67 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/dto/CustomerShowDTO.java @@ -0,0 +1,16 @@ +package com.example.lecture_13.dto; + +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.AllArgsConstructor; + +import java.util.UUID; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class CustomerShowDTO { + private UUID Id; + private String name; + private String phoneNumber; +} diff --git a/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/exception/BadRequestException.java b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/exception/BadRequestException.java new file mode 100644 index 0000000..645c68e --- /dev/null +++ b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/exception/BadRequestException.java @@ -0,0 +1,7 @@ +package com.example.lecture_13.exception; + +public class BadRequestException extends RuntimeException { + public BadRequestException(String message) { + super(message); + } +} diff --git a/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/exception/DuplicateStatusException.java b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/exception/DuplicateStatusException.java new file mode 100644 index 0000000..5f3f806 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/exception/DuplicateStatusException.java @@ -0,0 +1,7 @@ +package com.example.lecture_13.exception; + +public class DuplicateStatusException extends RuntimeException { + public DuplicateStatusException(String message) { + super(message); + } +} diff --git a/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/exception/GlobalExceptionHandler.java b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..b1fc0b4 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/exception/GlobalExceptionHandler.java @@ -0,0 +1,77 @@ +package com.example.lecture_13.exception; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.FieldError; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +@RestControllerAdvice +public class GlobalExceptionHandler { + + // Handle validation errors from @Valid annotated methods + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity>> handleValidationErrors(MethodArgumentNotValidException ex) { + List errors = ex.getBindingResult().getFieldErrors() + .stream().map(FieldError::getDefaultMessage).collect(Collectors.toList()); + return new ResponseEntity<>(getErrorsMap(errors), HttpStatus.BAD_REQUEST); + } + + private Map> getErrorsMap(List errors) { + Map> errorResponse = new HashMap<>(); + errorResponse.put("errors", errors); + return errorResponse; + } + + /** + * Handles generic exceptions by creating a response entity containing an error message. + * + * @param e the exception to handle + * @return a response entity containing a map with an error message + */ + @ExceptionHandler(Exception.class) + @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) + public ResponseEntity> handleException(Exception e) { + Map errorResponse = new HashMap<>(); + errorResponse.put("error", e.getMessage()); + return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR); + } + + // Custom exceptions + /** + * Handles {@link ResourceNotFoundException} by creating a response entity containing an error message. + * + * @param e the {@link ResourceNotFoundException} to handle + * @return a {@link ResponseEntity} containing a map with an error message + * @throws ResourceNotFoundException if the specified resource is not found + */ + @ExceptionHandler(ResourceNotFoundException.class) + @ResponseStatus(HttpStatus.NOT_FOUND) + public ResponseEntity> handleResourceNotFoundException(ResourceNotFoundException e) { + Map errorResponse = new HashMap<>(); + errorResponse.put("error", e.getMessage()); + return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND); + } + + /** + * Handles {@link BadRequestException} by creating a response entity containing an error message. + * + * @param e the {@link BadRequestException} to handle + * @return a {@link ResponseEntity} containing a map with an error message + */ + @ExceptionHandler(BadRequestException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public ResponseEntity> handleBadRequestException(BadRequestException e) { + Map errorResponse = new HashMap<>(); + errorResponse.put("error", e.getMessage()); + return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST); + } +} + diff --git a/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/exception/ResourceNotFoundException.java b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/exception/ResourceNotFoundException.java new file mode 100644 index 0000000..ad0e756 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/exception/ResourceNotFoundException.java @@ -0,0 +1,7 @@ +package com.example.lecture_13.exception; + +public class ResourceNotFoundException extends RuntimeException { + public ResourceNotFoundException(String message) { + super(message); + } +} diff --git a/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/mapper/CustomerMapper.java b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/mapper/CustomerMapper.java new file mode 100644 index 0000000..6ddfa82 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/mapper/CustomerMapper.java @@ -0,0 +1,40 @@ +package com.example.lecture_13.mapper; + +import com.example.lecture_13.data.model.Customer; +import com.example.lecture_13.dto.CustomerDTO; +import com.example.lecture_13.dto.CustomerShowDTO; +import com.example.lecture_13.dto.CustomerSaveDTO; + +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper(componentModel = "spring") +public interface CustomerMapper { + + CustomerMapper INSTANCE = Mappers.getMapper(CustomerMapper.class); + + // Customer - CustomerDTO + CustomerDTO toCustomerDTO(Customer customer); + + @Mapping(target = "createdAt", ignore = true) + @Mapping(target = "updatedAt", ignore = true) + Customer toCustomer(CustomerDTO customerDTO); + + // Customer - CustomerShowDTO + CustomerShowDTO toCustomerShowDTO(Customer customer); + + @Mapping(target = "status", ignore = true) + @Mapping(target = "createdAt", ignore = true) + @Mapping(target = "updatedAt", ignore = true) + Customer toCustomer(CustomerShowDTO customerShowDTO); + + // Customer - CustomerSaveDTO + CustomerSaveDTO toCustomerSaveDTO(Customer customer); + + @Mapping(target = "id", ignore = true) + @Mapping(target = "status", ignore = true) + @Mapping(target = "createdAt", ignore = true) + @Mapping(target = "updatedAt", ignore = true) + Customer toCustomer(CustomerSaveDTO customerSaveDTO); +} diff --git a/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/service/CustomerService.java b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/service/CustomerService.java new file mode 100644 index 0000000..d57b77e --- /dev/null +++ b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/service/CustomerService.java @@ -0,0 +1,35 @@ +package com.example.lecture_13.service; + +import java.util.UUID; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + +import com.example.lecture_13.data.model.Customer; +import com.example.lecture_13.data.model.Status; +import com.example.lecture_13.dto.CustomerDTO; +import com.example.lecture_13.dto.CustomerSaveDTO; +import com.example.lecture_13.dto.CustomerShowDTO; + +import jakarta.validation.Valid; + +public interface CustomerService { + + // Retrieves a paginated list of all customers. + Page findAllActiveCustomer(Pageable pageable); + + // Creating a new customer. + CustomerDTO createCustomer(@Valid CustomerSaveDTO customerSaveDTO); + + // Updates an existing customer with the provided customer details. + CustomerDTO updateCustomer(UUID id, @Valid CustomerSaveDTO customerSaveDTO); + + // Updates the status of an existing customer. + CustomerDTO updateCustomerStatus(UUID id, Status status); + + // Find customer by its id. + Customer findById(UUID id); + + // Deletes a customer from the repository. + void deleteCustomer(UUID id); +} \ No newline at end of file diff --git a/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/service/impl/CustomerServiceImpl.java b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/service/impl/CustomerServiceImpl.java new file mode 100644 index 0000000..a4ccaf7 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/java/com/example/lecture_13/service/impl/CustomerServiceImpl.java @@ -0,0 +1,129 @@ +package com.example.lecture_13.service.impl; + +import java.util.Date; +import java.util.UUID; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.validation.annotation.Validated; + +import com.example.lecture_13.data.model.Customer; +import com.example.lecture_13.data.model.Status; +import com.example.lecture_13.data.repository.CustomerRepository; +import com.example.lecture_13.dto.CustomerDTO; +import com.example.lecture_13.dto.CustomerSaveDTO; +import com.example.lecture_13.dto.CustomerShowDTO; +import com.example.lecture_13.exception.DuplicateStatusException; +import com.example.lecture_13.exception.ResourceNotFoundException; +import com.example.lecture_13.mapper.CustomerMapper; +import com.example.lecture_13.service.CustomerService; + +import jakarta.validation.Valid; + +@Service +@Validated +public class CustomerServiceImpl implements CustomerService { + + @Autowired + private CustomerMapper customerMapper; + + @Autowired + private CustomerRepository customerRepository; + + /** + * Retrieves a paginated list of all active customers from the repository. + * + * @param pageable The pagination parameters, including the page number and size. + * @return A Page object containing a list of {@link CustomerShowDTO} objects representing the customers on the specified page. + */ + @Override + public Page findAllActiveCustomer(Pageable pageable) { + return customerRepository.findByStatus(Status.Active, pageable).map(customerMapper::toCustomerShowDTO); + } + + /** + * Retrieves a customer from the repository based on the provided unique identifier. + * + * @param customerId The unique identifier of the customer to be retrieved. + * @return A {@link Customer} object representing the customer with the given ID. + * @throws ResourceNotFoundException if no customer is found with the given ID. + */ + @Override + public Customer findById(UUID customerId) { + return customerRepository.findById(customerId).orElseThrow(() -> new ResourceNotFoundException("Customer not found")); + } + + /** + * Creates a new customer in the repository and returns the corresponding {@link CustomerDTO} object. + * + * @param customerSaveDTO The {@link CustomerSaveDTO} object containing the details of the new customer to be created. + * @return A {@link CustomerDTO} object representing the newly created customer. + */ + @Override + public CustomerDTO createCustomer(@Valid CustomerSaveDTO customerSaveDTO) { + Customer customer = customerMapper.toCustomer(customerSaveDTO); + customer.setCreatedAt(new Date()); + customer.setUpdatedAt(new Date()); + Customer savedCustomer = customerRepository.save(customer); + return customerMapper.toCustomerDTO(savedCustomer); + } + + /** + * Updates an existing customer in the repository with the provided details from the {@link CustomerSaveDTO} object. + * + * @param id The unique identifier of the customer to be updated. + * @param customerSaveDTO The {@link CustomerSaveDTO} object containing the details of the customer to be updated. + * @return A {@link CustomerDTO} object representing the updated customer. + * @throws ResourceNotFoundException if the customer with the given ID is not found. + */ + @Override + public CustomerDTO updateCustomer(UUID id, @Valid CustomerSaveDTO customerSaveDTO) { + Customer customer = customerRepository.findById(id) + .orElseThrow(() -> new ResourceNotFoundException("Customer not found")); + + customer.setName(customerSaveDTO.getName()); + customer.setPhoneNumber(customerSaveDTO.getPhoneNumber()); + customer.setUpdatedAt(new Date()); + Customer updatedCustomer = customerRepository.save(customer); + return customerMapper.toCustomerDTO(updatedCustomer); + } + + /** + * Updates the status of an existing customer in the repository. + * + * @param id The unique identifier of the customer whose status is to be updated. + * @param status The new status to be assigned to the customer. + * @return A {@link CustomerDTO} object representing the updated customer. + * @throws ResourceNotFoundException if the customer with the given ID is not found. + * @throws DuplicateStatusException if the customer already has the specified status. + */ + @Override + public CustomerDTO updateCustomerStatus(UUID id, Status status) { + Customer customer = customerRepository.findById(id) + .orElseThrow(() -> new ResourceNotFoundException("Customer not found")); + + if (customer.getStatus() == status) { + throw new DuplicateStatusException("Customer status is already " + status); + } + + customer.setStatus(status); + customer.setUpdatedAt(new Date()); + Customer updatedCustomer = customerRepository.save(customer); + return customerMapper.toCustomerDTO(updatedCustomer); + } + + /** + * Deletes a customer from the repository based on the provided unique identifier. + * + * @param id The unique identifier of the customer to be deleted. + * @throws ResourceNotFoundException if no customer is found with the given ID. + */ + @Override + public void deleteCustomer(UUID id) { + Customer customer = customerRepository.findById(id) + .orElseThrow(() -> new ResourceNotFoundException("Customer not found")); + customerRepository.delete(customer); + } +} \ No newline at end of file diff --git a/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/resources/application.properties b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/resources/application.properties new file mode 100644 index 0000000..1aa55bc --- /dev/null +++ b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/resources/application.properties @@ -0,0 +1,31 @@ +spring.application.name=lecture_13 + +# Datasorce connection data +spring.config.import=file:env.properties +spring.datasource.url=${DB_DATABASE} +spring.datasource.username=${DB_USER} +spring.datasource.password=${DB_PASSWORD} +spring.datasource.driver-class-name=com.mysql.jdbc.Driver +spring.jpa.hibernate.ddl-auto=update + +# Enable SQL logging and show the statements and params + formatting +spring.jpa.show-sql=true +spring.jpa.properties.hibernate.format_sql=true +logging.level.org.hibernate.SQL=DEBUG +logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE + +# Swagger API documentation docs path +springdoc.api-docs.path=/api-docs + +# Enable the restart feature but exclude certain paths from triggering a restart +spring.devtools.restart.additional-paths=src/main/java +spring.devtools.restart.exclude=static/**,public/** + +# Enable the LiveReload feature +spring.devtools.livereload.enabled=true + +# Overriding bean +spring.main.allow-bean-definition-overriding=true + +# Port +server.port=${PORT} \ No newline at end of file diff --git a/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/resources/data.sql b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/resources/data.sql new file mode 100644 index 0000000..0338776 --- /dev/null +++ b/Week 08/Lecture 13/Assignment 03/lecture_13/src/main/resources/data.sql @@ -0,0 +1,57 @@ +-- Create the database +CREATE DATABASE week8_lecture13; + +-- Use the database +USE week8_lecture13; + +-- Initialize table with DDL +-- Create `Customer` table +CREATE TABLE Customer ( + ID BINARY(16) PRIMARY KEY, + name VARCHAR(255) NOT NULL, + phoneNumber VARCHAR(255), + status ENUM('Active', 'Deactivate') NOT NULL, + createdAt DATETIME, + updatedAt DATETIME +); + +-- Create `APIKey` table +CREATE TABLE APIKey ( + ID BIGINT AUTO_INCREMENT PRIMARY KEY, + api_key VARCHAR(255) NOT NULL, + description VARCHAR(255), -- Description or label for the API key + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, -- Timestamp of creation + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- Timestamp of last update + active BOOLEAN DEFAULT TRUE, -- Status to enable or disable the API key + last_used_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, -- Last time the API key was used + username VARCHAR(255) -- Username associated with the API key +); + +-- Initialize data on table with DML +-- Insert 20 customers +INSERT INTO Customer (ID, name, phone_number, status, created_at, updated_at) VALUES +(UUID_TO_BIN(UUID()), 'Alice Smith', '1234567890', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Bob Johnson', '0987654321', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Charlie Brown', '1122334455', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'David Wilson', '5566778899', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Eva Davis', '2233445566', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Frank Miller', '6677889900', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Grace Lee', '9988776655', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Hank Moore', '4455667788', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Ivy Taylor', '3344556677', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Jack Anderson', '7788990011', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Kara Thomas', '9988771122', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Leo Harris', '4455662233', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Mona Clark', '5566773344', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Nate Lewis', '3344558899', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Olivia Hall', '1122336677', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Paul Young', '8899001122', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Quinn Walker', '2233447788', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Rachel Allen', '6677883344', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Sam King', '9988773344', 'Active', NOW(), NOW()), +(UUID_TO_BIN(UUID()), 'Tina Scott', '5566778899', 'Active', NOW(), NOW()); + +-- Prepare API Keys +INSERT INTO APIKey (api_key, description, created_at, updated_at, active) VALUES +('12345-ABCDE', 'Primary API Key for System Access', NOW(), NOW(), TRUE), +('67890-FGHIJ', 'Secondary API Key for Testing', NOW(), NOW(), FALSE); \ No newline at end of file diff --git a/Week 08/Lecture 13/Assignment 03/lecture_13/src/test/java/com/example/lecture_13/Lecture13ApplicationTests.java b/Week 08/Lecture 13/Assignment 03/lecture_13/src/test/java/com/example/lecture_13/Lecture13ApplicationTests.java new file mode 100644 index 0000000..14fdbea --- /dev/null +++ b/Week 08/Lecture 13/Assignment 03/lecture_13/src/test/java/com/example/lecture_13/Lecture13ApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.lecture_13; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class Lecture13ApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/.gitignore b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/.mvn/wrapper/maven-wrapper.properties b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..8f96f52 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.7/apache-maven-3.9.7-bin.zip diff --git a/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/mvnw b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/mvnw new file mode 100644 index 0000000..d7c358e --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/mvnw @@ -0,0 +1,259 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.2 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/mvnw.cmd b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/mvnw.cmd new file mode 100644 index 0000000..6f779cf --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/mvnw.cmd @@ -0,0 +1,149 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.2 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' +$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/pom.xml b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/pom.xml new file mode 100644 index 0000000..9f93916 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/pom.xml @@ -0,0 +1,106 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 3.3.2 + + + + com.example + feignClientDemo + 1.0-SNAPSHOT + feignClientDemo + OpenFeign project for Spring Boot + + + + + + + + + + + + + + + 21 + 2023.0.3 + 3.0.1 + + + + + + org.springframework.cloud + spring-cloud-dependencies + 2023.0.3 + pom + import + + + + + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-web + + + + + org.springframework.cloud + spring-cloud-starter-openfeign + 4.1.3 + + + io.github.openfeign + feign-okhttp + + + + + org.apache.httpcomponents + httpclient + 4.5.13 + + + + + org.springframework.boot + spring-boot-starter-test + test + + + com.github.tomakehurst + wiremock-jre8 + 3.0.1 + test + + + junit + junit + 4.13.2 + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/FeignClientDemoApplication.java b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/FeignClientDemoApplication.java new file mode 100644 index 0000000..56d34cf --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/FeignClientDemoApplication.java @@ -0,0 +1,15 @@ +package com.example.feignClientDemo; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.openfeign.EnableFeignClients; + +@SpringBootApplication +@EnableFeignClients +public class FeignClientDemoApplication { + + public static void main(String[] args) { + SpringApplication.run(FeignClientDemoApplication.class, args); + } + +} diff --git a/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/client/AlbumClient.java b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/client/AlbumClient.java new file mode 100644 index 0000000..a6e542b --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/client/AlbumClient.java @@ -0,0 +1,16 @@ +package com.example.feignClientDemo.client; + +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; + +import com.example.feignClientDemo.model.Album; + +@FeignClient(name = "albumClient", url = "https://jsonplaceholder.typicode.com/albums/") +public interface AlbumClient { + @GetMapping(value = "/{id}") + Album getAlbumById(@PathVariable(value = "id") Integer id); + + @GetMapping(value = "/{id}") + Album getAlbumByIdAndDynamicUrl(@PathVariable(name = "id") Integer id); +} diff --git a/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/client/JSONPlaceHolderClient.java b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/client/JSONPlaceHolderClient.java new file mode 100644 index 0000000..2bd8a77 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/client/JSONPlaceHolderClient.java @@ -0,0 +1,22 @@ +package com.example.feignClientDemo.client; + +import java.util.List; + +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import com.example.feignClientDemo.config.ClientConfiguration; +import com.example.feignClientDemo.hystrix.JSONPlaceHolderFallback; +import com.example.feignClientDemo.model.Post; + +@FeignClient(value = "jplaceholder", url = "https://jsonplaceholder.typicode.com/", configuration = ClientConfiguration.class, fallback = JSONPlaceHolderFallback.class) +public interface JSONPlaceHolderClient { + + @RequestMapping(method = RequestMethod.GET, value = "/posts") + List getPosts(); + + @RequestMapping(method = RequestMethod.GET, value = "/posts/{postId}", produces = "application/json") + Post getPostById(@PathVariable("postId") Long postId); +} diff --git a/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/client/PostClient.java b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/client/PostClient.java new file mode 100644 index 0000000..d55db30 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/client/PostClient.java @@ -0,0 +1,13 @@ +package com.example.feignClientDemo.client; + +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; + +import com.example.feignClientDemo.model.Post; + +@FeignClient(name = "postClient", url = "${spring.cloud.openfeign.client.config.postClient.url}") +public interface PostClient { + @GetMapping(value = "/{id}") + Post getPostById(@PathVariable(value = "id") Integer id); +} diff --git a/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/client/TodoClient.java b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/client/TodoClient.java new file mode 100644 index 0000000..daf9f9c --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/client/TodoClient.java @@ -0,0 +1,15 @@ +package com.example.feignClientDemo.client; + +import java.net.URI; + +import org.springframework.cloud.openfeign.FeignClient; + +import com.example.feignClientDemo.model.Todo; + +import feign.RequestLine; + +@FeignClient(name = "todoClient") +public interface TodoClient { + @RequestLine(value = "GET") + Todo getTodoById(URI uri); +} diff --git a/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/config/ClientConfiguration.java b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/config/ClientConfiguration.java new file mode 100644 index 0000000..2d8c2a9 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/config/ClientConfiguration.java @@ -0,0 +1,42 @@ +package com.example.feignClientDemo.config; + +import org.apache.http.entity.ContentType; +import org.springframework.context.annotation.Bean; + +import feign.Logger; +import feign.RequestInterceptor; +import feign.auth.BasicAuthRequestInterceptor; +import feign.codec.ErrorDecoder; +import feign.okhttp.OkHttpClient; + +public class ClientConfiguration { + + @Bean + public Logger.Level feignLoggerLevel() { + return Logger.Level.FULL; + } + + @Bean + public ErrorDecoder errorDecoder() { + return new CustomErrorDecoder(); + } + + @Bean + public OkHttpClient client() { + return new OkHttpClient(); + } + + @Bean + public RequestInterceptor requestInterceptor() { + return requestTemplate -> { + requestTemplate.header("user", "ajeje"); + requestTemplate.header("password", "brazof"); + requestTemplate.header("Accept", ContentType.APPLICATION_JSON.getMimeType()); + }; + } + + // @Bean - uncomment to use this interceptor and remove @Bean from the requestInterceptor() + public BasicAuthRequestInterceptor basicAuthRequestInterceptor() { + return new BasicAuthRequestInterceptor("ajeje", "brazof"); + } +} diff --git a/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/config/CustomErrorDecoder.java b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/config/CustomErrorDecoder.java new file mode 100644 index 0000000..b481fbb --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/config/CustomErrorDecoder.java @@ -0,0 +1,19 @@ +package com.example.feignClientDemo.config; + +import com.example.feignClientDemo.exception.BadRequestException; +import com.example.feignClientDemo.exception.NotFoundException; + +import feign.Response; +import feign.codec.ErrorDecoder; + +public class CustomErrorDecoder implements ErrorDecoder { + @Override + public Exception decode(String methodKey, Response response) { + + return switch (response.status()) { + case 400 -> new BadRequestException(); + case 404 -> new NotFoundException("Not found !!!"); + default -> new Exception("Generic error"); + }; + } +} diff --git a/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/config/DynamicUrlInterceptor.java b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/config/DynamicUrlInterceptor.java new file mode 100644 index 0000000..4c6fce1 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/config/DynamicUrlInterceptor.java @@ -0,0 +1,23 @@ +package com.example.feignClientDemo.config; + +import java.util.function.Supplier; + +import feign.RequestInterceptor; +import feign.RequestTemplate; + +public class DynamicUrlInterceptor implements RequestInterceptor { + + private final Supplier urlSupplier; + + public DynamicUrlInterceptor(Supplier urlSupplier) { + this.urlSupplier = urlSupplier; + } + + @Override + public void apply(RequestTemplate template) { + String url = urlSupplier.get(); + if (url != null) { + template.target(url); + } + } +} diff --git a/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/controller/ConfigureFeignUrlController.java b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/controller/ConfigureFeignUrlController.java new file mode 100644 index 0000000..2771c4c --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/controller/ConfigureFeignUrlController.java @@ -0,0 +1,84 @@ +package com.example.feignClientDemo.controller; + +import java.net.URI; + +import org.springframework.beans.factory.ObjectFactory; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.boot.autoconfigure.http.HttpMessageConverters; +import org.springframework.cloud.openfeign.FeignClientsConfiguration; +import org.springframework.cloud.openfeign.support.HttpMessageConverterCustomizer; +import org.springframework.cloud.openfeign.support.SpringDecoder; +import org.springframework.cloud.openfeign.support.SpringEncoder; +import org.springframework.cloud.openfeign.support.SpringMvcContract; +import org.springframework.context.annotation.Import; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +import com.example.feignClientDemo.client.AlbumClient; +import com.example.feignClientDemo.client.PostClient; +import com.example.feignClientDemo.client.TodoClient; +import com.example.feignClientDemo.config.DynamicUrlInterceptor; +import com.example.feignClientDemo.model.Album; +import com.example.feignClientDemo.model.Post; +import com.example.feignClientDemo.model.Todo; + +import feign.Feign; +import feign.Target; +import feign.codec.Decoder; +import feign.codec.Encoder; + +@RestController +@Import(FeignClientsConfiguration.class) +public class ConfigureFeignUrlController { + private final AlbumClient albumClient; + + private final PostClient postClient; + + private final TodoClient todoClient; + + private final ObjectFactory messageConverters; + + private final ObjectProvider customizers; + + public ConfigureFeignUrlController(AlbumClient albumClient, + PostClient postClient, + Decoder decoder, + Encoder encoder, + ObjectFactory messageConverters, ObjectProvider customizers) { + this.albumClient = albumClient; + this.postClient = postClient; + this.messageConverters = messageConverters; + this.customizers = customizers; + this.todoClient = Feign.builder().encoder(encoder).decoder(decoder).target(Target.EmptyTarget.create(TodoClient.class)); + } + + @GetMapping(value = "albums/{id}") + public Album getAlbumById(@PathVariable(value = "id") Integer id) { + return albumClient.getAlbumById(id); + } + + @GetMapping(value = "posts/{id}") + public Post getPostById(@PathVariable(value = "id") Integer id) { + return postClient.getPostById(id); + } + + @GetMapping(value = "todos/{id}") + public Todo getTodoById(@PathVariable(value = "id") Integer id) { + return todoClient.getTodoById(URI.create("https://jsonplaceholder.typicode.com/todos/" + id)); + } + + @GetMapping(value = "/dynamicAlbums/{id}") + public Album getAlbumByIdAndDynamicUrl(@PathVariable(value = "id") Integer id) { + AlbumClient client = Feign.builder() + .requestInterceptor(new DynamicUrlInterceptor(() -> "https://jsonplaceholder.typicode.com/albums/")) + .contract(new SpringMvcContract()) + .encoder(new SpringEncoder(messageConverters)) + .decoder(new SpringDecoder(messageConverters, customizers)) + .target(Target.EmptyTarget.create(AlbumClient.class)); + + return client.getAlbumByIdAndDynamicUrl(id); + } +} + + diff --git a/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/exception/BadRequestException.java b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/exception/BadRequestException.java new file mode 100644 index 0000000..77565ef --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/exception/BadRequestException.java @@ -0,0 +1,20 @@ +package com.example.feignClientDemo.exception; + +public class BadRequestException extends Exception { + + public BadRequestException() { + } + + public BadRequestException(String message) { + super(message); + } + + public BadRequestException(Throwable cause) { + super(cause); + } + + @Override + public String toString() { + return "BadRequestException: "+getMessage(); + } +} \ No newline at end of file diff --git a/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/exception/NotFoundException.java b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/exception/NotFoundException.java new file mode 100644 index 0000000..4237b94 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/exception/NotFoundException.java @@ -0,0 +1,17 @@ +package com.example.feignClientDemo.exception; + +public class NotFoundException extends Exception { + + public NotFoundException(String message) { + super(message); + } + + public NotFoundException(Throwable cause) { + super(cause); + } + + @Override + public String toString() { + return "NotFoundException: " + getMessage(); + } +} diff --git a/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/hystrix/JSONPlaceHolderFallback.java b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/hystrix/JSONPlaceHolderFallback.java new file mode 100644 index 0000000..6f61a2b --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/hystrix/JSONPlaceHolderFallback.java @@ -0,0 +1,23 @@ +package com.example.feignClientDemo.hystrix; + +import java.util.Collections; +import java.util.List; + +import org.springframework.stereotype.Component; + +import com.example.feignClientDemo.client.JSONPlaceHolderClient; +import com.example.feignClientDemo.model.Post; + +@Component +public class JSONPlaceHolderFallback implements JSONPlaceHolderClient { + + @Override + public List getPosts() { + return Collections.emptyList(); + } + + @Override + public Post getPostById(Long postId) { + return null; + } +} diff --git a/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/model/Album.java b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/model/Album.java new file mode 100644 index 0000000..250bc55 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/model/Album.java @@ -0,0 +1,32 @@ +package com.example.feignClientDemo.model; + +public class Album { + + private Integer id; + private Integer userId; + private String title; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public Integer getUserId() { + return userId; + } + + public void setUserId(Integer userId) { + this.userId = userId; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } +} diff --git a/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/model/Post.java b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/model/Post.java new file mode 100644 index 0000000..6ca244e --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/model/Post.java @@ -0,0 +1,41 @@ +package com.example.feignClientDemo.model; + +public class Post { + + private String userId; + private Long id; + private String title; + private String body; + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getBody() { + return body; + } + + public void setBody(String body) { + this.body = body; + } +} diff --git a/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/model/Todo.java b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/model/Todo.java new file mode 100644 index 0000000..c5d638b --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/model/Todo.java @@ -0,0 +1,40 @@ +package com.example.feignClientDemo.model; + +public class Todo { + private Integer id; + private Integer userId; + private String title; + private Boolean completed; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public Integer getUserId() { + return userId; + } + + public void setUserId(Integer userId) { + this.userId = userId; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public Boolean getCompleted() { + return completed; + } + + public void setCompleted(Boolean completed) { + this.completed = completed; + } +} \ No newline at end of file diff --git a/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/patcherror/client/UserClient.java b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/patcherror/client/UserClient.java new file mode 100644 index 0000000..bb18fe8 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/patcherror/client/UserClient.java @@ -0,0 +1,16 @@ +package com.example.feignClientDemo.patcherror.client; + +import com.example.feignClientDemo.patcherror.model.User; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +@FeignClient(name = "user-client", url = "${user.api.url}") +public interface UserClient { + + @RequestMapping(value = "{userId}", method = RequestMethod.PATCH) + User updateUser(@PathVariable(value = "userId") String userId, @RequestBody User user); + +} diff --git a/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/patcherror/model/User.java b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/patcherror/model/User.java new file mode 100644 index 0000000..7b8021c --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/patcherror/model/User.java @@ -0,0 +1,34 @@ +package com.example.feignClientDemo.patcherror.model; + +public class User { + + private String userId; + + private String userName; + + private String email; + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } +} diff --git a/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/service/JSONPlaceHolderService.java b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/service/JSONPlaceHolderService.java new file mode 100644 index 0000000..209da25 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/service/JSONPlaceHolderService.java @@ -0,0 +1,12 @@ +package com.example.feignClientDemo.service; + +import java.util.List; + +import com.example.feignClientDemo.model.Post; + +public interface JSONPlaceHolderService { + + List getPosts(); + + Post getPostById(Long id); +} \ No newline at end of file diff --git a/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/service/impl/JSONPlaceHolderServiceImpl.java b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/service/impl/JSONPlaceHolderServiceImpl.java new file mode 100644 index 0000000..a9ddd7d --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/java/com/example/feignClientDemo/service/impl/JSONPlaceHolderServiceImpl.java @@ -0,0 +1,27 @@ +package com.example.feignClientDemo.service.impl; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.example.feignClientDemo.client.JSONPlaceHolderClient; +import com.example.feignClientDemo.model.Post; +import com.example.feignClientDemo.service.JSONPlaceHolderService; + +@Service +public class JSONPlaceHolderServiceImpl implements JSONPlaceHolderService { + + @Autowired + private JSONPlaceHolderClient jsonPlaceHolderClient; + + @Override + public List getPosts() { + return jsonPlaceHolderClient.getPosts(); + } + + @Override + public Post getPostById(Long id) { + return jsonPlaceHolderClient.getPostById(id); + } +} \ No newline at end of file diff --git a/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/resources/application.properties b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/resources/application.properties new file mode 100644 index 0000000..8b35812 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/main/resources/application.properties @@ -0,0 +1,10 @@ +spring.application.name=feignClientDemo +user.api.url=http://localhost:8080/api/user +feign.okhttp.enabled=true + +server.port=8085 +spring.main.allow-bean-definition-overriding=true +logging.level.com.example.feignClientDemo.cloud.openfeign.client=INFO +feign.hystrix.enabled=true + +spring.cloud.openfeign.client.config.postClient.url=https://jsonplaceholder.typicode.com/posts/ \ No newline at end of file diff --git a/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/test/java/com/example/feignClientDemo/OpenFeignManualTest.java b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/test/java/com/example/feignClientDemo/OpenFeignManualTest.java new file mode 100644 index 0000000..5fb1bed --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/test/java/com/example/feignClientDemo/OpenFeignManualTest.java @@ -0,0 +1,44 @@ +package com.example.feignClientDemo; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; + +import java.util.List; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.example.feignClientDemo.model.Post; +import com.example.feignClientDemo.service.JSONPlaceHolderService; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class OpenFeignManualTest { + + @Autowired + private JSONPlaceHolderService jsonPlaceHolderService; + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + + @Test + public void whenGetPosts_thenListPostSizeGreaterThanZero() { + + List posts = jsonPlaceHolderService.getPosts(); + + assertFalse(posts.isEmpty()); + } + + @Test + public void whenGetPostWithId_thenPostExist() { + + Post post = jsonPlaceHolderService.getPostById(1L); + + assertNotNull(post); + } + +} diff --git a/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/test/java/com/example/feignClientDemo/SpringContextTest.java b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/test/java/com/example/feignClientDemo/SpringContextTest.java new file mode 100644 index 0000000..cc42913 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/FeignClientDemo/feignClientDemo/src/test/java/com/example/feignClientDemo/SpringContextTest.java @@ -0,0 +1,15 @@ +package com.example.feignClientDemo; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = FeignClientDemoApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/Week 08/Lecture 14/Assignment 01/README.md b/Week 08/Lecture 14/Assignment 01/README.md new file mode 100644 index 0000000..ff1e325 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/README.md @@ -0,0 +1,148 @@ +# πŸ‘¨πŸ»β€πŸ« Lecture 14 - Spring Advanced Features: FeignClient, RestTemplate, WebClient + +> This repository is created as a part of an assignment for Lecture 14 on Spring Advanced Features: FeignClient, RestTemplate, WebClient. + +## πŸ’‘ Assignment 01 - FeignClient, RestTemplate, WebClient + +### 🧐 What are FeignClient, RestTemplate, and WebClient? + +Spring offers several tools for making HTTP requests to external services or APIs. Each tool has its own strengths and is suited for different use cases: + +- **FeignClient**: A declarative web service client that simplifies HTTP API calls by reducing the amount of boilerplate code required. It integrates seamlessly with Spring Cloud for easy integration with microservices. + + **Syntax Example**: + ```java + @FeignClient(name = "inventory-service", url = "http://inventory-service") + public interface InventoryClient { + + @GetMapping("/inventory/{productId}") + InventoryResponse getInventory(@PathVariable("productId") String productId); + } + ``` + +- **RestTemplate**: A synchronous HTTP client that provides a straightforward way to consume RESTful services. It's been a staple in Spring for many years, known for its simplicity and ease of use. + + **Syntax Example**: + ```java + @Bean + public RestTemplate restTemplate() { + return new RestTemplate(); + } + + // Usage + ResponseEntity response = restTemplate.getForEntity("http://example.com/api/resource", String.class); + ``` + +- **WebClient**: A modern, reactive, and non-blocking HTTP client designed to work well with the Spring WebFlux framework. It supports asynchronous and streaming scenarios, making it ideal for reactive programming. + + **Syntax Example**: + ```java + @Bean + public WebClient webClient() { + return WebClient.builder().baseUrl("http://example.com").build(); + } + + // Usage + Mono response = webClient.get() + .uri("/api/resource") + .retrieve() + .bodyToMono(String.class); + ``` + +### ❓ What are the Differences? + +Understanding the differences between FeignClient, RestTemplate, and WebClient helps in choosing the right tool for your specific needs: + +- **Declarative vs. Programmatic**: + - **FeignClient** is declarative, allowing you to define API clients using interfaces. + - **RestTemplate** and **WebClient** require more programmatic control but offer greater flexibility. + +- **Synchronous vs. Asynchronous**: + - **FeignClient** and **RestTemplate** are synchronous, meaning they block the calling thread until the response is received. + - **WebClient** supports both synchronous and asynchronous operations, making it suitable for reactive and non-blocking scenarios. + +- **Reactive Support**: + - **WebClient** is designed with reactive programming in mind and works seamlessly with Project Reactor and Spring WebFlux. + - **FeignClient** and **RestTemplate** are more traditional and do not support reactive paradigms. + +Here's a table summarizing these differences: + +| Feature | FeignClient | RestTemplate | WebClient | +|-------------------|------------------------------------------------|------------------------------------------------|-------------------------------------------------| +| **Declarative API** | Yes | No | Yes | +| **Asynchronous** | No | No | Yes | +| **Reactive Support** | No | No | Yes | +| **HTTP Methods** | Limited (GET, POST, etc.) | Full control | Full control | + +### πŸ€” Use Cases + +- **FeignClient**: Ideal for microservices architectures where you need to make simple, declarative HTTP requests. For example, when one microservice needs to call another microservice, FeignClient provides a clean and easy-to-understand interface. + + **Real Case**: In a microservices setup for an e-commerce application, a `PaymentService` might need to call an external `InventoryService` to check stock levels. Using FeignClient simplifies this inter-service communication. + +- **RestTemplate**: Best suited for straightforward, synchronous HTTP operations. It's often used in scenarios where you need to make blocking calls to RESTful services and handle simple request-response cycles. + + **Real Case**: When building a server-side application that needs to fetch data from an external weather API and display it on a dashboard, RestTemplate offers a simple way to make these HTTP calls and process the responses. + +- **WebClient**: Perfect for handling asynchronous and streaming scenarios, especially in reactive applications. It is the go-to choice for non-blocking I/O operations and integrating with reactive streams. + + **Real Case**: In a real-time chat application, WebClient can be used to stream data from a messaging service, allowing for asynchronous communication and real-time updates without blocking the main thread. + +### πŸ—‚οΈ List of Projects + +To provide clear examples and explanations, each project is organized separately: + +1. **FeignClient Demo** + - **Directory**: [feignClientDemo](/Week%2008/Lecture%2014/Assignment%2001/FeignClientDemo/feignClientDemo) + - **Inspiration**: [Baeldung FeignClient Guide](https://www.baeldung.com/spring-cloud-openfeign​) + - **Description**: Demonstrates how to use FeignClient to make HTTP requests using a declarative approach. Includes examples of GET and POST requests. + + **Key Points**: + - Declarative API definition + - Simplified microservices communication + - Integration with Spring Cloud + +2. **RestTemplate Demo** + - **Directories**: + - [RestTemplateDemo](/Week%2008/Lecture%2014/Assignment%2001/RestTemplateDemo/restTemplateDemo) + - [RestTemplateDemo1](/Week%2008/Lecture%2014/Assignment%2001/RestTemplateDemo/restTemplateDemo1) + - **Inspiration**: [Baeldung RestTemplate Guide](https://www.baeldung.com/rest-template​) and [Handling Lists with RestTemplate](https://www.baeldung.com/resttemplate-list​​) + - **Description**: Provides examples of how to use RestTemplate for synchronous HTTP requests. Includes scenarios for GET, POST, PUT, and DELETE operations, as well as handling complex responses. + + **Key Points**: + - Synchronous HTTP operations + - Handling various HTTP methods + - Processing complex responses + +3. **WebClient Demo** + - **Directory**: [webClientDemo](/Week%2008/Lecture%2014/Assignment%2001/WebClientDemo/webClientDemo) + - **Inspiration**: [Baeldung WebClient Guide](https://www.baeldung.com/spring-webclient-json-list​) + - **Description**: Showcases the capabilities of WebClient for asynchronous and reactive programming. Demonstrates how to handle various HTTP methods and stream data efficiently. + + **Key Points**: + - Asynchronous and reactive programming + - Streaming data handling + - Integration with Spring WebFlux + +### βš™οΈ How to run the program + +1. Navigate to the desired directory. For example, to run the WebClient demo: + ```bash + $ cd WebClientDemo/webClientDemo + ``` + +2. Ensure Maven is installed. Check the version with: + ```bash + $ mvn -v + ``` + +3. Execute the unit tests to verify functionalities: + ```bash + $ mvn test + ``` + +### πŸš€ Demonstration + +Here are the results from demonstrating all functionalities in the WebClientDemo project: + +![Demo](/Week%2008/Lecture%2014/Assignment%2001/img/demo.png) \ No newline at end of file diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/.mvn/wrapper/maven-wrapper.properties b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..8f96f52 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.7/apache-maven-3.9.7-bin.zip diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/mvnw b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/mvnw new file mode 100644 index 0000000..d7c358e --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/mvnw @@ -0,0 +1,259 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.2 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/mvnw.cmd b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/mvnw.cmd new file mode 100644 index 0000000..6f779cf --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/mvnw.cmd @@ -0,0 +1,149 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.2 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' +$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/pom.xml b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/pom.xml new file mode 100644 index 0000000..106b2f3 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/pom.xml @@ -0,0 +1,224 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.3.2 + + + com.example + restTemplateDemo + 0.0.1-SNAPSHOT + restTemplateDemo + Demo project for Spring Boot + + + + + + + + + + + + + + + 21 + 1.4.20 + + 1.6.1 + + 4.12.0 + 33.2.1-jre + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-actuator + + + com.thoughtworks.xstream + xstream + ${xstream.version} + + + + com.google.guava + guava + ${guava.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + com.squareup.okhttp3 + okhttp + ${com.squareup.okhttp3.version} + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + spring-resttemplate + + + src/main/resources + true + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + + + org.apache.maven.plugins + maven-war-plugin + + + org.apache.maven.plugins + maven-surefire-plugin + + 3 + true + + **/*IntegrationTest.java + **/*IntTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/JdbcTest.java + **/*LiveTest.java + + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + tomcat8x + embedded + + + + + + + 8082 + + + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*IntegrationTest.java + **/*IntTest.java + + + + + + + + + + live + + + + org.codehaus.cargo + cargo-maven2-plugin + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*LiveTest.java + + + cargo + + + + + + + + + + diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/mock/EmployeeService.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/mock/EmployeeService.java new file mode 100644 index 0000000..a24280f --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/mock/EmployeeService.java @@ -0,0 +1,26 @@ +package com.example.restTemplateDemo.mock; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; + +import com.example.restTemplateDemo.resttemplate.web.model.Employee; + +@Service +public class EmployeeService { + + static final String EMP_URL_PREFIX = "http://localhost:8080/employee"; + static final String URL_SEP = "/"; + + // private static final Logger logger = LoggerFactory.getLogger(EmployeeService.class); + + @Autowired + private RestTemplate restTemplate; + + public Employee getEmployee(String id) { + ResponseEntity resp = restTemplate.getForEntity(EMP_URL_PREFIX + URL_SEP + id, Employee.class); + return resp.getStatusCode() == HttpStatus.OK ? resp.getBody() : null; + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/resttemplate/RestTemplateConfigurationApplication.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/resttemplate/RestTemplateConfigurationApplication.java new file mode 100644 index 0000000..0a75f16 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/resttemplate/RestTemplateConfigurationApplication.java @@ -0,0 +1,14 @@ +package com.example.restTemplateDemo.resttemplate; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +@EnableAutoConfiguration +public class RestTemplateConfigurationApplication { + + public static void main(String[] args) { + SpringApplication.run(RestTemplateConfigurationApplication.class, args); + } +} \ No newline at end of file diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/resttemplate/web/dto/Foo.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/resttemplate/web/dto/Foo.java new file mode 100644 index 0000000..eced2a7 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/resttemplate/web/dto/Foo.java @@ -0,0 +1,43 @@ +package com.example.restTemplateDemo.resttemplate.web.dto; + +import com.thoughtworks.xstream.annotations.XStreamAlias; + +@XStreamAlias("Foo") +public class Foo { + private long id; + private String name; + + public Foo() { + super(); + } + + public Foo(final String name) { + super(); + + this.name = name; + } + + public Foo(final long id, final String name) { + super(); + + this.id = id; + this.name = name; + } + + // API + public long getId() { + return id; + } + + public void setId(final long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } +} \ No newline at end of file diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/resttemplate/web/exception/NotFoundException.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/resttemplate/web/exception/NotFoundException.java new file mode 100644 index 0000000..fc18c0f --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/resttemplate/web/exception/NotFoundException.java @@ -0,0 +1,4 @@ +package com.example.restTemplateDemo.resttemplate.web.exception; + +public class NotFoundException extends RuntimeException { +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/resttemplate/web/handler/RestTemplateRespErrorHandler.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/resttemplate/web/handler/RestTemplateRespErrorHandler.java new file mode 100644 index 0000000..889b81e --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/resttemplate/web/handler/RestTemplateRespErrorHandler.java @@ -0,0 +1,37 @@ +package com.example.restTemplateDemo.resttemplate.web.handler; + +import java.io.IOException; + +import org.springframework.http.HttpStatus; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.stereotype.Component; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.ResponseErrorHandler; + +import com.example.restTemplateDemo.resttemplate.web.exception.NotFoundException; + +@Component +public class RestTemplateRespErrorHandler implements ResponseErrorHandler { + + @Override + public boolean hasError(ClientHttpResponse httpResponse) throws IOException { + return httpResponse.getStatusCode() + .is5xxServerError() || httpResponse.getStatusCode() + .is4xxClientError(); + } + + @Override + public void handleError(ClientHttpResponse httpResponse) throws IOException { + if (httpResponse.getStatusCode() + .is5xxServerError()) { + //Handle SERVER_ERROR + throw new HttpClientErrorException(httpResponse.getStatusCode()); + } else if (httpResponse.getStatusCode() + .is4xxClientError()) { + //Handle CLIENT_ERROR + if (httpResponse.getStatusCode() == HttpStatus.NOT_FOUND) { + throw new NotFoundException(); + } + } + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/resttemplate/web/model/Bar.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/resttemplate/web/model/Bar.java new file mode 100644 index 0000000..863db29 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/resttemplate/web/model/Bar.java @@ -0,0 +1,22 @@ +package com.example.restTemplateDemo.resttemplate.web.model; + +public class Bar { + private String id; + private String name; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/resttemplate/web/model/Employee.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/resttemplate/web/model/Employee.java new file mode 100644 index 0000000..ff8b98c --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/resttemplate/web/model/Employee.java @@ -0,0 +1,47 @@ +package com.example.restTemplateDemo.resttemplate.web.model; + +import java.util.Objects; + +public class Employee { + + private String id; + private String name; + + public Employee(String id, String name) { + this.id = id; + this.name = name; + } + + public Employee() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + Employee employee = (Employee) o; + return Objects.equals(id, employee.id); + } + + @Override public int hashCode() { + + return Objects.hash(id); + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/resttemplate/web/service/BarConsumerService.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/resttemplate/web/service/BarConsumerService.java new file mode 100644 index 0000000..5727b3a --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/resttemplate/web/service/BarConsumerService.java @@ -0,0 +1,26 @@ +package com.example.restTemplateDemo.resttemplate.web.service; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; + +import com.example.restTemplateDemo.resttemplate.web.handler.RestTemplateRespErrorHandler; +import com.example.restTemplateDemo.resttemplate.web.model.Bar; + +@Service +public class BarConsumerService { + + private final RestTemplate restTemplate; + + @Autowired + public BarConsumerService(RestTemplateBuilder restTemplateBuilder) { + restTemplate = restTemplateBuilder + .errorHandler(new RestTemplateRespErrorHandler()) + .build(); + } + + public Bar fetchBarById(String barId) { + return restTemplate.getForObject("/bars/4242", Bar.class); + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/MainApplication.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/MainApplication.java new file mode 100644 index 0000000..ad6563c --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/MainApplication.java @@ -0,0 +1,15 @@ +package com.example.restTemplateDemo.sampleapp; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@EnableAutoConfiguration +@ComponentScan("com.example.restTemplateDemo.sampleapp") +public class MainApplication implements WebMvcConfigurer { + + public static void main(final String[] args) { + SpringApplication.run(MainApplication.class, args); + } +} \ No newline at end of file diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/config/RestClientConfig.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/config/RestClientConfig.java new file mode 100644 index 0000000..8c8024d --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/config/RestClientConfig.java @@ -0,0 +1,29 @@ +package com.example.restTemplateDemo.sampleapp.config; + +import java.util.ArrayList; +import java.util.List; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.client.ClientHttpRequestInterceptor; +import org.springframework.util.CollectionUtils; +import org.springframework.web.client.RestTemplate; + +import com.example.restTemplateDemo.sampleapp.interceptor.RestTemplateHeaderInterceptor; + +@Configuration +public class RestClientConfig { + + @Bean + public RestTemplate restTemplate() { + RestTemplate restTemplate = new RestTemplate(); + + List interceptors = restTemplate.getInterceptors(); + if (CollectionUtils.isEmpty(interceptors)) { + interceptors = new ArrayList<>(); + } + interceptors.add(new RestTemplateHeaderInterceptor()); + restTemplate.setInterceptors(interceptors); + return restTemplate; + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/config/WebConfig.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/config/WebConfig.java new file mode 100644 index 0000000..436f0db --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/config/WebConfig.java @@ -0,0 +1,16 @@ +package com.example.restTemplateDemo.sampleapp.config; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +@EnableWebMvc +@ComponentScan({ "com.example.restTemplateDemo.sampleapp.web" }) +public class WebConfig implements WebMvcConfigurer { + + public WebConfig() { + super(); + } +} \ No newline at end of file diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/interceptor/RestTemplateHeaderInterceptor.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/interceptor/RestTemplateHeaderInterceptor.java new file mode 100644 index 0000000..2c73a3d --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/interceptor/RestTemplateHeaderInterceptor.java @@ -0,0 +1,18 @@ +package com.example.restTemplateDemo.sampleapp.interceptor; + +import java.io.IOException; + +import org.springframework.http.HttpRequest; +import org.springframework.http.client.ClientHttpRequestExecution; +import org.springframework.http.client.ClientHttpRequestInterceptor; +import org.springframework.http.client.ClientHttpResponse; + +public class RestTemplateHeaderInterceptor implements ClientHttpRequestInterceptor { + + @Override + public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { + ClientHttpResponse response = execution.execute(request, body); + response.getHeaders().add("Foo", "bar"); + return response; + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/repository/HeavyResourceRepository.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/repository/HeavyResourceRepository.java new file mode 100644 index 0000000..4e74237 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/repository/HeavyResourceRepository.java @@ -0,0 +1,21 @@ +package com.example.restTemplateDemo.sampleapp.repository; + +import java.util.Map; + +import com.example.restTemplateDemo.sampleapp.web.dto.HeavyResource; +import com.example.restTemplateDemo.sampleapp.web.dto.HeavyResourceAddressOnly; + +public class HeavyResourceRepository { + + public void save(HeavyResource heavyResource, String id) { + } + + public void save(HeavyResourceAddressOnly partialUpdate) { + } + + public void save(Map updates, String id) { + } + + public void save(HeavyResourceAddressOnly partialUpdate, String id) { + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/controller/BarMappingExamplesController.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/controller/BarMappingExamplesController.java new file mode 100644 index 0000000..eb0cc68 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/controller/BarMappingExamplesController.java @@ -0,0 +1,43 @@ +package com.example.restTemplateDemo.sampleapp.web.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +@RequestMapping(value = "/ex") +public class BarMappingExamplesController { + + public BarMappingExamplesController() { + super(); + } + + // API + // with @RequestParam + @RequestMapping(value = "/bars") + @ResponseBody + public String getBarBySimplePathWithRequestParam(@RequestParam("id") final long id) { + return "Get a specific Bar with id=" + id; + } + + @RequestMapping(value = "/bars", params = "id") + @ResponseBody + public String getBarBySimplePathWithExplicitRequestParam(@RequestParam("id") final long id) { + return "Get a specific Bar with id=" + id; + } + + @RequestMapping(value = "/bars", params = { "id", "second" }) + @ResponseBody + public String getBarBySimplePathWithExplicitRequestParams(@RequestParam("id") final long id) { + return "Get a specific Bar with id=" + id; + } + + // with @PathVariable + @RequestMapping(value = "/bars/{numericId:[\\d]+}") + @ResponseBody + public String getBarsBySimplePathWithPathVariable(@PathVariable final long numericId) { + return "Get a specific Bar with id=" + numericId; + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/controller/CompanyController.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/controller/CompanyController.java new file mode 100644 index 0000000..9c4f5c2 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/controller/CompanyController.java @@ -0,0 +1,17 @@ +package com.example.restTemplateDemo.sampleapp.web.controller; + +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.example.restTemplateDemo.sampleapp.web.dto.Company; + +@RestController +public class CompanyController { + + @RequestMapping(value = "/companyRest", produces = MediaType.APPLICATION_JSON_VALUE) + public Company getCompanyRest() { + final Company company = new Company(1, "Xpto"); + return company; + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/controller/DeferredResultController.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/controller/DeferredResultController.java new file mode 100644 index 0000000..7ff0d20 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/controller/DeferredResultController.java @@ -0,0 +1,76 @@ +package com.example.restTemplateDemo.sampleapp.web.controller; + +import java.util.concurrent.CompletableFuture; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.context.request.async.DeferredResult; + +@RestController +public class DeferredResultController { + + private final static Logger LOG = LoggerFactory.getLogger(DeferredResultController.class); + + @GetMapping("/async-deferredresult") + public DeferredResult> handleReqDefResult(Model model) { + LOG.info("Received request"); + DeferredResult> deferredResult = new DeferredResult<>(); + + deferredResult.onCompletion(() -> LOG.info("Processing complete")); + + CompletableFuture.supplyAsync(() -> { + LOG.info("Processing in separate thread"); + try { + Thread.sleep(6000); + } catch (InterruptedException e) { + } + return "OK"; + }).whenCompleteAsync((result, exc) -> deferredResult.setResult(ResponseEntity.ok(result))); + + LOG.info("Servlet thread freed"); + return deferredResult; + } + + @GetMapping("/process-blocking") + public ResponseEntity handleReqSync(Model model) { + // ... + return ResponseEntity.ok("ok"); + } + + @GetMapping("/async-deferredresult-timeout") + public DeferredResult> handleReqWithTimeouts(Model model) { + LOG.info("Received async request with a configured timeout"); + DeferredResult> deferredResult = new DeferredResult<>(500l); + deferredResult.onTimeout(() -> deferredResult.setErrorResult(ResponseEntity.status(HttpStatus.REQUEST_TIMEOUT) + .body("Request timeout occurred."))); + + CompletableFuture.supplyAsync(() -> { + LOG.info("Processing in separate thread"); + try { + Thread.sleep(6000); + } catch (InterruptedException e) { + } + return "error"; + }) + .whenCompleteAsync((result, exc) -> deferredResult.setResult(ResponseEntity.ok(result))); + LOG.info("servlet thread freed"); + return deferredResult; + } + + @GetMapping("/async-deferredresult-error") + public DeferredResult> handleAsyncFailedRequest(Model model) { + LOG.info("Received async request with a configured error handler"); + DeferredResult> deferredResult = new DeferredResult<>(); + deferredResult.onError((Throwable t) -> { + deferredResult.setErrorResult(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body("An error occurred.")); + }); + LOG.info("servlet thread freed"); + return deferredResult; + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/controller/HeavyResourceController.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/controller/HeavyResourceController.java new file mode 100644 index 0000000..eab5a1a --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/controller/HeavyResourceController.java @@ -0,0 +1,40 @@ +package com.example.restTemplateDemo.sampleapp.web.controller; + +import java.util.Map; + +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import com.example.restTemplateDemo.sampleapp.repository.HeavyResourceRepository; +import com.example.restTemplateDemo.sampleapp.web.dto.HeavyResource; +import com.example.restTemplateDemo.sampleapp.web.dto.HeavyResourceAddressOnly; + +@RestController +public class HeavyResourceController { + + private final HeavyResourceRepository heavyResourceRepository = new HeavyResourceRepository(); + + @RequestMapping(value = "/heavyresource/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity saveResource(@RequestBody HeavyResource heavyResource, @PathVariable("id") String id) { + heavyResourceRepository.save(heavyResource, id); + return ResponseEntity.ok("resource saved"); + } + + @RequestMapping(value = "/heavyresource/{id}", method = RequestMethod.PATCH, consumes = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity partialUpdateName(@RequestBody HeavyResourceAddressOnly partialUpdate, @PathVariable("id") String id) { + heavyResourceRepository.save(partialUpdate, id); + return ResponseEntity.ok("resource address updated"); + } + + @RequestMapping(value = "/heavyresource2/{id}", method = RequestMethod.PATCH, consumes = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity partialUpdateGeneric(@RequestBody Map updates, + @PathVariable("id") String id) { + heavyResourceRepository.save(updates, id); + return ResponseEntity.ok("resource updated"); + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/controller/ItemController.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/controller/ItemController.java new file mode 100644 index 0000000..fecc47a --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/controller/ItemController.java @@ -0,0 +1,39 @@ +package com.example.restTemplateDemo.sampleapp.web.controller; + +import java.util.Date; + +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.example.restTemplateDemo.sampleapp.web.dto.Item; +import com.example.restTemplateDemo.sampleapp.web.dto.ItemManager; +import com.example.restTemplateDemo.sampleapp.web.dto.Views; +import com.fasterxml.jackson.annotation.JsonView; + +@RestController +public class ItemController { + + @JsonView(Views.Public.class) + @RequestMapping("/items/{id}") + public Item getItemPublic(@PathVariable final int id) { + return ItemManager.getById(id); + } + + @JsonView(Views.Internal.class) + @RequestMapping("/items/internal/{id}") + public Item getItemInternal(@PathVariable final int id) { + return ItemManager.getById(id); + } + + @RequestMapping("/date") + public Date getCurrentDate() throws Exception { + return new Date(); + } + + @RequestMapping("/delay/{seconds}") + public void getCurrentTime(@PathVariable final int seconds) throws Exception { + + Thread.sleep(seconds * 1000); + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/controller/MyFooController.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/controller/MyFooController.java new file mode 100644 index 0000000..9282887 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/controller/MyFooController.java @@ -0,0 +1,85 @@ +package com.example.restTemplateDemo.sampleapp.web.controller; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import com.example.restTemplateDemo.sampleapp.web.dto.Foo; +import com.example.restTemplateDemo.sampleapp.web.exception.ResourceNotFoundException; + +import jakarta.servlet.http.HttpServletResponse; + +@Controller +@RequestMapping(value = "/foo") +public class MyFooController { + + private final Map myfoos; + + public MyFooController() { + super(); + myfoos = new HashMap<>(); + myfoos.put(1L, new Foo(1L, "sample foo")); + } + + // API - read + + @RequestMapping(method = RequestMethod.GET, produces = { "application/json" }) + @ResponseBody + public Collection findAll() { + return myfoos.values(); + } + + @RequestMapping(method = RequestMethod.GET, value = "/{id}", produces = { "application/json" }) + @ResponseBody + public Foo findById(@PathVariable final long id) { + final Foo foo = myfoos.get(id); + if (foo == null) { + throw new ResourceNotFoundException(); + } + return foo; + } + + // API - write + + @RequestMapping(method = RequestMethod.PUT, value = "/{id}") + @ResponseStatus(HttpStatus.OK) + @ResponseBody + public Foo updateFoo(@PathVariable("id") final long id, @RequestBody final Foo foo) { + myfoos.put(id, foo); + return foo; + } + + @RequestMapping(method = RequestMethod.PATCH, value = "/{id}") + @ResponseStatus(HttpStatus.OK) + public void updateFoo2(@PathVariable("id") final long id, @RequestBody final Foo foo) { + myfoos.put(id, foo); + } + + @RequestMapping(method = RequestMethod.POST) + @ResponseStatus(HttpStatus.CREATED) + @ResponseBody + public Foo createFoo(@RequestBody final Foo foo, HttpServletResponse response) { + myfoos.put(foo.getId(), foo); + response.setHeader("Location", ServletUriComponentsBuilder.fromCurrentRequest() + .path("/" + foo.getId()) + .toUriString()); + return foo; + } + + @RequestMapping(method = RequestMethod.DELETE, value = "/{id}") + @ResponseStatus(HttpStatus.OK) + public void deleteById(@PathVariable final long id) { + myfoos.remove(id); + } + +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/controller/SimplePostController.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/controller/SimplePostController.java new file mode 100644 index 0000000..92b18fa --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/controller/SimplePostController.java @@ -0,0 +1,75 @@ +package com.example.restTemplateDemo.sampleapp.web.controller; + +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +import com.example.restTemplateDemo.sampleapp.web.dto.Foo; + +// used to test HttpClientPostingTest +@RestController +public class SimplePostController { + + @RequestMapping(value = "/users", method = RequestMethod.POST) + public String postUser(@RequestParam final String username, @RequestParam final String password) { + return "Success" + username; + } + + @RequestMapping(value = "/users/detail", method = RequestMethod.POST) + public String postUserDetail(@RequestBody final Foo entity) { + return "Success" + entity.getId(); + } + + @RequestMapping(value = "/users/multipart", method = RequestMethod.POST) + public String uploadFile(@RequestParam final String username, @RequestParam final String password, @RequestParam("file") final MultipartFile file) { + if (!file.isEmpty()) { + try { + final DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH.mm.ss"); + final String fileName = dateFormat.format(new Date()); + final File fileServer = new File(fileName); + fileServer.createNewFile(); + final byte[] bytes = file.getBytes(); + try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fileServer))) { + stream.write(bytes); + } + return "You successfully uploaded " + username; + } catch (final IOException e) { + return "You failed to upload " + e.getMessage(); + } + } else { + return "You failed to upload because the file was empty."; + } + } + + @RequestMapping(value = "/users/upload", method = RequestMethod.POST) + public String postMultipart(@RequestParam("file") final MultipartFile file) { + if (!file.isEmpty()) { + try { + final DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH.mm.ss"); + final String fileName = dateFormat.format(new Date()); + final File fileServer = new File(fileName); + fileServer.createNewFile(); + final byte[] bytes = file.getBytes(); + try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fileServer))) { + stream.write(bytes); + } + return "You successfully uploaded "; + } catch (final IOException e) { + return "You failed to upload " + e.getMessage(); + } + } else { + return "You failed to upload because the file was empty."; + } + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/dto/Company.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/dto/Company.java new file mode 100644 index 0000000..f126332 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/dto/Company.java @@ -0,0 +1,37 @@ +package com.example.restTemplateDemo.sampleapp.web.dto; + +public class Company { + + private long id; + private String name; + + public Company() { + super(); + } + + public Company(final long id, final String name) { + this.id = id; + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(final long id) { + this.id = id; + } + + @Override + public String toString() { + return "Company [id=" + id + ", name=" + name + "]"; + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/dto/Foo.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/dto/Foo.java new file mode 100644 index 0000000..86b0fa8 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/dto/Foo.java @@ -0,0 +1,38 @@ +package com.example.restTemplateDemo.sampleapp.web.dto; + +public class Foo { + private long id; + private String name; + + public Foo() { + super(); + } + + public Foo(final String name) { + super(); + this.name = name; + } + + public Foo(final long id, final String name) { + super(); + this.id = id; + this.name = name; + } + + // API + public long getId() { + return id; + } + + public void setId(final long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/dto/HeavyResource.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/dto/HeavyResource.java new file mode 100644 index 0000000..e5102b1 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/dto/HeavyResource.java @@ -0,0 +1,60 @@ +package com.example.restTemplateDemo.sampleapp.web.dto; + +public class HeavyResource { + private Integer id; + private String name; + private String surname; + private Integer age; + private String address; + + public HeavyResource() { + } + + public HeavyResource(Integer id, String name, String surname, Integer age, String address) { + this.id = id; + this.name = name; + this.surname = surname; + this.age = age; + this.address = address; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getSurname() { + return surname; + } + + public void setSurname(String surname) { + this.surname = surname; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/dto/HeavyResourceAddressOnly.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/dto/HeavyResourceAddressOnly.java new file mode 100644 index 0000000..d58763e --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/dto/HeavyResourceAddressOnly.java @@ -0,0 +1,30 @@ +package com.example.restTemplateDemo.sampleapp.web.dto; + +public class HeavyResourceAddressOnly { + private Integer id; + private String address; + + public HeavyResourceAddressOnly() { + } + + public HeavyResourceAddressOnly(Integer id, String address) { + this.id = id; + this.address = address; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/dto/HeavyResourceAddressPartialUpdate.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/dto/HeavyResourceAddressPartialUpdate.java new file mode 100644 index 0000000..a6cfe01 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/dto/HeavyResourceAddressPartialUpdate.java @@ -0,0 +1,30 @@ +package com.example.restTemplateDemo.sampleapp.web.dto; + +public class HeavyResourceAddressPartialUpdate { + private Integer id; + private String address; + + public HeavyResourceAddressPartialUpdate() { + } + + public HeavyResourceAddressPartialUpdate(Integer id, String address) { + this.id = id; + this.address = address; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/dto/Item.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/dto/Item.java new file mode 100644 index 0000000..68b4a52 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/dto/Item.java @@ -0,0 +1,36 @@ +package com.example.restTemplateDemo.sampleapp.web.dto; + +import com.fasterxml.jackson.annotation.JsonView; + +public class Item { + @JsonView(Views.Public.class) + public int id; + + @JsonView(Views.Public.class) + public String itemName; + + @JsonView(Views.Internal.class) + public String ownerName; + + public Item() { + super(); + } + + public Item(final int id, final String itemName, final String ownerName) { + this.id = id; + this.itemName = itemName; + this.ownerName = ownerName; + } + + public int getId() { + return id; + } + + public String getItemName() { + return itemName; + } + + public String getOwnerName() { + return ownerName; + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/dto/ItemManager.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/dto/ItemManager.java new file mode 100644 index 0000000..f447964 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/dto/ItemManager.java @@ -0,0 +1,9 @@ +package com.example.restTemplateDemo.sampleapp.web.dto; + +public class ItemManager { + + public static Item getById(final int id) { + final Item item = new Item(2, "book", "John"); + return item; + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/dto/Views.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/dto/Views.java new file mode 100644 index 0000000..b841fe2 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/dto/Views.java @@ -0,0 +1,9 @@ +package com.example.restTemplateDemo.sampleapp.web.dto; + +public class Views { + public static class Public { + } + + public static class Internal extends Public { + } +} \ No newline at end of file diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/exception/ResourceNotFoundException.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/exception/ResourceNotFoundException.java new file mode 100644 index 0000000..0dd847d --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/sampleapp/web/exception/ResourceNotFoundException.java @@ -0,0 +1,8 @@ +package com.example.restTemplateDemo.sampleapp.web.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(value = HttpStatus.NOT_FOUND) +public class ResourceNotFoundException extends RuntimeException { +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/transfer/LoginForm.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/transfer/LoginForm.java new file mode 100644 index 0000000..3e441b9 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/java/com/example/restTemplateDemo/transfer/LoginForm.java @@ -0,0 +1,31 @@ +package com.example.restTemplateDemo.transfer; + +public class LoginForm { + private String username; + private String password; + + public LoginForm() { + } + + public LoginForm(String username, String password) { + super(); + this.username = username; + this.password = password; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/resources/application.properties b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/resources/application.properties new file mode 100644 index 0000000..1a26e3a --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/resources/application.properties @@ -0,0 +1,2 @@ +server.port=8082 +server.servlet.context-path=/spring-rest \ No newline at end of file diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/resources/logback.xml b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/resources/logback.xml new file mode 100644 index 0000000..b2f79c1 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/main/resources/logback.xml @@ -0,0 +1,23 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/test/java/com/example/restTemplateDemo/SpringContextTest.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/test/java/com/example/restTemplateDemo/SpringContextTest.java new file mode 100644 index 0000000..9927a8c --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/test/java/com/example/restTemplateDemo/SpringContextTest.java @@ -0,0 +1,14 @@ +package com.example.restTemplateDemo; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +import com.example.restTemplateDemo.resttemplate.RestTemplateConfigurationApplication; + +@SpringBootTest(classes= RestTemplateConfigurationApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/test/java/com/example/restTemplateDemo/SpringTestConfig.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/test/java/com/example/restTemplateDemo/SpringTestConfig.java new file mode 100644 index 0000000..26d14da --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/test/java/com/example/restTemplateDemo/SpringTestConfig.java @@ -0,0 +1,11 @@ +package com.example.restTemplateDemo; + +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@EnableAutoConfiguration +@ComponentScan("com.example.restTemplateDemo") +public class SpringTestConfig { +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/test/java/com/example/restTemplateDemo/client/Consts.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/test/java/com/example/restTemplateDemo/client/Consts.java new file mode 100644 index 0000000..a938243 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/test/java/com/example/restTemplateDemo/client/Consts.java @@ -0,0 +1,5 @@ +package com.example.restTemplateDemo.client; + +public interface Consts { + int APPLICATION_PORT = 8082; +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/test/java/com/example/restTemplateDemo/client/TestRestTemplateBasicLiveTest.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/test/java/com/example/restTemplateDemo/client/TestRestTemplateBasicLiveTest.java new file mode 100644 index 0000000..12f97f9 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/test/java/com/example/restTemplateDemo/client/TestRestTemplateBasicLiveTest.java @@ -0,0 +1,124 @@ +package com.example.restTemplateDemo.client; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +import com.example.restTemplateDemo.resttemplate.web.dto.Foo; + +import okhttp3.Request; +import okhttp3.RequestBody; + +// This test needs RestTemplateConfigurationApplication to be up and running +public class TestRestTemplateBasicLiveTest { + + private RestTemplate restTemplate; + + private static final String FOO_RESOURCE_URL = "http://localhost:" + 8082 + "/spring-rest/foos"; + private static final String URL_SECURED_BY_AUTHENTICATION = "http://httpbin.org/basic-auth/user/passwd"; + private static final String BASE_URL = "http://localhost:" + 8082 + "/spring-rest"; + + @BeforeEach + public void beforeTest() { + restTemplate = new RestTemplate(); + } + + // GET + @Test + public void givenTestRestTemplate_whenSendGetForEntity_thenStatusOk() { + TestRestTemplate testRestTemplate = new TestRestTemplate(); + ResponseEntity response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", Foo.class); + Assertions.assertEquals(response.getStatusCode(), HttpStatus.OK); + } + + @Test + public void givenRestTemplateWrapper_whenSendGetForEntity_thenStatusOk() { + RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder(); + restTemplateBuilder.configure(restTemplate); + TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder); + ResponseEntity response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", Foo.class); + Assertions.assertEquals(response.getStatusCode(), HttpStatus.OK); + } + + @Test + public void givenRestTemplateBuilderWrapper_whenSendGetForEntity_thenStatusOk() { + RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder(); + restTemplateBuilder.build(); + TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder); + ResponseEntity response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", Foo.class); + Assertions.assertEquals(response.getStatusCode(), HttpStatus.OK); + } + + @Test + public void givenRestTemplateWrapperWithCredentials_whenSendGetForEntity_thenStatusOk() { + RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder(); + restTemplateBuilder.configure(restTemplate); + TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder, "user", "passwd"); + ResponseEntity response = testRestTemplate.getForEntity(URL_SECURED_BY_AUTHENTICATION, + String.class); + Assertions.assertEquals(response.getStatusCode(), HttpStatus.OK); + } + + @Test + public void givenTestRestTemplateWithCredentials_whenSendGetForEntity_thenStatusOk() { + TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd"); + ResponseEntity response = testRestTemplate.getForEntity(URL_SECURED_BY_AUTHENTICATION, + String.class); + Assertions.assertEquals(response.getStatusCode(), HttpStatus.OK); + } + + @Test + public void givenTestRestTemplateWithBasicAuth_whenSendGetForEntity_thenStatusOk() { + TestRestTemplate testRestTemplate = new TestRestTemplate(); + ResponseEntity response = testRestTemplate.withBasicAuth("user", "passwd"). + getForEntity(URL_SECURED_BY_AUTHENTICATION, String.class); + Assertions.assertEquals(response.getStatusCode(), HttpStatus.OK); + } + + @Test + public void givenTestRestTemplateWithCredentialsAndEnabledCookies_whenSendGetForEntity_thenStatusOk() { + TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd", TestRestTemplate. + HttpClientOption.ENABLE_COOKIES); + ResponseEntity response = testRestTemplate.getForEntity(URL_SECURED_BY_AUTHENTICATION, + String.class); + Assertions.assertEquals(response.getStatusCode(), HttpStatus.OK); + } + + // HEAD + @Test + public void givenFooService_whenCallHeadForHeaders_thenReceiveAllHeaders() { + TestRestTemplate testRestTemplate = new TestRestTemplate(); + final HttpHeaders httpHeaders = testRestTemplate.headForHeaders(FOO_RESOURCE_URL); + Assertions.assertTrue(httpHeaders.getContentType().includes(MediaType.APPLICATION_JSON)); + } + + // POST + @Test + public void givenService_whenPostForObject_thenCreatedObjectIsReturned() { + TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd"); + @SuppressWarnings("deprecation") + final RequestBody body = RequestBody.create(okhttp3.MediaType.parse("text/html; charset=utf-8"), + "{\"id\":1,\"name\":\"Jim\"}"); + final Request request = new Request.Builder().url(BASE_URL + "/users/detail").post(body).build(); + testRestTemplate.postForObject(URL_SECURED_BY_AUTHENTICATION, request, String.class); + } + + // PUT + @Test + public void givenService_whenPutForObject_thenCreatedObjectIsReturned() { + TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd"); + @SuppressWarnings("deprecation") + final RequestBody body = RequestBody.create(okhttp3.MediaType.parse("text/html; charset=utf-8"), + "{\"id\":1,\"name\":\"Jim\"}"); + final Request request = new Request.Builder().url(BASE_URL + "/users/detail").post(body).build(); + testRestTemplate.put(URL_SECURED_BY_AUTHENTICATION, request, String.class); + } + +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/test/java/com/example/restTemplateDemo/mock/EmployeeServiceMockRestServiceServerUnitTest.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/test/java/com/example/restTemplateDemo/mock/EmployeeServiceMockRestServiceServerUnitTest.java new file mode 100644 index 0000000..5433423 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/test/java/com/example/restTemplateDemo/mock/EmployeeServiceMockRestServiceServerUnitTest.java @@ -0,0 +1,50 @@ +package com.example.restTemplateDemo.mock; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.client.MockRestServiceServer; +import org.springframework.web.client.RestTemplate; + +import com.example.restTemplateDemo.SpringTestConfig; +import com.fasterxml.jackson.databind.ObjectMapper; + +@ExtendWith(SpringExtension.class) +@SpringBootTest(classes = SpringTestConfig.class) +public class EmployeeServiceMockRestServiceServerUnitTest { + + // private static final Logger logger = LoggerFactory.getLogger(EmployeeServiceMockRestServiceServerUnitTest.class); + + @Autowired + private EmployeeService empService; + + @Autowired + private RestTemplate restTemplate; + + private MockRestServiceServer mockServer; + + private final ObjectMapper mapper = new ObjectMapper(); + + @BeforeEach + public void init() { + mockServer = MockRestServiceServer.createServer(restTemplate); + } + + /* @Test + public void givenMockingIsDoneByMockRestServiceServer_whenGetIsCalled_shouldReturnMockedObject() throws Exception { + Employee emp = new Employee("E001", "Eric Simmons"); + + mockServer.expect(ExpectedCount.once(), + requestTo(new URI("http://localhost:8080/employee/E001"))) + .andExpect(method(HttpMethod.GET)) + .andRespond(withStatus(HttpStatus.OK) + .contentType(MediaType.APPLICATION_JSON) + .body(mapper.writeValueAsString(emp))); + + Employee employee = empService.getEmployee("E001"); + mockServer.verify(); + Assertions.assertEquals(emp, employee); + } */ +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/test/java/com/example/restTemplateDemo/mock/EmployeeServiceUnitTest.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/test/java/com/example/restTemplateDemo/mock/EmployeeServiceUnitTest.java new file mode 100644 index 0000000..65d522f --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/test/java/com/example/restTemplateDemo/mock/EmployeeServiceUnitTest.java @@ -0,0 +1,36 @@ +package com.example.restTemplateDemo.mock; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +import com.example.restTemplateDemo.resttemplate.web.model.Employee; + +@ExtendWith(MockitoExtension.class) +public class EmployeeServiceUnitTest { + + @Mock + private RestTemplate restTemplate; + + @InjectMocks + private final EmployeeService empService = new EmployeeService(); + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Test + public void givenMockingIsDoneByMockito_whenGetIsCalled_shouldReturnMockedObject() throws Exception { + Employee emp = new Employee("E001", "Eric Simmons"); + Mockito.when(restTemplate.getForEntity("http://localhost:8080/employee/E001", Employee.class)) + .thenReturn(new ResponseEntity(emp, HttpStatus.OK)); + + Employee employee = empService.getEmployee("E001"); + + assertEquals(emp, employee); + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/test/java/com/example/restTemplateDemo/resttemplate/RestTemplateBasicLiveTest.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/test/java/com/example/restTemplateDemo/resttemplate/RestTemplateBasicLiveTest.java new file mode 100644 index 0000000..3f0dc03 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/test/java/com/example/restTemplateDemo/resttemplate/RestTemplateBasicLiveTest.java @@ -0,0 +1,266 @@ +package com.example.restTemplateDemo.resttemplate; + +import java.io.IOException; +import java.net.URI; +import java.util.Arrays; +import java.util.Base64; +import java.util.Set; + +import org.junit.jupiter.api.Assertions; +import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.http.client.ClientHttpRequestFactory; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.RequestCallback; +import org.springframework.web.client.RestTemplate; + +import static com.example.restTemplateDemo.client.Consts.APPLICATION_PORT; +import com.example.restTemplateDemo.resttemplate.web.dto.Foo; +import com.example.restTemplateDemo.resttemplate.web.handler.RestTemplateRespErrorHandler; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Charsets; + +// This test needs RestTemplateConfigurationApplication to be up and running +public class RestTemplateBasicLiveTest { + + private RestTemplate restTemplate; + private static final String fooResourceUrl = "http://localhost:" + APPLICATION_PORT + "/spring-rest/foos"; + + @BeforeEach + public void beforeTest() { + restTemplate = new RestTemplate(); + restTemplate.setErrorHandler(new RestTemplateRespErrorHandler()); + // restTemplate.setMessageConverters(Arrays.asList(new MappingJackson2HttpMessageConverter())); + } + + // GET + + @Test + public void givenResourceUrl_whenSendGetForRequestEntity_thenStatusOk() throws IOException { + final ResponseEntity response = restTemplate.getForEntity(fooResourceUrl + "/1", Foo.class); + + Assertions.assertEquals(response.getStatusCode(), HttpStatus.OK); + } + + @Test + public void givenResourceUrl_whenSendGetForRequestEntity_thenBodyCorrect() throws IOException { + final RestTemplate template = new RestTemplate(); + final ResponseEntity response = template.getForEntity(fooResourceUrl + "/1", String.class); + + final ObjectMapper mapper = new ObjectMapper(); + final JsonNode root = mapper.readTree(response.getBody()); + final JsonNode name = root.path("name"); + Assertions.assertNotNull(name.asText()); + } + + @Test + public void givenResourceUrl_whenRetrievingResource_thenCorrect() throws IOException { + final Foo foo = restTemplate.getForObject(fooResourceUrl + "/1", Foo.class); + + Assertions.assertNotNull(foo.getName()); + Assertions.assertEquals(1L, foo.getId()); + } + + // HEAD, OPTIONS + @Test + public void givenFooService_whenCallHeadForHeaders_thenReceiveAllHeadersForThatResource() { + final HttpHeaders httpHeaders = restTemplate.headForHeaders(fooResourceUrl); + Assertions.assertTrue(httpHeaders.getContentType() + .includes(MediaType.APPLICATION_JSON)); + } + + // POST + + @Test + public void givenFooService_whenPostForObject_thenCreatedObjectIsReturned() { + final HttpEntity request = new HttpEntity<>(new Foo("bar")); + final Foo foo = restTemplate.postForObject(fooResourceUrl, request, Foo.class); + Assertions.assertNotNull(foo); + Assertions.assertEquals("bar", foo.getName()); + } + + @Test + public void givenFooService_whenPostForLocation_thenCreatedLocationIsReturned() { + final HttpEntity request = new HttpEntity<>(new Foo("bar")); + final URI location = restTemplate.postForLocation(fooResourceUrl, request, Foo.class); + Assertions.assertNotNull(location); + } + + @Test + public void givenFooService_whenPostResource_thenResourceIsCreated() { + final Foo foo = new Foo("bar"); + final ResponseEntity response = restTemplate.postForEntity(fooResourceUrl, foo, Foo.class); + + Assertions.assertEquals(response.getStatusCode(), HttpStatus.CREATED); + final Foo fooResponse = response.getBody(); + Assertions.assertNotNull(fooResponse); + Assertions.assertEquals("bar", fooResponse.getName()); + } + + @Test + public void givenFooService_whenCallOptionsForAllow_thenReceiveValueOfAllowHeader() { + final Set optionsForAllow = restTemplate.optionsForAllow(fooResourceUrl); + final HttpMethod[] supportedMethods = { HttpMethod.GET, HttpMethod.POST, HttpMethod.HEAD }; + + Assertions.assertTrue(optionsForAllow.containsAll(Arrays.asList(supportedMethods))); + } + + // PUT + + @Test + public void givenFooService_whenPutExistingEntity_thenItIsUpdated() { + final HttpHeaders headers = prepareBasicAuthHeaders(); + final HttpEntity request = new HttpEntity<>(new Foo("bar"), headers); + + // Create Resource + final ResponseEntity createResponse = restTemplate.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class); + + // Update Resource + final Foo updatedInstance = new Foo("newName"); + updatedInstance.setId(createResponse.getBody() + .getId()); + final String resourceUrl = fooResourceUrl + '/' + createResponse.getBody() + .getId(); + final HttpEntity requestUpdate = new HttpEntity<>(updatedInstance, headers); + restTemplate.exchange(resourceUrl, HttpMethod.PUT, requestUpdate, Void.class); + + // Check that Resource was updated + final ResponseEntity updateResponse = restTemplate.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class); + final Foo foo = updateResponse.getBody(); + Assertions.assertEquals(foo.getName(), updatedInstance.getName()); + } + + @Test + public void givenFooService_whenPutExistingEntityWithCallback_thenItIsUpdated() { + final HttpHeaders headers = prepareBasicAuthHeaders(); + final HttpEntity request = new HttpEntity<>(new Foo("bar"), headers); + + // Create entity + ResponseEntity response = restTemplate.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class); + Assertions.assertEquals(response.getStatusCode(), HttpStatus.CREATED); + + // Update entity + final Foo updatedInstance = new Foo("newName"); + updatedInstance.setId(response.getBody() + .getId()); + final String resourceUrl = fooResourceUrl + '/' + response.getBody() + .getId(); + restTemplate.execute(resourceUrl, HttpMethod.PUT, requestCallback(updatedInstance), clientHttpResponse -> null); + + // Check that entity was updated + response = restTemplate.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class); + final Foo foo = response.getBody(); + Assertions.assertEquals(foo.getName(), updatedInstance.getName()); + } + + // PATCH + + @Test + public void givenFooService_whenPatchExistingEntity_thenItIsUpdated() { + final HttpHeaders headers = prepareBasicAuthHeaders(); + final HttpEntity request = new HttpEntity<>(new Foo("bar"), headers); + + // Create Resource + final ResponseEntity createResponse = restTemplate.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class); + + // Update Resource + final Foo updatedResource = new Foo("newName"); + updatedResource.setId(createResponse.getBody() + .getId()); + final String resourceUrl = fooResourceUrl + '/' + createResponse.getBody() + .getId(); + final HttpEntity requestUpdate = new HttpEntity<>(updatedResource, headers); + final ClientHttpRequestFactory requestFactory = getClientHttpRequestFactory(); + final RestTemplate template = new RestTemplate(requestFactory); + template.setMessageConverters(Arrays.asList(new MappingJackson2HttpMessageConverter())); + template.patchForObject(resourceUrl, requestUpdate, Void.class); + + // Check that Resource was updated + final ResponseEntity updateResponse = restTemplate.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class); + final Foo foo = updateResponse.getBody(); + Assertions.assertEquals(foo.getName(), updatedResource.getName()); + } + + // DELETE + + @Test + public void givenFooService_whenCallDelete_thenEntityIsRemoved() { + final Foo foo = new Foo("remove me"); + final ResponseEntity response = restTemplate.postForEntity(fooResourceUrl, foo, Foo.class); + Assertions.assertEquals(response.getStatusCode(), HttpStatus.CREATED); + + final String entityUrl = fooResourceUrl + "/" + response.getBody() + .getId(); + restTemplate.delete(entityUrl); + try { + restTemplate.getForEntity(entityUrl, Foo.class); + fail(); + } catch (final HttpClientErrorException ex) { + Assertions.assertEquals(ex.getStatusCode(), HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + @Test + public void givenFooService_whenFormSubmit_thenResourceIsCreated() { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); + + MultiValueMap map= new LinkedMultiValueMap<>(); + map.add("id", "10"); + + HttpEntity> request = new HttpEntity<>(map, headers); + + ResponseEntity response = restTemplate.postForEntity( fooResourceUrl+"/form", request , String.class); + + Assertions.assertEquals(response.getStatusCode(), HttpStatus.CREATED); + final String fooResponse = response.getBody(); + Assertions.assertNotNull(fooResponse); + Assertions.assertEquals("10", fooResponse); + } + + private HttpHeaders prepareBasicAuthHeaders() { + final HttpHeaders headers = new HttpHeaders(); + final String encodedLogPass = getBase64EncodedLogPass(); + headers.add(HttpHeaders.AUTHORIZATION, "Basic " + encodedLogPass); + return headers; + } + + private String getBase64EncodedLogPass() { + final String logPass = "user1:user1Pass"; + final byte[] authHeaderBytes = Base64.getEncoder().encode(logPass.getBytes(Charsets.US_ASCII)); + return new String(authHeaderBytes, Charsets.US_ASCII); + } + + private RequestCallback requestCallback(final Foo updatedInstance) { + return clientHttpRequest -> { + final ObjectMapper mapper = new ObjectMapper(); + mapper.writeValue(clientHttpRequest.getBody(), updatedInstance); + clientHttpRequest.getHeaders() + .add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); + clientHttpRequest.getHeaders() + .add(HttpHeaders.AUTHORIZATION, "Basic " + getBase64EncodedLogPass()); + }; + } + + // Simply setting restTemplate timeout using ClientHttpRequestFactory + + ClientHttpRequestFactory getClientHttpRequestFactory() { + final int timeout = 5; + final HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(); + clientHttpRequestFactory.setConnectTimeout(timeout * 1000); + return clientHttpRequestFactory; + } + +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/test/java/com/example/restTemplateDemo/resttemplate/RestTemplateLiveTest.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/test/java/com/example/restTemplateDemo/resttemplate/RestTemplateLiveTest.java new file mode 100644 index 0000000..e8ab9c9 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/test/java/com/example/restTemplateDemo/resttemplate/RestTemplateLiveTest.java @@ -0,0 +1,40 @@ +package com.example.restTemplateDemo.resttemplate; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.web.client.RestTemplate; + +import com.example.restTemplateDemo.sampleapp.config.RestClientConfig; +import com.example.restTemplateDemo.transfer.LoginForm; + +@ExtendWith(SpringExtension.class) +@ContextConfiguration(classes = RestClientConfig.class) +public class RestTemplateLiveTest { + + @Autowired + RestTemplate restTemplate; + + @Test + public void givenRestTemplate_whenRequested_thenLogAndModifyResponse() { + LoginForm loginForm = new LoginForm("userName", "password"); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + HttpEntity requestEntity = new HttpEntity(loginForm, headers); + + ResponseEntity responseEntity = restTemplate.postForEntity("http://httpbin.org/post", requestEntity, String.class); + + Assertions.assertEquals(responseEntity.getStatusCode(), HttpStatus.OK); + Assertions.assertEquals("bar", responseEntity.getHeaders() + .get("Foo") + .get(0)); + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/test/java/com/example/restTemplateDemo/web/handler/RestTemplateResponseErrorHandlerTest.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/test/java/com/example/restTemplateDemo/web/handler/RestTemplateResponseErrorHandlerTest.java new file mode 100644 index 0000000..e19ce7e --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/test/java/com/example/restTemplateDemo/web/handler/RestTemplateResponseErrorHandlerTest.java @@ -0,0 +1,50 @@ +package com.example.restTemplateDemo.web.handler; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.client.RestClientTest; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.client.ExpectedCount; +import org.springframework.test.web.client.MockRestServiceServer; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; +import org.springframework.web.client.RestTemplate; + +import com.example.restTemplateDemo.resttemplate.web.exception.NotFoundException; +import com.example.restTemplateDemo.resttemplate.web.handler.RestTemplateRespErrorHandler; +import com.example.restTemplateDemo.resttemplate.web.model.Bar; + +@ExtendWith(SpringExtension.class) +@ContextConfiguration(classes = { NotFoundException.class, Bar.class }) +@RestClientTest +public class RestTemplateResponseErrorHandlerTest { + + @Autowired private MockRestServiceServer server; + @Autowired private RestTemplateBuilder builder; + + @Test + public void givenRemoteApiCall_when404Error_thenThrowNotFound() { + Assertions.assertNotNull(this.builder); + Assertions.assertNotNull(this.server); + + RestTemplate restTemplate = this.builder + .errorHandler(new RestTemplateRespErrorHandler()) + .build(); + + this.server + .expect(ExpectedCount.once(), requestTo("/bars/4242")) + .andExpect(method(HttpMethod.GET)) + .andRespond(withStatus(HttpStatus.NOT_FOUND)); + + Assertions.assertThrows(NotFoundException.class, () -> { + Bar response = restTemplate.getForObject("/bars/4242", Bar.class); + }); + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/test/resources/.gitignore b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/test/resources/.gitignore new file mode 100644 index 0000000..f9bfbae --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/test/resources/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/test/resources/logback-test.xml b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/test/resources/logback-test.xml new file mode 100644 index 0000000..b2f79c1 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo/src/test/resources/logback-test.xml @@ -0,0 +1,23 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/.gitignore b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/.mvn/wrapper/maven-wrapper.properties b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..8f96f52 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.7/apache-maven-3.9.7-bin.zip diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/mvnw b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/mvnw new file mode 100644 index 0000000..d7c358e --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/mvnw @@ -0,0 +1,259 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.2 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/mvnw.cmd b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/mvnw.cmd new file mode 100644 index 0000000..6f779cf --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/mvnw.cmd @@ -0,0 +1,149 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.2 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' +$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/pom.xml b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/pom.xml new file mode 100644 index 0000000..b646706 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/pom.xml @@ -0,0 +1,65 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.3.2 + + + com.example + restTemplateDemo1 + 0.0.1-SNAPSHOT + restTemplateDemo1 + Demo project for Spring Boot + + + + + + + + + + + + + + + 21 + com.example.restTemplateDemo1.RestTemplateDemo1Application + + + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + + + junit + junit + 4.13.2 + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/RestTemplateConfigurationApplication.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/RestTemplateConfigurationApplication.java new file mode 100644 index 0000000..675c981 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/RestTemplateConfigurationApplication.java @@ -0,0 +1,12 @@ +package com.example.restTemplateDemo1; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class RestTemplateConfigurationApplication { + + public static void main(String[] args) { + SpringApplication.run(RestTemplateConfigurationApplication.class, args); + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/RestTemplateDemo1Application.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/RestTemplateDemo1Application.java new file mode 100644 index 0000000..115a8e1 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/RestTemplateDemo1Application.java @@ -0,0 +1,16 @@ +package com.example.restTemplateDemo1; + +import java.util.Collections; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class RestTemplateDemo1Application { + + public static void main(String[] args) { + SpringApplication app = new SpringApplication(RestTemplateDemo1Application.class); + app.setDefaultProperties(Collections.singletonMap("server.servlet.encoding.charset", "ISO-8859-1")); + app.run(args); + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/lists/EmployeeApplication.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/lists/EmployeeApplication.java new file mode 100644 index 0000000..8ec4112 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/lists/EmployeeApplication.java @@ -0,0 +1,16 @@ +package com.example.restTemplateDemo1.lists; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * Sample application used to demonstrate working with Lists and RestTemplate. + */ +@SpringBootApplication +public class EmployeeApplication +{ + public static void main(String[] args) + { + SpringApplication.run(EmployeeApplication.class, args); + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/lists/client/EmployeeClient.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/lists/client/EmployeeClient.java new file mode 100644 index 0000000..94b21ae --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/lists/client/EmployeeClient.java @@ -0,0 +1,121 @@ +package com.example.restTemplateDemo1.lists.client; + +import static java.util.Arrays.asList; + +import java.util.ArrayList; +import java.util.List; + +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +import com.example.restTemplateDemo1.lists.dto.Employee; +import com.example.restTemplateDemo1.lists.dto.EmployeeList; + +/** + * Application that shows how to use Lists with RestTemplate. + */ +public class EmployeeClient { + public static void main(String[] args) { + EmployeeClient employeeClient = new EmployeeClient(); + + System.out.println("Calling GET for entity using arrays"); + employeeClient.getForEntityEmployeesAsArray(); + + System.out.println("Calling GET using ParameterizedTypeReference"); + employeeClient.getAllEmployeesUsingParameterizedTypeReference(); + + System.out.println("Calling GET using wrapper class"); + employeeClient.getAllEmployeesUsingWrapperClass(); + + System.out.println("Calling POST using normal lists"); + employeeClient.createEmployeesUsingLists(); + + System.out.println("Calling POST using wrapper class"); + employeeClient.createEmployeesUsingWrapperClass(); + } + + public EmployeeClient() { + + } + + public Employee[] getForEntityEmployeesAsArray() { + + RestTemplate restTemplate = new RestTemplate(); + + ResponseEntity response = + restTemplate.getForEntity( + "http://localhost:8080/spring-rest/employees/", + Employee[].class); + + Employee[] employees = response.getBody(); + + assert employees != null; + asList(employees).forEach(System.out::println); + + return employees; + + } + + + public List getAllEmployeesUsingParameterizedTypeReference() { + RestTemplate restTemplate = new RestTemplate(); + + ResponseEntity> response = + restTemplate.exchange( + "http://localhost:8080/spring-rest/employees/", + HttpMethod.GET, + null, + new ParameterizedTypeReference>() { + }); + + List employees = response.getBody(); + + assert employees != null; + employees.forEach(System.out::println); + + return employees; + } + + public List getAllEmployeesUsingWrapperClass() { + RestTemplate restTemplate = new RestTemplate(); + + EmployeeList response = + restTemplate.getForObject( + "http://localhost:8080/spring-rest/employees/v2", + EmployeeList.class); + + List employees = response.getEmployees(); + + employees.forEach(System.out::println); + + return employees; + } + + public void createEmployeesUsingLists() { + RestTemplate restTemplate = new RestTemplate(); + + List newEmployees = new ArrayList<>(); + newEmployees.add(new Employee(3, "Intern")); + newEmployees.add(new Employee(4, "CEO")); + + restTemplate.postForObject( + "http://localhost:8080/spring-rest/employees/", + newEmployees, + ResponseEntity.class); + } + + public void createEmployeesUsingWrapperClass() { + RestTemplate restTemplate = new RestTemplate(); + + List newEmployees = new ArrayList<>(); + newEmployees.add(new Employee(3, "Intern")); + newEmployees.add(new Employee(4, "CEO")); + + restTemplate.postForObject( + "http://localhost:8080/spring-rest/employees/v2", + new EmployeeList(newEmployees), + ResponseEntity.class); + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/lists/controller/EmployeeResource.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/lists/controller/EmployeeResource.java new file mode 100644 index 0000000..57af327 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/lists/controller/EmployeeResource.java @@ -0,0 +1,46 @@ +package com.example.restTemplateDemo1.lists.controller; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import com.example.restTemplateDemo1.lists.dto.Employee; +import com.example.restTemplateDemo1.lists.dto.EmployeeList; +import com.example.restTemplateDemo1.lists.service.EmployeeService; + +@RestController +@RequestMapping("/employees") +public class EmployeeResource +{ + @Autowired + private EmployeeService employeeService; + + @RequestMapping(method = RequestMethod.GET, path = "/") + public List getEmployees() + { + return employeeService.getAllEmployees(); + } + + @RequestMapping(method = RequestMethod.GET, path = "/v2") + public EmployeeList getEmployeesUsingWrapperClass() + { + List employees = employeeService.getAllEmployees(); + return new EmployeeList(employees); + } + + @RequestMapping(method = RequestMethod.POST, path = "/") + public void addEmployees(@RequestBody List employees) + { + employeeService.addEmployees(employees); + } + + @RequestMapping(method = RequestMethod.POST, path = "/v2") + public void addEmployeesUsingWrapperClass(@RequestBody EmployeeList employeeWrapper) + { + employeeService.addEmployees(employeeWrapper.getEmployees()); + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/lists/dto/Employee.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/lists/dto/Employee.java new file mode 100644 index 0000000..2f47f49 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/lists/dto/Employee.java @@ -0,0 +1,40 @@ +package com.example.restTemplateDemo1.lists.dto; + +public class Employee { + + public long id; + public String title; + + public Employee() + { + + } + + public Employee(long id, String title) + { + this.id = id; + this.title = title; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + @Override + public String toString() + { + return "Employee #" + id + "[" + title + "]"; + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/lists/dto/EmployeeList.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/lists/dto/EmployeeList.java new file mode 100644 index 0000000..a9fa1dd --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/lists/dto/EmployeeList.java @@ -0,0 +1,29 @@ +package com.example.restTemplateDemo1.lists.dto; + +import java.util.ArrayList; +import java.util.List; + +public class EmployeeList +{ + public List employees; + + public EmployeeList() + { + employees = new ArrayList<>(); + } + + public EmployeeList(List employees) + { + this.employees = employees; + } + + public void setEmployees(List employees) + { + this.employees = employees; + } + + public List getEmployees() + { + return employees; + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/lists/service/EmployeeService.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/lists/service/EmployeeService.java new file mode 100644 index 0000000..5fb31d1 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/lists/service/EmployeeService.java @@ -0,0 +1,25 @@ +package com.example.restTemplateDemo1.lists.service; + +import java.util.ArrayList; +import java.util.List; + +import org.springframework.stereotype.Service; + +import com.example.restTemplateDemo1.lists.dto.Employee; + +@Service("EmployeeListService") +public class EmployeeService +{ + public List getAllEmployees() + { + List employees = new ArrayList<>(); + employees.add(new Employee(1, "Manager")); + employees.add(new Employee(2, "Java Developer")); + return employees; + } + + public void addEmployees(List employees) + { + employees.forEach(e -> System.out.println("Adding new employee " + e)); + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/web/controller/PersonAPI.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/web/controller/PersonAPI.java new file mode 100644 index 0000000..ae150cf --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/web/controller/PersonAPI.java @@ -0,0 +1,38 @@ +package com.example.restTemplateDemo1.web.controller; + +import jakarta.servlet.http.HttpServletResponse; + +import com.example.restTemplateDemo1.web.service.PersonService; +import com.example.restTemplateDemo1.web.dto.Person; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +@RestController +public class PersonAPI { + + @Autowired + private PersonService personService; + + @GetMapping("/") + public String home() { + return "Spring boot is working!"; + } + + @PostMapping(value = "/createPerson", consumes = "application/json", produces = "application/json") + public Person createPerson(@RequestBody Person person) { + return personService.saveUpdatePerson(person); + } + + @PostMapping(value = "/updatePerson", consumes = "application/json", produces = "application/json") + public Person updatePerson(@RequestBody Person person, HttpServletResponse response) { + response.setHeader("Location", ServletUriComponentsBuilder.fromCurrentContextPath() + .path("/findPerson/" + person.getId()) + .toUriString()); + return personService.saveUpdatePerson(person); + } + +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/web/dto/Person.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/web/dto/Person.java new file mode 100644 index 0000000..0ff8c23 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/web/dto/Person.java @@ -0,0 +1,32 @@ +package com.example.restTemplateDemo1.web.dto; + +public class Person { + private Integer id; + private String name; + + public Person() { + + } + + public Person(Integer id, String name) { + this.id = id; + this.name = name; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/web/service/PersonService.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/web/service/PersonService.java new file mode 100644 index 0000000..7714589 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/web/service/PersonService.java @@ -0,0 +1,10 @@ +package com.example.restTemplateDemo1.web.service; + +import com.example.restTemplateDemo1.web.dto.Person; + +public interface PersonService { + + public Person saveUpdatePerson(Person person); + + public Person findPersonById(Integer id); +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/web/service/PersonServiceImpl.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/web/service/PersonServiceImpl.java new file mode 100644 index 0000000..ddd02fd --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/java/com/example/restTemplateDemo1/web/service/PersonServiceImpl.java @@ -0,0 +1,19 @@ +package com.example.restTemplateDemo1.web.service; + +import com.example.restTemplateDemo1.web.dto.Person; +import org.springframework.stereotype.Component; + +@Component +public class PersonServiceImpl implements PersonService { + + @Override + public Person saveUpdatePerson(Person person) { + return person; + } + + @Override + public Person findPersonById(Integer id) { + return new Person(id, "John"); + } + +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/resources/application.properties b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/resources/application.properties new file mode 100644 index 0000000..345e237 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/main/resources/application.properties @@ -0,0 +1,2 @@ +server.port=8080 +server.servlet.context-path=/spring-rest diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/test/java/com/example/restTemplateDemo1/lists/postjson/PersonAPILiveTest.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/test/java/com/example/restTemplateDemo1/lists/postjson/PersonAPILiveTest.java new file mode 100644 index 0000000..25acd91 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/test/java/com/example/restTemplateDemo1/lists/postjson/PersonAPILiveTest.java @@ -0,0 +1,96 @@ +package com.example.restTemplateDemo1.lists.postjson; + +import java.io.IOException; +import java.net.URI; + +import org.json.JSONException; +import org.json.JSONObject; +import static org.junit.Assert.assertNotNull; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.client.RestTemplate; + +import com.example.restTemplateDemo1.RestTemplateConfigurationApplication; +import com.example.restTemplateDemo1.web.dto.Person; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = RestTemplateConfigurationApplication.class) +public class PersonAPILiveTest { + + private static String createPersonUrl; + private static String updatePersonUrl; + + private static RestTemplate restTemplate; + + private static HttpHeaders headers; + + private final ObjectMapper objectMapper = new ObjectMapper(); + + private static JSONObject personJsonObject; + + @BeforeClass + public static void runBeforeAllTestMethods() throws JSONException { + createPersonUrl = "http://localhost:8080/spring-rest/createPerson"; + updatePersonUrl = "http://localhost:8080/spring-rest/updatePerson"; + + restTemplate = new RestTemplate(); + + headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + personJsonObject = new JSONObject(); + personJsonObject.put("id", 1); + personJsonObject.put("name", "John"); + } + + @Test + public void givenDataIsJson_whenDataIsPostedByPostForObject_thenResponseBodyIsNotNull() throws IOException { + HttpEntity request = new HttpEntity<>(personJsonObject.toString(), headers); + String personResultAsJsonStr = restTemplate.postForObject(createPersonUrl, request, String.class); + JsonNode root = objectMapper.readTree(personResultAsJsonStr); + + Person person = restTemplate.postForObject(createPersonUrl, request, Person.class); + + assertNotNull(personResultAsJsonStr); + assertNotNull(root); + assertNotNull(root.path("name") + .asText()); + + assertNotNull(person); + assertNotNull(person.getName()); + } + + @Test + public void givenDataIsJson_whenDataIsPostedByPostForEntity_thenResponseBodyIsNotNull() throws IOException { + HttpEntity request = new HttpEntity<>(personJsonObject.toString(), headers); + ResponseEntity responseEntityStr = restTemplate.postForEntity(createPersonUrl, request, String.class); + JsonNode root = objectMapper.readTree(responseEntityStr.getBody()); + + ResponseEntity responseEntityPerson = restTemplate.postForEntity(createPersonUrl, request, Person.class); + + assertNotNull(responseEntityStr.getBody()); + assertNotNull(root.path("name") + .asText()); + + assertNotNull(responseEntityPerson.getBody()); + assertNotNull(responseEntityPerson.getBody() + .getName()); + } + + @Test + public void givenDataIsJson_whenDataIsPostedByPostForLocation_thenResponseBodyIsTheLocationHeader() throws JsonProcessingException { + HttpEntity request = new HttpEntity<>(personJsonObject.toString(), headers); + URI locationHeader = restTemplate.postForLocation(updatePersonUrl, request); + + assertNotNull(locationHeader); + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/test/java/com/example/restTemplateDemo1/lists/postjson/RestTemplatePostReqEncLiveTest.java b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/test/java/com/example/restTemplateDemo1/lists/postjson/RestTemplatePostReqEncLiveTest.java new file mode 100644 index 0000000..90444cc --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/test/java/com/example/restTemplateDemo1/lists/postjson/RestTemplatePostReqEncLiveTest.java @@ -0,0 +1,57 @@ +package com.example.restTemplateDemo1.lists.postjson; + +import org.json.JSONException; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.client.RestTemplate; + +import com.example.restTemplateDemo1.RestTemplateDemo1Application; +import com.example.restTemplateDemo1.web.dto.Person; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = RestTemplateDemo1Application.class) +public class RestTemplatePostReqEncLiveTest { + private static String createPersonUrl; + private static RestTemplate restTemplate; + + @BeforeClass + public static void runBeforeAllTestMethods() throws JSONException { + createPersonUrl = "http://localhost:8080/spring-rest/createPerson"; + restTemplate = new RestTemplate(); + } + + @Test + public void givenJapaneseNameInDataWithoutHeaderEncoding_whenDataIsPostedByPostForObject_thenSaveIncorrectly() { + Person japanese = new Person(100, "閒連当"); + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + HttpEntity request = new HttpEntity<>(japanese, headers); + + Person person = restTemplate.postForObject(createPersonUrl, request, Person.class); + assertNotNull(person); + assertNotEquals("閒連当", person.getName()); + } + + @Test + public void givenJapaneseNameInDataWithHeaderEncoding_whenDataIsPostedByPostForObject_thenSaveCorrectly() { + Person japanese = new Person(100, "閒連当"); + + HttpHeaders headers = new HttpHeaders(); + headers.set("Content-type", "application/json;charset=UTF-8"); + HttpEntity request = new HttpEntity<>(japanese, headers); + + Person person = restTemplate.postForObject(createPersonUrl, request, Person.class); + assertNotNull(person); + assertEquals("閒連当", person.getName()); + } +} diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/test/resources/application.properties b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/test/resources/application.properties new file mode 100644 index 0000000..8e60ed4 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/test/resources/application.properties @@ -0,0 +1,5 @@ +logging.level.org.springframework.web.client.RestTemplate=DEBUG +logging.level.com.example.restTemplateDemo1.resttemplate.logging=DEBUG +logging.level.org.apache.http=DEBUG +logging.level.httpclient.wire=DEBUG +logging.pattern.console=%20logger{20} - %msg%n diff --git a/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/test/resources/logback-test.xml b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/test/resources/logback-test.xml new file mode 100644 index 0000000..d9b5dda --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/RestTemplateDemo/restTemplateDemo1/src/test/resources/logback-test.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + \ No newline at end of file diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/.gitignore b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/.mvn/wrapper/maven-wrapper.properties b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..8f96f52 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.7/apache-maven-3.9.7-bin.zip diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/mvnw b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/mvnw new file mode 100644 index 0000000..d7c358e --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/mvnw @@ -0,0 +1,259 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.2 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/mvnw.cmd b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/mvnw.cmd new file mode 100644 index 0000000..6f779cf --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/mvnw.cmd @@ -0,0 +1,149 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.2 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' +$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/pom.xml b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/pom.xml new file mode 100644 index 0000000..f092748 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/pom.xml @@ -0,0 +1,233 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.3.2 + + + com.example + webClientDemo + 0.0.1-SNAPSHOT + webClientDemo + Demo project for Spring Boot + + + + + + + + + + + + + + + 21 + 1.0.1.RELEASE + 1.0 + 4.0.3 + 5.0.0-alpha.12 + 3.5.3 + 3.4.2 + 4.0.3 + 2.0.0-Beta4 + 2.0.0 + 2.1.3 + 4.4 + 4.11.0 + 12.0.10 + logback.xml + + + + + + org.springframework.cloud + spring-cloud-dependencies + 2023.0.3 + pom + import + + + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-webflux + + + org.springframework.cloud + spring-cloud-starter-openfeign + ${spring-cloud-starter-openfeign.version} + + + org.projectreactor + reactor-spring + ${reactor-spring.version} + + + jakarta.json.bind + jakarta.json.bind-api + + + jakarta.json + jakarta.json-api + ${jakarta.json-api.version} + + + org.apache.geronimo.specs + geronimo-json_1.1_spec + ${geronimo-json_1.1_spec.version} + + + org.apache.johnzon + johnzon-jsonb + ${johnzon-jsonb.version} + + + + org.apache.commons + commons-lang3 + + + + com.squareup.okhttp3 + okhttp + ${okhttp.version} + + + com.squareup.okhttp3 + mockwebserver + ${okhttp.version} + test + + + + org.springframework.boot + spring-boot-devtools + runtime + + + com.h2database + h2 + runtime + + + org.springframework + spring-test + + + org.springframework.boot + spring-boot-starter-test + test + + + org.wiremock + wiremock-standalone + ${wiremock-standalone.version} + test + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + test + + + org.projectlombok + lombok + ${lombok.version} + + + org.mockito + mockito-junit-jupiter + ${mockito-junit-jupiter.version} + test + + + io.projectreactor + reactor-test + test + + + org.eclipse.jetty + jetty-reactive-httpclient + ${jetty-reactive-httpclient.version} + test + + + org.eclipse.jetty + jetty-client + ${jetty-client.version} + test + + + org.jetbrains.kotlin + kotlin-stdlib + ${kotlin-stdlib.version} + + + + + + integration-lite-first + + + + org.apache.maven.plugins + maven-surefire-plugin + + + ${project.basedir}/src/test/resources/logback-test.xml + + + + + + + + integration-lite-second + + + + org.apache.maven.plugins + maven-surefire-plugin + + + ${project.basedir}/src/test/resources/logback-test.xml + + + + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/reactive/controller/UploadController.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/reactive/controller/UploadController.java new file mode 100644 index 0000000..4c9a5ae --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/reactive/controller/UploadController.java @@ -0,0 +1,28 @@ +package com.example.webClientDemo.reactive.controller; + +import com.example.webClientDemo.reactive.service.ReactiveUploadService; +import org.springframework.http.HttpStatusCode; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; +import reactor.core.publisher.Mono; + +@RestController +public class UploadController { + final ReactiveUploadService uploadService; + + public UploadController(ReactiveUploadService uploadService) { + this.uploadService = uploadService; + } + + @PostMapping(path = "/upload") + @ResponseBody + public Mono uploadPdf(@RequestParam("file") final MultipartFile multipartFile) { + return uploadService.uploadPdf(multipartFile.getResource()); + } + + @PostMapping(path = "/upload/multipart") + @ResponseBody + public Mono uploadMultipart(@RequestParam("file") final MultipartFile multipartFile) { + return uploadService.uploadMultipart(multipartFile); + } +} diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/reactive/enums/Role.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/reactive/enums/Role.java new file mode 100644 index 0000000..2b1d95e --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/reactive/enums/Role.java @@ -0,0 +1,5 @@ +package com.example.webClientDemo.reactive.enums; + +public enum Role { + ENGINEER, SENIOR_ENGINEER, LEAD_ENGINEER +} diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/reactive/exception/ServiceException.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/reactive/exception/ServiceException.java new file mode 100644 index 0000000..e324730 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/reactive/exception/ServiceException.java @@ -0,0 +1,8 @@ +package com.example.webClientDemo.reactive.exception; + +public class ServiceException extends RuntimeException{ + + public ServiceException(String message) { + super(message); + } +} diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/reactive/model/Employee.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/reactive/model/Employee.java new file mode 100644 index 0000000..cd54ca0 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/reactive/model/Employee.java @@ -0,0 +1,18 @@ +package com.example.webClientDemo.reactive.model; + +import com.example.webClientDemo.reactive.enums.Role; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@AllArgsConstructor +@NoArgsConstructor +@Data +public class Employee { + private Integer employeeId; + private String firstName; + private String lastName; + private Integer age; + private Role role; +} diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/reactive/model/Foo.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/reactive/model/Foo.java new file mode 100644 index 0000000..7fbe3bb --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/reactive/model/Foo.java @@ -0,0 +1,11 @@ +package com.example.webClientDemo.reactive.model; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@AllArgsConstructor +@Data +public class Foo { + private long id; + private String name; +} diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/reactive/service/EmployeeService.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/reactive/service/EmployeeService.java new file mode 100644 index 0000000..9f49676 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/reactive/service/EmployeeService.java @@ -0,0 +1,60 @@ +package com.example.webClientDemo.reactive.service; + +import org.springframework.web.reactive.function.client.WebClient; + +import com.example.webClientDemo.reactive.model.Employee; + +import reactor.core.publisher.Mono; + +public class EmployeeService { + + private final WebClient webClient; + public static String PATH_PARAM_BY_ID = "/employee/{id}"; + public static String ADD_EMPLOYEE = "/employee"; + + public EmployeeService(WebClient webClient) { + this.webClient = webClient; + } + + public EmployeeService(String baseUrl) { + this.webClient = WebClient.create(baseUrl); + } + + public Mono getEmployeeById(Integer employeeId) { + return webClient + .get() + .uri(PATH_PARAM_BY_ID, employeeId) + .retrieve() + .bodyToMono(Employee.class); + } + + @SuppressWarnings("deprecation") + public Mono addNewEmployee(Employee newEmployee) { + + return webClient + .post() + .uri(ADD_EMPLOYEE) + .syncBody(newEmployee) + .retrieve(). + bodyToMono(Employee.class); + } + + @SuppressWarnings("deprecation") + public Mono updateEmployee(Integer employeeId, Employee updateEmployee) { + + return webClient + .put() + .uri(PATH_PARAM_BY_ID,employeeId) + .syncBody(updateEmployee) + .retrieve() + .bodyToMono(Employee.class); + } + + public Mono deleteEmployeeById(Integer employeeId) { + return webClient + .delete() + .uri(PATH_PARAM_BY_ID,employeeId) + .retrieve() + .bodyToMono(String.class); + } +} diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/reactive/service/ReactiveUploadService.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/reactive/service/ReactiveUploadService.java new file mode 100644 index 0000000..7a35c3e --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/reactive/service/ReactiveUploadService.java @@ -0,0 +1,66 @@ +package com.example.webClientDemo.reactive.service; + +import com.example.webClientDemo.reactive.exception.ServiceException; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; +import org.springframework.http.MediaType; +import org.springframework.http.client.MultipartBodyBuilder; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.reactive.function.BodyInserters; +import org.springframework.web.reactive.function.client.WebClient; +import org.springframework.web.util.UriComponentsBuilder; +import reactor.core.publisher.Mono; + +import java.net.URI; + +@Service +public class ReactiveUploadService { + + private final WebClient webClient; + private static final String EXTERNAL_UPLOAD_URL = "http://localhost:8080/external/upload"; + + public ReactiveUploadService(final WebClient webClient) { + this.webClient = webClient; + } + + + public Mono uploadPdf(final Resource resource) { + + final URI url = UriComponentsBuilder.fromHttpUrl(EXTERNAL_UPLOAD_URL).build().toUri(); + Mono httpStatusMono = webClient.post() + .uri(url) + .contentType(MediaType.APPLICATION_PDF) + .body(BodyInserters.fromResource(resource)) + .exchangeToMono(response -> { + if (response.statusCode().equals(HttpStatus.OK)) { + return response.bodyToMono(HttpStatus.class).thenReturn(response.statusCode()); + } else { + throw new ServiceException("Error uploading file"); + } + }); + return httpStatusMono; + } + + + public Mono uploadMultipart(final MultipartFile multipartFile) { + final URI url = UriComponentsBuilder.fromHttpUrl(EXTERNAL_UPLOAD_URL).build().toUri(); + + final MultipartBodyBuilder builder = new MultipartBodyBuilder(); + builder.part("file", multipartFile.getResource()); + + Mono httpStatusMono = webClient.post() + .uri(url) + .contentType(MediaType.MULTIPART_FORM_DATA) + .body(BodyInserters.fromMultipartData(builder.build())) + .exchangeToMono(response -> { + if (response.statusCode().equals(HttpStatus.OK)) { + return response.bodyToMono(HttpStatus.class).thenReturn(response.statusCode()); + } else { + throw new ServiceException("Error uploading file"); + } + }); + return httpStatusMono; + } +} diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/reactive/webclient/simultaneous/Client.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/reactive/webclient/simultaneous/Client.java new file mode 100644 index 0000000..b31539e --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/reactive/webclient/simultaneous/Client.java @@ -0,0 +1,58 @@ +package com.example.webClientDemo.reactive.webclient.simultaneous; + +import java.util.List; + +import org.springframework.web.reactive.function.client.WebClient; + +import lombok.Data; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +@Data +public class Client { + + // private static final Logger LOG = Logger.getLogger(Client.class.getName()); + + private final WebClient webClient; + + public Client(String uri) { + this.webClient = WebClient.create(uri); + } + + public Mono getUser(int id) { + return webClient.get() + .uri("/user/{id}", id) + .retrieve() + .bodyToMono(User.class); + } + + public Mono getItem(int id) { + return webClient.get() + .uri("/item/{id}", id) + .retrieve() + .bodyToMono(Item.class); + } + + public Mono getOtherUser(int id) { + return webClient.get() + .uri("/otheruser/{id}", id) + .retrieve() + .bodyToMono(User.class); + } + + public Flux fetchUsers(List userIds) { + return Flux.fromIterable(userIds) + .flatMap(this::getUser); + } + + public Flux fetchUserAndOtherUser(int id) { + return Flux.merge(getUser(id), getOtherUser(id)); + } + + public Mono fetchUserAndItem(int userId, int itemId) { + Mono user = getUser(userId); + Mono item = getItem(itemId); + + return Mono.zip(user, item, UserWithItem::new); + } +} diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/reactive/webclient/simultaneous/Item.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/reactive/webclient/simultaneous/Item.java new file mode 100644 index 0000000..f6f66ee --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/reactive/webclient/simultaneous/Item.java @@ -0,0 +1,20 @@ +package com.example.webClientDemo.reactive.webclient.simultaneous; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +import lombok.Data; + +@Data +public class Item { + private int id; + + @JsonCreator + public Item(@JsonProperty("id") int id) { + this.id = id; + } + + public int id() { + return id; + } +} \ No newline at end of file diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/reactive/webclient/simultaneous/User.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/reactive/webclient/simultaneous/User.java new file mode 100644 index 0000000..ad511ff --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/reactive/webclient/simultaneous/User.java @@ -0,0 +1,20 @@ +package com.example.webClientDemo.reactive.webclient.simultaneous; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +import lombok.Data; + +@Data +public class User { + private int id; + + @JsonCreator + public User(@JsonProperty("id") int id) { + this.id = id; + } + + public int id() { + return id; + } +} diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/reactive/webclient/simultaneous/UserWithItem.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/reactive/webclient/simultaneous/UserWithItem.java new file mode 100644 index 0000000..ca8e7e5 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/reactive/webclient/simultaneous/UserWithItem.java @@ -0,0 +1,22 @@ +package com.example.webClientDemo.reactive.webclient.simultaneous; + +import lombok.Data; + +@Data +public class UserWithItem { + private User user; + private Item item; + + public UserWithItem(User user, Item item) { + this.user = user; + this.item = item; + } + + public User user() { + return user; + } + + public Item item() { + return item; + } +} diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/Product.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/Product.java new file mode 100644 index 0000000..6b477e3 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/Product.java @@ -0,0 +1,13 @@ +package com.example.webClientDemo.webclient; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class Product { + private String title; + private String description; +} diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/ProductsFeignClient.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/ProductsFeignClient.java new file mode 100644 index 0000000..2d0b823 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/ProductsFeignClient.java @@ -0,0 +1,15 @@ +package com.example.webClientDemo.webclient; + +import java.net.URI; +import java.util.List; + +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +@FeignClient(value = "productsBlocking", url = "http://localhost:8080") +public interface ProductsFeignClient { + + @RequestMapping(method = RequestMethod.GET, value = "/slow-service-products", produces = "application/json") + List getProductsBlocking(URI baseUrl); +} diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/ProductsSlowServiceController.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/ProductsSlowServiceController.java new file mode 100644 index 0000000..304cc01 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/ProductsSlowServiceController.java @@ -0,0 +1,21 @@ +package com.example.webClientDemo.webclient; + +import java.util.Arrays; +import java.util.List; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class ProductsSlowServiceController { + + @GetMapping("/slow-service-products") + private List getAllProducts() throws InterruptedException { + Thread.sleep(2000L); // delay + return Arrays.asList( + new Product("Fancy Smartphone", "A stylish phone you need"), + new Product("Cool Watch", "The only device you need"), + new Product("Smart TV", "Cristal clean images") + ); + } +} diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/WebClientApplication.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/WebClientApplication.java new file mode 100644 index 0000000..ddc25c7 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/WebClientApplication.java @@ -0,0 +1,15 @@ +package com.example.webClientDemo.webclient; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.openfeign.EnableFeignClients; + +@SpringBootApplication +@EnableFeignClients +public class WebClientApplication { + + public static void main(String[] args) { + SpringApplication.run(WebClientApplication.class, args); + } +} + diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/WebController.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/WebController.java new file mode 100644 index 0000000..6d96ae3 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/WebController.java @@ -0,0 +1,59 @@ +package com.example.webClientDemo.webclient; + +import java.net.URI; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.reactive.function.client.WebClient; + +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; +import reactor.core.publisher.Flux; + +@Slf4j +@RestController +public class WebController { + + private static final int DEFAULT_PORT = 8080; + + public static final String SLOW_SERVICE_PRODUCTS_ENDPOINT_NAME = "/slow-service-products"; + + @Setter + private int serverPort = DEFAULT_PORT; + + @Autowired + private ProductsFeignClient productsFeignClient; + + @GetMapping("/products-blocking") + public List getProductsBlocking() { + log.info("Starting BLOCKING Controller!"); + final URI uri = URI.create(getSlowServiceBaseUri()); + + List result = productsFeignClient.getProductsBlocking(uri); + result.forEach(product -> log.info(product.toString())); + log.info("Exiting BLOCKING Controller!"); + return result; + } + + @GetMapping(value = "/products-non-blocking", produces = MediaType.TEXT_EVENT_STREAM_VALUE) + public Flux getProductsNonBlocking() { + log.info("Starting NON-BLOCKING Controller!"); + Flux productFlux = WebClient.create() + .get() + .uri(getSlowServiceBaseUri() + SLOW_SERVICE_PRODUCTS_ENDPOINT_NAME) + .retrieve() + .bodyToFlux(Product.class); + + productFlux.subscribe(product -> log.info(product.toString())); + log.info("Exiting NON-BLOCKING Controller!"); + return productFlux; + } + + private String getSlowServiceBaseUri() { + return "http://localhost:" + serverPort; + } + +} diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/json/ReaderConsumerService.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/json/ReaderConsumerService.java new file mode 100644 index 0000000..9ed47ef --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/json/ReaderConsumerService.java @@ -0,0 +1,18 @@ +package com.example.webClientDemo.webclient.json; + +import com.example.webClientDemo.webclient.json.model.Book; + +import java.util.List; + +public interface ReaderConsumerService { + + List processReaderDataFromObjectArray(); + + List processReaderDataFromReaderArray(); + + List processReaderDataFromReaderList(); + + List processNestedReaderDataFromReaderArray(); + + List processNestedReaderDataFromReaderList(); +} diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/json/ReaderConsumerServiceImpl.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/json/ReaderConsumerServiceImpl.java new file mode 100644 index 0000000..fe71d43 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/json/ReaderConsumerServiceImpl.java @@ -0,0 +1,90 @@ +package com.example.webClientDemo.webclient.json; + +import com.example.webClientDemo.webclient.json.model.Book; +import com.example.webClientDemo.webclient.json.model.Reader; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.MediaType; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Mono; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public class ReaderConsumerServiceImpl implements ReaderConsumerService { + + private final WebClient webClient; + private static final ObjectMapper mapper = new ObjectMapper(); + + public ReaderConsumerServiceImpl(WebClient webClient) { + this.webClient = webClient; + } + @Override + public List processReaderDataFromObjectArray() { + Mono response = webClient.get() + .accept(MediaType.APPLICATION_JSON) + .retrieve() + .bodyToMono(Object[].class).log(); + Object[] objects = response.block(); + return Arrays.stream(objects) + .map(object -> mapper.convertValue(object, Reader.class)) + .map(Reader::getFavouriteBook) + .collect(Collectors.toList()); + } + + @Override + public List processReaderDataFromReaderArray() { + Mono response = + webClient.get() + .accept(MediaType.APPLICATION_JSON) + .retrieve() + .bodyToMono(Reader[].class).log(); + + Reader[] readers = response.block(); + return Arrays.stream(readers) + .map(Reader::getFavouriteBook) + .collect(Collectors.toList()); + } + + @Override + public List processReaderDataFromReaderList() { + Mono> response = webClient.get() + .accept(MediaType.APPLICATION_JSON) + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() {}); + List readers = response.block(); + + return readers.stream() + .map(Reader::getFavouriteBook) + .collect(Collectors.toList()); + } + + @Override + public List processNestedReaderDataFromReaderArray() { + Mono response = webClient.get() + .accept(MediaType.APPLICATION_JSON) + .retrieve() + .bodyToMono(Reader[].class).log(); + Reader[] readers = response.block(); + + return Arrays.stream(readers) + .flatMap(reader -> reader.getBooksRead().stream()) + .map(Book::getAuthor) + .collect(Collectors.toList()); + } + + @Override + public List processNestedReaderDataFromReaderList() { + Mono> response = webClient.get() + .accept(MediaType.APPLICATION_JSON) + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() {}); + + List readers = response.block(); + return readers.stream() + .flatMap(reader -> reader.getBooksRead().stream()) + .map(Book::getAuthor) + .collect(Collectors.toList()); + } +} diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/json/model/Book.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/json/model/Book.java new file mode 100644 index 0000000..c07b25c --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/json/model/Book.java @@ -0,0 +1,22 @@ +package com.example.webClientDemo.webclient.json.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +import lombok.Data; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@Data +public class Book { + private final String author; + private final String title; + + @JsonCreator + public Book( + @JsonProperty("author") String author, + @JsonProperty("title") String title) { + this.author = author; + this.title = title; + } +} diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/json/model/Reader.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/json/model/Reader.java new file mode 100644 index 0000000..003f873 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/json/model/Reader.java @@ -0,0 +1,30 @@ +package com.example.webClientDemo.webclient.json.model; + +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +import lombok.Data; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@Data +public class Reader { + private final int id; + private final String name; + private final Book favouriteBook; + private final List booksRead; + + @JsonCreator + public Reader( + @JsonProperty("id") int id, + @JsonProperty("name") String name, + @JsonProperty("favouriteBook") Book favouriteBook, + @JsonProperty("booksRead") List booksRead) { + this.id = id; + this.name = name; + this.favouriteBook = favouriteBook; + this.booksRead =booksRead; + } +} diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/status/WebClientStatusCodeHandler.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/status/WebClientStatusCodeHandler.java new file mode 100644 index 0000000..c368bd7 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/status/WebClientStatusCodeHandler.java @@ -0,0 +1,58 @@ +package com.example.webClientDemo.webclient.status; + +import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; +import org.springframework.web.reactive.function.client.ClientResponse; +import org.springframework.web.reactive.function.client.ExchangeFilterFunction; +import org.springframework.web.reactive.function.client.WebClient; + +import com.example.webClientDemo.webclient.status.exception.CustomBadRequestException; +import com.example.webClientDemo.webclient.status.exception.CustomServerErrorException; + +import reactor.core.publisher.Mono; + +public class WebClientStatusCodeHandler { + + public static Mono getResponseBodyUsingExchangeFilterFunction(String uri) { + ExchangeFilterFunction errorResponseFilter = ExchangeFilterFunction + .ofResponseProcessor(WebClientStatusCodeHandler::exchangeFilterResponseProcessor); + return WebClient + .builder() + .filter(errorResponseFilter) + .build() + .post() + .uri(uri) + .retrieve() + .bodyToMono(String.class); + } + + @SuppressWarnings("unlikely-arg-type") + public static Mono getResponseBodyUsingOnStatus(String uri) { + return WebClient + .builder() + .build() + .post() + .uri(uri) + .retrieve() + .onStatus( + HttpStatus.INTERNAL_SERVER_ERROR::equals, + response -> response.bodyToMono(String.class).map(CustomServerErrorException::new)) + .onStatus( + HttpStatus.BAD_REQUEST::equals, + response -> response.bodyToMono(String.class).map(CustomBadRequestException::new)) + .bodyToMono(String.class); + } + + private static Mono exchangeFilterResponseProcessor(ClientResponse response) { + HttpStatusCode status = response.statusCode(); + if (HttpStatus.INTERNAL_SERVER_ERROR.equals(status)) { + return response.bodyToMono(String.class) + .flatMap(body -> Mono.error(new CustomServerErrorException(body))); + } + if (HttpStatus.BAD_REQUEST.equals(status)) { + return response.bodyToMono(String.class) + .flatMap(body -> Mono.error(new CustomBadRequestException(body))); + } + return Mono.just(response); + } +} diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/status/exception/CustomBadRequestException.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/status/exception/CustomBadRequestException.java new file mode 100644 index 0000000..0087f86 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/status/exception/CustomBadRequestException.java @@ -0,0 +1,7 @@ +package com.example.webClientDemo.webclient.status.exception; + +public class CustomBadRequestException extends Exception { + public CustomBadRequestException(String message) { + super(message); + } +} \ No newline at end of file diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/status/exception/CustomServerErrorException.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/status/exception/CustomServerErrorException.java new file mode 100644 index 0000000..bb0b4d2 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/status/exception/CustomServerErrorException.java @@ -0,0 +1,7 @@ +package com.example.webClientDemo.webclient.status.exception; + +public class CustomServerErrorException extends Exception { + public CustomServerErrorException(String message) { + super(message); + } +} diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/timeout/WebClientTimeoutProvider.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/timeout/WebClientTimeoutProvider.java new file mode 100644 index 0000000..3592018 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/java/com/example/webClientDemo/webclient/timeout/WebClientTimeoutProvider.java @@ -0,0 +1,92 @@ +package com.example.webClientDemo.webclient.timeout; + +import java.time.Duration; +import java.util.concurrent.TimeUnit; + +import org.springframework.http.client.reactive.ReactorClientHttpConnector; +import org.springframework.web.reactive.function.client.WebClient; + +import io.netty.channel.ChannelOption; +import io.netty.channel.epoll.EpollChannelOption; +import io.netty.handler.ssl.SslContextBuilder; +import io.netty.handler.timeout.ReadTimeoutHandler; +import io.netty.handler.timeout.WriteTimeoutHandler; +import lombok.experimental.UtilityClass; +import reactor.netty.http.client.HttpClient; +import reactor.netty.tcp.SslProvider; +import reactor.netty.transport.ProxyProvider; + +@UtilityClass +public class WebClientTimeoutProvider { + + public static WebClient defaultWebClient() { + HttpClient httpClient = HttpClient.create(); + + return buildWebClient(httpClient); + } + + public WebClient responseTimeoutClient() { + HttpClient httpClient = HttpClient.create() + .responseTimeout(Duration.ofSeconds(1)); + + return buildWebClient(httpClient); + } + + public WebClient connectionTimeoutClient() { + HttpClient httpClient = HttpClient.create() + .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000); + + return buildWebClient(httpClient); + } + + public WebClient connectionTimeoutWithKeepAliveClient() { + HttpClient httpClient = HttpClient.create() + .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000) + .option(ChannelOption.SO_KEEPALIVE, true) + .option(EpollChannelOption.TCP_KEEPIDLE, 300) + .option(EpollChannelOption.TCP_KEEPINTVL, 60) + .option(EpollChannelOption.TCP_KEEPCNT, 8); + + return buildWebClient(httpClient); + } + + public WebClient readWriteTimeoutClient() { + @SuppressWarnings("deprecation") + HttpClient httpClient = HttpClient.create() + .doOnConnected(conn -> conn + .addHandler(new ReadTimeoutHandler(5, TimeUnit.SECONDS)) + .addHandler(new WriteTimeoutHandler(5))); + + return buildWebClient(httpClient); + } + + public WebClient sslTimeoutClient() { + @SuppressWarnings("deprecation") + HttpClient httpClient = HttpClient.create() + .secure(spec -> spec + .sslContext(SslContextBuilder.forClient()) + .defaultConfiguration(SslProvider.DefaultConfigurationType.TCP) + .handshakeTimeout(Duration.ofSeconds(30)) + .closeNotifyFlushTimeout(Duration.ofSeconds(10)) + .closeNotifyReadTimeout(Duration.ofSeconds(10))); + + return buildWebClient(httpClient); + } + + public WebClient proxyTimeoutClient() { + HttpClient httpClient = HttpClient.create() + .proxy(spec -> spec + .type(ProxyProvider.Proxy.HTTP) + .host("http://proxy") + .port(8080) + .connectTimeoutMillis(3000)); + + return buildWebClient(httpClient); + } + + private WebClient buildWebClient(HttpClient httpClient) { + return WebClient.builder() + .clientConnector(new ReactorClientHttpConnector(httpClient)) + .build(); + } +} diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/resources/application.properties b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/resources/application.properties new file mode 100644 index 0000000..39eeab8 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/resources/application.properties @@ -0,0 +1,3 @@ +logging.level.root=INFO +server.port=8081 +logging.level.reactor.netty.http.client.HttpClient=DEBUG diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/resources/logback.xml b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/resources/logback.xml new file mode 100644 index 0000000..2721b93 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/resources/logback.xml @@ -0,0 +1,20 @@ + + + + + # Pattern of log message for console appender + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/webapp/WEB-INF/web.xml b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000..5c53472 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,21 @@ + + + + Spring Functional Application + + + functional + com.example.webClientDemo.functional.RootServlet + 1 + true + + + functional + / + + + + \ No newline at end of file diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/SpringContextTest.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/SpringContextTest.java new file mode 100644 index 0000000..f20669b --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/SpringContextTest.java @@ -0,0 +1,17 @@ +package com.example.webClientDemo; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.example.webClientDemo.reactive.SpringReactiveTestApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringReactiveTestApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/reactive/ReactiveIntegrationTest.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/reactive/ReactiveIntegrationTest.java new file mode 100644 index 0000000..0b3a68e --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/reactive/ReactiveIntegrationTest.java @@ -0,0 +1,73 @@ +package com.example.webClientDemo.reactive; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.reactive.function.client.ClientResponse; +import org.springframework.web.reactive.function.client.WebClient; + +import com.example.webClientDemo.reactive.model.Foo; +import com.github.tomakehurst.wiremock.WireMockServer; +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; + +import reactor.core.publisher.Mono; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class ReactiveIntegrationTest { + + private WebClient client; + private final int singleRequestTime = 1000; + private WireMockServer wireMockServer; + + @Before + public void setup() { + wireMockServer = new WireMockServer(wireMockConfig().dynamicPort()); + wireMockServer.start(); + configureFor("localhost", wireMockServer.port()); + client = WebClient.create("http://localhost:" + wireMockServer.port()); + } + + @After + public void tearDown() { + wireMockServer.stop(); + } + + @Test + public void whenMonoReactiveEndpointIsConsumed_thenCorrectOutput() { + stubFor(get(urlEqualTo("/foo/123")).willReturn(aResponse().withFixedDelay(singleRequestTime) + .withStatus(200) + .withHeader("Content-Type", "application/json") + .withBody("{\"id\":123, \"name\":\"foo\"}"))); + + final Mono fooMono = client.get().uri("/foo/123").retrieve() + .bodyToMono(ClientResponse.class) + .log(); + + System.out.println(fooMono.subscribe()); + } + + @Test + public void whenFluxReactiveEndpointIsConsumed_thenCorrectOutput() throws InterruptedException { + stubFor(get(urlEqualTo("/foo")).willReturn(aResponse().withFixedDelay(singleRequestTime) + .withStatus(200) + .withHeader("Content-Type", "application/json") + .withBody("{\"id\":1, \"name\":\"foo\"}"))); + + client.get().uri("/foo") + .retrieve() + .bodyToFlux(Foo.class).log() + .subscribe(System.out::println); + + System.out.println(); + } + +} diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/reactive/SpringReactiveTestApplication.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/reactive/SpringReactiveTestApplication.java new file mode 100644 index 0000000..2396c64 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/reactive/SpringReactiveTestApplication.java @@ -0,0 +1,34 @@ +package com.example.webClientDemo.reactive; + +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.web.reactive.function.client.WebClient; + +import com.example.webClientDemo.reactive.model.Foo; + +@SpringBootApplication +public class SpringReactiveTestApplication { + + @Bean + public WebClient client() { + return WebClient.create("http://localhost:8080"); + } + + @Bean + CommandLineRunner cmd(WebClient client) { + return args -> { + client.get().uri("/foos2") + .retrieve() + .bodyToFlux(Foo.class).log() + .subscribe(System.out::println); + }; + } + + // + public static void main(String[] args) { + SpringApplication.run(SpringReactiveTestApplication.class, args); + } + +} diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/reactive/logging/WebClientLoggingIntegrationTest.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/reactive/logging/WebClientLoggingIntegrationTest.java new file mode 100644 index 0000000..b48d4a0 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/reactive/logging/WebClientLoggingIntegrationTest.java @@ -0,0 +1,129 @@ +package com.example.webClientDemo.reactive.logging; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import org.slf4j.LoggerFactory; +import org.springframework.http.client.reactive.ReactorClientHttpConnector; +import org.springframework.web.reactive.function.BodyInserters; +import org.springframework.web.reactive.function.client.WebClient; + +import com.example.webClientDemo.reactive.logging.filters.LogFilters; +import com.fasterxml.jackson.databind.ObjectMapper; + +import ch.qos.logback.classic.spi.LoggingEvent; +import ch.qos.logback.core.Appender; +import io.netty.handler.logging.LogLevel; +import lombok.AllArgsConstructor; +import lombok.Data; +import reactor.netty.http.client.HttpClient; +import reactor.netty.transport.logging.AdvancedByteBufFormat; + + +public class WebClientLoggingIntegrationTest { + + @AllArgsConstructor + @Data + class Post { + private String title; + private String body; + private int userId; + } + + @SuppressWarnings("rawtypes") + private Appender jettyAppender; + @SuppressWarnings("rawtypes") + private Appender nettyAppender; + @SuppressWarnings("rawtypes") + private Appender mockAppender; + private final String sampleUrl = "https://jsonplaceholder.typicode.com/posts"; + + private Post post; + private String sampleResponseBody; + + @SuppressWarnings("unchecked") + @BeforeEach + void setup() throws Exception { + + post = new Post("Learn WebClient logging with Baeldung!", "", 1); + sampleResponseBody = new ObjectMapper().writeValueAsString(post); + + ch.qos.logback.classic.Logger jetty = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("com.example.webClientDemo.reactive.logging.jetty"); + jettyAppender = mock(Appender.class); + when(jettyAppender.getName()).thenReturn("com.example.webClientDemo.reactive.logging.jetty"); + jetty.addAppender(jettyAppender); + + ch.qos.logback.classic.Logger netty = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("reactor.netty.http.client"); + nettyAppender = mock(Appender.class); + when(nettyAppender.getName()).thenReturn("reactor.netty.http.client"); + netty.addAppender(nettyAppender); + + ch.qos.logback.classic.Logger test = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("com.example.webClientDemo.reactive"); + mockAppender = mock(Appender.class); + when(mockAppender.getName()).thenReturn("com.example.webClientDemo.reactive"); + test.addAppender(mockAppender); + + } + + @SuppressWarnings("unchecked") + @Test + public void givenNettyHttpClientWithWiretap_whenEndpointIsConsumed_thenRequestAndResponseBodyLogged() { + + reactor.netty.http.client.HttpClient httpClient = HttpClient + .create() + .wiretap(true); + + WebClient + .builder() + .clientConnector(new ReactorClientHttpConnector(httpClient)) + .build() + .post() + .uri(sampleUrl) + .body(BodyInserters.fromValue(post)) + .retrieve() + .bodyToMono(String.class) + .block(); + + verify(nettyAppender).doAppend(argThat(argument -> (((LoggingEvent) argument).getFormattedMessage()).contains("00000300"))); + } + + @SuppressWarnings("unchecked") + @Test + public void givenNettyHttpClientWithCustomLogger_whenEndpointIsConsumed_thenRequestAndResponseBodyLogged() { + reactor.netty.http.client.HttpClient httpClient = HttpClient.create() + .wiretap("reactor.netty.http.client.HttpClient", LogLevel.DEBUG, AdvancedByteBufFormat.TEXTUAL); + + WebClient.builder() + .clientConnector(new ReactorClientHttpConnector(httpClient)) + .build() + .post() + .uri(sampleUrl) + .body(BodyInserters.fromValue(post)) + .retrieve() + .bodyToMono(String.class) + .block(); + + verify(nettyAppender).doAppend(argThat(argument -> (((LoggingEvent) argument).getFormattedMessage()).contains(sampleResponseBody))); + } + + @SuppressWarnings("unchecked") + @Test + public void givenDefaultHttpClientWithFilter_whenEndpointIsConsumed_thenRequestAndResponseLogged() { + WebClient + .builder() + .filters(exchangeFilterFunctions -> exchangeFilterFunctions.addAll(LogFilters.prepareFilters())) + .build() + .post() + .uri(sampleUrl) + .body(BodyInserters.fromValue(post)) + .retrieve() + .bodyToMono(String.class) + .block(); + + verify(mockAppender, atLeast(1)).doAppend(argThat(argument -> (((LoggingEvent) argument).getFormattedMessage()).contains(sampleUrl))); + } +} \ No newline at end of file diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/reactive/logging/filters/LogFilters.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/reactive/logging/filters/LogFilters.java new file mode 100644 index 0000000..74a6c95 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/reactive/logging/filters/LogFilters.java @@ -0,0 +1,54 @@ +package com.example.webClientDemo.reactive.logging.filters; + +import java.util.Arrays; +import java.util.List; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.reactive.function.client.ExchangeFilterFunction; +import reactor.core.publisher.Mono; + +@Slf4j +public class LogFilters { + public static List prepareFilters() { + return Arrays.asList(logRequest(), logResponse()); + } + + private static ExchangeFilterFunction logRequest() { + return ExchangeFilterFunction.ofRequestProcessor(clientRequest -> { + if (log.isDebugEnabled()) { + StringBuilder sb = new StringBuilder("Request: \n") + .append(clientRequest.method()) + .append(" ") + .append(clientRequest.url()); + clientRequest + .headers() + .forEach((name, values) -> values.forEach(value -> sb + .append("\n") + .append(name) + .append(":") + .append(value))); + log.debug(sb.toString()); + } + return Mono.just(clientRequest); + }); + } + + private static ExchangeFilterFunction logResponse() { + return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> { + if (log.isDebugEnabled()) { + StringBuilder sb = new StringBuilder("Response: \n") + .append("Status: ") + .append(clientResponse.statusCode()); + clientResponse + .headers() + .asHttpHeaders() + .forEach((key, value1) -> value1.forEach(value -> sb + .append("\n") + .append(key) + .append(":") + .append(value))); + log.debug(sb.toString()); + } + return Mono.just(clientResponse); + }); + } +} diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/reactive/logging/jetty/RequestLogEnhancer.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/reactive/logging/jetty/RequestLogEnhancer.java new file mode 100644 index 0000000..1cba936 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/reactive/logging/jetty/RequestLogEnhancer.java @@ -0,0 +1,95 @@ +package com.example.webClientDemo.reactive.logging.jetty; + +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.Locale; + +import org.eclipse.jetty.client.Request; +import org.eclipse.jetty.http.HttpField; +import org.eclipse.jetty.http.HttpFields; +import org.eclipse.jetty.http.HttpHeader; + +import lombok.extern.slf4j.Slf4j; + +@Slf4j +public class RequestLogEnhancer { + + public static Request enhance(Request request) { + StringBuilder group = new StringBuilder(); + request.onRequestBegin(theRequest -> group + .append("Request ") + .append(theRequest.getMethod()) + .append(" ") + .append(theRequest.getURI()) + .append("\n")); + request.onRequestHeaders(theRequest -> { + for (HttpField header : theRequest.getHeaders()) + group + .append(header) + .append("\n"); + }); + request.onRequestContent((theRequest, content) -> { + group.append(toString(content, getCharset(theRequest.getHeaders()))); + }); + request.onRequestSuccess(theRequest -> { + log.debug(group.toString()); + group.delete(0, group.length()); + }); + group.append("\n"); + request.onResponseBegin(theResponse -> { + group + .append("Response \n") + .append(theResponse.getVersion()) + .append(" ") + .append(theResponse.getStatus()); + if (theResponse.getReason() != null) { + group + .append(" ") + .append(theResponse.getReason()); + } + group.append("\n"); + }); + request.onResponseHeaders(theResponse -> { + for (HttpField header : theResponse.getHeaders()) + group + .append(header) + .append("\n"); + }); + request.onResponseContent((theResponse, content) -> { + group.append(toString(content, getCharset(theResponse.getHeaders()))); + }); + request.onResponseSuccess(theResponse -> { + log.debug(group.toString()); + }); + return request; + } + + private static String toString(ByteBuffer buffer, Charset charset) { + byte[] bytes; + if (buffer.hasArray()) { + bytes = new byte[buffer.capacity()]; + System.arraycopy(buffer.array(), 0, bytes, 0, buffer.capacity()); + } else { + bytes = new byte[buffer.remaining()]; + buffer.get(bytes, 0, bytes.length); + } + return new String(bytes, charset); + } + + private static Charset getCharset(HttpFields headers) { + String contentType = headers.get(HttpHeader.CONTENT_TYPE); + if (contentType != null) { + String[] tokens = contentType + .toLowerCase(Locale.US) + .split("charset="); + if (tokens.length == 2) { + String encoding = tokens[1].replaceAll("[;\"]", ""); + return Charset.forName(encoding); + } + } + return StandardCharsets.UTF_8; + } + +} + diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/reactive/service/EmployeeServiceIntgerationTest.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/reactive/service/EmployeeServiceIntgerationTest.java new file mode 100644 index 0000000..addc247 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/reactive/service/EmployeeServiceIntgerationTest.java @@ -0,0 +1,123 @@ +package com.example.webClientDemo.reactive.service; + +import java.io.IOException; +import java.util.Objects; + +import org.junit.jupiter.api.AfterAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.example.webClientDemo.reactive.enums.Role; +import com.example.webClientDemo.reactive.model.Employee; +import com.fasterxml.jackson.databind.ObjectMapper; + +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import okhttp3.mockwebserver.RecordedRequest; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +class EmployeeServiceIntegrationTest { + + public static MockWebServer mockBackEnd; + private EmployeeService employeeService; + private final ObjectMapper MAPPER = new ObjectMapper(); + + @BeforeAll + static void setUp() throws IOException { + mockBackEnd = new MockWebServer(); + mockBackEnd.start(); + } + + @AfterAll + static void tearDown() throws IOException { + mockBackEnd.shutdown(); + } + + @BeforeEach + void initialize() { + String baseUrl = String.format("http://localhost:%s", mockBackEnd.getPort()); + employeeService = new EmployeeService(baseUrl); + } + + @Test + void getEmployeeById() throws Exception { + + Employee mockEmployee = new Employee(100, "Adam", "Sandler", 32, Role.LEAD_ENGINEER); + mockBackEnd.enqueue(new MockResponse().setBody(MAPPER.writeValueAsString(mockEmployee)) + .addHeader("Content-Type", "application/json")); + + Mono employeeMono = employeeService.getEmployeeById(100); + + StepVerifier.create(employeeMono) + .expectNextMatches(employee -> employee.getRole().equals(Role.LEAD_ENGINEER)) + .verifyComplete(); + + RecordedRequest recordedRequest = mockBackEnd.takeRequest(); + assertEquals("GET", recordedRequest.getMethod()); + assertEquals("/employee/100", recordedRequest.getPath()); + } + + @Test + void addNewEmployee() throws Exception { + + Employee newEmployee = new Employee(null, "Adam", "Sandler", 32, Role.LEAD_ENGINEER); + Employee webClientResponse = new Employee(100, "Adam", "Sandler", 32, Role.LEAD_ENGINEER); + mockBackEnd.enqueue(new MockResponse().setBody(MAPPER.writeValueAsString(webClientResponse)) + .addHeader("Content-Type", "application/json")); + + Mono employeeMono = employeeService.addNewEmployee(newEmployee); + + StepVerifier.create(employeeMono) + .expectNextMatches(employee -> employee.getEmployeeId().equals(100)) + .verifyComplete(); + + RecordedRequest recordedRequest = mockBackEnd.takeRequest(); + assertEquals("POST", recordedRequest.getMethod()); + assertEquals("/employee", recordedRequest.getPath()); + } + + @Test + void updateEmployee() throws Exception { + + Integer newAge = 33; + String newLastName = "Sandler New"; + Employee updateEmployee = new Employee(100, "Adam", newLastName, newAge, Role.LEAD_ENGINEER); + mockBackEnd.enqueue(new MockResponse().setBody(MAPPER.writeValueAsString(updateEmployee)) + .addHeader("Content-Type", "application/json")); + + Mono updatedEmploye = employeeService.updateEmployee(100, updateEmployee); + + StepVerifier.create(updatedEmploye) + .expectNextMatches(employee -> employee.getLastName().equals(newLastName) && Objects.equals(employee.getAge(), newAge)) + .verifyComplete(); + + RecordedRequest recordedRequest = mockBackEnd.takeRequest(); + assertEquals("PUT", recordedRequest.getMethod()); + assertEquals("/employee/100", recordedRequest.getPath()); + + } + + + @Test + void deleteEmployee() throws Exception { + + String responseMessage = "Employee Deleted SuccessFully"; + Integer employeeId = 100; + mockBackEnd.enqueue(new MockResponse().setBody(MAPPER.writeValueAsString(responseMessage)) + .addHeader("Content-Type", "application/json")); + + Mono deletedEmployee = employeeService.deleteEmployeeById(employeeId); + + StepVerifier.create(deletedEmployee) + .expectNext("\"Employee Deleted SuccessFully\"") + .verifyComplete(); + + RecordedRequest recordedRequest = mockBackEnd.takeRequest(); + assertEquals("DELETE", recordedRequest.getMethod()); + assertEquals("/employee/100", recordedRequest.getPath()); + } + +} diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/reactive/service/EmployeeServiceUnitTest.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/reactive/service/EmployeeServiceUnitTest.java new file mode 100644 index 0000000..5dfbe41 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/reactive/service/EmployeeServiceUnitTest.java @@ -0,0 +1,117 @@ +package com.example.webClientDemo.reactive.service; + +import java.util.Objects; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import static org.mockito.Mockito.when; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.web.reactive.function.client.WebClient; + +import com.example.webClientDemo.reactive.enums.Role; +import com.example.webClientDemo.reactive.model.Employee; + +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +@ExtendWith(MockitoExtension.class) +class EmployeeServiceUnitTest { + + EmployeeService employeeService; + @Mock + private WebClient webClientMock; + @SuppressWarnings("rawtypes") + @Mock + private WebClient.RequestHeadersSpec requestHeadersMock; + @SuppressWarnings("rawtypes") + @Mock + private WebClient.RequestHeadersUriSpec requestHeadersUriMock; + @Mock + private WebClient.RequestBodySpec requestBodyMock; + @Mock + private WebClient.RequestBodyUriSpec requestBodyUriMock; + @Mock + private WebClient.ResponseSpec responseMock; + + @BeforeEach + void setUp() { + employeeService = new EmployeeService(webClientMock); + } + + @SuppressWarnings("unchecked") + @Test + void givenEmployeeId_whenGetEmployeeById_thenReturnEmployee() { + + Integer employeeId = 100; + Employee mockEmployee = new Employee(100, "Adam", "Sandler", 32, Role.LEAD_ENGINEER); + when(webClientMock.get()).thenReturn(requestHeadersUriMock); + when(requestHeadersUriMock.uri("/employee/{id}", employeeId)).thenReturn(requestHeadersMock); + when(requestHeadersMock.retrieve()).thenReturn(responseMock); + when(responseMock.bodyToMono(Employee.class)).thenReturn(Mono.just(mockEmployee)); + + Mono employeeMono = employeeService.getEmployeeById(employeeId); + + StepVerifier.create(employeeMono) + .expectNextMatches(employee -> employee.getRole().equals(Role.LEAD_ENGINEER)) + .verifyComplete(); + } + + @SuppressWarnings({ "deprecation", "unchecked" }) + @Test + void givenEmployee_whenAddEmployee_thenAddNewEmployee() { + + Employee newEmployee = new Employee(null, "Adam", "Sandler", 32, Role.LEAD_ENGINEER); + Employee webClientResponse = new Employee(100, "Adam", "Sandler", 32, Role.LEAD_ENGINEER); + when(webClientMock.post()).thenReturn(requestBodyUriMock); + when(requestBodyUriMock.uri(EmployeeService.ADD_EMPLOYEE)).thenReturn(requestBodyMock); + when(requestBodyMock.syncBody(newEmployee)).thenReturn(requestHeadersMock); + when(requestHeadersMock.retrieve()).thenReturn(responseMock); + when(responseMock.bodyToMono(Employee.class)).thenReturn(Mono.just(webClientResponse)); + + Mono employeeMono = employeeService.addNewEmployee(newEmployee); + + StepVerifier.create(employeeMono) + .expectNextMatches(employee -> employee.getEmployeeId().equals(100)) + .verifyComplete(); + } + + @SuppressWarnings({ "deprecation", "unchecked" }) + @Test + void givenEmployee_whenupdateEmployee_thenUpdatedEmployee() { + + Integer newAge = 33; + String newLastName = "Sandler New"; + Employee updateEmployee = new Employee(100, "Adam", newLastName, newAge, Role.LEAD_ENGINEER); + when(webClientMock.put()).thenReturn(requestBodyUriMock); + when(requestBodyUriMock.uri(EmployeeService.PATH_PARAM_BY_ID, 100)).thenReturn(requestBodyMock); + when(requestBodyMock.syncBody(updateEmployee)).thenReturn(requestHeadersMock); + when(requestHeadersMock.retrieve()).thenReturn(responseMock); + when(responseMock.bodyToMono(Employee.class)).thenReturn(Mono.just(updateEmployee)); + + Mono updatedEmployee = employeeService.updateEmployee(100, updateEmployee); + + StepVerifier.create(updatedEmployee) + .expectNextMatches(employee -> employee.getLastName().equals(newLastName) && Objects.equals(employee.getAge(), newAge)) + .verifyComplete(); + + } + + @SuppressWarnings("unchecked") + @Test + void givenEmployee_whenDeleteEmployeeById_thenDeleteSuccessful() { + + String responseMessage = "Employee Deleted SuccessFully"; + when(webClientMock.delete()).thenReturn(requestHeadersUriMock); + when(requestHeadersUriMock.uri(EmployeeService.PATH_PARAM_BY_ID, 100)).thenReturn(requestHeadersMock); + when(requestHeadersMock.retrieve()).thenReturn(responseMock); + when(responseMock.bodyToMono(String.class)).thenReturn(Mono.just(responseMessage)); + + Mono deletedEmployee = employeeService.deleteEmployeeById(100); + + StepVerifier.create(deletedEmployee) + .expectNext(responseMessage) + .verifyComplete(); + } +} diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/reactive/service/ReactiveUploadServiceUnitTest.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/reactive/service/ReactiveUploadServiceUnitTest.java new file mode 100644 index 0000000..547dee8 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/reactive/service/ReactiveUploadServiceUnitTest.java @@ -0,0 +1,49 @@ +package com.example.webClientDemo.reactive.service; + +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.jupiter.api.Test; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.reactive.function.client.ClientResponse; +import org.springframework.web.reactive.function.client.WebClient; + +import reactor.core.publisher.Mono; + +class ReactiveUploadServiceUnitTest { + + private static final String BASE_URL = "http://localhost:8080/external/upload"; + + final WebClient webClientMock = WebClient.builder().baseUrl(BASE_URL) + .exchangeFunction(clientRequest -> Mono.just(ClientResponse.create(HttpStatus.OK) + .header("content-type", "application/json") + .build())) + .build(); + + private final ReactiveUploadService tested = new ReactiveUploadService(webClientMock); + + @Test + void givenAPdf_whenUploadingWithWebClient_thenOK() { + final Resource file = mock(Resource.class); + + final Mono result = tested.uploadPdf(file); + final HttpStatusCode status = result.block(); + + assertThat(status).isEqualTo(HttpStatus.OK); + } + + @Test + void givenAMultipartPdf_whenUploadingWithWebClient_thenOK() { + final Resource file = mock(Resource.class); + final MultipartFile multipartFile = mock(MultipartFile.class); + when(multipartFile.getResource()).thenReturn(file); + + final Mono result = tested.uploadMultipart(multipartFile); + final HttpStatusCode status = result.block(); + + assertThat(status).isEqualTo(HttpStatus.OK); + } +} diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/reactive/webclient/simultaneous/ClientIntegrationTest.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/reactive/webclient/simultaneous/ClientIntegrationTest.java new file mode 100644 index 0000000..4afbd67 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/reactive/webclient/simultaneous/ClientIntegrationTest.java @@ -0,0 +1,77 @@ +package com.example.webClientDemo.reactive.webclient.simultaneous; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import org.junit.After; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.junit4.SpringRunner; + +import com.github.tomakehurst.wiremock.WireMockServer; +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; + +@RunWith(SpringRunner.class) +@SpringBootTest +@DirtiesContext +public class ClientIntegrationTest { + + private WireMockServer wireMockServer; + + private Client client; + + @Before + public void setup() { + wireMockServer = new WireMockServer(wireMockConfig().dynamicPort()); + wireMockServer.start(); + configureFor("localhost", wireMockServer.port()); + client = new Client("http://localhost:" + wireMockServer.port()); + } + + @After + public void tearDown() { + wireMockServer.stop(); + } + + @Test + public void givenClient_whenFetchingUsers_thenExecutionTimeIsLessThanDouble() { + // Arrange + int requestsNumber = 5; + int singleRequestTime = 1000; + + for (int i = 1; i <= requestsNumber; i++) { + stubFor(get(urlEqualTo("/user/" + i)).willReturn(aResponse().withFixedDelay(singleRequestTime) + .withStatus(200) + .withHeader("Content-Type", "application/json") + .withBody(String.format("{ \"id\": %d }", i)))); + } + + List userIds = IntStream.rangeClosed(1, requestsNumber) + .boxed() + .collect(Collectors.toList()); + + // Act + long start = System.currentTimeMillis(); + List users = client.fetchUsers(userIds) + .collectList() + .block(); + long end = System.currentTimeMillis(); + + // Assert + long totalExecutionTime = end - start; + + assertEquals("Unexpected number of users", requestsNumber, users.size()); + assertTrue("Execution time is too big", 2 * singleRequestTime > totalExecutionTime); + } +} diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/webclient/WebClientStatusCodeHandlerIntegrationTest.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/webclient/WebClientStatusCodeHandlerIntegrationTest.java new file mode 100644 index 0000000..20390d3 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/webclient/WebClientStatusCodeHandlerIntegrationTest.java @@ -0,0 +1,98 @@ +package com.example.webClientDemo.webclient; + +import com.example.webClientDemo.webclient.status.WebClientStatusCodeHandler; +import com.github.tomakehurst.wiremock.WireMockServer; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.junit4.SpringRunner; +import reactor.core.publisher.Mono; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; +import static java.lang.String.format; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; + +@RunWith(SpringRunner.class) +public class WebClientStatusCodeHandlerIntegrationTest { + private String baseUrl; + private WireMockServer wireMockServer; + + @Before + public void setUp() { + wireMockServer = new WireMockServer(wireMockConfig().dynamicPort()); + wireMockServer.start(); + configureFor("localhost", wireMockServer.port()); + baseUrl = format("http://localhost:%s", wireMockServer.port()); + } + + @After + public void tearDown() { + wireMockServer.stop(); + } + + @Test + public void whenResponseIs2XX_thenBothStatusHandlerAndExchangeFilterReturnEqualResponses() { + stubPostResponse("/success", 200, "success"); + + Mono responseStatusHandler = WebClientStatusCodeHandler + .getResponseBodyUsingOnStatus(baseUrl + "/success"); + + Mono responseExchangeFilter = WebClientStatusCodeHandler + .getResponseBodyUsingExchangeFilterFunction(baseUrl + "/success"); + + assertThat(responseStatusHandler.block()) + .isEqualTo(responseExchangeFilter.block()) + .isEqualTo("success"); + } + + @Test + public void whenResponseIs500_thenBothStatusHandlerAndExchangeFilterReturnEqualResponses() { + stubPostResponse("/server-error", 500, "Internal Server Error"); + + Mono responseStatusHandler = WebClientStatusCodeHandler + .getResponseBodyUsingOnStatus(baseUrl + "/server-error"); + + Mono responseExchangeFilter = WebClientStatusCodeHandler + .getResponseBodyUsingExchangeFilterFunction(baseUrl + "/server-error"); + + assertThatThrownBy(responseStatusHandler::block) + .isInstanceOf(Exception.class) + .hasMessageContaining("Internal Server Error"); + + assertThatThrownBy(responseExchangeFilter::block) + .isInstanceOf(Exception.class) + .hasMessageContaining("Internal Server Error"); + } + + @Test + public void whenResponseIs400_thenBothStatusHandlerAndExchangeFilterReturnEqualResponses() { + stubPostResponse("/client-error", 400, "Bad Request"); + + Mono responseStatusHandler = WebClientStatusCodeHandler + .getResponseBodyUsingOnStatus(baseUrl + "/client-error"); + + Mono responseExchangeFilter = WebClientStatusCodeHandler + .getResponseBodyUsingExchangeFilterFunction(baseUrl + "/client-error"); + + assertThatThrownBy(responseStatusHandler::block) + .isInstanceOf(Exception.class) + .hasMessageContaining("Bad Request"); + + assertThatThrownBy(responseExchangeFilter::block) + .isInstanceOf(Exception.class) + .hasMessageContaining("Bad Request"); + } + + private static void stubPostResponse(String url, int statusCode, String response) { + stubFor(post(urlEqualTo(url)).willReturn(aResponse() + .withStatus(statusCode) + .withBody(response))); + } +} diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/webclient/WebControllerIntegrationTest.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/webclient/WebControllerIntegrationTest.java new file mode 100644 index 0000000..c3747d2 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/webclient/WebControllerIntegrationTest.java @@ -0,0 +1,49 @@ +package com.example.webClientDemo.webclient; + +import static org.springframework.test.annotation.DirtiesContext.ClassMode.BEFORE_CLASS; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.web.reactive.server.WebTestClient; + +@DirtiesContext(classMode = BEFORE_CLASS) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = WebClientApplication.class) +class WebControllerIntegrationTest { + + @LocalServerPort + private int randomServerPort; + + @Autowired + private WebTestClient testClient; + + @Autowired + private WebController webController; + + @BeforeEach + void setup() { + webController.setServerPort(randomServerPort); + } + + @Test + void whenEndpointWithBlockingClientIsCalled_thenThreeProductsAreReceived() { + testClient.get() + .uri("/products-blocking") + .exchange() + .expectStatus().isOk() + .expectBodyList(Product.class).hasSize(3); + } + + @Test + void whenEndpointWithNonBlockingClientIsCalled_thenThreeProductsAreReceived() { + testClient.get() + .uri("/products-non-blocking") + .exchange() + .expectStatus().isOk() + .expectBodyList(Product.class).hasSize(3); + } +} diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/webclient/json/ReaderConsumerServiceImplUnitTest.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/webclient/json/ReaderConsumerServiceImplUnitTest.java new file mode 100644 index 0000000..7eeabb0 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/webclient/json/ReaderConsumerServiceImplUnitTest.java @@ -0,0 +1,88 @@ +package com.example.webClientDemo.webclient.json; + +import com.example.webClientDemo.webclient.json.model.Book; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; +import org.springframework.web.reactive.function.client.ClientResponse; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Mono; + +import java.util.Arrays; +import java.util.List; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.CoreMatchers.hasItems; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.Matchers.hasProperty; + +public class ReaderConsumerServiceImplUnitTest { + + private static final String READER_JSON = "[{\"id\":1,\"name\":\"reader1\",\"favouriteBook\":{\"author\":\"Milan Kundera\",\"title\":\"The Unbearable Lightness of Being\"}," + + "\"booksRead\":[{\"author\":\"Charles Dickens\",\"title\":\"Oliver Twist\"},{\"author\":\"Milan Kundera\",\"title\":\"The Unbearable Lightness of Being\"}]}," + + "{\"id\":2,\"name\":\"reader2\",\"favouriteBook\":{\"author\":\"Douglas Adams\",\"title\":\"The Hitchhiker\'s Guide to the Galaxy\"}," + + "\"booksRead\":[{\"author\":\"J.R.R. Tolkien\",\"title\":\"Lord of the Rings\"}, " + + "{\"author\":\"Douglas Adams\",\"title\":\"The Hitchhiker\'s Guide to the Galaxy\"}]}]"; + + private static final String BASE_URL = "http://localhost:8080/readers"; + + WebClient webClientMock = WebClient.builder().baseUrl(BASE_URL) + .exchangeFunction(clientRequest -> Mono.just(ClientResponse.create(HttpStatus.OK) + .header("content-type", "application/json") + .body(READER_JSON) + .build())) + .build(); + + private final ReaderConsumerService tested = new ReaderConsumerServiceImpl(webClientMock); + + @Test + void when_processReaderDataFromObjectArray_then_OK() { + String expectedAuthor1 = "Milan Kundera"; + String expectedAuthor2 = "Douglas Adams"; + List actual = tested.processReaderDataFromObjectArray(); + assertThat(actual, hasItems(hasProperty("author", is(expectedAuthor1)), + hasProperty("author", is(expectedAuthor2)))); + } + + @Test + void when_processReaderDataFromReaderArray_then_OK() { + String expectedAuthor1 = "Milan Kundera"; + String expectedAuthor2 = "Douglas Adams"; + List actual = tested.processReaderDataFromReaderArray(); + assertThat(actual, hasItems(hasProperty("author", is(expectedAuthor1)), + hasProperty("author", is(expectedAuthor2)))); + } + + @Test + void when_processReaderDataFromReaderList_then_OK() { + String expectedAuthor1 = "Milan Kundera"; + String expectedAuthor2 = "Douglas Adams"; + List actual = tested.processReaderDataFromReaderList(); + assertThat(actual, hasItems(hasProperty("author", is(expectedAuthor1)), + hasProperty("author", is(expectedAuthor2)))); + + } + + @Test + void when_processNestedReaderDataFromReaderArray_then_OK() { + List expected = Arrays.asList( + "Milan Kundera", + "Charles Dickens", + "J.R.R. Tolkien", + "Douglas Adams"); + + List actual = tested.processNestedReaderDataFromReaderArray(); + assertThat(actual, hasItems(expected.get(0), expected.get(1), expected.get(2), expected.get(3))); + } + + @Test + void when_processNestedReaderDataFromReaderList_then_OK() { + List expected = Arrays.asList( + "Milan Kundera", + "Charles Dickens", + "J.R.R. Tolkien", + "Douglas Adams"); + + List actual = tested.processNestedReaderDataFromReaderList(); + assertThat(actual, hasItems(expected.get(0), expected.get(1), expected.get(2), expected.get(3))); + } +} diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/webclient/timeout/WebClientTimeoutIntegrationTest.java b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/webclient/timeout/WebClientTimeoutIntegrationTest.java new file mode 100644 index 0000000..54367fc --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/java/com/example/webClientDemo/webclient/timeout/WebClientTimeoutIntegrationTest.java @@ -0,0 +1,133 @@ +package com.example.webClientDemo.webclient.timeout; + +import com.github.tomakehurst.wiremock.WireMockServer; +import io.netty.handler.timeout.ReadTimeoutException; +import lombok.val; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.springframework.http.HttpStatus; +import org.springframework.web.reactive.function.client.WebClientRequestException; +import reactor.core.publisher.Mono; +import reactor.netty.http.client.HttpClientRequest; + + +import java.time.Duration; +import java.util.concurrent.TimeoutException; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +public class WebClientTimeoutIntegrationTest { + + private WireMockServer wireMockServer; + + @Before + public void setup() { + wireMockServer = new WireMockServer(wireMockConfig().dynamicPort()); + wireMockServer.start(); + configureFor("localhost", wireMockServer.port()); + } + + @After + public void tearDown() { + wireMockServer.stop(); + } + + @AfterEach + public void tearDownEach() { + wireMockServer.resetAll(); + } + + @SuppressWarnings("deprecation") + @Test + public void givenResponseTimeoutClientWhenRequestTimeoutThenReadTimeoutException() { + val path = "/response-timeout"; + val delay = Math.toIntExact(Duration.ofSeconds(2).toMillis()); + stubFor(get(urlEqualTo(path)).willReturn(aResponse().withFixedDelay(delay) + .withStatus(HttpStatus.OK.value()))); + + val webClient = WebClientTimeoutProvider.responseTimeoutClient(); + + val ex = assertThrows(RuntimeException.class, () -> + webClient.get() + .uri(wireMockServer.baseUrl() + path) + .exchangeToMono(Mono::just) + .log() + .block()); + assertThat(ex).isInstanceOf(WebClientRequestException.class) + .getCause().isInstanceOf(ReadTimeoutException.class); + } + + @SuppressWarnings("deprecation") + @Test + public void givenReadWriteTimeoutClientWhenRequestTimeoutThenReadTimeoutException() { + val path = "/read-write-timeout"; + val delay = Math.toIntExact(Duration.ofSeconds(6).toMillis()); + stubFor(get(urlEqualTo(path)).willReturn(aResponse().withFixedDelay(delay) + .withStatus(HttpStatus.OK.value()))); + + val webClient = WebClientTimeoutProvider.readWriteTimeoutClient(); + + val ex = assertThrows(RuntimeException.class, () -> + webClient.get() + .uri(wireMockServer.baseUrl() + path) + .exchangeToMono(Mono::just) + .log() + .block()); + assertThat(ex).isInstanceOf(WebClientRequestException.class) + .getCause().isInstanceOf(ReadTimeoutException.class); + } + + @SuppressWarnings("deprecation") + @Test + public void givenNoTimeoutClientAndReactorTimeoutWhenRequestTimeoutThenTimeoutException() { + val path = "/reactor-timeout"; + val delay = Math.toIntExact(Duration.ofSeconds(5).toMillis()); + stubFor(get(urlEqualTo(path)).willReturn(aResponse().withFixedDelay(delay) + .withStatus(HttpStatus.OK.value()))); + + val webClient = WebClientTimeoutProvider.defaultWebClient(); + + val ex = assertThrows(RuntimeException.class, () -> + webClient.get() + .uri(wireMockServer.baseUrl() + path) + .exchangeToMono(Mono::just) + .timeout(Duration.ofSeconds(1)) + .log() + .block()); + assertThat(ex).hasMessageContaining("Did not observe any item") + .getCause().isInstanceOf(TimeoutException.class); + } + + @SuppressWarnings("deprecation") + @Test + public void givenNoTimeoutClientAndTimeoutHttpRequestWhenRequestTimeoutThenReadTimeoutException() { + val path = "/reactor-http-request-timeout"; + val delay = Math.toIntExact(Duration.ofSeconds(5).toMillis()); + stubFor(get(urlEqualTo(path)).willReturn(aResponse().withFixedDelay(delay) + .withStatus(HttpStatus.OK.value()))); + + val webClient = WebClientTimeoutProvider.defaultWebClient(); + + val ex = assertThrows(RuntimeException.class, () -> + webClient.get() + .uri(wireMockServer.baseUrl() + path) + .httpRequest(httpRequest -> { + HttpClientRequest reactorRequest = httpRequest.getNativeRequest(); + reactorRequest.responseTimeout(Duration.ofSeconds(1)); + }) + .exchangeToMono(Mono::just) + .log() + .block()); + assertThat(ex).isInstanceOf(WebClientRequestException.class) + .getCause().isInstanceOf(ReadTimeoutException.class); + } +} diff --git a/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/resources/logback-test.xml b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/resources/logback-test.xml new file mode 100644 index 0000000..f814800 --- /dev/null +++ b/Week 08/Lecture 14/Assignment 01/WebClientDemo/webClientDemo/src/test/resources/logback-test.xml @@ -0,0 +1,20 @@ + + + + + # Pattern of log message for console appender + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Week 08/Lecture 14/Assignment 01/img/demo.png b/Week 08/Lecture 14/Assignment 01/img/demo.png new file mode 100644 index 0000000..84965b7 Binary files /dev/null and b/Week 08/Lecture 14/Assignment 01/img/demo.png differ