import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableCaching
public class CacheConfig {
}
Start Caching
@Component
@CacheConfig(cacheNames = "books")
public class SimpleBookRepository implements BookRepository {
@Cacheable
@Override
public Book getByIsbn(String isbn) {
simulateSlowService();
return new Book(isbn, "Some book");
}
// Don't do this at home
private void simulateSlowService() {
try {
long time = 3000L;
Thread.sleep(time);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
}
@Component
@CacheConfig(cacheNames = "files")
public class SimpleFileRepository implements FileRepository {
private static final Logger LOGGER = LoggerFactory.getLogger(SimpleFileRepository.class);
@Override
@Cacheable
public String load(String project) {
return asString(new FileSystemResource(project));
}
@Override
@CachePut
public String reLoad(String project) {
return asString(new FileSystemResource(project));
}
private String asString(Resource resource) {
try (Reader reader = new InputStreamReader(resource.getInputStream(), UTF_8)) {
return FileCopyUtils.copyToString(reader);
} catch (IOException e) {
LOGGER.error("Error Proessing ", e);
throw new UncheckedIOException(e);
}
}
}
import java.util.Date;
public class JwtToken {
private Date iat;
private Date expiration;
private String token;
public JwtToken(Date iat, Date expiration, String token) {
this.iat = iat;
this.expiration = expiration;
this.token = token;
}
public Date getIat() {
return iat;
}
public Date getExpiration() {
return expiration;
}
public String getToken() {
return token;
}
public boolean isExpired() {
return expiration.before(new Date());
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private Date iat;
private Date expiration;
private String token;
public Builder issuedAt(Date iat) {
this.iat = iat;
return this;
}
public Builder expiration(Date expiration) {
this.expiration = expiration;
return this;
}
public Builder expiration(String token) {
this.token = token;
return this;
}
public JwtToken build() {
return new JwtToken(iat, expiration, token);
}
}
}
DefaultJwtTokenService.java
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Value;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
public class DefaultJwtTokenService implements JwtTokenService {
private static final String ROLE_SYSTEM = "SYSTEM";
private static final String CLAIM_ROLES = "roles";
@Value("${app.jwt.secret}")
private String jwtSecret;
@Value("${app.jwt.token_duration.minutes}")
private long tokenDurationInMinutes;
@Override
public JwtToken generateToken(String user) {
Map<String, Object> claims = new HashMap<>();
return doGenerateToken(claims, user);
}
// while creating the token -
// 1. Define claims of the token, like Issuer, Expiration, Subject, and the ID
// 2. Sign the JWT using the HS512 algorithm and secret key.
// 3. According to JWS Compact
// Serialization(https://tools.ietf.org/html/draft-ietf-jose-json-web-signature-41#section-3.1)
// compaction of the JWT to a URL-safe string
private JwtToken doGenerateToken(Map<String, Object> claims, String subject) {
long currentTime = System.currentTimeMillis();
long expiration = currentTime + TimeUnit.MINUTES.toMillis(tokenDurationInMinutes);
Date iat = new Date(currentTime);
Date exp = new Date(expiration);
String token = Jwts.builder()
.setClaims(claims)
.setSubject(subject)
.setIssuedAt(iat)
.setExpiration(exp)
.claim(CLAIM_ROLES, Arrays.asList(ROLE_SYSTEM))
.signWith(SignatureAlgorithm.HS512, jwtSecret.getBytes())
.compact();
return new JwtToken(iat, exp, token);
}
}
DefaultJwtTokenProvider.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DefaultJwtTokenProvider implements JwtTokenProvider {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultJwtTokenProvider.class);
private static final String USER_NAME_PROJECT = "PROJECT";
private final JwtTokenService jwtTokenService;
private JwtToken jwtToken;
public DefaultJwtTokenProvider(JwtTokenService jwtTokenService) {
this.jwtTokenService = jwtTokenService;
this.jwtToken = jwtTokenService.generateToken(USER_NAME_PROJECT);
}
@Override
public String getJwtToken() {
if (this.jwtToken.isExpired()) {
refreshToken();
}
return jwtToken.getToken();
}
private void refreshToken() {
LOGGER.debug("Token Experied, Refreshing token");
this.jwtToken = jwtTokenService.generateToken(USER_NAME_PROJECT);
}
}