Search in sources :

Example 41 with Context

use of javax.ws.rs.core.Context in project narayana by jbosstm.

the class ServerSRAFilter method filter.

@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
    // a request is leaving the container so clear any context on the thread and fix up the LRA response header
    Object newLRA = Current.getState("newLRA");
    URL current = Current.peek();
    try {
        if (current != null) {
            int status = responseContext.getStatus();
            Response.Status.Family[] cancel0nFamily = (Response.Status.Family[]) requestContext.getProperty(CANCEL_ON_FAMILY_PROP);
            Response.Status[] cancel0n = (Response.Status[]) requestContext.getProperty(CANCEL_ON_PROP);
            Boolean closeCurrent = (Boolean) requestContext.getProperty(TERMINAL_LRA_PROP);
            if (cancel0nFamily != null)
                if (Arrays.stream(cancel0nFamily).anyMatch(f -> Response.Status.Family.familyOf(status) == f))
                    closeCurrent = true;
            if (cancel0n != null && !closeCurrent)
                if (Arrays.stream(cancel0n).anyMatch(f -> status == f.getStatusCode()))
                    closeCurrent = true;
            if (closeCurrent != null && closeCurrent) {
                lraTrace(requestContext, (URL) newLRA, "ServerLRAFilter after: closing LRA becasue http status is " + status);
                lraClient.cancelSRA(current);
                if (current.equals(newLRA))
                    // don't try to cancle newKRA twice
                    newLRA = null;
            }
        }
        if (newLRA != null) {
            lraTrace(requestContext, (URL) newLRA, "ServerLRAFilter after: closing LRA");
            lraClient.commitSRA((URL) newLRA);
        }
    } finally {
        Current.updateLRAContext(responseContext.getHeaders());
        Current.popAll();
    }
}
Also used : Response(javax.ws.rs.core.Response) Status(io.narayana.sra.annotation.Status) SRA_HTTP_HEADER(io.narayana.sra.client.SRAClient.SRA_HTTP_HEADER) Arrays(java.util.Arrays) Provider(javax.ws.rs.ext.Provider) URL(java.net.URL) Path(javax.ws.rs.Path) HashMap(java.util.HashMap) ContainerRequestFilter(javax.ws.rs.container.ContainerRequestFilter) Commit(io.narayana.sra.annotation.Commit) ContainerResponseFilter(javax.ws.rs.container.ContainerResponseFilter) ContainerRequestContext(javax.ws.rs.container.ContainerRequestContext) Inject(javax.inject.Inject) MediaType(javax.ws.rs.core.MediaType) ResourceInfo(javax.ws.rs.container.ResourceInfo) Map(java.util.Map) URI(java.net.URI) TimeLimit(io.narayana.sra.annotation.TimeLimit) Method(java.lang.reflect.Method) Prepare(io.narayana.sra.annotation.Prepare) Context(javax.ws.rs.core.Context) Status(io.narayana.sra.annotation.Status) IOException(java.io.IOException) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) TimeUnit(java.util.concurrent.TimeUnit) RTS_HTTP_RECOVERY_HEADER(io.narayana.sra.client.SRAClient.RTS_HTTP_RECOVERY_HEADER) Response(javax.ws.rs.core.Response) Annotation(java.lang.annotation.Annotation) OnePhaseCommit(io.narayana.sra.annotation.OnePhaseCommit) SRA(io.narayana.sra.annotation.SRA) WebApplicationException(javax.ws.rs.WebApplicationException) Rollback(io.narayana.sra.annotation.Rollback) ContainerResponseContext(javax.ws.rs.container.ContainerResponseContext) Link(javax.ws.rs.core.Link) URL(java.net.URL)

Example 42 with Context

use of javax.ws.rs.core.Context in project ovirt-engine by oVirt.

the class V3Server method setUriInfo.

// We need to have the URI info object injected, as we need to manually inject into the V4 implementation of
// the service.
@Context
public void setUriInfo(UriInfo uriInfo) {
    if (delegate instanceof BaseBackendResource) {
        BaseBackendResource resource = (BaseBackendResource) delegate;
        resource.setUriInfo(uriInfo);
    }
}
Also used : BaseBackendResource(org.ovirt.engine.api.restapi.resource.BaseBackendResource) Context(javax.ws.rs.core.Context)

Example 43 with Context

use of javax.ws.rs.core.Context 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 44 with Context

use of javax.ws.rs.core.Context in project tomee by apache.

the class ResourceUtils method getParameter.

// CHECKSTYLE:OFF
public static Parameter getParameter(int index, Annotation[] anns, Class<?> type) {
    Context ctx = AnnotationUtils.getAnnotation(anns, Context.class);
    if (ctx != null) {
        return new Parameter(ParameterType.CONTEXT, index, null);
    }
    boolean isEncoded = AnnotationUtils.getAnnotation(anns, Encoded.class) != null;
    BeanParam bp = AnnotationUtils.getAnnotation(anns, BeanParam.class);
    if (bp != null) {
        return new Parameter(ParameterType.BEAN, index, null, isEncoded, null);
    }
    String dValue = AnnotationUtils.getDefaultParameterValue(anns);
    PathParam a = AnnotationUtils.getAnnotation(anns, PathParam.class);
    if (a != null) {
        return new Parameter(ParameterType.PATH, index, a.value(), isEncoded, dValue);
    }
    QueryParam q = AnnotationUtils.getAnnotation(anns, QueryParam.class);
    if (q != null) {
        return new Parameter(ParameterType.QUERY, index, q.value(), isEncoded, dValue);
    }
    MatrixParam m = AnnotationUtils.getAnnotation(anns, MatrixParam.class);
    if (m != null) {
        return new Parameter(ParameterType.MATRIX, index, m.value(), isEncoded, dValue);
    }
    FormParam f = AnnotationUtils.getAnnotation(anns, FormParam.class);
    if (f != null) {
        return new Parameter(ParameterType.FORM, index, f.value(), isEncoded, dValue);
    }
    HeaderParam h = AnnotationUtils.getAnnotation(anns, HeaderParam.class);
    if (h != null) {
        return new Parameter(ParameterType.HEADER, index, h.value(), isEncoded, dValue);
    }
    CookieParam c = AnnotationUtils.getAnnotation(anns, CookieParam.class);
    if (c != null) {
        return new Parameter(ParameterType.COOKIE, index, c.value(), isEncoded, dValue);
    }
    return new Parameter(ParameterType.REQUEST_BODY, index, null);
}
Also used : Context(javax.ws.rs.core.Context) CookieParam(javax.ws.rs.CookieParam) MatrixParam(javax.ws.rs.MatrixParam) HeaderParam(javax.ws.rs.HeaderParam) Encoded(javax.ws.rs.Encoded) QueryParam(javax.ws.rs.QueryParam) Parameter(org.apache.cxf.jaxrs.model.Parameter) PathParam(javax.ws.rs.PathParam) FormParam(javax.ws.rs.FormParam) BeanParam(javax.ws.rs.BeanParam)

Example 45 with Context

use of javax.ws.rs.core.Context in project graphhopper by graphhopper.

the class SPTResource method doGet.

// Annotating this as application/json because errors come out as json, and
// IllegalArgumentExceptions are not mapped to a fixed mediatype, because in RouteResource, it could be GPX.
@GET
@Produces({ "text/csv", "application/json" })
public Response doGet(@Context UriInfo uriInfo, @QueryParam("profile") String profileName, @QueryParam("reverse_flow") @DefaultValue("false") boolean reverseFlow, @QueryParam("point") @NotNull GHPointParam point, @QueryParam("columns") String columnsParam, @QueryParam("time_limit") @DefaultValue("600") LongParam timeLimitInSeconds, @QueryParam("distance_limit") @DefaultValue("-1") LongParam distanceInMeter) {
    StopWatch sw = new StopWatch().start();
    PMap hintsMap = new PMap();
    RouteResource.initHints(hintsMap, uriInfo.getQueryParameters());
    hintsMap.putObject(Parameters.CH.DISABLE, true);
    hintsMap.putObject(Parameters.Landmark.DISABLE, true);
    if (Helper.isEmpty(profileName)) {
        profileName = profileResolver.resolveProfile(hintsMap).getName();
        removeLegacyParameters(hintsMap);
    }
    errorIfLegacyParameters(hintsMap);
    Profile profile = graphHopper.getProfile(profileName);
    if (profile == null)
        throw new IllegalArgumentException("The requested profile '" + profileName + "' does not exist");
    LocationIndex locationIndex = graphHopper.getLocationIndex();
    Graph graph = graphHopper.getGraphHopperStorage();
    Weighting weighting = graphHopper.createWeighting(profile, hintsMap);
    BooleanEncodedValue inSubnetworkEnc = graphHopper.getEncodingManager().getBooleanEncodedValue(Subnetwork.key(profileName));
    if (hintsMap.has(Parameters.Routing.BLOCK_AREA)) {
        GraphEdgeIdFinder.BlockArea blockArea = GraphEdgeIdFinder.createBlockArea(graph, locationIndex, Collections.singletonList(point.get()), hintsMap, new FiniteWeightFilter(weighting));
        weighting = new BlockAreaWeighting(weighting, blockArea);
    }
    Snap snap = locationIndex.findClosest(point.get().lat, point.get().lon, new DefaultSnapFilter(weighting, inSubnetworkEnc));
    if (!snap.isValid())
        throw new IllegalArgumentException("Point not found:" + point);
    QueryGraph queryGraph = QueryGraph.create(graph, snap);
    NodeAccess nodeAccess = queryGraph.getNodeAccess();
    TraversalMode traversalMode = profile.isTurnCosts() ? EDGE_BASED : NODE_BASED;
    ShortestPathTree shortestPathTree = new ShortestPathTree(queryGraph, queryGraph.wrapWeighting(weighting), reverseFlow, traversalMode);
    if (distanceInMeter.get() > 0) {
        shortestPathTree.setDistanceLimit(distanceInMeter.get());
    } else {
        double limit = timeLimitInSeconds.get() * 1000;
        shortestPathTree.setTimeLimit(limit);
    }
    final String COL_SEP = ",", LINE_SEP = "\n";
    List<String> columns;
    if (!Helper.isEmpty(columnsParam))
        columns = Arrays.asList(columnsParam.split(","));
    else
        columns = Arrays.asList("longitude", "latitude", "time", "distance");
    if (columns.isEmpty())
        throw new IllegalArgumentException("Either omit the columns parameter or specify the columns via comma separated values");
    Map<String, EncodedValue> pathDetails = new HashMap<>();
    for (String col : columns) {
        if (encodingManager.hasEncodedValue(col))
            pathDetails.put(col, encodingManager.getEncodedValue(col, EncodedValue.class));
    }
    StreamingOutput out = output -> {
        try (Writer writer = new BufferedWriter(new OutputStreamWriter(output, Helper.UTF_CS))) {
            StringBuilder sb = new StringBuilder();
            for (String col : columns) {
                if (sb.length() > 0)
                    sb.append(COL_SEP);
                sb.append(col);
            }
            sb.append(LINE_SEP);
            writer.write(sb.toString());
            shortestPathTree.search(snap.getClosestNode(), l -> {
                IsoLabelWithCoordinates label = isoLabelWithCoordinates(nodeAccess, l);
                sb.setLength(0);
                for (int colIndex = 0; colIndex < columns.size(); colIndex++) {
                    String col = columns.get(colIndex);
                    if (colIndex > 0)
                        sb.append(COL_SEP);
                    switch(col) {
                        case "node_id":
                            sb.append(label.nodeId);
                            continue;
                        case "prev_node_id":
                            sb.append(label.prevNodeId);
                            continue;
                        case "edge_id":
                            sb.append(label.edgeId);
                            continue;
                        case "prev_edge_id":
                            sb.append(label.prevEdgeId);
                            continue;
                        case "distance":
                            sb.append(label.distance);
                            continue;
                        case "prev_distance":
                            sb.append(label.prevCoordinate == null ? 0 : label.prevDistance);
                            continue;
                        case "time":
                            sb.append(label.timeMillis);
                            continue;
                        case "prev_time":
                            sb.append(label.prevCoordinate == null ? 0 : label.prevTimeMillis);
                            continue;
                        case "longitude":
                            sb.append(Helper.round6(label.coordinate.lon));
                            continue;
                        case "prev_longitude":
                            sb.append(label.prevCoordinate == null ? null : Helper.round6(label.prevCoordinate.lon));
                            continue;
                        case "latitude":
                            sb.append(Helper.round6(label.coordinate.lat));
                            continue;
                        case "prev_latitude":
                            sb.append(label.prevCoordinate == null ? null : Helper.round6(label.prevCoordinate.lat));
                            continue;
                    }
                    if (!EdgeIterator.Edge.isValid(label.edgeId))
                        continue;
                    EdgeIteratorState edge = queryGraph.getEdgeIteratorState(label.edgeId, label.nodeId);
                    if (edge == null)
                        continue;
                    if (col.equals(Parameters.Details.STREET_NAME)) {
                        sb.append(edge.getName().replaceAll(",", ""));
                        continue;
                    }
                    EncodedValue ev = pathDetails.get(col);
                    if (ev instanceof DecimalEncodedValue) {
                        DecimalEncodedValue dev = (DecimalEncodedValue) ev;
                        sb.append(reverseFlow ? edge.getReverse(dev) : edge.get(dev));
                    } else if (ev instanceof EnumEncodedValue) {
                        EnumEncodedValue eev = (EnumEncodedValue) ev;
                        sb.append(reverseFlow ? edge.getReverse(eev) : edge.get(eev));
                    } else if (ev instanceof BooleanEncodedValue) {
                        BooleanEncodedValue eev = (BooleanEncodedValue) ev;
                        sb.append(reverseFlow ? edge.getReverse(eev) : edge.get(eev));
                    } else if (ev instanceof IntEncodedValue) {
                        IntEncodedValue eev = (IntEncodedValue) ev;
                        sb.append(reverseFlow ? edge.getReverse(eev) : edge.get(eev));
                    } else {
                        throw new IllegalArgumentException("Unknown property " + col);
                    }
                }
                sb.append(LINE_SEP);
                try {
                    writer.write(sb.toString());
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            });
            logger.info("took: " + sw.stop().getSeconds() + ", visited nodes:" + shortestPathTree.getVisitedNodes() + ", " + uriInfo.getQueryParameters());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    };
    // Give media type explicitly since we are annotating CSV and JSON, because error messages are JSON.
    return Response.ok(out).type("text/csv").build();
}
Also used : com.graphhopper.routing.ev(com.graphhopper.routing.ev) java.util(java.util) ProfileResolver(com.graphhopper.routing.ProfileResolver) LoggerFactory(org.slf4j.LoggerFactory) EncodingManager(com.graphhopper.routing.util.EncodingManager) Inject(javax.inject.Inject) ShortestPathTree(com.graphhopper.isochrone.algorithm.ShortestPathTree) BlockAreaWeighting(com.graphhopper.routing.weighting.BlockAreaWeighting) Profile(com.graphhopper.config.Profile) TraversalMode(com.graphhopper.routing.util.TraversalMode) Graph(com.graphhopper.storage.Graph) OutputStreamWriter(java.io.OutputStreamWriter) NODE_BASED(com.graphhopper.routing.util.TraversalMode.NODE_BASED) GraphHopper(com.graphhopper.GraphHopper) com.graphhopper.util(com.graphhopper.util) Logger(org.slf4j.Logger) Context(javax.ws.rs.core.Context) LocationIndex(com.graphhopper.storage.index.LocationIndex) RouteResource.errorIfLegacyParameters(com.graphhopper.resources.RouteResource.errorIfLegacyParameters) BufferedWriter(java.io.BufferedWriter) LongParam(io.dropwizard.jersey.params.LongParam) StreamingOutput(javax.ws.rs.core.StreamingOutput) IOException(java.io.IOException) NotNull(javax.validation.constraints.NotNull) QueryGraph(com.graphhopper.routing.querygraph.QueryGraph) GHPointParam(com.graphhopper.http.GHPointParam) GraphEdgeIdFinder(com.graphhopper.storage.GraphEdgeIdFinder) NodeAccess(com.graphhopper.storage.NodeAccess) javax.ws.rs(javax.ws.rs) Response(javax.ws.rs.core.Response) Weighting(com.graphhopper.routing.weighting.Weighting) FiniteWeightFilter(com.graphhopper.routing.util.FiniteWeightFilter) Writer(java.io.Writer) DefaultSnapFilter(com.graphhopper.routing.util.DefaultSnapFilter) Snap(com.graphhopper.storage.index.Snap) UriInfo(javax.ws.rs.core.UriInfo) EDGE_BASED(com.graphhopper.routing.util.TraversalMode.EDGE_BASED) GHPoint(com.graphhopper.util.shapes.GHPoint) RouteResource.removeLegacyParameters(com.graphhopper.resources.RouteResource.removeLegacyParameters) GraphEdgeIdFinder(com.graphhopper.storage.GraphEdgeIdFinder) NodeAccess(com.graphhopper.storage.NodeAccess) BlockAreaWeighting(com.graphhopper.routing.weighting.BlockAreaWeighting) StreamingOutput(javax.ws.rs.core.StreamingOutput) TraversalMode(com.graphhopper.routing.util.TraversalMode) Snap(com.graphhopper.storage.index.Snap) Profile(com.graphhopper.config.Profile) BufferedWriter(java.io.BufferedWriter) FiniteWeightFilter(com.graphhopper.routing.util.FiniteWeightFilter) DefaultSnapFilter(com.graphhopper.routing.util.DefaultSnapFilter) IOException(java.io.IOException) LocationIndex(com.graphhopper.storage.index.LocationIndex) Graph(com.graphhopper.storage.Graph) QueryGraph(com.graphhopper.routing.querygraph.QueryGraph) BlockAreaWeighting(com.graphhopper.routing.weighting.BlockAreaWeighting) Weighting(com.graphhopper.routing.weighting.Weighting) ShortestPathTree(com.graphhopper.isochrone.algorithm.ShortestPathTree) OutputStreamWriter(java.io.OutputStreamWriter) QueryGraph(com.graphhopper.routing.querygraph.QueryGraph) OutputStreamWriter(java.io.OutputStreamWriter) BufferedWriter(java.io.BufferedWriter) Writer(java.io.Writer)

Aggregations

Context (javax.ws.rs.core.Context)70 Response (javax.ws.rs.core.Response)51 Path (javax.ws.rs.Path)48 PathParam (javax.ws.rs.PathParam)41 GET (javax.ws.rs.GET)39 List (java.util.List)38 MediaType (javax.ws.rs.core.MediaType)36 POST (javax.ws.rs.POST)34 UriInfo (javax.ws.rs.core.UriInfo)32 Produces (javax.ws.rs.Produces)30 PUT (javax.ws.rs.PUT)29 Inject (javax.inject.Inject)27 HttpServletRequest (javax.servlet.http.HttpServletRequest)27 QueryParam (javax.ws.rs.QueryParam)27 Map (java.util.Map)25 IOException (java.io.IOException)24 Api (io.swagger.annotations.Api)23 ApiOperation (io.swagger.annotations.ApiOperation)23 ApiParam (io.swagger.annotations.ApiParam)23 URI (java.net.URI)23