Search in sources :

Example 56 with NotNull

use of javax.validation.constraints.NotNull 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)

Example 57 with NotNull

use of javax.validation.constraints.NotNull in project vboard by voyages-sncf-technologies.

the class AuthenticationController method createUserFromAuth.

@NotNull
@SuppressFBWarnings("CLI_CONSTANT_LIST_INDEX")
private static User createUserFromAuth(Authentication auth) {
    if (auth instanceof JsonWebTokenAuthentication) {
        JsonWebTokenAuthentication jwtAuth = ((JsonWebTokenAuthentication) auth);
        String username = jwtAuth.getName();
        String[] parts = StringUtils.split(username, "\\");
        if (parts != null) {
            username = parts[1];
        }
        parts = StringUtils.split(username, "_");
        if (parts == null) {
            throw new IllegalArgumentException("The username in the JWT token provided does not contain a '_'");
        }
        String firstName = StringUtils.capitalize(parts[0]);
        String lastName = StringUtils.capitalize(parts[1]);
        LOGGER.info("createUserFromAuth/JWT: email={} firstName={} lastName={}", jwtAuth.getEmail(), firstName, lastName);
        return new User(jwtAuth.getEmail(), firstName, lastName);
    }
    final KeycloakPrincipal userDetails = (KeycloakPrincipal) auth.getPrincipal();
    final IDToken idToken = userDetails.getKeycloakSecurityContext().getToken();
    LOGGER.info("createUserFromAuth/Keycloak: email={} firstName={} lastName={}", idToken.getEmail(), idToken.getGivenName(), idToken.getFamilyName());
    return new User(idToken.getEmail(), idToken.getGivenName(), idToken.getFamilyName());
}
Also used : User(com.vsct.vboard.models.User) JsonWebTokenAuthentication(com.vsct.vboard.config.cognito.JsonWebTokenAuthentication) IDToken(org.keycloak.representations.IDToken) KeycloakPrincipal(org.keycloak.KeycloakPrincipal) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) NotNull(javax.validation.constraints.NotNull)

Example 58 with NotNull

use of javax.validation.constraints.NotNull in project mica2 by obiba.

the class CommentDtos method fromDto.

@NotNull
Comment fromDto(@NotNull Mica.CommentDtoOrBuilder dto) {
    Comment.Builder commentBuilder = // 
    Comment.newBuilder().id(// 
    dto.getId()).message(// 
    dto.getMessage()).resourceId(// 
    dto.getResourceId()).instanceId(dto.getInstanceId());
    if (dto.hasAdmin())
        commentBuilder.admin(dto.getAdmin());
    Comment comment = commentBuilder.build();
    if (dto.hasModifiedBy())
        comment.setLastModifiedBy(dto.getModifiedBy());
    TimestampsDtos.fromDto(dto.getTimestamps(), comment);
    return comment;
}
Also used : Comment(org.obiba.mica.core.domain.Comment) NotNull(javax.validation.constraints.NotNull)

Example 59 with NotNull

use of javax.validation.constraints.NotNull in project mica2 by obiba.

the class DataAccessRequestDtos method asDto.

@NotNull
public Mica.DataAccessRequestDto asDto(@NotNull DataAccessRequest request) {
    Mica.DataAccessRequestDto.Builder builder = asDtoBuilder(request);
    String title = dataAccessRequestUtilService.getRequestTitle(request);
    if (!Strings.isNullOrEmpty(title)) {
        builder.setTitle(title);
    }
    if (request.hasStartDate())
        builder.setStartDate(ISO_8601.format(request.getStartDate()));
    DataAccessRequestTimeline timeline = dataAccessRequestReportNotificationService.getReportsTimeline(request);
    if (timeline.hasStartDate() && timeline.hasEndDate()) {
        builder.setReportsTimeline(Mica.TimelineDto.newBuilder().setStartDate(ISO_8601.format(timeline.getStartDate())).setEndDate(ISO_8601.format(timeline.getEndDate())).addAllIntermediateDates(timeline.getIntermediateDates().stream().map(d -> ISO_8601.format(d)).collect(Collectors.toList())));
    }
    builder.setArchived(request.isArchived());
    request.getAttachments().forEach(attachment -> builder.addAttachments(attachmentDtos.asDto(attachment)));
    if (!request.isArchived()) {
        builder.addAllActions(addDataAccessEntityActions(request, "/data-access-request"));
        if (subjectAclService.isPermitted(Paths.get("/data-access-request", request.getId(), "/amendment").toString(), "ADD")) {
            builder.addActions("ADD_AMENDMENTS");
        }
        boolean hasAdministrativeRole = SecurityUtils.getSubject().hasRole(Roles.MICA_DAO) || SecurityUtils.getSubject().hasRole(Roles.MICA_ADMIN);
        if (hasAdministrativeRole || subjectAclService.isPermitted("/data-access-request/private-comment", "VIEW")) {
            builder.addActions("VIEW_PRIVATE_COMMENTS");
        }
        if (hasAdministrativeRole || subjectAclService.isPermitted(Paths.get("/data-access-request", request.getId(), "_attachments").toString(), "EDIT")) {
            builder.addActions("EDIT_ATTACHMENTS");
            if (hasAdministrativeRole) {
                builder.addActions("DELETE_ATTACHMENTS");
                builder.addActions("EDIT_ACTION_LOGS");
            }
        }
    }
    try {
        Project project = projectService.findById(request.getId());
        Mica.PermissionsDto permissionsDto = permissionsDtos.asDto(project);
        Mica.ProjectSummaryDto.Builder projectSummaryDtoBuilder = Mica.ProjectSummaryDto.newBuilder();
        projectSummaryDtoBuilder.setId(project.getId());
        projectSummaryDtoBuilder.setPermissions(permissionsDto);
        builder.setProject(projectSummaryDtoBuilder.build());
    } catch (NoSuchProjectException e) {
    // do nothing
    }
    return builder.build();
}
Also used : NoSuchProjectException(org.obiba.mica.project.service.NoSuchProjectException) Project(org.obiba.mica.project.domain.Project) java.util(java.util) Builder(org.obiba.mica.web.model.Mica.DataAccessRequestDto.StatusChangeDto.Builder) Roles(org.obiba.mica.security.Roles) ProjectService(org.obiba.mica.project.service.ProjectService) UserProfileService(org.obiba.mica.user.UserProfileService) SimpleDateFormat(java.text.SimpleDateFormat) Inject(javax.inject.Inject) Strings(com.google.common.base.Strings) DataAccessRequestUtilService(org.obiba.mica.access.service.DataAccessRequestUtilService) Lists(com.google.common.collect.Lists) Subject(org.obiba.shiro.realm.ObibaRealm.Subject) ZoneOffset(java.time.ZoneOffset) ParseException(java.text.ParseException) SubjectAclService(org.obiba.mica.security.service.SubjectAclService) DataAccessRequestRepository(org.obiba.mica.access.DataAccessRequestRepository) DataAccessRequestReportNotificationService(org.obiba.mica.access.notification.DataAccessRequestReportNotificationService) NotNull(javax.validation.constraints.NotNull) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) Component(org.springframework.stereotype.Component) Paths(java.nio.file.Paths) org.obiba.mica.access.domain(org.obiba.mica.access.domain) SecurityUtils(org.apache.shiro.SecurityUtils) Project(org.obiba.mica.project.domain.Project) NoSuchProjectException(org.obiba.mica.project.service.NoSuchProjectException) NotNull(javax.validation.constraints.NotNull)

Example 60 with NotNull

use of javax.validation.constraints.NotNull in project mica2 by obiba.

the class TempFileService method addTempFile.

@NotNull
public TempFile addTempFile(@NotNull String fileName, @NotNull InputStream uploadedInputStream) throws IOException {
    TempFile tempFile = new TempFile();
    tempFile.setName(fileName);
    return addTempFile(tempFile, uploadedInputStream);
}
Also used : TempFile(org.obiba.mica.file.TempFile) NotNull(javax.validation.constraints.NotNull)

Aggregations

NotNull (javax.validation.constraints.NotNull)77 List (java.util.List)24 Map (java.util.Map)18 Collectors (java.util.stream.Collectors)16 Inject (javax.inject.Inject)16 Logger (org.slf4j.Logger)14 ArrayList (java.util.ArrayList)13 LoggerFactory (org.slf4j.LoggerFactory)13 HashMap (java.util.HashMap)11 Response (javax.ws.rs.core.Response)10 Optional (java.util.Optional)9 Strings (com.google.common.base.Strings)8 Lists (com.google.common.collect.Lists)8 Set (java.util.Set)8 Valid (javax.validation.Valid)8 Api (io.swagger.annotations.Api)7 ApiParam (io.swagger.annotations.ApiParam)7 IOException (java.io.IOException)7 Collection (java.util.Collection)7 Nullable (javax.annotation.Nullable)7