Skip to content

Commit 2f6b6fe

Browse files
committed
Format code in project shopapp-backend
1 parent e3b84ed commit 2f6b6fe

File tree

103 files changed

+2778
-2630
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

103 files changed

+2778
-2630
lines changed

shopapp-backend/src/main/java/com/project/shopapp/ShopappApplication.java

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,7 @@
77
@SpringBootApplication
88
public class ShopappApplication {
99

10-
public static void main(String[] args) {
11-
SpringApplication.run(ShopappApplication.class, args);
12-
}
13-
10+
public static void main(String[] args) {
11+
SpringApplication.run(ShopappApplication.class, args);
12+
}
1413
}

shopapp-backend/src/main/java/com/project/shopapp/components/CustomHealthCheck.java

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -10,18 +10,18 @@
1010

1111
@Component
1212
public class CustomHealthCheck implements HealthIndicator {
13-
@Override
14-
public Health health() {
15-
// Implement your custom health check logic here
16-
try {
17-
String computerName = InetAddress.getLocalHost().getHostName();
18-
return Health.up().withDetail("computerName", computerName).build();//code: 200
19-
//DOWN => 503
20-
} catch (Exception e) {
21-
//throw new RuntimeException(e);
22-
return Health.down()
23-
.withDetail("Error", e.getMessage()).build();
24-
}
25-
13+
@Override
14+
public Health health() {
15+
// Implement your custom health check logic here
16+
try {
17+
String computerName = InetAddress.getLocalHost().getHostName();
18+
return Health.up().withDetail("computerName", computerName).build();//code: 200
19+
//DOWN => 503
20+
} catch (Exception e) {
21+
//throw new RuntimeException(e);
22+
return Health.down()
23+
.withDetail("Error", e.getMessage()).build();
2624
}
27-
}
25+
26+
}
27+
}
Lines changed: 87 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
package com.project.shopapp.components;
2+
23
import com.project.shopapp.models.User;
34
import org.slf4j.Logger;
45
import org.slf4j.LoggerFactory;
@@ -24,89 +25,95 @@
2425
@Component
2526
@RequiredArgsConstructor
2627
public class JwtTokenUtils {
27-
@Value("${jwt.expiration}")
28-
private int expiration; //save to an environment variable
29-
30-
@Value("${jwt.expiration-refresh-token}")
31-
private int expirationRefreshToken;
28+
private static final Logger logger = LoggerFactory.getLogger(JwtTokenUtils.class);
29+
private final TokenRepository tokenRepository;
30+
@Value("${jwt.expiration}")
31+
private int expiration; //save to an environment variable
32+
@Value("${jwt.expiration-refresh-token}")
33+
private int expirationRefreshToken;
34+
@Value("${jwt.secretKey}")
35+
private String secretKey;
3236

33-
@Value("${jwt.secretKey}")
34-
private String secretKey;
35-
private static final Logger logger = LoggerFactory.getLogger(JwtTokenUtils.class);
36-
private final TokenRepository tokenRepository;
37-
public String generateToken(com.project.shopapp.models.User user) throws Exception{
38-
//properties => claims
39-
Map<String, Object> claims = new HashMap<>();
40-
//this.generateSecretKey();
41-
claims.put("phoneNumber", user.getPhoneNumber());
42-
claims.put("userId", user.getId());
43-
try {
44-
String token = Jwts.builder()
45-
.setClaims(claims) //how to extract claims from this ?
46-
.setSubject(user.getPhoneNumber())
47-
.setExpiration(new Date(System.currentTimeMillis() + expiration * 1000L))
48-
.signWith(getSignInKey(), SignatureAlgorithm.HS256)
49-
.compact();
50-
return token;
51-
}catch (Exception e) {
52-
//you can "inject" Logger, instead System.out.println
53-
throw new InvalidParamException("Cannot create jwt token, error: "+e.getMessage());
54-
//return null;
55-
}
56-
}
57-
private Key getSignInKey() {
58-
byte[] bytes = Decoders.BASE64.decode(secretKey);
59-
//Keys.hmacShaKeyFor(Decoders.BASE64.decode("TaqlmGv1iEDMRiFp/pHuID1+T84IABfuA0xXh4GhiUI="));
60-
return Keys.hmacShaKeyFor(bytes);
61-
}
62-
private String generateSecretKey() {
63-
SecureRandom random = new SecureRandom();
64-
byte[] keyBytes = new byte[32]; // 256-bit key
65-
random.nextBytes(keyBytes);
66-
String secretKey = Encoders.BASE64.encode(keyBytes);
67-
return secretKey;
68-
}
69-
private Claims extractAllClaims(String token) {
70-
return Jwts.parserBuilder()
71-
.setSigningKey(getSignInKey())
72-
.build()
73-
.parseClaimsJws(token)
74-
.getBody();
75-
}
76-
public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
77-
final Claims claims = this.extractAllClaims(token);
78-
return claimsResolver.apply(claims);
79-
}
80-
//check expiration
81-
public boolean isTokenExpired(String token) {
82-
Date expirationDate = this.extractClaim(token, Claims::getExpiration);
83-
return expirationDate.before(new Date());
84-
}
85-
public String extractPhoneNumber(String token) {
86-
return extractClaim(token, Claims::getSubject);
37+
public String generateToken(com.project.shopapp.models.User user) throws Exception {
38+
//properties => claims
39+
Map<String, Object> claims = new HashMap<>();
40+
//this.generateSecretKey();
41+
claims.put("phoneNumber", user.getPhoneNumber());
42+
claims.put("userId", user.getId());
43+
try {
44+
String token = Jwts.builder()
45+
.setClaims(claims) //how to extract claims from this ?
46+
.setSubject(user.getPhoneNumber())
47+
.setExpiration(new Date(System.currentTimeMillis() + expiration * 1000L))
48+
.signWith(getSignInKey(), SignatureAlgorithm.HS256)
49+
.compact();
50+
return token;
51+
} catch (Exception e) {
52+
//you can "inject" Logger, instead System.out.println
53+
throw new InvalidParamException("Cannot create jwt token, error: " + e.getMessage());
54+
//return null;
8755
}
88-
public boolean validateToken(String token, User userDetails) {
89-
try {
90-
String phoneNumber = extractPhoneNumber(token);
91-
Token existingToken = tokenRepository.findByToken(token);
92-
if(existingToken == null ||
93-
existingToken.isRevoked() == true ||
94-
!userDetails.isActive()
95-
) {
96-
return false;
97-
}
98-
return (phoneNumber.equals(userDetails.getUsername()))
99-
&& !isTokenExpired(token);
100-
} catch (MalformedJwtException e) {
101-
logger.error("Invalid JWT token: {}", e.getMessage());
102-
} catch (ExpiredJwtException e) {
103-
logger.error("JWT token is expired: {}", e.getMessage());
104-
} catch (UnsupportedJwtException e) {
105-
logger.error("JWT token is unsupported: {}", e.getMessage());
106-
} catch (IllegalArgumentException e) {
107-
logger.error("JWT claims string is empty: {}", e.getMessage());
108-
}
56+
}
10957

58+
private Key getSignInKey() {
59+
byte[] bytes = Decoders.BASE64.decode(secretKey);
60+
//Keys.hmacShaKeyFor(Decoders.BASE64.decode("TaqlmGv1iEDMRiFp/pHuID1+T84IABfuA0xXh4GhiUI="));
61+
return Keys.hmacShaKeyFor(bytes);
62+
}
63+
64+
private String generateSecretKey() {
65+
SecureRandom random = new SecureRandom();
66+
byte[] keyBytes = new byte[32]; // 256-bit key
67+
random.nextBytes(keyBytes);
68+
String secretKey = Encoders.BASE64.encode(keyBytes);
69+
return secretKey;
70+
}
71+
72+
private Claims extractAllClaims(String token) {
73+
return Jwts.parserBuilder()
74+
.setSigningKey(getSignInKey())
75+
.build()
76+
.parseClaimsJws(token)
77+
.getBody();
78+
}
79+
80+
public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
81+
final Claims claims = this.extractAllClaims(token);
82+
return claimsResolver.apply(claims);
83+
}
84+
85+
//check expiration
86+
public boolean isTokenExpired(String token) {
87+
Date expirationDate = this.extractClaim(token, Claims::getExpiration);
88+
return expirationDate.before(new Date());
89+
}
90+
91+
public String extractPhoneNumber(String token) {
92+
return extractClaim(token, Claims::getSubject);
93+
}
94+
95+
public boolean validateToken(String token, User userDetails) {
96+
try {
97+
String phoneNumber = extractPhoneNumber(token);
98+
Token existingToken = tokenRepository.findByToken(token);
99+
if (existingToken == null ||
100+
existingToken.isRevoked() ||
101+
!userDetails.isActive()
102+
) {
110103
return false;
104+
}
105+
return (phoneNumber.equals(userDetails.getUsername()))
106+
&& !isTokenExpired(token);
107+
} catch (MalformedJwtException e) {
108+
logger.error("Invalid JWT token: {}", e.getMessage());
109+
} catch (ExpiredJwtException e) {
110+
logger.error("JWT token is expired: {}", e.getMessage());
111+
} catch (UnsupportedJwtException e) {
112+
logger.error("JWT token is unsupported: {}", e.getMessage());
113+
} catch (IllegalArgumentException e) {
114+
logger.error("JWT claims string is empty: {}", e.getMessage());
111115
}
116+
117+
return false;
118+
}
112119
}

shopapp-backend/src/main/java/com/project/shopapp/components/LocalizationUtils.java

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,12 @@
1212
@RequiredArgsConstructor
1313
@Component
1414
public class LocalizationUtils {
15-
private final MessageSource messageSource;
16-
private final LocaleResolver localeResolver;
17-
public String getLocalizedMessage(String messageKey, Object... params) {//spread operator
18-
HttpServletRequest request = WebUtils.getCurrentRequest();
19-
Locale locale = localeResolver.resolveLocale(request);
20-
return messageSource.getMessage(messageKey, params, locale);
21-
}
15+
private final MessageSource messageSource;
16+
private final LocaleResolver localeResolver;
17+
18+
public String getLocalizedMessage(String messageKey, Object... params) {//spread operator
19+
HttpServletRequest request = WebUtils.getCurrentRequest();
20+
Locale locale = localeResolver.resolveLocale(request);
21+
return messageSource.getMessage(messageKey, params, locale);
22+
}
2223
}

shopapp-backend/src/main/java/com/project/shopapp/configurations/FlywayConfig.java

Lines changed: 34 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -5,40 +5,42 @@
55
import org.springframework.context.annotation.Configuration;
66
import org.springframework.beans.factory.annotation.Value;
77
import org.springframework.jdbc.datasource.DriverManagerDataSource;
8+
89
import javax.sql.DataSource;
910

1011
@Configuration
1112
public class FlywayConfig {
12-
@Value("${spring.flyway.locations}")
13-
private String[] flywayLocations;
14-
15-
@Value("${spring.datasource.url}")
16-
private String datasourceUrl;
17-
18-
@Value("${spring.datasource.username}")
19-
private String datasourceUsername;
20-
21-
@Value("${spring.datasource.password}")
22-
private String datasourcePassword;
23-
24-
@Bean
25-
public Flyway flyway() {
26-
Flyway flyway = Flyway.configure()
27-
.dataSource(dataSource())
28-
.locations(flywayLocations)
29-
.baselineOnMigrate(true)//default baseline is V1
30-
.baselineVersion("0")
31-
.load();
32-
flyway.migrate();//run .sql file, IF VERSION IS NEWER
33-
//System.out.println("migrating...");
34-
return flyway;
35-
}
36-
@Bean
37-
public DataSource dataSource() {
38-
DriverManagerDataSource dataSource = new DriverManagerDataSource();
39-
dataSource.setUrl(datasourceUrl);
40-
dataSource.setUsername(datasourceUsername);
41-
dataSource.setPassword(datasourcePassword);
42-
return dataSource;
43-
}
13+
@Value("${spring.flyway.locations}")
14+
private String[] flywayLocations;
15+
16+
@Value("${spring.datasource.url}")
17+
private String datasourceUrl;
18+
19+
@Value("${spring.datasource.username}")
20+
private String datasourceUsername;
21+
22+
@Value("${spring.datasource.password}")
23+
private String datasourcePassword;
24+
25+
@Bean
26+
public Flyway flyway() {
27+
Flyway flyway = Flyway.configure()
28+
.dataSource(dataSource())
29+
.locations(flywayLocations)
30+
.baselineOnMigrate(true)//default baseline is V1
31+
.baselineVersion("0")
32+
.load();
33+
flyway.migrate();//run .sql file, IF VERSION IS NEWER
34+
//System.out.println("migrating...");
35+
return flyway;
36+
}
37+
38+
@Bean
39+
public DataSource dataSource() {
40+
DriverManagerDataSource dataSource = new DriverManagerDataSource();
41+
dataSource.setUrl(datasourceUrl);
42+
dataSource.setUsername(datasourceUsername);
43+
dataSource.setPassword(datasourcePassword);
44+
return dataSource;
45+
}
4446
}
Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
package com.project.shopapp.configurations;
2+
23
import org.apache.kafka.clients.producer.ProducerConfig;
34
import org.apache.kafka.common.serialization.StringSerializer;
45
import org.springframework.context.annotation.Bean;
@@ -8,27 +9,30 @@
89
import org.springframework.kafka.core.ProducerFactory;
910
import org.springframework.kafka.support.serializer.ErrorHandlingDeserializer;
1011
import org.springframework.kafka.support.serializer.JsonSerializer;
12+
1113
import java.util.HashMap;
1214
import java.util.Map;
15+
1316
/*
1417
Thông Báo và Gửi Email: Kafka có thể được sử dụng để gửi thông báo và email đến người dùng.
15-
Sau khi một đơn hàng được xử lý, bạn có thể gửi một thông điệp Kafka để thông báo cho người dùng về trạng thái đơn hàng
18+
Sau khi một đơn hàng được xử lý, bạn có thể gửi một thông điệp Kafka để thông báo cho người dùng
19+
về trạng thái đơn hàng
1620
và gửi email xác nhận
1721
* */
1822
@Configuration
1923
public class KafkaProducerConfig {
2024

21-
@Bean
22-
public ProducerFactory<String, String> producerFactory() {
23-
Map<String, Object> producerConfig = new HashMap<>();
24-
producerConfig.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "your-kafka-broker:9092");
25-
producerConfig.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
26-
producerConfig.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
27-
return new DefaultKafkaProducerFactory<>(producerConfig);
28-
}
25+
@Bean
26+
public ProducerFactory<String, String> producerFactory() {
27+
Map<String, Object> producerConfig = new HashMap<>();
28+
producerConfig.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "your-kafka-broker:9092");
29+
producerConfig.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
30+
producerConfig.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
31+
return new DefaultKafkaProducerFactory<>(producerConfig);
32+
}
2933

30-
@Bean
31-
public KafkaTemplate<String, String> kafkaTemplate() {
32-
return new KafkaTemplate<>(producerFactory());
33-
}
34+
@Bean
35+
public KafkaTemplate<String, String> kafkaTemplate() {
36+
return new KafkaTemplate<>(producerFactory());
37+
}
3438
}

shopapp-backend/src/main/java/com/project/shopapp/configurations/LanguageConfig.java

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,11 @@
88
import org.springframework.context.support.ResourceBundleMessageSource;
99

1010
public class LanguageConfig {
11-
@Bean
12-
public MessageSource messageSource(){
13-
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
14-
messageSource.setBasename("i18n.messages"); // Tên cơ sở của các tệp tài liệu ngôn ngữ
15-
messageSource.setDefaultEncoding("UTF-8");
16-
return messageSource;
17-
}
18-
}
11+
@Bean
12+
public MessageSource messageSource() {
13+
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
14+
messageSource.setBasename("i18n.messages"); // Tên cơ sở của các tệp tài liệu ngôn ngữ
15+
messageSource.setDefaultEncoding("UTF-8");
16+
return messageSource;
17+
}
18+
}

0 commit comments

Comments
 (0)