use of javax.ws.rs.core.Context in project tomee by apache.
the class ResourceUtils method createConstructorArguments.
public static Object[] createConstructorArguments(Constructor<?> c, Message m, boolean perRequest, Map<Class<?>, Object> contextValues, Class<?>[] params, Annotation[][] anns, Type[] genericTypes) {
if (m == null) {
m = new MessageImpl();
}
@SuppressWarnings("unchecked") MultivaluedMap<String, String> templateValues = (MultivaluedMap<String, String>) m.get(URITemplate.TEMPLATE_PARAMETERS);
Object[] values = new Object[params.length];
for (int i = 0; i < params.length; i++) {
if (AnnotationUtils.getAnnotation(anns[i], Context.class) != null) {
Object contextValue = contextValues != null ? contextValues.get(params[i]) : null;
if (contextValue == null) {
if (perRequest || InjectionUtils.VALUE_CONTEXTS.contains(params[i].getName())) {
values[i] = JAXRSUtils.createContextValue(m, genericTypes[i], params[i]);
} else {
values[i] = InjectionUtils.createThreadLocalProxy(params[i]);
}
} else {
values[i] = contextValue;
}
} else {
// this branch won't execute for singletons given that the found constructor
// is guaranteed to have only Context parameters, if any, for singletons
Parameter p = ResourceUtils.getParameter(i, anns[i], params[i]);
values[i] = JAXRSUtils.createHttpParameterValue(p, params[i], genericTypes[i], anns[i], m, templateValues, null);
}
}
return values;
}
use of javax.ws.rs.core.Context in project graphhopper by graphhopper.
the class IsochroneResource method doGet.
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response doGet(@Context UriInfo uriInfo, @QueryParam("profile") String profileName, @QueryParam("buckets") @Range(min = 1, max = 20) @DefaultValue("1") IntParam nBuckets, @QueryParam("reverse_flow") @DefaultValue("false") boolean reverseFlow, @QueryParam("point") @NotNull GHPointParam point, @QueryParam("time_limit") @DefaultValue("600") LongParam timeLimitInSeconds, @QueryParam("distance_limit") @DefaultValue("-1") LongParam distanceLimitInMeter, @QueryParam("weight_limit") @DefaultValue("-1") LongParam weightLimit, @QueryParam("type") @DefaultValue("json") ResponseType respType, @QueryParam("tolerance") @DefaultValue("0") double toleranceInMeter, @QueryParam("full_geometry") @DefaultValue("false") boolean fullGeometry) {
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);
TraversalMode traversalMode = profile.isTurnCosts() ? EDGE_BASED : NODE_BASED;
ShortestPathTree shortestPathTree = new ShortestPathTree(queryGraph, queryGraph.wrapWeighting(weighting), reverseFlow, traversalMode);
double limit;
if (weightLimit.get() > 0) {
limit = weightLimit.get();
shortestPathTree.setWeightLimit(limit + Math.max(limit * 0.14, 2_000));
} else if (distanceLimitInMeter.get() > 0) {
limit = distanceLimitInMeter.get();
shortestPathTree.setDistanceLimit(limit + Math.max(limit * 0.14, 2_000));
} else {
limit = timeLimitInSeconds.get() * 1000;
shortestPathTree.setTimeLimit(limit + Math.max(limit * 0.14, 200_000));
}
ArrayList<Double> zs = new ArrayList<>();
double delta = limit / nBuckets.get();
for (int i = 0; i < nBuckets.get(); i++) {
zs.add((i + 1) * delta);
}
ToDoubleFunction<ShortestPathTree.IsoLabel> fz;
if (weightLimit.get() > 0) {
fz = l -> l.weight;
} else if (distanceLimitInMeter.get() > 0) {
fz = l -> l.distance;
} else {
fz = l -> l.time;
}
Triangulator.Result result = triangulator.triangulate(snap, queryGraph, shortestPathTree, fz, degreesFromMeters(toleranceInMeter));
ContourBuilder contourBuilder = new ContourBuilder(result.triangulation);
ArrayList<Geometry> isochrones = new ArrayList<>();
for (Double z : zs) {
logger.info("Building contour z={}", z);
MultiPolygon isochrone = contourBuilder.computeIsoline(z, result.seedEdges);
if (fullGeometry) {
isochrones.add(isochrone);
} else {
Polygon maxPolygon = heuristicallyFindMainConnectedComponent(isochrone, isochrone.getFactory().createPoint(new Coordinate(point.get().lon, point.get().lat)));
isochrones.add(isochrone.getFactory().createPolygon(((LinearRing) maxPolygon.getExteriorRing())));
}
}
ArrayList<JsonFeature> features = new ArrayList<>();
for (Geometry isochrone : isochrones) {
JsonFeature feature = new JsonFeature();
HashMap<String, Object> properties = new HashMap<>();
properties.put("bucket", features.size());
if (respType == geojson) {
properties.put("copyrights", ResponsePathSerializer.COPYRIGHTS);
}
feature.setProperties(properties);
feature.setGeometry(isochrone);
features.add(feature);
}
ObjectNode json = JsonNodeFactory.instance.objectNode();
sw.stop();
ObjectNode finalJson = null;
if (respType == geojson) {
json.put("type", "FeatureCollection");
json.putPOJO("features", features);
finalJson = json;
} else {
json.putPOJO("polygons", features);
final ObjectNode info = json.putObject("info");
info.putPOJO("copyrights", ResponsePathSerializer.COPYRIGHTS);
info.put("took", Math.round((float) sw.getMillis()));
finalJson = json;
}
logger.info("took: " + sw.getSeconds() + ", visited nodes:" + shortestPathTree.getVisitedNodes());
return Response.ok(finalJson).header("X-GH-Took", "" + sw.getSeconds() * 1000).build();
}
use of javax.ws.rs.core.Context in project graylog2-server by Graylog2.
the class StreamResource method create.
@POST
@Timed
@ApiOperation(value = "Create a stream")
@RequiresPermissions(RestPermissions.STREAMS_CREATE)
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@AuditEvent(type = AuditEventTypes.STREAM_CREATE)
public Response create(@ApiParam(name = "JSON body", required = true) final CreateStreamRequest cr, @Context UserContext userContext) throws ValidationException {
// Create stream.
final Stream stream = streamService.create(cr, getCurrentUser().getName());
stream.setDisabled(true);
final IndexSet indexSet = stream.getIndexSet();
if (!indexSet.getConfig().isWritable()) {
throw new BadRequestException("Assigned index set must be writable!");
} else if (!indexSet.getConfig().isRegularIndex()) {
throw new BadRequestException("Assigned index set is not usable");
}
final Set<StreamRule> streamRules = cr.rules().stream().map(streamRule -> streamRuleService.create(null, streamRule)).collect(Collectors.toSet());
final String id = streamService.saveWithRulesAndOwnership(stream, streamRules, userContext.getUser());
final Map<String, String> result = ImmutableMap.of("stream_id", id);
final URI streamUri = getUriBuilderToSelf().path(StreamResource.class).path("{streamId}").build(id);
return Response.created(streamUri).entity(result).build();
}
use of javax.ws.rs.core.Context in project hippo by NHS-digital-website.
the class OrganisationDataResource method getOrg.
@GET
@Path("/")
public List<OdsOrganisation> getOrg(@Context HttpServletRequest request, @Context HttpServletResponse servletResponse, @QueryParam("orgName") String orgName) {
if (odsResults == null) {
try {
log.debug("Loading ODS Data");
HstRequestContext context = new DefaultRestContext(this, request).getRequestContext();
QueryManager manager = context.getSession().getWorkspace().getQueryManager();
Query jcrQuery = manager.createQuery("/jcr:root/content/assets//*[@jcr:primaryType='externalstorage:resource']", "xpath");
QueryResult execute = jcrQuery.execute();
NodeIterator iterator = execute.getNodes();
while (iterator.hasNext()) {
Node node = iterator.nextNode();
if (node.getPath().contains("/content/assets/ODS_Data")) {
Value val = node.getProperty("jcr:data").getValue();
// convert JSON array to Java List
odsResults = new ObjectMapper().readValue(val.getString().replace("\n", ""), new TypeReference<List<OdsOrganisation>>() {
});
break;
}
}
} catch (RepositoryException | JsonProcessingException e) {
log.debug("Failed to load ODS Data ", e);
}
}
List<OdsOrganisation> filterOrg = odsResults.stream().filter(b -> (b.getOrgName() + " " + b.getCode()).toUpperCase().contains(orgName.toUpperCase())).collect(Collectors.toList());
return filterOrg;
}
use of javax.ws.rs.core.Context in project Summer by yale8848.
the class MethodsProcessor method get.
public static ClassInfo get(List<ClassInfo> classInfos, Class clazz) {
Path path = (Path) clazz.getAnnotation(Path.class);
if (path == null || path.value() == null) {
return null;
}
ClassInfo classInfo = new ClassInfo();
classInfo.setClassPath(path.value());
classInfo.setClazzObj(newClass(clazz));
classInfo.setClazz(clazz);
Interceptor[] interceptorsClazz = getBefores((Before) clazz.getAnnotation(Before.class));
if (interceptorsClazz != null) {
classInfo.setBefores(interceptorsClazz);
}
interceptorsClazz = getAfters((After) clazz.getAnnotation(After.class));
if (interceptorsClazz != null) {
classInfo.setAfters(interceptorsClazz);
}
for (Method method : clazz.getMethods()) {
Class mt = method.getDeclaringClass();
if (mt == Object.class) {
continue;
}
MethodInfo methodInfo = new MethodInfo();
Interceptor[] interceptorsMethod = getBefores((Before) method.getAnnotation(Before.class));
if (interceptorsMethod != null) {
methodInfo.setBefores(interceptorsMethod);
}
interceptorsMethod = getAfters((After) method.getAnnotation(After.class));
if (interceptorsMethod != null) {
methodInfo.setAfters(interceptorsMethod);
}
Blocking blocking = method.getAnnotation(Blocking.class);
if (blocking != null) {
methodInfo.setBlocking(true);
}
Path pathMthod = (Path) method.getAnnotation(Path.class);
Produces produces = (Produces) method.getAnnotation(Produces.class);
methodInfo.setMethodPath(getPathValue(pathMthod));
methodInfo.setProducesType(getProducesValue(produces));
methodInfo.setHttpMethod(getHttpMethod(method));
methodInfo.setMethod(method);
Parameter[] parameters = method.getParameters();
Class<?>[] parameterTypes = method.getParameterTypes();
Annotation[][] annotations = method.getParameterAnnotations();
int i = 0;
for (Annotation[] an : annotations) {
ArgInfo argInfo = new ArgInfo();
argInfo.setAnnotation(an);
argInfo.setClazz(parameterTypes[i]);
argInfo.setParameter(parameters[i]);
for (Annotation ant : an) {
if (ant instanceof Context) {
argInfo.setContext(true);
} else if (ant instanceof DefaultValue) {
argInfo.setDefaultValue(((DefaultValue) ant).value());
} else if (ant instanceof PathParam) {
argInfo.setPathParam(true);
argInfo.setPathParam(((PathParam) ant).value());
} else if (ant instanceof QueryParam) {
argInfo.setQueryParam(true);
argInfo.setQueryParam(((QueryParam) ant).value());
} else if (ant instanceof FormParam) {
argInfo.setFormParam(true);
argInfo.setFormParam(((FormParam) ant).value());
}
}
i++;
methodInfo.addArgInfo(argInfo);
}
classInfo.addMethodInfo(methodInfo);
}
classInfos.add(classInfo);
return classInfo;
}
Aggregations