Search in sources :

Example 1 with Request

use of org.glassfish.grizzly.http.server.Request in project jersey by jersey.

the class GrizzlyHttpContainer method service.

@Override
public void service(final Request request, final Response response) {
    final ResponseWriter responseWriter = new ResponseWriter(response, configSetStatusOverSendError);
    try {
        logger.debugLog("GrizzlyHttpContainer.service(...) started");
        URI baseUri = getBaseUri(request);
        URI requestUri = getRequestUri(request);
        final ContainerRequest requestContext = new ContainerRequest(baseUri, requestUri, request.getMethod().getMethodString(), getSecurityContext(request), new GrizzlyRequestPropertiesDelegate(request));
        requestContext.setEntityStream(request.getInputStream());
        for (final String headerName : request.getHeaderNames()) {
            requestContext.headers(headerName, request.getHeaders(headerName));
        }
        requestContext.setWriter(responseWriter);
        requestContext.setRequestScopedInitializer(injectionManager -> {
            injectionManager.<Ref<Request>>getInstance(RequestTYPE).set(request);
            injectionManager.<Ref<Response>>getInstance(ResponseTYPE).set(response);
        });
        appHandler.handle(requestContext);
    } finally {
        logger.debugLog("GrizzlyHttpContainer.service(...) finished");
    }
}
Also used : Response(org.glassfish.grizzly.http.server.Response) ContainerResponse(org.glassfish.jersey.server.ContainerResponse) ContainerResponseWriter(org.glassfish.jersey.server.spi.ContainerResponseWriter) Request(org.glassfish.grizzly.http.server.Request) ContainerRequest(org.glassfish.jersey.server.ContainerRequest) ContainerRequest(org.glassfish.jersey.server.ContainerRequest) URI(java.net.URI)

Example 2 with Request

use of org.glassfish.grizzly.http.server.Request in project edammap by edamontology.

the class Server method run.

private static void run() throws IOException, ParseException {
    paramsMain.add(new Param("Ontology file", ServerArgs.EDAM, new File(args.getEdam()).getName(), "https://github.com/edamontology/edamontology/tree/master/releases"));
    for (Stopwords stopwords : Stopwords.values()) {
        stopwordsAll.put(stopwords, PreProcessor.getStopwords(stopwords));
    }
    processor = new Processor(args.getProcessorArgs());
    if (args.getProcessorArgs().getIdf() != null && !args.getProcessorArgs().getIdf().isEmpty()) {
        idf = new Idf(args.getProcessorArgs().getIdf());
    }
    if (args.getProcessorArgs().getIdfStemmed() != null && !args.getProcessorArgs().getIdfStemmed().isEmpty()) {
        idfStemmed = new Idf(args.getProcessorArgs().getIdfStemmed());
    }
    logger.info("Loading concepts");
    concepts = Edam.load(args.getEdam());
    logger.info("Configuring server");
    final ResourceConfig rc = new ResourceConfig().packages("org.edamontology.edammap.server");
    // TODO .property(JsonGenerator.PRETTY_PRINTING, true);
    HttpServer httpServer = GrizzlyHttpServerFactory.createHttpServer(URI.create(args.getBaseUri() + "/" + args.getPath() + "/api"), rc, false);
    final StaticHttpHandler filesHttpHandler = new StaticHttpHandler(args.getFiles());
    filesHttpHandler.setDirectorySlashOff(true);
    httpServer.getServerConfiguration().addHttpHandler(filesHttpHandler, "/" + args.getPath() + "/*");
    httpServer.getServerConfiguration().addHttpHandler(new HttpHandler() {

        @Override
        public void service(Request request, Response response) throws Exception {
            // TODO replace null with request.getParameterMap()
            String responseText = Resource.runGet(null, request);
            response.setContentType(MediaType.TEXT_HTML);
            response.setContentLength(responseText.length());
            response.getWriter().write(responseText);
        }
    }, "/" + args.getPath() + "/");
    if (args.getLog() != null) {
        Path accessDir = Paths.get(args.getLog() + "/access");
        if (!Files.exists(accessDir)) {
            Files.createDirectory(accessDir);
        }
        final AccessLogBuilder builder = new AccessLogBuilder(accessDir + "/edammap-access.log");
        builder.rotatedDaily();
        // builder.format(ApacheLogFormat.COMBINED); // TODO
        builder.instrument(httpServer.getServerConfiguration());
    }
    logger.info("Starting server");
    httpServer.start();
    logger.info("{} has started", version.getName());
}
Also used : Path(java.nio.file.Path) StaticHttpHandler(org.glassfish.grizzly.http.server.StaticHttpHandler) HttpHandler(org.glassfish.grizzly.http.server.HttpHandler) PreProcessor(org.edamontology.edammap.core.preprocessing.PreProcessor) Processor(org.edamontology.edammap.core.processing.Processor) Request(org.glassfish.grizzly.http.server.Request) AccessLogBuilder(org.glassfish.grizzly.http.server.accesslog.AccessLogBuilder) Idf(org.edamontology.edammap.core.idf.Idf) Stopwords(org.edamontology.edammap.core.preprocessing.Stopwords) ParseException(java.text.ParseException) IOException(java.io.IOException) Response(org.glassfish.grizzly.http.server.Response) StaticHttpHandler(org.glassfish.grizzly.http.server.StaticHttpHandler) Param(org.edamontology.edammap.core.output.Param) HttpServer(org.glassfish.grizzly.http.server.HttpServer) ResourceConfig(org.glassfish.jersey.server.ResourceConfig) File(java.io.File)

Example 3 with Request

use of org.glassfish.grizzly.http.server.Request in project OpenTripPlanner by opentripplanner.

the class BrokerHttpHandler method service.

@Override
public void service(Request request, Response response) throws Exception {
    response.setContentType("application/json");
    // request.getRequestURI(); // without protocol or server, only request path
    // request.getPathInfo(); // without handler base path
    String[] pathComponents = request.getPathInfo().split("/");
    // Path component 0 is empty since the path always starts with a slash.
    if (pathComponents.length < 2) {
        response.setStatus(HttpStatus.BAD_REQUEST_400);
        response.setDetailMessage("path should have at least one part");
    }
    try {
        if (request.getMethod() == Method.HEAD) {
            /* Let the client know server is alive and URI + request are valid. */
            mapper.readTree(request.getInputStream());
            response.setStatus(HttpStatus.OK_200);
            return;
        } else if (request.getMethod() == Method.GET && "status".equals(pathComponents[1])) {
            /* fetch job status */
            String[] jobIds = pathComponents[2].split(",");
            List<JobStatus> ret = Arrays.asList(jobIds).stream().map(id -> broker.findJob(id)).filter(job -> job != null).map(job -> new JobStatus(job)).collect(Collectors.toList());
            if (ret.isEmpty()) {
                response.setStatus(HttpStatus.NOT_FOUND_404);
                response.setDetailMessage("no job IDs were found");
            } else {
                response.setStatus(HttpStatus.OK_200);
                OutputStream os = response.getOutputStream();
                mapper.writeValue(os, ret);
                os.close();
            }
            return;
        } else if (request.getMethod() == Method.POST) {
            /* dequeue messages. */
            String command = pathComponents[1];
            if ("dequeue".equals(command)) {
                String graphAffinity = pathComponents[2];
                request.getRequest().getConnection().addCloseListener((closeable, iCloseType) -> {
                    broker.removeSuspendedResponse(graphAffinity, response);
                });
                // The request should survive after the handler function exits.
                response.suspend();
                broker.registerSuspendedResponse(graphAffinity, response);
            } else /* not dequeueing, enqueuing */
            if ("enqueue".equals(command)) {
                String context = pathComponents[2];
                if ("priority".equals(context)) {
                    // Enqueue a single priority task
                    AnalystClusterRequest task = mapper.readValue(request.getInputStream(), AnalystClusterRequest.class);
                    broker.enqueuePriorityTask(task, response);
                    // Enqueueing the priority task has set its internal taskId.
                    // TODO move all removal listener registration into the broker functions.
                    request.getRequest().getConnection().addCloseListener((closeable, iCloseType) -> {
                        broker.deletePriorityTask(task.taskId);
                    });
                    // The request should survive after the handler function exits.
                    response.suspend();
                    return;
                } else if ("jobs".equals(context)) {
                    // Enqueue a list of tasks that belong to jobs
                    List<AnalystClusterRequest> tasks = mapper.readValue(request.getInputStream(), new TypeReference<List<AnalystClusterRequest>>() {
                    });
                    // Pre-validate tasks checking that they are all on the same job
                    AnalystClusterRequest exemplar = tasks.get(0);
                    for (AnalystClusterRequest task : tasks) {
                        if (task.jobId != exemplar.jobId || task.graphId != exemplar.graphId) {
                            response.setStatus(HttpStatus.BAD_REQUEST_400);
                            response.setDetailMessage("All tasks must be for the same graph and job.");
                        }
                    }
                    broker.enqueueTasks(tasks);
                    response.setStatus(HttpStatus.ACCEPTED_202);
                } else {
                    response.setStatus(HttpStatus.NOT_FOUND_404);
                    response.setDetailMessage("Context not found; should be either 'jobs' or 'priority'");
                }
            } else if ("complete".equals(command)) {
                // Mark a specific high-priority task as completed, and record its result.
                // We were originally planning to do this with a DELETE request that has a body,
                // but that is nonstandard enough to anger many libraries including Grizzly.
                int taskId = Integer.parseInt(pathComponents[3]);
                Response suspendedProducerResponse = broker.deletePriorityTask(taskId);
                if (suspendedProducerResponse == null) {
                    response.setStatus(HttpStatus.NOT_FOUND_404);
                    return;
                }
                // Copy the result back to the connection that was the source of the task.
                try {
                    ByteStreams.copy(request.getInputStream(), suspendedProducerResponse.getOutputStream());
                } catch (IOException ioex) {
                // Apparently the task producer did not wait to retrieve its result. Priority task result delivery
                // is not guaranteed, we don't need to retry, this is not considered an error by the worker.
                }
                response.setStatus(HttpStatus.OK_200);
                suspendedProducerResponse.setStatus(HttpStatus.OK_200);
                suspendedProducerResponse.resume();
                return;
            } else if ("single".equals(command)) {
                // await single point responses
                String graphAffinity = pathComponents[2];
                Broker.WrappedResponse wr = new Broker.WrappedResponse(request, response);
                request.getRequest().getConnection().addCloseListener((c, i) -> {
                    broker.removeSinglePointChannel(graphAffinity, wr);
                });
                response.suspend();
                broker.registerSinglePointChannel(graphAffinity, wr);
            }
        } else if (request.getMethod() == Method.DELETE) {
            /* Acknowledge completion of a task and remove it from queues, avoiding re-delivery. */
            if ("tasks".equalsIgnoreCase(pathComponents[1])) {
                int taskId = Integer.parseInt(pathComponents[2]);
                // This must not have been a priority task. Try to delete it as a normal job task.
                if (broker.markTaskCompleted(taskId)) {
                    response.setStatus(HttpStatus.OK_200);
                } else {
                    response.setStatus(HttpStatus.NOT_FOUND_404);
                }
            } else if ("jobs".equals((pathComponents[1]))) {
                if (broker.deleteJob(pathComponents[2])) {
                    response.setStatus(HttpStatus.OK_200);
                    response.setDetailMessage("job deleted");
                } else {
                    response.setStatus(HttpStatus.NOT_FOUND_404);
                    response.setDetailMessage("job not found");
                }
            } else {
                response.setStatus(HttpStatus.BAD_REQUEST_400);
                response.setDetailMessage("Delete is only allowed for tasks and jobs.");
            }
        } else {
            response.setStatus(HttpStatus.BAD_REQUEST_400);
            response.setDetailMessage("Unrecognized HTTP method.");
        }
    } catch (JsonProcessingException jpex) {
        response.setStatus(HttpStatus.BAD_REQUEST_400);
        response.setDetailMessage("Could not decode/encode JSON payload. " + jpex.getMessage());
        LOG.info("Error processing JSON from client", jpex);
    } catch (Exception ex) {
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR_500);
        response.setDetailMessage(ex.toString());
        LOG.info("Error processing client request", ex);
    }
}
Also used : OutputStream(java.io.OutputStream) Arrays(java.util.Arrays) Request(org.glassfish.grizzly.http.server.Request) Logger(org.slf4j.Logger) Method(org.glassfish.grizzly.http.Method) JodaLocalDateSerializer(org.opentripplanner.api.model.JodaLocalDateSerializer) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HttpHandler(org.glassfish.grizzly.http.server.HttpHandler) AgencyAndIdSerializer(org.opentripplanner.api.model.AgencyAndIdSerializer) LoggerFactory(org.slf4j.LoggerFactory) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) Response(org.glassfish.grizzly.http.server.Response) Collectors(java.util.stream.Collectors) List(java.util.List) GeoJsonModule(com.conveyal.geojson.GeoJsonModule) ByteStreams(com.google.common.io.ByteStreams) JsonInclude(com.fasterxml.jackson.annotation.JsonInclude) AnalystClusterRequest(org.opentripplanner.analyst.cluster.AnalystClusterRequest) TypeReference(com.fasterxml.jackson.core.type.TypeReference) HttpStatus(org.glassfish.grizzly.http.util.HttpStatus) OutputStream(java.io.OutputStream) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) Response(org.glassfish.grizzly.http.server.Response) List(java.util.List) AnalystClusterRequest(org.opentripplanner.analyst.cluster.AnalystClusterRequest) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 4 with Request

use of org.glassfish.grizzly.http.server.Request in project graylog2-server by Graylog2.

the class RestToolsTest method getRemoteAddrFromRequestWorksWithIPv6IfSubnetsContainsOnlyIPv4.

@Test
public void getRemoteAddrFromRequestWorksWithIPv6IfSubnetsContainsOnlyIPv4() throws Exception {
    final Request request = mock(Request.class);
    when(request.getRemoteAddr()).thenReturn("2001:DB8::42");
    when(request.getHeader("X-Forwarded-For")).thenReturn("2001:DB8::1");
    final String s = RestTools.getRemoteAddrFromRequest(request, Collections.singleton(new IpSubnet("127.0.0.1/32")));
    assertThat(s).isEqualTo("2001:DB8::42");
}
Also used : IpSubnet(org.graylog2.utilities.IpSubnet) Request(org.glassfish.grizzly.http.server.Request) Test(org.junit.Test)

Example 5 with Request

use of org.glassfish.grizzly.http.server.Request in project ddf by codice.

the class SecureStubServer method stubsToHandler.

@SuppressWarnings("squid:S2177")
private HttpHandler stubsToHandler() {
    return new HttpHandler() {

        @Override
        public void service(Request request, Response response) throws Exception {
            Call call = Call.fromRequest(request);
            CallsHelper.logCall(call);
            boolean processed = false;
            ListIterator<Stub> iterator = stubs.listIterator(stubs.size());
            while (iterator.hasPrevious()) {
                Stub stub = iterator.previous();
                if (!stub.isApplicable(call)) {
                    continue;
                }
                stub.apply(response);
                processed = true;
                break;
            }
            if (!processed) {
                response.setStatus(HttpStatus.NOT_FOUND_404);
                LOGGER.debug("Request {} hasn't been covered by any of {} stubs.", request.getRequestURI(), stubs.size());
            }
            calls.add(call);
        }
    };
}
Also used : Response(org.glassfish.grizzly.http.server.Response) HttpHandler(org.glassfish.grizzly.http.server.HttpHandler) Call(com.xebialabs.restito.semantics.Call) Request(org.glassfish.grizzly.http.server.Request) Stub(com.xebialabs.restito.semantics.Stub)

Aggregations

Request (org.glassfish.grizzly.http.server.Request)16 Test (org.junit.Test)6 IOException (java.io.IOException)5 Response (org.glassfish.grizzly.http.server.Response)5 HttpHandler (org.glassfish.grizzly.http.server.HttpHandler)4 IpSubnet (org.graylog2.utilities.IpSubnet)4 URI (java.net.URI)3 URISyntaxException (java.net.URISyntaxException)3 ParseException (java.text.ParseException)3 List (java.util.List)3 Collectors (java.util.stream.Collectors)3 Consumes (javax.ws.rs.Consumes)3 POST (javax.ws.rs.POST)3 Produces (javax.ws.rs.Produces)3 Response (javax.ws.rs.core.Response)3 Idf (org.edamontology.edammap.core.idf.Idf)3 PreProcessor (org.edamontology.edammap.core.preprocessing.PreProcessor)3 Files (java.nio.file.Files)2 Paths (java.nio.file.Paths)2 Instant (java.time.Instant)2