Skip to content

Instantly share code, notes, and snippets.

protected final Function<UserNotPresentError, ResponseEntity<?>> userFacadeErrorHandler =
userNotPresentError -> ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
protected final Function<Either<ItemsError, ?>, ResponseEntity> resultHandler = serviceResult -> serviceResult.fold(
itemsError -> handleItemsError(itemsError),
successValue -> Match(successValue).of(
Case($(), () -> ResponseEntity.ok(successValue).build())
)
);
protected Either<UserNotPresentError, UserId> userOrFail(RequestContext requestContext) {
return requestContext.userId().toEither(UserNotPresentError::new);
}
protected <T> Either<ItemsDbError, T> tryDbCall(Supplier<T> dbCall) {
return Try.of(dbCall::get)
.fold(
dbError -> {
logger.warn("Problem executing db operation", dbError);
return Left(new ItemsDbError(dbError.getMessage()));
},
Either::right
);
}
@Bean
@Scope(scopeName = ScopeConfig.THREAD_INHERITED,
proxyMode = ScopedProxyMode.TARGET_CLASS)
public TokenString tokenString() {
HttpServletRequest request = ((ServletRequestAttributes)
RequestContextHolder
.currentRequestAttributes())
.getRequest();
String value = request.getHeader("Authorization").split(" ")[1];
return new TokenString(value);
@Bean
public CustomScopeConfigurer customScopeConfigurer() {
CustomScopeConfigurer configurer = new CustomScopeConfigurer();
Map<String, Object> scopes = new HashMap<>();
scopes.put(THREAD_INHERITED, new InheritedThreadScope());
configurer.setScopes(scopes);
return configurer;
}
public class InheritedThreadScope implements Scope {
private static final Logger logger = LoggerFactory.getLogger(InheritedThreadScope.class);
private final ThreadLocal<Map<String, Object>> threadScope =
new InheritableThreadLocal() {
@Override
protected Map<String, Object> initialValue() {
return new HashMap<>();
}
@GetMapping
public CompletableFuture<ResponseEntity> get() {
logger.info("GET request");
return myService.callBAsync().thenApply(status ->
status.equals("ok") ?
ResponseEntity.ok().build() :
ResponseEntity.badRequest().build());
}
@Autowired
TokenString tokenString;
public CompletableFuture<String> callBAsync() {
return supplyAsync(() -> {
logger.info("calling B");
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "bearer "+tokenString.getValue());
HttpEntity entity = new HttpEntity(headers);
ResponseEntity re = restTemplate.exchange(
@GetMapping
public CompletableFuture<ResponseEntity> get() {
return supplyAsync(() -> ResponseEntity.ok().build())
}
public class TokenString {
private final String value;
public TokenString(String value) {
this.value = value;
}
public String getValue() {
return this.value;
}