Compare commits

..

32 Commits

Author SHA1 Message Date
d1a297b6b8 Update AbstractBaseEntity for fixing builder
Some checks failed
SNAPSHOT - Build and Publish Maven Artifacts / Run Sonarqube Tests (push) Has been cancelled
SNAPSHOT - Build and Publish Maven Artifacts / Build Java Package and Publish (push) Has been cancelled
2024-09-11 21:01:50 +10:00
94b638a2a5 Update AbstractBaseEntity for fixing builder 2024-09-11 20:45:05 +10:00
57e853788d remove profile hikari 2024-09-11 17:29:36 +10:00
605d80d8c9 update AbstractBaseEntity for common entity properties 2024-09-11 11:06:44 +10:00
04dd613e1e add AbstractBaseEntity for common entity properties 2024-09-10 17:42:05 +10:00
0e1364fa14 add AbstractBaseEntity for common entity properties 2024-09-10 17:41:47 +10:00
cefddb61e1 update security module 2024-09-10 17:21:09 +10:00
41102b7453 Merge pull request #5 from 3dwardch3ng/renovate/actions-setup-java-4.x
chore(deps): update actions/setup-java action to v4.3.0
2024-09-10 16:26:11 +10:00
renovate[bot]
3fa029b2d3 chore(deps): update actions/setup-java action to v4.3.0 2024-09-09 14:51:45 +00:00
badf9f7741 add module exception with WrongCredentialsException 2024-09-10 00:51:09 +10:00
4047ea5b9b fix groupId for ec-microservice-commons-swagger 2024-09-10 00:13:37 +10:00
ca9329b543 Merge pull request #4 from 3dwardch3ng/renovate/actions-cache-4.x
chore(deps): update actions/cache action to v4
2024-09-09 21:29:02 +10:00
renovate[bot]
910abdc14c chore(deps): update actions/cache action to v4 2024-09-09 11:21:13 +00:00
cadd18386a add GHA pipeline for sonarqube test 2024-09-09 21:20:37 +10:00
b7286c4928 add GHA pipeline for sonarqube test 2024-09-09 21:17:46 +10:00
92bb98fd16 Merge remote-tracking branch 'origin/develop' into develop 2024-09-09 21:08:35 +10:00
d7dade9e78 add GHA pipeline for sonarqube test 2024-09-09 21:08:29 +10:00
35868d40f2 Update for next development version [skip ci] 2024-09-09 10:42:42 +00:00
951bf56fe7 Merge tag '1.0.0' into develop
Tag release
2024-09-09 10:42:41 +00:00
ffd7f8a6b3 [RELEASE] 1.0.0 2024-09-09 10:42:41 +00:00
14fd4199e7 Update versions for release 2024-09-09 10:42:12 +00:00
5d92718924 Merge pull request #3 from 3dwardch3ng/develop
release
2024-09-09 20:41:30 +10:00
3f79a52b8a testing GHA pipelines
Some checks failed
SNAPSHOT - Build and Publish Maven Artifacts / Build Java Package and Publish (push) Has been cancelled
2024-09-09 20:33:45 +10:00
38e452cded testing GHA pipelines 2024-09-09 20:31:11 +10:00
4e485d93cf testing GHA pipelines 2024-09-09 20:23:59 +10:00
a0da8f1093 testing GHA pipelines 2024-09-09 20:18:36 +10:00
9fc335b81a testing GHA pipelines 2024-09-09 20:16:52 +10:00
2e4cc225fb testing GHA pipelines 2024-09-09 20:06:35 +10:00
74ecaf7f8b Adding github action pipelines 2024-09-09 20:00:39 +10:00
22a0a0eba0 Adding maven registries for renovates 2024-09-09 19:50:01 +10:00
888b495f48 Add issue templates 2024-09-09 19:48:22 +10:00
dcd7d3c7fb Init Check In with modules of Swagger, Entity, Database and Configuration 2024-09-09 19:47:17 +10:00
46 changed files with 1453 additions and 7 deletions

38
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View File

@@ -0,0 +1,38 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Desktop (please complete the following information):**
- OS: [e.g. iOS]
- Browser [e.g. chrome, safari]
- Version [e.g. 22]
**Smartphone (please complete the following information):**
- Device: [e.g. iPhone6]
- OS: [e.g. iOS8.1]
- Browser [e.g. stock browser, safari]
- Version [e.g. 22]
**Additional context**
Add any other context about the problem here.

10
.github/ISSUE_TEMPLATE/custom.md vendored Normal file
View File

@@ -0,0 +1,10 @@
---
name: Custom issue template
about: Describe this issue template's purpose here.
title: ''
labels: ''
assignees: ''
---

View File

@@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

View File

@@ -0,0 +1,132 @@
name: SNAPSHOT - Build and Publish Maven Artifacts
on:
workflow_dispatch:
push:
branches:
- develop
env:
NEXUS_USERNAME: 'edward'
NEXUS_PASSWORD: ${{ secrets.NEXUS_PASSWORD }}
MAVEN_PUBLIC_REPOSITORY_URL: ${{ secrets.MAVEN_PUBLIC_REPOSITORY_URL }}
SNAPSHOT_DEPLOYMENT_REPOSITORY_URL: ${{ secrets.SNAPSHOT_DEPLOYMENT_REPOSITORY_URL }}
RELEASE_DEPLOYMENT_REPOSITORY_URL: ${{ secrets.RELEASE_DEPLOYMENT_REPOSITORY_URL }}
jobs:
sonarqube-test:
runs-on: ubuntu-latest
permissions:
id-token: write
contents: write
packages: write
name: Run Sonarqube Tests
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis
- uses: actions/setup-java@v4.3.0
if: ${{ hashFiles('**/pom.xml') }}
with:
java-version: 17
distribution: zulu
cache: 'maven'
- name: Cache SonarQube packages
uses: actions/cache@v4
with:
path: ~/.sonar/cache
key: ${{ runner.os }}-sonar
restore-keys: ${{ runner.os }}-sonar
- name: Cache Maven packages
uses: actions/cache@v4
with:
path: ~/.m2
key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }}
restore-keys: ${{ runner.os }}-m2
- name: maven-settings-xml-action
uses: whelk-io/maven-settings-xml-action@v22
with:
profiles: >
[{
"id": "homelab",
"properties": {
"altSnapshotDeploymentRepository": "nexus-snapshot::${env.SNAPSHOT_DEPLOYMENT_REPOSITORY_URL}",
"altReleaseDeploymentRepository": "nexus-release::${env.RELEASE_DEPLOYMENT_REPOSITORY_URL}"
}
}]
repositories: >
[{
"id": "maven-public",
"url": "${env.MAVEN_PUBLIC_REPOSITORY_URL}",
"snapshots": {
"enabled": "true"
}
}]
servers: >
[{
"id": "nexus-snapshot",
"username": "${env.NEXUS_USERNAME}",
"password": "${env.NEXUS_PASSWORD}"
},
{
"id": "nexus-release",
"username": "${env.NEXUS_USERNAME}",
"password": "${env.NEXUS_PASSWORD}"
}]
- name: Build and analyse
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}
run: mvn -B verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar -Dsonar.projectKey=ec-microservice-commons -Dsonar.projectName='ec-microservice-commons' -P homelab
build-java:
runs-on: ubuntu-latest
needs:
- sonarqube-test
permissions:
id-token: write
contents: write
packages: write
name: Build Java Package and Publish
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-java@v4.3.0
if: ${{ hashFiles('**/pom.xml') }}
with:
java-version: 17
distribution: zulu
cache: 'maven'
- name: maven-settings-xml-action
uses: whelk-io/maven-settings-xml-action@v22
with:
profiles: >
[{
"id": "homelab",
"properties": {
"altSnapshotDeploymentRepository": "nexus-snapshot::${env.SNAPSHOT_DEPLOYMENT_REPOSITORY_URL}",
"altReleaseDeploymentRepository": "nexus-release::${env.RELEASE_DEPLOYMENT_REPOSITORY_URL}"
}
}]
repositories: >
[{
"id": "maven-public",
"url": "${env.MAVEN_PUBLIC_REPOSITORY_URL}",
"snapshots": {
"enabled": "true"
}
}]
servers: >
[{
"id": "nexus-snapshot",
"username": "${env.NEXUS_USERNAME}",
"password": "${env.NEXUS_PASSWORD}"
},
{
"id": "nexus-release",
"username": "${env.NEXUS_USERNAME}",
"password": "${env.NEXUS_PASSWORD}"
}]
- name: Maven Publish
run: |
mvn -B deploy -P homelab

View File

@@ -0,0 +1,146 @@
name: RELEASE - Build and Publish Maven Artifacts
on:
workflow_dispatch:
push:
branches:
- main
env:
NEXUS_USERNAME: 'edward'
NEXUS_PASSWORD: ${{ secrets.NEXUS_PASSWORD }}
MAVEN_PUBLIC_REPOSITORY_URL: ${{ secrets.MAVEN_PUBLIC_REPOSITORY_URL }}
SNAPSHOT_DEPLOYMENT_REPOSITORY_URL: ${{ secrets.SNAPSHOT_DEPLOYMENT_REPOSITORY_URL }}
RELEASE_DEPLOYMENT_REPOSITORY_URL: ${{ secrets.RELEASE_DEPLOYMENT_REPOSITORY_URL }}
jobs:
sonarqube-test:
runs-on: ubuntu-latest
permissions:
id-token: write
contents: write
packages: write
name: Run Sonarqube Tests
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis
- uses: actions/setup-java@v4.3.0
if: ${{ hashFiles('**/pom.xml') }}
with:
java-version: 17
distribution: zulu
cache: 'maven'
- name: Cache SonarQube packages
uses: actions/cache@v4
with:
path: ~/.sonar/cache
key: ${{ runner.os }}-sonar
restore-keys: ${{ runner.os }}-sonar
- name: Cache Maven packages
uses: actions/cache@v4
with:
path: ~/.m2
key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }}
restore-keys: ${{ runner.os }}-m2
- name: maven-settings-xml-action
uses: whelk-io/maven-settings-xml-action@v22
with:
profiles: >
[{
"id": "homelab",
"properties": {
"altSnapshotDeploymentRepository": "nexus-snapshot::${env.SNAPSHOT_DEPLOYMENT_REPOSITORY_URL}",
"altReleaseDeploymentRepository": "nexus-release::${env.RELEASE_DEPLOYMENT_REPOSITORY_URL}"
}
}]
repositories: >
[{
"id": "maven-public",
"url": "${env.MAVEN_PUBLIC_REPOSITORY_URL}",
"snapshots": {
"enabled": "true"
}
}]
servers: >
[{
"id": "nexus-snapshot",
"username": "${env.NEXUS_USERNAME}",
"password": "${env.NEXUS_PASSWORD}"
},
{
"id": "nexus-release",
"username": "${env.NEXUS_USERNAME}",
"password": "${env.NEXUS_PASSWORD}"
}]
- name: Build and analyse
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}
run: mvn -B verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar -Dsonar.projectKey=ec-microservice-commons -Dsonar.projectName='ec-microservice-commons' -P homelab
build-java:
runs-on: ubuntu-latest
needs:
- sonarqube-test
permissions:
id-token: write
contents: write
packages: write
name: Build Java Package and Publish
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-java@v4.3.0
if: ${{ hashFiles('**/pom.xml') }}
with:
java-version: 17
distribution: zulu
cache: 'maven'
- name: maven-settings-xml-action
uses: whelk-io/maven-settings-xml-action@v22
with:
profiles: >
[{
"id": "homelab",
"properties": {
"altSnapshotDeploymentRepository": "nexus-snapshot::${env.SNAPSHOT_DEPLOYMENT_REPOSITORY_URL}",
"altReleaseDeploymentRepository": "nexus-release::${env.RELEASE_DEPLOYMENT_REPOSITORY_URL}"
}
}]
repositories: >
[{
"id": "maven-public",
"url": "${env.MAVEN_PUBLIC_REPOSITORY_URL}",
"snapshots": {
"enabled": "true"
}
}]
servers: >
[{
"id": "nexus-snapshot",
"username": "${env.NEXUS_USERNAME}",
"password": "${env.NEXUS_PASSWORD}"
},
{
"id": "nexus-release",
"username": "${env.NEXUS_USERNAME}",
"password": "${env.NEXUS_PASSWORD}"
}]
- name: Config Git
run: |
git config --global user.email "edward@cheng.sydney"
git config --global user.name "3dwardch3ng"
git config --global core.autocrlf input
- name: Start release
run: |
mvn gitflow:release-start -B -DpushRemote=true -DallowSnapshots=true -P homelab
- name: Maven Publish
run: |
mvn -B deploy -P homelab
- name: Finish release
env:
GITHUB_ACTOR: 3dwardch3ng
GITHUB_TOKEN: ${{ secrets.GH_TOKEN }}
run: |
mvn gitflow:release-finish -B -DpushRemote=true -DallowSnapshots=true -P homelab

71
.github/workflows/sonarqube.yaml vendored Normal file
View File

@@ -0,0 +1,71 @@
name: Build
on:
workflow_dispatch:
push:
branches:
- '!main'
- '!develop'
jobs:
build:
name: Build and analyze
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis
- uses: actions/setup-java@v4.3.0
if: ${{ hashFiles('**/pom.xml') }}
with:
java-version: 17
distribution: zulu
cache: 'maven'
- name: Cache SonarQube packages
uses: actions/cache@v4
with:
path: ~/.sonar/cache
key: ${{ runner.os }}-sonar
restore-keys: ${{ runner.os }}-sonar
- name: Cache Maven packages
uses: actions/cache@v4
with:
path: ~/.m2
key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }}
restore-keys: ${{ runner.os }}-m2
- name: maven-settings-xml-action
uses: whelk-io/maven-settings-xml-action@v22
with:
profiles: >
[{
"id": "homelab",
"properties": {
"altSnapshotDeploymentRepository": "nexus-snapshot::${env.SNAPSHOT_DEPLOYMENT_REPOSITORY_URL}",
"altReleaseDeploymentRepository": "nexus-release::${env.RELEASE_DEPLOYMENT_REPOSITORY_URL}"
}
}]
repositories: >
[{
"id": "maven-public",
"url": "${env.MAVEN_PUBLIC_REPOSITORY_URL}",
"snapshots": {
"enabled": "true"
}
}]
servers: >
[{
"id": "nexus-snapshot",
"username": "${env.NEXUS_USERNAME}",
"password": "${env.NEXUS_PASSWORD}"
},
{
"id": "nexus-release",
"username": "${env.NEXUS_USERNAME}",
"password": "${env.NEXUS_PASSWORD}"
}]
- name: Build and analyze
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}
run: mvn -B verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar -Dsonar.projectKey=ec-microservice-commons -Dsonar.projectName='ec-microservice-commons'

26
configuration/pom.xml Normal file
View File

@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>sydney.cheng</groupId>
<artifactId>ec-microservice-commons</artifactId>
<version>1.0.1-SNAPSHOT</version>
</parent>
<artifactId>ec-microservice-commons-configuration</artifactId>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,26 @@
package sydney.cheng.microservice.commons.configuration.properties;
import lombok.AccessLevel;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.context.annotation.Configuration;
import sydney.cheng.microservice.commons.configuration.properties.auth.SecurityProperties;
import sydney.cheng.microservice.commons.configuration.properties.database.DatabaseProperties;
@Data
@ConfigurationPropertiesScan(basePackages = {"sydney.cheng.**.properties"})
@ConfigurationProperties("app")
@Configuration
public class AppConfiguration {
private ApplicationConfiguration application;
private SecurityProperties security;
private DatabaseProperties database;
@Data
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public static class ApplicationConfiguration {
private String deploymentTarget;
}
}

View File

@@ -0,0 +1,32 @@
package sydney.cheng.microservice.commons.configuration.properties.auth;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.Arrays;
import java.util.List;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ConfigurationProperties(prefix = "app.security.cors")
public class CorsProperties {
private String allowedUrls;
private String allowedOrigins;
private List<String> allowedHeaders;
private List<String> allowedMethods;
private long allowedMaxAge = 3600;
private boolean allowCredentials = true;
public List<String> getAllowedUrlList() {
return Arrays.asList(allowedUrls.split(","));
}
public List<String> getAllowedOriginList() {
return Arrays.asList(allowedOrigins.split(","));
}
}

View File

@@ -0,0 +1,24 @@
package sydney.cheng.microservice.commons.configuration.properties.auth;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ConfigurationProperties(prefix = "app.security.oauth2")
public class OAuth2Properties {
private RemoteTokenCheckProperties remoteTokenCheck;
@Getter
@Setter
public static class RemoteTokenCheckProperties {
String checkTokenUrl;
String clientId;
String clientSecret;
}
}

View File

@@ -0,0 +1,12 @@
package sydney.cheng.microservice.commons.configuration.properties.auth;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
@Data
@ConfigurationProperties("app.security")
public class SecurityProperties {
private UrlProperties url;
private CorsProperties cors;
private OAuth2Properties oauth2;
}

View File

@@ -0,0 +1,13 @@
package sydney.cheng.microservice.commons.configuration.properties.auth;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
@Data
@ConfigurationProperties(prefix = "app.security.url")
public class UrlProperties {
private String frontend;
private String backend;
private String gateway;
private String frontendDefaultLogin;
}

View File

@@ -0,0 +1,18 @@
package sydney.cheng.microservice.commons.configuration.properties.database;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.context.annotation.Profile;
import java.io.Serializable;
@Profile("database")
@EqualsAndHashCode(callSuper = true)
@Data
public class DataSourceProperties extends org.springframework.boot.autoconfigure.jdbc.DataSourceProperties implements Serializable {
private HikariDataSourceProperties hikari;
public DataSourceProperties() {
super();
}
}

View File

@@ -0,0 +1,12 @@
package sydney.cheng.microservice.commons.configuration.properties.database;
import lombok.Data;
import org.springframework.context.annotation.Profile;
import java.io.Serializable;
@Profile("database")
@Data
public class DatabaseNodeProperties implements Serializable {
DataSourceProperties datasource;
}

View File

@@ -0,0 +1,25 @@
package sydney.cheng.microservice.commons.configuration.properties.database;
import lombok.Data;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import java.io.Serializable;
@Profile("database")
@Data
@PropertySource("classpath:application.yml")
@ConfigurationProperties(prefix = "app.database")
public class DatabaseProperties {
EntityManagerProperties entityManager;
JpaProperties jpa;
DatabaseNodeProperties master;
DatabaseNodeProperties replica;
@Data
public static class EntityManagerProperties implements Serializable {
String packages;
}
}

View File

@@ -0,0 +1,28 @@
package sydney.cheng.microservice.commons.configuration.properties.database;
import com.zaxxer.hikari.HikariConfig;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.context.annotation.Profile;
import java.io.Serializable;
import java.util.Properties;
@Profile(value = {"database"})
@EqualsAndHashCode(callSuper = true)
@Data
public class HikariDataSourceProperties extends HikariConfig implements Serializable {
private String urlPrefix;
public HikariDataSourceProperties() {
super();
}
public HikariDataSourceProperties(Properties properties) {
super(properties);
}
public HikariDataSourceProperties(String propertyFileName) {
super(propertyFileName);
}
}

View File

@@ -0,0 +1,22 @@
package sydney.cheng.microservice.commons.configuration.properties.database;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Profile;
import java.util.Properties;
@Profile(value = {"database"})
@ConfigurationProperties("app.database.primary.datasource.hikari")
public class PrimaryHikariDataSourceProperties extends HikariDataSourceProperties {
public PrimaryHikariDataSourceProperties() {
super();
}
public PrimaryHikariDataSourceProperties(Properties properties) {
super(properties);
}
public PrimaryHikariDataSourceProperties(String propertyFileName) {
super(propertyFileName);
}
}

View File

@@ -0,0 +1,22 @@
package sydney.cheng.microservice.commons.configuration.properties.database;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Profile;
import java.util.Properties;
@Profile(value = {"database"})
@ConfigurationProperties("app.database.replica.datasource.hikari")
public class ReplicaHikariDataSourceProperties extends HikariDataSourceProperties {
public ReplicaHikariDataSourceProperties() {
super();
}
public ReplicaHikariDataSourceProperties(String propertyFileName) {
super(propertyFileName);
}
public ReplicaHikariDataSourceProperties(Properties properties) {
super(properties);
}
}

36
database/pom.xml Normal file
View File

@@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>sydney.cheng</groupId>
<artifactId>ec-microservice-commons</artifactId>
<version>1.0.1-SNAPSHOT</version>
</parent>
<artifactId>ec-microservice-commons-database</artifactId>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>sydney.cheng</groupId>
<artifactId>ec-microservice-commons-configuration</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>${caffeine.version}</version>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,22 @@
package sydney.cheng.microservice.commons.database.annotation;
import org.springframework.context.annotation.Profile;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Profile("database")
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Transactional("ecTransactionManager")
public @interface DatabaseTransactional {
boolean readOnly() default false;
Propagation propagation() default Propagation.REQUIRED;
Class<? extends Throwable>[] noRollbackFor() default {};
}

View File

@@ -0,0 +1,12 @@
package sydney.cheng.microservice.commons.database.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ReadOnlyConnection {
}

View File

@@ -0,0 +1,52 @@
package sydney.cheng.microservice.commons.database.annotation;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import sydney.cheng.microservice.commons.database.constant.DbType;
import sydney.cheng.microservice.commons.database.datasource.DbContextHolder;
@Aspect
@ToString
@NoArgsConstructor
@Component
public class ReadOnlyConnectionInterceptor implements Ordered {
private int order;
@Override
public int getOrder() {
return order;
}
@Value("20")
public void setOrder(int order) {
this.order = order;
}
/*
* handle interceptor for any public method execution
*/
@Pointcut(value = "execution(public * *(..))")
public void anyPublicMethod() {
throw new UnsupportedOperationException();
}
@Around("@annotation(readOnlyConnection)")
public Object proceed(ProceedingJoinPoint pjp, ReadOnlyConnection readOnlyConnection) throws Throwable {
try {
DbContextHolder.setDbType(DbType.REPLICA);
Object result = pjp.proceed();
DbContextHolder.clearDbType();
return result;
} finally {
// restore state
DbContextHolder.clearDbType();
}
}
}

View File

@@ -0,0 +1,26 @@
package sydney.cheng.microservice.commons.database.config;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.TimeUnit;
@EnableCaching
@Configuration
public class CacheManagerConfiguration {
@Bean
public Caffeine<Object, Object> caffeineConfig() {
return Caffeine.newBuilder().expireAfterWrite(12, TimeUnit.HOURS);
}
@Bean
public CacheManager cacheManager(Caffeine<Object, Object> caffeine) {
CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager();
caffeineCacheManager.setCaffeine(caffeine);
return caffeineCacheManager;
}
}

View File

@@ -0,0 +1,57 @@
package sydney.cheng.microservice.commons.database.config;
import com.zaxxer.hikari.HikariDataSource;
import lombok.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import sydney.cheng.microservice.commons.configuration.properties.database.PrimaryHikariDataSourceProperties;
import sydney.cheng.microservice.commons.configuration.properties.database.ReplicaHikariDataSourceProperties;
import sydney.cheng.microservice.commons.database.constant.DbType;
import sydney.cheng.microservice.commons.database.datasource.RoutingDataSource;
import javax.sql.DataSource;
import java.util.Map;
import static sydney.cheng.microservice.commons.database.constant.DatabaseBeanConstant.*;
@Profile(value = {"database"})
@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor(access = AccessLevel.PRIVATE, force = true)
@Configuration
public class HikariDataSourceConfiguration {
private final PrimaryHikariDataSourceProperties primaryHikariDataSourceProperties;
private final ReplicaHikariDataSourceProperties replicaHikariDataSourceProperties;
@Bean(name = PRIMARY_DS_BEAN_NAME)
public DataSource primaryDataSource() {
if (this.primaryHikariDataSourceProperties == null) throw new AssertionError();
this.primaryHikariDataSourceProperties.setPoolName(PRIMARY_DS_BEAN_NAME);
return new HikariDataSource(this.primaryHikariDataSourceProperties);
}
@Bean(name = REPLICA_DS_BEAN_NAME)
public DataSource replicaDataSource() {
if (this.replicaHikariDataSourceProperties == null) throw new AssertionError();
this.replicaHikariDataSourceProperties.setPoolName(REPLICA_DS_BEAN_NAME);
return new HikariDataSource(this.replicaHikariDataSourceProperties);
}
/**
* Configure data source routing for MRCENTRAL.
*
* @return data source
* @see RoutingDataSource
*/
@Bean(name = {"dataSource", DS_BEAN_NAME})
public DataSource centralDataSource() {
RoutingDataSource rds = new RoutingDataSource();
rds.setTargetDataSources(Map
.of(DbType.PRIMARY, this.primaryDataSource(), DbType.REPLICA, this.replicaDataSource()));
rds.setDefaultTargetDataSource(this.primaryDataSource());
return rds;
}
}

View File

@@ -0,0 +1,70 @@
package sydney.cheng.microservice.commons.database.config;
import jakarta.persistence.EntityManagerFactory;
import org.hibernate.cfg.AvailableSettings;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.hibernate5.SpringBeanContainer;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import sydney.cheng.microservice.commons.configuration.properties.database.DatabaseProperties;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
import static sydney.cheng.microservice.commons.database.constant.DatabaseBeanConstant.*;
@Profile(value = {"database"})
@Configuration
@EnableJpaRepositories(
basePackages = "sydney.cheng.**.repository",
entityManagerFactoryRef = "entityManagerFactory",
transactionManagerRef = "transactionManager"
)
public class JPAPersistenceConfiguration {
private final ConfigurableListableBeanFactory beanFactory;
private final DatabaseProperties databaseProperties;
public JPAPersistenceConfiguration(
ConfigurableListableBeanFactory beanFactory,
DatabaseProperties databaseProperties
) {
this.beanFactory = beanFactory;
this.databaseProperties = databaseProperties;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(@Qualifier(DS_BEAN_NAME) DataSource dataSource) {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setPersistenceUnitName("persistence-unit");
em.setPackagesToScan(this.databaseProperties.getEntityManager().getPackages());
em.setDataSource(dataSource);
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
Map<String, Object> properties = new HashMap<>(this.databaseProperties.getJpa().getProperties());
properties.put(AvailableSettings.PHYSICAL_NAMING_STRATEGY, "org.hibernate.boot.model.naming.CamelCaseToUnderscoresNamingStrategy");
properties.put(AvailableSettings.IMPLICIT_NAMING_STRATEGY, "org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy");
properties.put(AvailableSettings.BEAN_CONTAINER, new SpringBeanContainer(this.beanFactory));
em.setJpaPropertyMap(properties);
return em;
}
@Bean
public JpaTransactionManager transactionManager(@Qualifier("entityManagerFactory") EntityManagerFactory emf) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
}

View File

@@ -0,0 +1,10 @@
package sydney.cheng.microservice.commons.database.constant;
import lombok.NoArgsConstructor;
@NoArgsConstructor(access = lombok.AccessLevel.PRIVATE)
public class DatabaseBeanConstant {
public static final String DS_BEAN_NAME = "databaseDataSource";
public static final String PRIMARY_DS_BEAN_NAME = "databaseDataSourcePrimary";
public static final String REPLICA_DS_BEAN_NAME = "databaseDataSourceReplica";
}

View File

@@ -0,0 +1,5 @@
package sydney.cheng.microservice.commons.database.constant;
public enum DbType {
PRIMARY, REPLICA
}

View File

@@ -0,0 +1,27 @@
package sydney.cheng.microservice.commons.database.datasource;
import sydney.cheng.microservice.commons.database.constant.DbType;
public class DbContextHolder {
private static final ThreadLocal<DbType> contextHolder = new ThreadLocal<>();
private DbContextHolder() {
super();
}
public static DbType getDbType() {
return contextHolder.get();
}
public static void setDbType(DbType dbType) {
if (dbType == null) {
throw new NullPointerException();
}
contextHolder.set(dbType);
}
public static void clearDbType() {
contextHolder.remove();
}
}

View File

@@ -0,0 +1,11 @@
package sydney.cheng.microservice.commons.database.datasource;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class RoutingDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DbContextHolder.getDbType();
}
}

26
entity/pom.xml Normal file
View File

@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>sydney.cheng</groupId>
<artifactId>ec-microservice-commons</artifactId>
<version>1.0.1-SNAPSHOT</version>
</parent>
<artifactId>ec-microservice-commons-entity</artifactId>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,29 @@
package sydney.cheng.microservice.commons.entity;
import jakarta.persistence.Id;
import jakarta.persistence.MappedSuperclass;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import org.hibernate.annotations.UuidGenerator;
import java.io.Serializable;
import java.time.LocalDateTime;
@MappedSuperclass
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AbstractBaseEntity implements Serializable {
@Id
@UuidGenerator(style = UuidGenerator.Style.TIME)
private String id;
@CreationTimestamp
private LocalDateTime creationTimestamp;
@UpdateTimestamp
private LocalDateTime updateTimestamp;
}

View File

@@ -0,0 +1,31 @@
package sydney.cheng.microservice.commons.entity;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.UuidGenerator;
import java.io.Serializable;
@MappedSuperclass
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public abstract class AbstractUser implements Serializable {
@Id
@UuidGenerator(style = UuidGenerator.Style.TIME)
@Column(name = "id")
private String id;
@Column(name = "username", nullable = false)
private String username;
@Column(name = "email", nullable = false, unique = true)
private String email;
@Column(name = "password", nullable = false)
private String password;
}

26
exception/pom.xml Normal file
View File

@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>sydney.cheng</groupId>
<artifactId>ec-microservice-commons</artifactId>
<version>1.0.1-SNAPSHOT</version>
</parent>
<artifactId>ec-microservice-commons-exceptions</artifactId>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,11 @@
package sydney.cheng.microservice.commons.exceptions.auth;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public class WrongCredentialsException extends RuntimeException {
public WrongCredentialsException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,12 @@
package sydney.cheng.microservice.commons.exceptions.feign;
import lombok.Builder;
import lombok.Getter;
import java.util.Map;
@Builder
@Getter
public class FeignBadRequestException extends RuntimeException {
private Map<String, String> errors;
}

View File

@@ -0,0 +1,18 @@
package sydney.cheng.microservice.commons.exceptions.feign;
import lombok.Builder;
import lombok.Getter;
import org.springframework.http.HttpStatus;
@Builder
@Getter
public class FeignErrorException extends RuntimeException {
private final String message;
private final HttpStatus httpStatus;
public FeignErrorException(String message, HttpStatus httpStatus) {
super(message);
this.message = message;
this.httpStatus = httpStatus;
}
}

View File

@@ -0,0 +1,22 @@
package sydney.cheng.microservice.commons.exceptions.handlers;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import sydney.cheng.microservice.commons.exceptions.auth.WrongCredentialsException;
import java.util.HashMap;
import java.util.Map;
@RestControllerAdvice
public class AuthExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(WrongCredentialsException.class)
public ResponseEntity<?> usernameOrPasswordInvalidException(WrongCredentialsException exception) {
Map<String, String> errors = new HashMap<>();
errors.put("error", exception.getMessage());
return new ResponseEntity<>(errors, HttpStatus.UNAUTHORIZED);
}
}

View File

@@ -0,0 +1,26 @@
package sydney.cheng.microservice.commons.exceptions.handlers;
import sydney.cheng.microservice.commons.exceptions.feign.*;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import java.util.HashMap;
import java.util.Map;
@RestControllerAdvice
public class FeignExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(FeignErrorException.class)
public ResponseEntity<?> genericError(FeignErrorException exception) {
Map<String, String> errors = new HashMap<>();
errors.put("error", exception.getMessage());
return new ResponseEntity<>(errors, exception.getHttpStatus());
}
@ExceptionHandler(FeignBadRequestException.class)
public ResponseEntity<?> validationException(FeignBadRequestException exception) {
return ResponseEntity.badRequest().body(exception.getErrors());
}
}

View File

@@ -0,0 +1,21 @@
package sydney.cheng.microservice.commons.exceptions.handlers;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import java.util.HashMap;
import java.util.Map;
@RestControllerAdvice
public class GenericExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(Exception.class)
public final ResponseEntity<?> handleAllException(Exception ex) {
Map<String, String> errors = new HashMap<>();
errors.put("error", ex.getMessage());
return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
}
}

56
pom.xml
View File

@@ -7,11 +7,11 @@
<parent>
<groupId>sydney.cheng</groupId>
<artifactId>ec-super-pom</artifactId>
<version>1.0.1</version>
<version>1.0.5</version>
</parent>
<artifactId>ec-microservice-commons</artifactId>
<version>1.0.0-SNAPSHOT</version>
<version>1.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<licenses>
@@ -40,9 +40,22 @@
<modules>
<module>swagger</module>
<module>entity</module>
<module>configuration</module>
<module>database</module>
<module>exception</module>
<module>security</module>
</modules>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Dependency Versions -->
<spring-context-support.version>6.1.12</spring-context-support.version>
<springdoc-openapi-starter-common.version>2.6.0</springdoc-openapi-starter-common.version>
<atomikos.version>6.0.0</atomikos.version>
<caffeine.version>3.1.8</caffeine.version>
<!-- Sonar Properties -->
<sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>
<sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis>
@@ -52,4 +65,43 @@
<sonar.organization>3dwardch3ng</sonar.organization>
<sonar.host.url>https://sonarqube.cluster.edward.sydney</sonar.host.url>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>${maven-source-plugin.version}</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-autoconfigure -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

View File

@@ -2,5 +2,15 @@
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": [
"local>3dwardch3ng/renovate-config"
],
"packageRules": [
{
"matchDatasources": ["maven"],
"registryUrls": [
"https://nexus.cluster.edward.sydney/repository/maven-releases",
"https://nexus.cluster.edward.sydney/repository/maven-snapshots",
"https://repo.maven.apache.org/maven2"
]
}
]
}

44
security/pom.xml Normal file
View File

@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>sydney.cheng</groupId>
<artifactId>ec-microservice-commons</artifactId>
<version>1.0.1-SNAPSHOT</version>
</parent>
<artifactId>ec-microservice-commons-security</artifactId>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>sydney.cheng</groupId>
<artifactId>ec-microservice-commons-configuration</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>sydney.cheng</groupId>
<artifactId>ec-microservice-commons-exceptions</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,14 @@
package sydney.cheng.microservice.commons.security.config;
import feign.codec.ErrorDecoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import sydney.cheng.microservice.commons.security.utils.FeignErrorDecoder;
@Configuration
public class FeignConfig {
@Bean
public ErrorDecoder errorDecoder() {
return new FeignErrorDecoder();
}
}

View File

@@ -0,0 +1,60 @@
package sydney.cheng.microservice.commons.security.config;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.access.AccessDeniedHandlerImpl;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import sydney.cheng.microservice.commons.configuration.properties.auth.CorsProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
@AllArgsConstructor
public class SecurityConfig {
private final CorsProperties corsProperties;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.formLogin(AbstractHttpConfigurer::disable)
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
.csrf(csrf -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()))
.authorizeHttpRequests(authorize ->
authorize
.requestMatchers(HttpMethod.OPTIONS, "*").permitAll()
.requestMatchers("/actuator/**",
"/swagger-ui/**", "/swagger-resources/**", "/api-docs/**",
"/config/**"
).permitAll()
.anyRequest().authenticated()
)
.exceptionHandling(exceptionHandling -> exceptionHandling.accessDeniedHandler(new AccessDeniedHandlerImpl()))
.sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.httpBasic(Customizer.withDefaults())
.build();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(corsProperties.isAllowCredentials());
corsConfiguration.setAllowedOrigins(corsProperties.getAllowedUrlList());
corsConfiguration.setAllowedHeaders(corsProperties.getAllowedHeaders());
corsConfiguration.setAllowedMethods(corsProperties.getAllowedMethods());
corsConfiguration.setMaxAge(corsProperties.getAllowedMaxAge());
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfiguration);
return source;
}
}

View File

@@ -0,0 +1,41 @@
package sydney.cheng.microservice.commons.security.utils;
import com.fasterxml.jackson.databind.ObjectMapper;
import feign.Response;
import feign.codec.ErrorDecoder;
import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpStatus;
import sydney.cheng.microservice.commons.exceptions.feign.FeignBadRequestException;
import sydney.cheng.microservice.commons.exceptions.feign.FeignErrorException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
public class FeignErrorDecoder implements ErrorDecoder {
private final ObjectMapper mapper = new ObjectMapper();
@Override
public Exception decode(String methodKey, Response response) {
try (InputStream body = response.body().asInputStream()) {
Map<String, String> errors =
mapper.readValue(IOUtils.toString(body, StandardCharsets.UTF_8), Map.class);
if (response.status() == 400) {
return FeignBadRequestException.builder()
.errors(errors).build();
} else
return FeignErrorException
.builder()
.httpStatus(HttpStatus.valueOf(response.status()))
.message(errors.get("error"))
.build();
} catch (IOException exception) {
throw FeignErrorException.builder()
.httpStatus(HttpStatus.valueOf(response.status()))
.message(exception.getMessage())
.build();
}
}
}

View File

@@ -7,19 +7,17 @@
<parent>
<groupId>sydney.cheng</groupId>
<artifactId>ec-microservice-commons</artifactId>
<version>1.0.0-SNAPSHOT</version>
<version>1.0.1-SNAPSHOT</version>
</parent>
<groupId>cheng.edward</groupId>
<groupId>sydney.cheng</groupId>
<artifactId>ec-microservice-commons-swagger</artifactId>
<version>1.0.0-SNAPSHOT</version>
<version>1.0.1-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Dependency Versions -->
<springdoc-openapi-starter-common.version>2.6.0</springdoc-openapi-starter-common.version>
</properties>
<dependencies>