private void sendEmail(URL templateUrl, String emailAddress, String subject, String message) { try { String template = IoUtils.toString(templateUrl); String content = template.replace("${message-content}", message); // AwsUtils.sendEmail(subject, content, "Munchie Monster <support@munchiemonster.com>", new MunMonEmailAddress(emailAddress)); } catch (Exception e) { String msg = String.format("Exception sending email to %s", emailAddress); throw ApiException.internalServerError(msg, e); } }
public String shortenEncodedUrl(String longUrl) throws IOException { String prettyUrl = StringUtils.decodeUrl(longUrl); String path = String.format(urlTemplate, version, "shorten"); URI uri = URI.create(path); try { Response response = client.target(uri) .queryParam("format", "txt") .queryParam("longUrl", longUrl) .queryParam("access_token", accessToken) .request(MediaType.APPLICATION_JSON_TYPE) .get(); int status = response.getStatus(); String text = response.readEntity(String.class).trim(); if (status == 200) { return text; } else { String msg = String.format("%s: Unable to process request to shortenEncoded %s (%s)", status, prettyUrl, text); throw new ApiException(HttpStatusCode.findByCode(status), msg); } } catch (ApiException ex) { throw ex; } catch (Exception ex) { String msg = String.format("Unexpected exception shortening %s", prettyUrl); throw new IOException(msg, ex); } }
public ApiException toBadRequestException() { String msg = StringUtils.toDelineatedString("\n", this); return ApiException.badRequest(msg); } }
ApiException apiEx = (ApiException)ex; if (apiEx.getHttpStatusCode().isBadRequest()) return createResponse_400(ex); if (apiEx.getHttpStatusCode().isForbidden()) return createResponse_403(ex); if (apiEx.getHttpStatusCode().isNotFound()) return createResponse_404(ex); if (apiEx.getHttpStatusCode().isMethodNotAllowed()) return createResponse_405(ex); response = Response.status(apiEx.getStatusCode()).entity(ex.getMessage()).type(MediaType.TEXT_PLAIN).build();
@Override public Response toResponse(Throwable ex) { String exceptionName = ex.getClass().getName(); if (exceptionMap.containsKey(exceptionName)) { int status = exceptionMap.get(exceptionName); return createResponse(status, ex); } if (ex instanceof ApiException) { ApiException apiEx = (ApiException)ex; int status = apiEx.getHttpStatusCode().getCode(); return createResponse(status, ex); } else if (ex instanceof WebApplicationException) { WebApplicationException wae = (WebApplicationException)ex; if (wae.getResponse() != null) { int status = wae.getResponse().getStatus(); return createResponse(status, ex); } } return createResponse(500, ex); }
@POST @Path("/update") public Response updateAccount(@FormParam("firstName") String firstName, @FormParam("lastName") String lastName, @FormParam("emailAddress") String newEmailAddress) throws Exception { String oldEmailAddress = account.getEmailAddress(); if (EqualsUtils.objectsNotEqual(oldEmailAddress, newEmailAddress)) { // They are changing the emails address. if (execContext.getAccountStore().getByEmail(newEmailAddress) != null) { String msg = String.format("The email address %s is already in use.", newEmailAddress); throw ApiException.conflict(msg); } } UpdateAccountAction action = new UpdateAccountAction(firstName, lastName, newEmailAddress); account.apply(action); execContext.getAccountStore().update(account); if (EqualsUtils.objectsNotEqual(oldEmailAddress, newEmailAddress)) { // The email address has changed - we will need to update the session execContext.getSessionStore().newSession(newEmailAddress); } execContext.setLastMessage("You account details have been updated."); return Response.seeOther(new URI("manage/account")).build(); }
public static DrivingDirections getDrivingDirections(LatLng locationA, LatLng locationB) throws IOException { // https://developers.google.com/maps/documentation/directions/ ExceptionUtils.assertNotNull(locationA, "locationA"); ExceptionUtils.assertNotNull(locationB, "locationB"); String url = "http://maps.googleapis.com/maps/api/directions/json"; url += String.format("?origin=%s,%s", locationA.getLatitude(), locationA.getLongitude()); url += String.format("&destination=%s,%s", locationB.getLatitude(), locationB.getLongitude()); url += "&sensor=false"; URLConnection connection = new URL(url).openConnection(); String json = IoUtils.toString(connection.getInputStream()); DrivingDirections directions = objectMapper.readValue(json, DrivingDirections.class); if (directions.getStatus().isNotOK()) { String msg = String.format("Unable to compute driving directions: %s (%s)", directions.getStatus(), directions.getStatus().getDescription()); throw ApiException.internalServerError(msg); } return directions; }
public Account executeOperation(Account account, CreateAccountAction operation) { if (account != null) { String msg = String.format("The email address \"%s\" already exists.", operation.getEmailAddress()); throw ApiException.badRequest(msg); } account = new Account(operation); store.create(account); return account; }
protected void assertResponse(int status) { HttpStatusCode statusCode = HttpStatusCode.findByCode(status); if (statusCode.isOk() == false) { String msg = String.format("Unexpected response: %s %s", status, statusCode.getReason()); throw new ApiException(statusCode, msg); } }
@Override protected UserDetails retrieveUser(String userName, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { try { if (ProviderUtils.isGoogleAuthentication(authentication) == false) { throw new UsernameNotFoundException("Not Goolge Authentication"); } String code = authentication.getCredentials().toString(); GoogleAuthentication googleAuth = getAuthResponse(code, clientId, clientSecret); UserInfo userInfo = getUserInfo(googleAuth); CurrentUserSource source = store.getCurrentUserSourceByEmail(userInfo.getEmail()); if (source == null) { throw new BadCredentialsException(CurrentUser.INVALID_USER_NAME_OR_PASSWORD); } return new CurrentUser(source); } catch (IOException e) { throw ApiException.internalServerError("Exception during Google-Authentication", e); } }
@POST public Response updateClient(@FormParam("domainKey") String domainKey, @FormParam("domainPassword") String domainPassword, @FormParam("retentionDays") int retentionDays) throws Exception { Domain domain = getDomain(); DomainStore domainStore = execContext.getDomainStore(); if (domain.getDomainKey().equals(domainKey) == false && domainStore.getByDomainKey(domainKey) != null) { // The specified name is not the same as the current value but it is already in use by another account. String msg = String.format("The client name %s already exists.", domainKey); throw ApiException.badRequest(msg); } UpdateDomainAction action = new UpdateDomainAction(domainKey, domainPassword, retentionDays); execContext.setLastMessage("Domain configuration changed."); domain.apply(action); domainStore.update(domain); URI uri = execContext.getUriInfo().getBaseUriBuilder().path("manage").path("domain").path(domain.getDomainKey()).build(); return Response.seeOther(uri).build(); }
throw ApiException.internalServerError(msg);
public Account executeOperation(Account account, LogInAction operation) { if (account == null) { throw ApiException.badRequest(Account.INVALID_USER_NAME_OR_PASSWORD); } if (account.hasTempPassword()) { account.clearTempPassword(); store.update(account); } return account; }
@Override protected UserDetails retrieveUser(String userName, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { try { if (ProviderUtils.isGoogleAuthentication(authentication) == false) { throw new UsernameNotFoundException("Not Goolge Authentication"); } String code = authentication.getCredentials().toString(); GoogleAuthentication googleAuth = GoogleUsersUtils.getAuthResponse(code, clientId, clientSecret); UserInfo userInfo = GoogleUsersUtils.getUserInfo(googleAuth.getAccessToken()); CurrentUserSource source = store.getCurrentUserSourceByEmail(userInfo.getEmail()); if (source == null) { throw new BadCredentialsException(CurrentUser.INVALID_USER_NAME_OR_PASSWORD); } return new CurrentUser(source); } catch (IOException e) { throw ApiException.internalServerError("Exception during Google-Authentication", e); } } }
@POST @Path("/domain") public Response createDomain(@FormParam("domainKey") String domainKey, @FormParam("domainPassword") String domainPassword) throws Exception { if (execContext.getDomainStore().getByDomainKey(domainKey) != null) { throw ApiException.badRequest(String.format("The domain \"%s\" already exists.", domainKey)); } CreateDomainAction action = new CreateDomainAction(execContext.getAccount(), domainKey, domainPassword); Domain domain = execContext.getAccount().add(action); execContext.getDomainStore().create(domain); execContext.getAccountStore().update(execContext.getAccount()); return Response.seeOther(new URI("manage/domain/"+domain.getDomainKey())).build(); } }
public static GoogleAuthentication getAuthResponse(String code, String clientId, String clientSecret) throws IOException { Client client = ClientBuilder.newBuilder().build(); Form form = new Form(); form.param("code", code); form.param("client_id", clientId); form.param("client_secret", clientSecret); form.param("grant_type", "authorization_code"); form.param("redirect_uri", "postmessage"); UriBuilder uriBuilder = new JerseyUriBuilder().uri("https://accounts.google.com/o/oauth2/token"); Response jerseyResponse = client.target(uriBuilder) .request(MediaType.APPLICATION_JSON_TYPE) .post(Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED_TYPE)); int status = jerseyResponse.getStatus(); String json = jerseyResponse.readEntity(String.class); YakJacksonObjectMapper objectMapper = new YakJacksonObjectMapper(); GoogleAuthentication googleAuth = objectMapper.readValue(json, GoogleAuthentication.class); // If there was an error in the token info, abort. if (StringUtils.isNotBlank(googleAuth.getError())) { String msg = String.format("Authentication Error: %s", googleAuth.getError()); throw ApiException.internalServerError(msg); } return googleAuth; }
public Account executeOperation(Account account, ResetPasswordAction operation) { if (account == null) { throw ApiException.badRequest("The email address was not found."); } String tempPassword = account.createTempPassword(); store.update(account); String message = String.format("<h1 style='margin-top:0'>Password Reset</h1><p>Your temporary password for %s is %s.</p>", account.getEmailAddress(), tempPassword); sendEmail(operation.getTemplateUrl(), account.getEmailAddress(), "Password Reset", message); return account; }
public static boolean createDatabase(CouchDatabase database, IdGenerator idGenerator, List<String> documentPaths) throws IOException { if (database.exists()) { log.info("The database "+database.getDatabaseName()+" already exists."); return false; } log.warn("Creating the database " + database.getDatabaseName()); WriteResponse response = database.createDatabase(); if (response.isCreated() == false) { String msg = String.format("Unable to create database: %s %s", response.getStatusCode().getCode(), response.getStatusCode().getReason()); throw ApiException.internalServerError(msg); } for (String documentPath : documentPaths) { log.warn("Creating the document "+documentPath); String json = IoUtils.toString(CouchUtils.class.getResourceAsStream(documentPath)); response = database.put().document(idGenerator.newId(), json).execute(); if (response.isCreated() == false) { String msg = String.format("Unable to put document %s: %s %s", documentPath, response.getStatusCode().getCode(), response.getStatusCode().getReason()); throw ApiException.internalServerError(msg); } } return true; }
if (errors.isEmpty() == false) { String msg = StringUtils.toDelineatedString("\n", errors); throw ApiException.badRequest(msg);