Search in sources :

Example 1 with LongParam

use of io.dropwizard.jersey.params.LongParam 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();
}
Also used : ProfileResolver(com.graphhopper.routing.ProfileResolver) LoggerFactory(org.slf4j.LoggerFactory) Subnetwork(com.graphhopper.routing.ev.Subnetwork) HashMap(java.util.HashMap) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) ArrayList(java.util.ArrayList) Range(org.hibernate.validator.constraints.Range) Inject(javax.inject.Inject) MediaType(javax.ws.rs.core.MediaType) ShortestPathTree(com.graphhopper.isochrone.algorithm.ShortestPathTree) BlockAreaWeighting(com.graphhopper.routing.weighting.BlockAreaWeighting) IntParam(io.dropwizard.jersey.params.IntParam) Profile(com.graphhopper.config.Profile) TraversalMode(com.graphhopper.routing.util.TraversalMode) Graph(com.graphhopper.storage.Graph) NODE_BASED(com.graphhopper.routing.util.TraversalMode.NODE_BASED) GraphHopper(com.graphhopper.GraphHopper) org.locationtech.jts.geom(org.locationtech.jts.geom) com.graphhopper.util(com.graphhopper.util) Logger(org.slf4j.Logger) Context(javax.ws.rs.core.Context) ResponsePathSerializer(com.graphhopper.jackson.ResponsePathSerializer) LocationIndex(com.graphhopper.storage.index.LocationIndex) RouteResource.errorIfLegacyParameters(com.graphhopper.resources.RouteResource.errorIfLegacyParameters) LongParam(io.dropwizard.jersey.params.LongParam) BooleanEncodedValue(com.graphhopper.routing.ev.BooleanEncodedValue) NotNull(javax.validation.constraints.NotNull) ResponseType.geojson(com.graphhopper.resources.IsochroneResource.ResponseType.geojson) QueryGraph(com.graphhopper.routing.querygraph.QueryGraph) GHPointParam(com.graphhopper.http.GHPointParam) GraphEdgeIdFinder(com.graphhopper.storage.GraphEdgeIdFinder) Triangulator(com.graphhopper.isochrone.algorithm.Triangulator) ContourBuilder(com.graphhopper.isochrone.algorithm.ContourBuilder) javax.ws.rs(javax.ws.rs) Response(javax.ws.rs.core.Response) JsonNodeFactory(com.fasterxml.jackson.databind.node.JsonNodeFactory) Weighting(com.graphhopper.routing.weighting.Weighting) ToDoubleFunction(java.util.function.ToDoubleFunction) FiniteWeightFilter(com.graphhopper.routing.util.FiniteWeightFilter) 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) Collections(java.util.Collections) RouteResource.removeLegacyParameters(com.graphhopper.resources.RouteResource.removeLegacyParameters) GraphEdgeIdFinder(com.graphhopper.storage.GraphEdgeIdFinder) Triangulator(com.graphhopper.isochrone.algorithm.Triangulator) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) BlockAreaWeighting(com.graphhopper.routing.weighting.BlockAreaWeighting) TraversalMode(com.graphhopper.routing.util.TraversalMode) Snap(com.graphhopper.storage.index.Snap) Profile(com.graphhopper.config.Profile) FiniteWeightFilter(com.graphhopper.routing.util.FiniteWeightFilter) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) DefaultSnapFilter(com.graphhopper.routing.util.DefaultSnapFilter) 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) BooleanEncodedValue(com.graphhopper.routing.ev.BooleanEncodedValue) ContourBuilder(com.graphhopper.isochrone.algorithm.ContourBuilder) ShortestPathTree(com.graphhopper.isochrone.algorithm.ShortestPathTree) QueryGraph(com.graphhopper.routing.querygraph.QueryGraph)

Example 2 with LongParam

use of io.dropwizard.jersey.params.LongParam in project keywhiz by square.

the class AutomationGroupResourceTest method findGroupById.

@Test
public void findGroupById() {
    Group group = new Group(50, "testGroup", "testing group", now, "automation client", now, "automation client", ImmutableMap.of("app", "keywhiz"));
    when(groupDAO.getGroupById(50)).thenReturn(Optional.of(group));
    when(aclDAO.getClientsFor(group)).thenReturn(ImmutableSet.of());
    when(aclDAO.getSanitizedSecretsFor(group)).thenReturn(ImmutableSet.of());
    GroupDetailResponse expectedResponse = GroupDetailResponse.fromGroup(group, ImmutableList.of(), ImmutableList.of());
    GroupDetailResponse response = resource.getGroupById(automation, new LongParam("50"));
    assertThat(response).isEqualTo(expectedResponse);
}
Also used : Group(keywhiz.api.model.Group) GroupDetailResponse(keywhiz.api.GroupDetailResponse) LongParam(io.dropwizard.jersey.params.LongParam) Test(org.junit.Test)

Example 3 with LongParam

use of io.dropwizard.jersey.params.LongParam in project keywhiz by square.

the class SecretsResourceTest method setCurrentSecretVersionBySecretId.

@Test
public void setCurrentSecretVersionBySecretId() {
    when(secretController.getSecretById(1)).thenReturn(Optional.of(secret));
    Response response = resource.updateCurrentSecretVersion(user, new LongParam(Long.toString(1)), new LongParam(Long.toString(10)));
    verify(secretDAO).setCurrentSecretVersionBySecretId(1, 10, "user");
    assertThat(response.getStatus()).isEqualTo(204);
}
Also used : Response(javax.ws.rs.core.Response) SecretDetailResponse(keywhiz.api.SecretDetailResponse) LongParam(io.dropwizard.jersey.params.LongParam) Test(org.junit.Test)

Example 4 with LongParam

use of io.dropwizard.jersey.params.LongParam in project keywhiz by square.

the class SecretsResourceTest method includesTheSecret.

@Test
public void includesTheSecret() {
    when(secretController.getSecretById(22)).thenReturn(Optional.of(secret));
    when(aclDAO.getGroupsFor(secret)).thenReturn(Collections.emptySet());
    when(aclDAO.getClientsFor(secret)).thenReturn(Collections.emptySet());
    SecretDetailResponse response = resource.retrieveSecret(user, new LongParam("22"));
    assertThat(response.id).isEqualTo(secret.getId());
    assertThat(response.name).isEqualTo(secret.getName());
    assertThat(response.description).isEqualTo(secret.getDescription());
    assertThat(response.createdAt).isEqualTo(secret.getCreatedAt());
    assertThat(response.createdBy).isEqualTo(secret.getCreatedBy());
    assertThat(response.updatedAt).isEqualTo(secret.getUpdatedAt());
    assertThat(response.updatedBy).isEqualTo(secret.getUpdatedBy());
    assertThat(response.metadata).isEqualTo(secret.getMetadata());
}
Also used : SecretDetailResponse(keywhiz.api.SecretDetailResponse) LongParam(io.dropwizard.jersey.params.LongParam) Test(org.junit.Test)

Example 5 with LongParam

use of io.dropwizard.jersey.params.LongParam in project keywhiz by square.

the class SecretsResourceTest method rollbackSuccess.

@Test
public void rollbackSuccess() {
    Secret secret1 = new Secret(1, "name1", null, "desc", () -> "secret", "checksum", NOW, "user", NOW, "user", emptyMap, null, null, 1136214245, 125L, NOW, "user");
    when(secretController.getSecretByName("name1")).thenReturn(Optional.of(secret1));
    Response response = resource.resetSecretVersion(user, "name1", new LongParam("125"));
    assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_CREATED);
}
Also used : Secret(keywhiz.api.model.Secret) SanitizedSecret(keywhiz.api.model.SanitizedSecret) Response(javax.ws.rs.core.Response) SecretDetailResponse(keywhiz.api.SecretDetailResponse) LongParam(io.dropwizard.jersey.params.LongParam) Test(org.junit.Test)

Aggregations

LongParam (io.dropwizard.jersey.params.LongParam)36 Test (org.junit.Test)34 Response (javax.ws.rs.core.Response)11 SecretDetailResponse (keywhiz.api.SecretDetailResponse)8 ClientDetailResponse (keywhiz.api.ClientDetailResponse)4 Group (keywhiz.api.model.Group)4 GraphHopper (com.graphhopper.GraphHopper)2 Profile (com.graphhopper.config.Profile)2 GHPointParam (com.graphhopper.http.GHPointParam)2 ShortestPathTree (com.graphhopper.isochrone.algorithm.ShortestPathTree)2 RouteResource.errorIfLegacyParameters (com.graphhopper.resources.RouteResource.errorIfLegacyParameters)2 RouteResource.removeLegacyParameters (com.graphhopper.resources.RouteResource.removeLegacyParameters)2 ProfileResolver (com.graphhopper.routing.ProfileResolver)2 QueryGraph (com.graphhopper.routing.querygraph.QueryGraph)2 DefaultSnapFilter (com.graphhopper.routing.util.DefaultSnapFilter)2 FiniteWeightFilter (com.graphhopper.routing.util.FiniteWeightFilter)2 TraversalMode (com.graphhopper.routing.util.TraversalMode)2 EDGE_BASED (com.graphhopper.routing.util.TraversalMode.EDGE_BASED)2 NODE_BASED (com.graphhopper.routing.util.TraversalMode.NODE_BASED)2 BlockAreaWeighting (com.graphhopper.routing.weighting.BlockAreaWeighting)2