use of com.cinchapi.concourse.server.http.errors.HttpError in project concourse by cinchapi.
the class HttpServer method initialize.
/**
* Initialize a {@link EndpointContainer container} by registering all of
* its
* endpoints.
*
* @param container the {@link EndpointContainer} to initialize
*/
private static void initialize(EndpointContainer container) {
for (final Endpoint endpoint : container.endpoints()) {
String action = endpoint.getAction();
Route route = new Route(endpoint.getPath()) {
@Override
public Object handle(Request request, Response response) {
response.type(endpoint.getContentType().toString());
// The HttpRequests preprocessor assigns attributes to the
// request in order for the Endpoint to make calls into
// ConcourseServer.
AccessToken creds = (AccessToken) request.attribute(GlobalState.HTTP_ACCESS_TOKEN_ATTRIBUTE);
String environment = MoreObjects.firstNonNull((String) request.attribute(GlobalState.HTTP_ENVIRONMENT_ATTRIBUTE), GlobalState.DEFAULT_ENVIRONMENT);
String fingerprint = (String) request.attribute(GlobalState.HTTP_FINGERPRINT_ATTRIBUTE);
// does the fingerprint match?
if ((boolean) request.attribute(GlobalState.HTTP_REQUIRE_AUTH_ATTRIBUTE) && creds == null) {
halt(401);
}
if (!Strings.isNullOrEmpty(fingerprint) && !fingerprint.equals(HttpRequests.getFingerprint(request))) {
Logger.warn("Request made with mismatching fingerprint. Expecting {} but got {}", HttpRequests.getFingerprint(request), fingerprint);
halt(401);
}
TransactionToken transaction = null;
try {
Long timestamp = Longs.tryParse((String) request.attribute(GlobalState.HTTP_TRANSACTION_TOKEN_ATTRIBUTE));
transaction = creds != null && timestamp != null ? new TransactionToken(creds, timestamp) : transaction;
} catch (NullPointerException e) {
}
try {
return endpoint.serve(request, response, creds, transaction, environment);
} catch (Exception e) {
if (e instanceof HttpError) {
response.status(((HttpError) e).getCode());
} else if (e instanceof SecurityException || e instanceof java.lang.SecurityException) {
response.removeCookie(GlobalState.HTTP_AUTH_TOKEN_COOKIE);
response.status(401);
} else if (e instanceof IllegalArgumentException) {
response.status(400);
} else {
response.status(500);
Logger.error("", e);
}
JsonObject json = new JsonObject();
json.addProperty("error", e.getMessage());
return json.toString();
}
}
};
if (action.equals("get")) {
Spark.get(route);
} else if (action.equals("post")) {
Spark.post(route);
} else if (action.equals("put")) {
Spark.put(route);
} else if (action.equals("delete")) {
Spark.delete(route);
} else if (action.equals("upsert")) {
Spark.post(route);
Spark.put(route);
} else if (action.equals("options")) {
Spark.options(route);
}
}
}
Aggregations