-
Notifications
You must be signed in to change notification settings - Fork 0
Week 08 - Assignment on Lecture 13 and 14 #6
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
mikeleo03
wants to merge
24
commits into
main
Choose a base branch
from
Week_08
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
24 commits
Select commit
Hold shift + click to select a range
55d29ff
[Refactor] Fix on Assignment 05
mikeleo03 77f0bea
[Refactor] Fix on Assignment 06
mikeleo03 05d249e
Merge pull request #1 from affandyfandy/Week_02
mikeleo03 2fbcaf5
[Feat] Finishing Assignment 01
mikeleo03 e4569e1
[Init] Initiate SpringBoot project
mikeleo03 f49a043
[Feat] Basic Customer CRUD
mikeleo03 59184c1
[Feat] Implementation done
mikeleo03 41c874c
[Feat] README Assignment 02
mikeleo03 ab5637b
[Init] Copying Assignment 02 to 03
mikeleo03 76e55be
[Feat] Assignment 03 done (need to add detail)
mikeleo03 75561e2
[Feat] Add some code documentation
mikeleo03 07ac8a3
[Feat] Update some commentaries and SQL data
mikeleo03 ea8f8db
[Feat] Update documentation
mikeleo03 78a99c4
[Refactor] README from Assignment 02
mikeleo03 c289ced
[Feat] Implementation for README from assignment 03
mikeleo03 128127a
[Refactor] README image redirection
mikeleo03 2740532
[Feat] Swagger documentation
mikeleo03 f9db9b2
[Init] Initiate FeignClient demo project
mikeleo03 aeb50e7
[Feat] FeignClient Demo done
mikeleo03 1274368
[Feat] Implementation of Rest Template Demo 1
mikeleo03 56bebcf
[Feat] Implementation of Rest Template 2
mikeleo03 39f535e
[Feat] Implementation of WebClient
mikeleo03 0f48e99
[Fix] Redirection and renaming
mikeleo03 0c5ee6d
[Feat] README documentation
mikeleo03 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,2 @@ | ||
| target | ||
| target | ||
| HELP.md |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
65 changes: 37 additions & 28 deletions
65
Week 02/Lecture 04/Assignment 06/RemoveDuplicatesCSV.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,46 +1,55 @@ | ||
| 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) { | ||
| String inputFilePath = "data/data.csv"; | ||
| String outputFilePath = "data/unique.csv"; | ||
| String keyFieldName = "id"; | ||
|
|
||
| try (BufferedReader reader = Files.newBufferedReader(Paths.get(inputFilePath))) { | ||
| List<String> 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<String> 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<String> 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<String> 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); | ||
| } | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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> customAuthenticationFilter() { | ||
| FilterRegistrationBean<CustomAuthenticationFilter> 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. |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The looks great explaination about onceperrequestfilter with example Authentication filter. Great job leon