Search in sources :

Example 6 with Request

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

the class JerseyContainerCommandService method getJerseyContainer.

private JerseyContainer getJerseyContainer(ResourceConfig rc) {
    AdminJerseyServiceIteratorProvider iteratorProvider = new AdminJerseyServiceIteratorProvider();
    try {
        ServiceFinder.setIteratorProvider(iteratorProvider);
        final HttpHandler httpHandler = ContainerFactory.createContainer(HttpHandler.class, rc);
        return new JerseyContainer() {

            @Override
            public void service(Request request, Response response) throws Exception {
                httpHandler.service(request, response);
            }
        };
    } finally {
        iteratorProvider.disable();
    }
}
Also used : Response(org.glassfish.grizzly.http.server.Response) HttpHandler(org.glassfish.grizzly.http.server.HttpHandler) Request(org.glassfish.grizzly.http.server.Request)

Example 7 with Request

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

the class Resource method checkEdam.

@Path("edam")
@POST
@Produces(MediaType.TEXT_PLAIN)
public Response checkEdam(String requestString, @Context Request request) {
    try {
        logger.info("POST /edam {} from {}", requestString, request.getRemoteAddr());
        Response response = Response.ok(QueryLoader.fromServerEdam(requestString, Server.concepts).entrySet().stream().map(c -> c.getKey() + " : " + c.getValue().getLabel()).collect(Collectors.joining("\n"))).build();
        logger.info("POSTED /edam {}", response.getEntity());
        return response;
    } catch (IllegalArgumentException e) {
        logger.error("Exception!", e);
        return Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
    } catch (Throwable e) {
        logger.error("Exception!", e);
        throw e;
    }
}
Also used : Response(javax.ws.rs.core.Response) Results(org.edamontology.edammap.core.benchmarking.Results) Query(org.edamontology.edammap.core.query.Query) Request(org.glassfish.grizzly.http.server.Request) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) URISyntaxException(java.net.URISyntaxException) Path(javax.ws.rs.Path) Benchmark(org.edamontology.edammap.core.benchmarking.Benchmark) PreProcessor(org.edamontology.edammap.core.preprocessing.PreProcessor) Output(org.edamontology.edammap.core.output.Output) ConceptProcessed(org.edamontology.edammap.core.processing.ConceptProcessed) QueryLoader(org.edamontology.edammap.core.query.QueryLoader) MediaType(javax.ws.rs.core.MediaType) Consumes(javax.ws.rs.Consumes) FetcherArgs(org.edamontology.pubfetcher.FetcherArgs) Locale(java.util.Locale) Map(java.util.Map) URI(java.net.URI) PATCH(javax.ws.rs.PATCH) ParseException(java.text.ParseException) Status(javax.ws.rs.core.Response.Status) POST(javax.ws.rs.POST) Context(javax.ws.rs.core.Context) Files(java.nio.file.Files) Idf(org.edamontology.edammap.core.idf.Idf) IOException(java.io.IOException) QueryProcessed(org.edamontology.edammap.core.processing.QueryProcessed) UUID(java.util.UUID) Mapping(org.edamontology.edammap.core.mapping.Mapping) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) EdamUri(org.edamontology.edammap.core.edam.EdamUri) CoreArgs(org.edamontology.edammap.core.args.CoreArgs) QueryType(org.edamontology.edammap.core.query.QueryType) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) ServerInput(org.edamontology.edammap.core.input.ServerInput) List(java.util.List) Logger(org.apache.logging.log4j.Logger) Response(javax.ws.rs.core.Response) Webpage(org.edamontology.pubfetcher.Webpage) Paths(java.nio.file.Paths) Publication(org.edamontology.pubfetcher.Publication) UriInfo(javax.ws.rs.core.UriInfo) Collections(java.util.Collections) LogManager(org.apache.logging.log4j.LogManager) Mapper(org.edamontology.edammap.core.mapping.Mapper) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces)

Example 8 with Request

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

the class Resource method patch.

/* TODO JSON
	// curl -H "Content-Type: application/json" -X POST -d '{"threads":2,"reportPaginationSize":"7","mapperArgs":{"algorithmArgs":{"compoundWords":2}}}' http://localhost:8080/api
	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.TEXT_PLAIN)
	public String json(JsonObject json) {
		StringBuilder sb = new StringBuilder();
		for (Map.Entry<String, JsonValue> entry : json.entrySet()) {
			if (entry.getValue().getValueType() == JsonValue.ValueType.STRING || entry.getValue().getValueType() == JsonValue.ValueType.NUMBER) {
				sb.append(entry.getKey()).append(" --> ").append(entry.getValue().toString()).append("\n");
			}
		}
		return sb.toString();
	}
*/
private Response patch(String requestString, Request request, String resource, Class<?> clazz, boolean doc, int max) {
    try {
        logger.info("PATCH {} {} from {}", resource, requestString, request.getRemoteAddr());
        // TODO get actual args from form
        FetcherArgs fetcherArgs = new FetcherArgs();
        fetcherArgs.setPrivateArgs(Server.args.getFetcherPrivateArgs());
        Response response = Response.ok(Server.processor.getDatabaseEntries(QueryLoader.fromServerEntry(requestString, clazz, max), fetcherArgs, clazz, doc).stream().map(p -> p.toStringId() + " : " + p.getStatusString(fetcherArgs).toUpperCase(Locale.ROOT)).collect(Collectors.joining("\n"))).build();
        logger.info("PATCHED {} {}", resource, response.getEntity());
        return response;
    } catch (IllegalArgumentException e) {
        logger.error("Exception!", e);
        return Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
    } catch (Throwable e) {
        logger.error("Exception!", e);
        throw e;
    }
}
Also used : Response(javax.ws.rs.core.Response) Results(org.edamontology.edammap.core.benchmarking.Results) Query(org.edamontology.edammap.core.query.Query) Request(org.glassfish.grizzly.http.server.Request) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) URISyntaxException(java.net.URISyntaxException) Path(javax.ws.rs.Path) Benchmark(org.edamontology.edammap.core.benchmarking.Benchmark) PreProcessor(org.edamontology.edammap.core.preprocessing.PreProcessor) Output(org.edamontology.edammap.core.output.Output) ConceptProcessed(org.edamontology.edammap.core.processing.ConceptProcessed) QueryLoader(org.edamontology.edammap.core.query.QueryLoader) MediaType(javax.ws.rs.core.MediaType) Consumes(javax.ws.rs.Consumes) FetcherArgs(org.edamontology.pubfetcher.FetcherArgs) Locale(java.util.Locale) Map(java.util.Map) URI(java.net.URI) PATCH(javax.ws.rs.PATCH) ParseException(java.text.ParseException) Status(javax.ws.rs.core.Response.Status) POST(javax.ws.rs.POST) Context(javax.ws.rs.core.Context) Files(java.nio.file.Files) Idf(org.edamontology.edammap.core.idf.Idf) IOException(java.io.IOException) QueryProcessed(org.edamontology.edammap.core.processing.QueryProcessed) UUID(java.util.UUID) Mapping(org.edamontology.edammap.core.mapping.Mapping) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) EdamUri(org.edamontology.edammap.core.edam.EdamUri) CoreArgs(org.edamontology.edammap.core.args.CoreArgs) QueryType(org.edamontology.edammap.core.query.QueryType) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) ServerInput(org.edamontology.edammap.core.input.ServerInput) List(java.util.List) Logger(org.apache.logging.log4j.Logger) Response(javax.ws.rs.core.Response) Webpage(org.edamontology.pubfetcher.Webpage) Paths(java.nio.file.Paths) Publication(org.edamontology.pubfetcher.Publication) UriInfo(javax.ws.rs.core.UriInfo) Collections(java.util.Collections) LogManager(org.apache.logging.log4j.LogManager) Mapper(org.edamontology.edammap.core.mapping.Mapper) FetcherArgs(org.edamontology.pubfetcher.FetcherArgs)

Example 9 with Request

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

the class GrizzlyConfigTest method backendConfig.

@Test
public void backendConfig() throws IOException, InstantiationException {
    GrizzlyConfig grizzlyConfig = null;
    try {
        grizzlyConfig = new GrizzlyConfig("grizzly-backend-config.xml");
        grizzlyConfig.setupNetwork();
        for (GrizzlyListener listener : grizzlyConfig.getListeners()) {
            setHttpHandler((GenericGrizzlyListener) listener, new HttpHandler() {

                @Override
                public void service(Request request, Response response) throws Exception {
                    response.getWriter().write(request.getScheme());
                    final String remoteUser = request.getRemoteUser();
                    if (remoteUser != null) {
                        response.getWriter().write(request.getRemoteUser());
                    }
                }
            });
        }
        final String content = getContent(new URL("http://localhost:38082").openConnection());
        final String content2 = getContent(new URL("http://localhost:38083").openConnection());
        final URLConnection c3 = new URL("http://localhost:38084").openConnection();
        c3.addRequestProperty("my-scheme", "https");
        final String content3 = getContent(c3);
        final URLConnection c4 = new URL("http://localhost:38085").openConnection();
        c4.addRequestProperty("my-remote-user", "glassfish");
        final String content4 = getContent(c4);
        Assert.assertEquals("http", content);
        Assert.assertEquals("https", content2);
        Assert.assertEquals("https", content3);
        Assert.assertEquals("httpglassfish", content4);
    } finally {
        if (grizzlyConfig != null) {
            grizzlyConfig.shutdown();
        }
    }
}
Also used : Response(org.glassfish.grizzly.http.server.Response) HttpHandler(org.glassfish.grizzly.http.server.HttpHandler) Request(org.glassfish.grizzly.http.server.Request) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URL(java.net.URL) URLConnection(java.net.URLConnection) Test(org.junit.Test)

Example 10 with Request

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

the class SessionsResource method create.

/**
 * Get a new session with GlassFish Rest service
 * If a request lands here when authentication has been turned on => it has been authenticated.
 * @return a new session with GlassFish Rest service
 */
@POST
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.APPLICATION_FORM_URLENCODED })
@Produces({ MediaType.TEXT_HTML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response create(HashMap<String, String> data) {
    if (data == null) {
        data = new HashMap<String, String>();
    }
    final RestConfig restConfig = ResourceUtil.getRestConfig(locatorBridge.getRemoteLocator());
    Response.ResponseBuilder responseBuilder = Response.status(UNAUTHORIZED);
    RestActionReporter ar = new RestActionReporter();
    Request grizzlyRequest = request.get();
    // If the call flow reached here, the request has been authenticated by logic in RestAdapater
    // probably with an admin username and password.  The remoteHostName value
    // in the data object is the actual remote host of the end-user who is
    // using the console (or, conceivably, some other client).  We need to
    // authenticate here once again with that supplied remoteHostName to
    // make sure we enforce remote access rules correctly.
    String hostName = data.get("remoteHostName");
    boolean isAuthorized = false;
    boolean responseErrorStatusSet = false;
    Subject subject = null;
    try {
        subject = ResourceUtil.authenticateViaAdminRealm(locatorBridge.getRemoteLocator(), grizzlyRequest, hostName);
        isAuthorized = ResourceUtil.isAuthorized(locatorBridge.getRemoteLocator(), subject, "domain/rest-sessions/rest-session", "create");
    } catch (RemoteAdminAccessException e) {
        responseBuilder.status(FORBIDDEN);
        responseErrorStatusSet = true;
    } catch (Exception e) {
        ar.setMessage("Error while authenticating " + e);
    }
    if (isAuthorized) {
        responseBuilder.status(OK);
        // Check to see if the username has been set (anonymous user case)
        String username = (String) grizzlyRequest.getAttribute("restUser");
        if (username != null) {
            ar.getExtraProperties().put("username", username);
        }
        ar.getExtraProperties().put("token", sessionManager.createSession(grizzlyRequest.getRemoteAddr(), subject, chooseTimeout(restConfig)));
    } else {
        if (!responseErrorStatusSet) {
            responseBuilder.status(UNAUTHORIZED);
        }
    }
    return responseBuilder.entity(new ActionReportResult(ar)).build();
}
Also used : Response(javax.ws.rs.core.Response) RestConfig(org.glassfish.admin.restconnector.RestConfig) ActionReportResult(org.glassfish.admin.rest.results.ActionReportResult) RestActionReporter(org.glassfish.admin.rest.utils.xml.RestActionReporter) Request(org.glassfish.grizzly.http.server.Request) Subject(javax.security.auth.Subject) RemoteAdminAccessException(org.glassfish.internal.api.RemoteAdminAccessException) RemoteAdminAccessException(org.glassfish.internal.api.RemoteAdminAccessException) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

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