Created
September 12, 2017 09:26
-
-
Save ihommani/031f4d6d75ad226a67f68c12be4240ee to your computer and use it in GitHub Desktop.
Generic code to wrap lambdas into a common pattern
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
public class WrapperUser extends AbstractEndpoint{ | |
public doWrappedOperation(){ | |
return wrap(user, appUser -> new ApiUpdateList(updateService.list(appUser, exportId, limit, pageToken))); | |
} | |
} | |
public class AbstractEndpoint { //should be abstract, but prevents discovery generation if not | |
private StoreService storeService = new StoreService(); | |
protected interface ApiTask<T> { | |
T apply(AppUser user) throws ServiceException, ApiException; | |
} | |
protected <T> T wrap(User user, ApiTask<T> action) throws ServiceException { | |
Preconditions.checkNotNull(user, "Please use OAuth2 to authenticate").getEmail(); | |
AppUser appUser = storeService.load(AppUser.class, user.getId()) | |
.orElseThrow(() -> new UnauthorizedException("User not recognized")); | |
try { | |
return action.apply(appUser); | |
} catch (UnauthorizedException e) { | |
throw new UnauthorizedException(e.getMessage(), e); | |
} catch (ForbiddenException e) { | |
throw new ForbiddenException(e.getMessage(), e); | |
} catch (NotFoundException e) { | |
throw new NotFoundException(e.getMessage(), e); | |
} catch (BadRequestException e) { | |
throw new BadRequestException(e.getMessage(), e); | |
} catch (ConflictException e) { | |
throw new ConflictException(e.getMessage(), e); | |
} catch (ApiException e) { | |
throw Throwables.propagate(e); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment