/** * This method is used to construct a standard error status in JSON format from an error code. * * @param exchange HttpServerExchange * @param code error code * @param args arguments for error description */ default void setExchangeStatus(HttpServerExchange exchange, String code, final Object... args) { Status status = new Status(code, args); if(status.getStatusCode() == 0) { // There is no entry in status.yml for this particular error code. status = new Status(ERROR_NOT_DEFINED, code); } exchange.setStatusCode(status.getStatusCode()); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json"); status.setDescription(status.getDescription().replaceAll("\\\\", "\\\\\\\\")); exchange.getResponseSender().send(status.toString()); StackTraceElement[] elements = Thread.currentThread().getStackTrace(); logger.error(status.toString() + " at " + elements[2].getClassName() + "." + elements[2].getMethodName() + "(" + elements[2].getFileName() + ":" + elements[2].getLineNumber() + ")"); }
@Override public String toString() { if(statusSerializer != null) { return statusSerializer.serializeStatus(this); } else { return "{\"statusCode\":" + getStatusCode() + ",\"code\":\"" + getCode() + "\",\"message\":\"" + getMessage() + "\",\"description\":\"" + getDescription() + "\",\"severity\":\"" + getSeverity() + "\"}"; } } }
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); locationRequest.setInterval(30 * 1000); locationRequest.setFastestInterval(5 * 1000); LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() .addLocationRequest(locationRequest); final Status status = result.getStatus(); final LocationSettingsStates state = result.getLocationSettingsStates(); switch (status.getStatusCode()) { case LocationSettingsStatusCodes.SUCCESS: status.startResolutionForResult( getActivity(), 1000); } catch (IntentSender.SendIntentException e) {
@SuppressWarnings("unchecked") @Override public void handleRequest(HttpServerExchange exchange) throws Exception { Map<String, Object> body = (Map)exchange.getAttachment(BodyHandler.REQUEST_BODY); Client client = Config.getInstance().getMapper().convertValue(body, Client.class); if(client.getDerefClientId() != null && Client.ClientTypeEnum.EXTERNAL != client.getClientType()) { IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients"); Client originalClient = clients.get(clientId); if(originalClient == null) { setExchangeStatus(exchange, CLIENT_NOT_FOUND, clientId); IMap<String, User> users = CacheStartupHookProvider.hz.getMap("users"); if(!users.containsKey(ownerId)) { Status status = new Status(USER_NOT_FOUND, ownerId); exchange.setStatusCode(status.getStatusCode()); exchange.getResponseSender().send(status.toString()); processAudit(exchange); return; clients.set(clientId, client);
private Client validateClientSecret(String clientId, String clientSecret) throws ApiException { IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients"); Client client = clients.get(clientId); if(client == null) { throw new ApiException(new Status(CLIENT_NOT_FOUND, clientId)); } else { try { if(HashUtil.validatePassword(clientSecret.toCharArray(), client.getClientSecret())) { return client; } else { throw new ApiException(new Status(UNAUTHORIZED_CLIENT)); } } catch ( NoSuchAlgorithmException | InvalidKeySpecException e) { logger.error("Exception:", e); throw new ApiException(new Status(RUNTIME_EXCEPTION)); } } }
if (exchange.isInIoThread()) { exchange.dispatch(this); return; } catch (Throwable e) { logger.error("Exception:", e); if(exchange.isResponseChannelAvailable()) { exchange.setStatusCode(fe.getStatus().getStatusCode()); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json"); exchange.getResponseSender().send(fe.getStatus().toString()); logger.error(fe.getStatus().toString(), e); } else { setExchangeStatus(exchange, STATUS_RUNTIME_EXCEPTION); if(e instanceof ApiException) { ApiException ae = (ApiException)e; exchange.setStatusCode(ae.getStatus().getStatusCode()); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json"); exchange.getResponseSender().send(ae.getStatus().toString()); logger.error(ae.getStatus().toString(), e); } else { setExchangeStatus(exchange, STATUS_UNCAUGHT_EXCEPTION);
@Override public void handleRequest(final HttpServerExchange exchange) throws Exception { final NormalisedPath requestPath = new ApiNormalisedPath(exchange.getRequestURI()); OpenApiOperation openApiOperation = null; Map<String, Object> auditInfo = exchange.getAttachment(AuditHandler.AUDIT_INFO); if(auditInfo != null) { openApiOperation = (OpenApiOperation)auditInfo.get(Constants.OPENAPI_OPERATION_STRING); } if(openApiOperation == null) { setExchangeStatus(exchange, STATUS_MISSING_OPENAPI_OPERATION); return; } Status status = requestValidator.validateRequest(requestPath, exchange, openApiOperation); if(status != null) { exchange.setStatusCode(status.getStatusCode()); status.setDescription(status.getDescription().replaceAll("\\\\", "\\\\\\\\")); exchange.getResponseSender().send(status.toString()); if(config.logError) logger.error("ValidationError:" + status.toString()); return; } Handler.next(exchange, next); }
if(client != null) { IMap<String, RefreshToken> tokens = CacheStartupHookProvider.hz.getMap("tokens"); RefreshToken token = tokens.remove(refreshToken); if(token != null) { String userId = token.getUserId(); throw new ApiException(new Status(MISMATCH_SCOPE, scope, oldScope)); throw new ApiException(new Status(GENERIC_EXCEPTION, e.getMessage())); newToken.setClientId(client.getClientId()); newToken.setScope(scope); tokens.put(refreshToken, newToken); throw new ApiException(new Status(MISMATCH_CLIENT_ID, client.getClientId(), clientId)); throw new ApiException(new Status(REFRESH_TOKEN_NOT_FOUND, refreshToken));
@Override public void handleRequest(HttpServerExchange exchange) throws Exception { ObjectMapper mapper = Config.getInstance().getMapper(); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json"); // check authorization header for basic authentication Client client = authenticateClient(exchange); if(client != null) { String jwt; Map<String, Object> body = (Map<String, Object>)exchange.getAttachment(BodyHandler.REQUEST_BODY); SignRequest sr = Config.getInstance().getMapper().convertValue(body, SignRequest.class); int expires = sr.getExpires(); try { // assume that the custom_claim is in format of json map string. Map<String, Object> customClaim = sr.getPayload(); jwt = JwtIssuer.getJwt(mockCcClaims(client.getClientId(), expires, customClaim)); } catch (Exception e) { logger.error("Exception:", e); throw new ApiException(new Status(GENERIC_EXCEPTION, e.getMessage())); } Map<String, Object> resMap = new HashMap<>(); resMap.put("access_token", jwt); resMap.put("token_type", "bearer"); resMap.put("expires_in", expires); exchange.getResponseSender().send(mapper.writeValueAsString(resMap)); } processAudit(exchange); }
throw new ApiException(new Status(MISSING_REDIRECT_URI, uri)); } else { if(!uri.equals(redirectUri)) { throw new ApiException(new Status(MISMATCH_REDIRECT_URI, redirectUri, uri)); throw new ApiException(new Status(MISMATCH_SCOPE, scope, client.getScope())); throw new ApiException(new Status(CODE_VERIFIER_MISSING)); throw new ApiException(new Status(CODE_VERIFIER_TOO_SHORT, codeVerifier)); throw new ApiException(new Status(CODE_VERIFIER_TOO_LONG, codeVerifier)); throw new ApiException(new Status(INVALID_CODE_VERIFIER, codeVerifier)); String s = CodeVerifierUtil.deriveCodeVerifierChallenge(codeVerifier); if(!codeChallenge.equals(s)) { throw new ApiException(new Status(CODE_VERIFIER_FAILED)); throw new ApiException(new Status(CODE_VERIFIER_FAILED)); throw new ApiException(new Status(INVALID_CODE_CHALLENGE_METHOD, codeChallengeMethod)); throw new ApiException(new Status(GENERIC_EXCEPTION, e.getMessage())); return resMap; } else { throw new ApiException(new Status(INVALID_AUTHORIZATION_CODE, code));
@Override public void handleRequest(HttpServerExchange exchange) throws Exception { ObjectMapper mapper = Config.getInstance().getMapper(); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json"); Map<String, Object> formMap = new HashMap<>(); String grantType = (String)formMap.remove("grant_type"); if("client_credentials".equals(grantType)) { exchange.getResponseSender().send(mapper.writeValueAsString(handleClientCredentials(exchange, formMap))); } else if("authorization_code".equals(grantType)) { exchange.getResponseSender().send(mapper.writeValueAsString(handleAuthorizationCode(exchange, formMap))); } else if("password".equals(grantType)) { exchange.getResponseSender().send(mapper.writeValueAsString(handlePassword(exchange, formMap))); } else if("refresh_token".equals(grantType)) { exchange.getResponseSender().send(mapper.writeValueAsString(handleRefreshToken(exchange, formMap))); } catch (ApiException e) { logger.error("ApiException", e); exchange.setStatusCode(e.getStatus().getStatusCode()); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json"); exchange.getResponseSender().send(e.getStatus().toString());
throw new ApiException(new Status(MISMATCH_SCOPE, scope, client.getScope())); throw new ApiException(new Status(USER_ID_REQUIRED_FOR_CLIENT_AUTHENTICATED_USER_GRANT_TYPE)); throw new ApiException(new Status(USER_TYPE_REQUIRED_FOR_CLIENT_AUTHENTICATED_USER_GRANT_TYPE)); jwt = JwtIssuer.getJwt(mockAcClaims(client.getClientId(), scope, userId, userType, roles, null, formMap)); } catch (Exception e) { throw new ApiException(new Status(GENERIC_EXCEPTION, e.getMessage())); token.setClientId(client.getClientId()); token.setScope(scope); IMap<String, RefreshToken> tokens = CacheStartupHookProvider.hz.getMap("tokens"); tokens.set(refreshToken, token); } else { throw new ApiException(new Status(NOT_TRUSTED_CLIENT));
private Status validateHeader(final HttpServerExchange exchange, final SwaggerOperation swaggerOperation, final Parameter headerParameter) { final HeaderValues headerValues = exchange.getRequestHeaders().get(headerParameter.getName()); if ((headerValues == null || headerValues.isEmpty())) { if(headerParameter.getRequired()) { return new Status(VALIDATOR_REQUEST_PARAMETER_HEADER_MISSING, headerParameter.getName(), swaggerOperation.getPathString().original()); } } else { Optional<Status> optional = headerValues .stream() .map((v) -> parameterValidators.validate(v, headerParameter)) .filter(s -> s != null) .findFirst(); if(optional.isPresent()) { return optional.get(); } } return null; } }
/** * Validate the given response against the API operation. * * @param exchange The exchange to validate * @param swaggerOperation The API operation to validate the response against * * @return A status containing validation error */ public Status validateResponse(final HttpServerExchange exchange, final SwaggerOperation swaggerOperation) { requireNonNull(exchange, "An exchange is required"); requireNonNull(swaggerOperation, "A swagger operation is required"); io.swagger.models.Response swaggerResponse = swaggerOperation.getOperation().getResponses().get(Integer.toString(exchange.getStatusCode())); if (swaggerResponse == null) { swaggerResponse = swaggerOperation.getOperation().getResponses().get("default"); // try the default response } if (swaggerResponse == null) { return new Status("ERR11015", exchange.getStatusCode(), swaggerOperation.getPathString().original()); } if (swaggerResponse.getSchema() == null) { return null; } String body = exchange.getOutputStream().toString(); if (body == null || body.length() == 0) { return new Status("ERR11016", swaggerOperation.getMethod(), swaggerOperation.getPathString().original()); } return schemaValidator.validate(body, swaggerResponse.getSchema()); }
private Status validateQueryParameter(final HttpServerExchange exchange, final SwaggerOperation swaggerOperation, final Parameter queryParameter) { final Collection<String> queryParameterValues = exchange.getQueryParameters().get(queryParameter.getName()); if ((queryParameterValues == null || queryParameterValues.isEmpty())) { if(queryParameter.getRequired()) { return new Status(VALIDATOR_REQUEST_PARAMETER_QUERY_MISSING, queryParameter.getName(), swaggerOperation.getPathString().original()); } } else { Optional<Status> optional = queryParameterValues .stream() .map((v) -> parameterValidators.validate(v, queryParameter)) .filter(s -> s != null) .findFirst(); if(optional.isPresent()) { return optional.get(); } } return null; }
private void buildWeightsMap(Map<String, Integer> weights, RpcCommand.ClientCommand command) { for (String rule : command.getMergeGroups()) { String[] gw = rule.split(":"); int weight = 1; if (gw.length > 1) { try { weight = Integer.parseInt(gw[1]); } catch (NumberFormatException e) { throw new FrameworkException(new Status(WEIGHT_OUT_OF_RANGE, weight)); } if (weight < 0 || weight > 100) { throw new FrameworkException(new Status(WEIGHT_OUT_OF_RANGE, weight)); } } weights.put(gw[0], weight); } }
public ApiException(Status status, Throwable cause) { super(status.toString(), cause); this.status = status; } }
final Status status = result.getStatus(); switch (status.getStatusCode()) { case LocationSettingsStatusCodes.SUCCESS: status.startResolutionForResult( MapActivity.this, REQUEST_CHECK_SETTINGS);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); locationRequest.setInterval(30 * 1000); locationRequest.setNumUpdates(1); locationRequest.setExpirationDuration(20000); locationRequest.setFastestInterval(500); final Status status = result.getStatus(); final LocationSettingsStates state = result.getLocationSettingsStates(); switch (status.getStatusCode()) { case LocationSettingsStatusCodes.SUCCESS: { LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, this); status.startResolutionForResult(MainTab.this, REQUEST_CHECK_SETTINGS); } catch (IntentSender.SendIntentException e) {
LocationRequest mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(10000); mLocationRequest.setFastestInterval(5000); switch (status.getStatusCode()) { case LocationSettingsStatusCodes.SUCCESS: status.startResolutionForResult(LocationByGPS.this, REQUEST_CHECK_SETTINGS);