Search in sources :

Example 1 with Route

use of spark.Route in project concourse by cinchapi.

the class MatcherFilter method doFilter.

public void doFilter(ServletRequest servletRequest, // NOSONAR
ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
    // NOSONAR
    // NOSONAR
    HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
    HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
    // NOSONAR
    String httpMethodStr = httpRequest.getMethod().toLowerCase();
    // NOSONAR
    String uri = httpRequest.getRequestURI();
    String acceptType = httpRequest.getHeader(ACCEPT_TYPE_REQUEST_MIME_HEADER);
    String bodyContent = null;
    if (!isStaticFileRequest(servletRequest, servletResponse, chain)) {
        RequestWrapper req = new RequestWrapper();
        ResponseWrapper res = new ResponseWrapper();
        try {
            // BEFORE filters
            List<RouteMatch> matchSet = routeMatcher.findTargetsForRequestedRoute(HttpMethod.before, uri, acceptType);
            for (RouteMatch filterMatch : matchSet) {
                Object filterTarget = filterMatch.getTarget();
                if (filterTarget instanceof spark.Filter) {
                    Request request = RequestResponseFactory.create(filterMatch, httpRequest);
                    Response response = RequestResponseFactory.create(httpResponse);
                    spark.Filter filter = (spark.Filter) filterTarget;
                    req.setDelegate(request);
                    res.setDelegate(response);
                    filter.handle(req, res);
                    String bodyAfterFilter = Access.getBody(response);
                    if (bodyAfterFilter != null) {
                        bodyContent = bodyAfterFilter;
                    }
                }
            }
            // BEFORE filters, END
            HttpMethod httpMethod = HttpMethod.valueOf(httpMethodStr);
            RouteMatch match = null;
            match = routeMatcher.findTargetForRequestedRoute(httpMethod, uri, acceptType);
            Object target = null;
            if (match != null) {
                target = match.getTarget();
            } else if (httpMethod == HttpMethod.head && bodyContent == null) {
                // See if get is mapped to provide default head mapping
                bodyContent = routeMatcher.findTargetForRequestedRoute(HttpMethod.get, uri, acceptType) != null ? "" : null;
            } else if (httpMethod == HttpMethod.options && bodyContent == null) {
                // CON-476: For an OPTIONS request, attempt to get all the
                // targets for the route and specify those in the response
                Set<HttpMethod> methods = routeMatcher.findMethodsForRequestedPath(uri, acceptType);
                if (!methods.isEmpty()) {
                    httpResponse.setHeader("Allow", StringUtils.join(methods, ','));
                    bodyContent = "";
                }
            }
            if (target != null) {
                try {
                    String result = null;
                    if (target instanceof Route) {
                        Route route = ((Route) target);
                        Request request = RequestResponseFactory.create(match, httpRequest);
                        Response response = RequestResponseFactory.create(httpResponse);
                        req.setDelegate(request);
                        res.setDelegate(response);
                        Object element = route.handle(req, res);
                        result = route.render(element);
                    }
                    if (result != null) {
                        bodyContent = result;
                    }
                } catch (HaltException hEx) {
                    // NOSONAR
                    throw hEx;
                } catch (Exception e) {
                    Logger.error("", e);
                    httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    bodyContent = INTERNAL_ERROR;
                }
            }
            // AFTER filters
            matchSet = routeMatcher.findTargetsForRequestedRoute(HttpMethod.after, uri, acceptType);
            for (RouteMatch filterMatch : matchSet) {
                Object filterTarget = filterMatch.getTarget();
                if (filterTarget instanceof spark.Filter) {
                    Request request = RequestResponseFactory.create(filterMatch, httpRequest);
                    Response response = RequestResponseFactory.create(httpResponse);
                    req.setDelegate(request);
                    res.setDelegate(response);
                    spark.Filter filter = (spark.Filter) filterTarget;
                    filter.handle(req, res);
                    String bodyAfterFilter = Access.getBody(response);
                    if (bodyAfterFilter != null) {
                        bodyContent = bodyAfterFilter;
                    }
                }
            }
        // AFTER filters, END
        } catch (HaltException hEx) {
            httpResponse.setStatus(hEx.getStatusCode());
            if (hEx.getBody() != null) {
                bodyContent = hEx.getBody();
            } else {
                bodyContent = "";
            }
        }
    }
    boolean consumed = bodyContent != null;
    if (!consumed && hasOtherHandlers) {
        throw new NotConsumedException();
    }
    if (!consumed && !isServletContext) {
        httpResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
        bodyContent = String.format(NOT_FOUND, uri);
        consumed = true;
    }
    if (consumed) {
        // Write body content
        if (!httpResponse.isCommitted()) {
            if (httpResponse.getContentType() == null) {
                httpResponse.setContentType("text/html; charset=utf-8");
            }
            httpResponse.getOutputStream().write(bodyContent.getBytes("utf-8"));
        }
    } else if (chain != null) {
        chain.doFilter(httpRequest, httpResponse);
    }
}
Also used : HaltException(spark.HaltException) ServletRequest(javax.servlet.ServletRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) Request(spark.Request) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) HaltException(spark.HaltException) RouteMatch(spark.route.RouteMatch) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletResponse(javax.servlet.ServletResponse) Response(spark.Response) Filter(javax.servlet.Filter) HttpMethod(spark.route.HttpMethod) Route(spark.Route)

Example 2 with Route

use of spark.Route in project apm-agent-java by elastic.

the class RoutesAdviceTest method startServer.

@BeforeAll
static void startServer() {
    port(0);
    init();
    awaitInitialization();
    get("/foo/:bar", new Route() {

        @Override
        public Object handle(Request request, Response response) {
            return "bar";
        }
    });
}
Also used : Response(spark.Response) Request(spark.Request) Route(spark.Route) BeforeAll(org.junit.jupiter.api.BeforeAll)

Example 3 with Route

use of spark.Route 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);
        }
    }
}
Also used : TransactionToken(com.cinchapi.concourse.thrift.TransactionToken) Request(spark.Request) JsonObject(com.google.gson.JsonObject) Response(spark.Response) AccessToken(com.cinchapi.concourse.thrift.AccessToken) HttpError(com.cinchapi.concourse.server.http.errors.HttpError) Route(spark.Route)

Example 4 with Route

use of spark.Route in project sendgrid-java by sendgrid.

the class Example method main.

public static void main(String[] args) {
    Security.addProvider(new BouncyCastleProvider());
    final Route webhookHandler = (req, res) -> {
        try {
            final String publicKey = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE83T4O/n84iotIvIW4mdBgQ/7dAfSmpqIM8kF9mN1flpVKS3GRqe62gw+2fNNRaINXvVpiglSI8eNEc6wEA3F+g==";
            final String signature = req.headers(EventWebhookHeader.SIGNATURE.toString());
            final String timestamp = req.headers(EventWebhookHeader.TIMESTAMP.toString());
            final byte[] requestBody = req.bodyAsBytes();
            final EventWebhook ew = new EventWebhook();
            final ECPublicKey ellipticCurvePublicKey = ew.ConvertPublicKeyToECDSA(publicKey);
            final boolean valid = ew.VerifySignature(ellipticCurvePublicKey, requestBody, signature, timestamp);
            System.out.println("Valid Signature: " + valid);
            if (valid) {
                res.status(204);
            } else {
                res.status(403);
            }
            return null;
        } catch (final Exception exception) {
            res.status(500);
            return exception.toString();
        }
    };
    post("/sendgrid/webhook", webhookHandler);
}
Also used : EventWebhook(com.sendgrid.helpers.eventwebhook.EventWebhook) Body(com.twilio.twiml.messaging.Body) Security(java.security.Security) Spark.post(spark.Spark.post) HashMap(java.util.HashMap) MessagingResponse(com.twilio.twiml.MessagingResponse) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) Message(com.twilio.twiml.messaging.Message) EventWebhookHeader(com.sendgrid.helpers.eventwebhook.EventWebhookHeader) Map(java.util.Map) Route(spark.Route) RequestValidator(com.twilio.security.RequestValidator) ECPublicKey(java.security.interfaces.ECPublicKey) ECPublicKey(java.security.interfaces.ECPublicKey) Route(spark.Route) EventWebhook(com.sendgrid.helpers.eventwebhook.EventWebhook) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 5 with Route

use of spark.Route in project waitt by kawasima.

the class DashboardApplication method init.

@Override
public void init() {
    final AdminConfig adminConfig = new AdminConfig();
    adminConfig.read();
    options("/*", new Route() {

        @Override
        public Object handle(Request request, Response response) throws Exception {
            String accessControlRequestHeaders = request.headers("Access-Control-Request-Headers");
            if (accessControlRequestHeaders != null) {
                response.header("Access-Control-Allow-Headers", accessControlRequestHeaders);
            }
            String accessControlRequestMethod = request.headers("Access-Control-Request-Method");
            if (accessControlRequestMethod != null) {
                response.header("Access-Control-Allow-Methods", accessControlRequestMethod);
            }
            return "OK";
        }
    });
    before(new Filter() {

        @Override
        public void handle(Request req, Response res) throws Exception {
            res.header("Access-Control-Allow-Origin", "*");
            res.header("Access-Control-Allow-Headers", "*");
            res.type("application/json");
        }
    });
    get("/application", new ApplicationRoute(adminConfig));
    get("/server", new ServerRoute(adminConfig));
    post("/server/reload", new ServerRestartRoute(adminConfig));
    get("/env", new EnvPropertyRoute());
    get("/heap", new HeapDumpRoute());
    get("/thread", new ThreadDumpRoute());
    get("/prometheus", new PrometheusRoute());
    staticFileLocation("/public");
}
Also used : Request(spark.Request) Response(spark.Response) Filter(spark.Filter) Route(spark.Route)

Aggregations

Route (spark.Route)5 Request (spark.Request)4 Response (spark.Response)4 HttpError (com.cinchapi.concourse.server.http.errors.HttpError)1 AccessToken (com.cinchapi.concourse.thrift.AccessToken)1 TransactionToken (com.cinchapi.concourse.thrift.TransactionToken)1 JsonObject (com.google.gson.JsonObject)1 EventWebhook (com.sendgrid.helpers.eventwebhook.EventWebhook)1 EventWebhookHeader (com.sendgrid.helpers.eventwebhook.EventWebhookHeader)1 RequestValidator (com.twilio.security.RequestValidator)1 MessagingResponse (com.twilio.twiml.MessagingResponse)1 Body (com.twilio.twiml.messaging.Body)1 Message (com.twilio.twiml.messaging.Message)1 IOException (java.io.IOException)1 Security (java.security.Security)1 ECPublicKey (java.security.interfaces.ECPublicKey)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 Filter (javax.servlet.Filter)1 ServletException (javax.servlet.ServletException)1