Java Code Examples for com.sun.jersey.spi.container.ContainerRequest#getPathSegments()

The following examples show how to use com.sun.jersey.spi.container.ContainerRequest#getPathSegments() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AccessValidator.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
/**
 * check if a path can be accessed according to stored business rules
 * 
 * @param ContextRequest
 *            request
 * @return true if request is allowed
 */
public boolean isAllowed(ContainerRequest request) {
    if (request == null || request.getPathSegments() == null) {
        return false;
    }
    
    List<String> paths = cleanPath(request.getPathSegments());
    
    if (paths.isEmpty()) {
        return false;
    }
    
    if (isDisiplineRelated(paths)) {
        return false;
    }
    
    if (ResourceMethod.getWriteOps().contains(request.getMethod())) {
        return isWriteAllowed(paths, request.getMethod());
    } 
    
    return isReadAllowed(paths, request.getQueryParameters());
}
 
Example 2
Source File: URITranslator.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
public void translate(ContainerRequest request) {
    String uri = request.getPath();
    List<PathSegment> segments = request.getPathSegments();
    String version = PathConstants.V1;

    if (!segments.isEmpty()) {
        version = segments.get(0).getPath();
    }

    for (Map.Entry<String, URITranslation> entry : uriTranslationMap.entrySet()) {
        String key = entry.getKey();
        if (uri.contains(key)) {
            String newPath = uriTranslationMap.get(key).translate(request.getPath());
            if (!newPath.equals(uri)) {
                request.setUris(request.getBaseUri(),
                    request.getBaseUriBuilder().path(version).path(newPath).build());
            }
        }
    }
}
 
Example 3
Source File: EndpointMutator.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
/**
 * Sanitizes the path segments currently contained in the request by removing empty segments.
 * This is required because a trailing slash causes an empty segment to exist, e.g.
 * /v1/students/ produces ["v1","students", ""].
 *
 * @param request
 *            Container Request to get path segments from.
 * @return Sane set of path segments.
 */
protected List<PathSegment> sanitizePathSegments(ContainerRequest request) {
    List<PathSegment> segments = request.getPathSegments();
    for (Iterator<PathSegment> i = segments.iterator(); i.hasNext();) {
        if (i.next().getPath().isEmpty()) {
            i.remove();
        }
    }
    return segments;
}
 
Example 4
Source File: DateSearchFilter.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
/**
 * Dissallows any date range searches for v1.0 URIs
 * @param request
 */
private void validateNotVersionOneZero(ContainerRequest request) {
    List<PathSegment> segments = request.getPathSegments();
    if (segments.size() > 0) {
        String version = segments.get(0).getPath();
        if (PathConstants.V1_0.equals(version)) {

            List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS);
            if (schoolYears != null && schoolYears.size() > 0){
                throw new QueryParseException("Date range filtering not allowed", request.getPath());
            }
        }
    }
}
 
Example 5
Source File: VersionFilter.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Override
public ContainerRequest filter(ContainerRequest containerRequest) {

    List<PathSegment> segments = containerRequest.getPathSegments();

    if (!segments.isEmpty()) {
        String version = segments.get(0).getPath();
        boolean isBulkNonVersion = version.equals("bulk");

        SortedSet<String> minorVersions = resourceEndPoint.getNameSpaceMappings().get(version);

        String newVersion = null;

        if(isBulkNonVersion || (segments.size() > 1 && segments.get(1).getPath().equals("bulk"))) {
            if (!isBulkNonVersion) {
                //remove the version
                segments.remove(0);
            } else {
                //there is no version specified in the request for bulk extract
                version = "";
            }

            // Bulk extract always returns latest API version.
            newVersion = getLatestApiVersion(version);

            updateContainerRequest(containerRequest, segments, newVersion);
            LOG.info("Version Rewrite: {} --> {}", new Object[] { version, newVersion });

        } else if ((minorVersions != null) && !minorVersions.isEmpty()) {
            segments.remove(0);

            newVersion = version + "." + minorVersions.last();

            updateContainerRequest(containerRequest, segments, newVersion);
            LOG.info("Version Rewrite: {} --> {}", new Object[] { version, newVersion });
        }
    }

    return containerRequest;
}
 
Example 6
Source File: DisabledFilter.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Override
public ContainerRequest filter(ContainerRequest request) {

    //skip this filter of the request is not a put and not a patch
    if(!request.getMethod().equalsIgnoreCase("put") && !request.getMethod().equalsIgnoreCase("patch")) {
        return request;
    }

    //always allow access to put and patch on custom data
    if(resourceHelper.resolveResourcePath("/rest/"+request.getPath(), ResourceTemplate.CUSTOM)) {
        return request;
    }

    if(resourceHelper.resolveResourcePath("/rest/"+request.getPath(), ResourceTemplate.UNVERSIONED_CUSTOM)) {
        return request;
    }

    //check each segment, find the associated resource and verify that put or patch is enabled
    List<PathSegment> segs = request.getPathSegments();
    segs = contextValidator.cleanEmptySegments(segs);

    for(PathSegment seg : segs) {
        EntityDefinition entityDef = entityDefinitionStore.lookupByResourceName(seg.getPath());

        if(entityDef != null) {
            if(request.getMethod().equalsIgnoreCase("put") && !entityDef.supportsPut()) {
                throw new MethodNotAllowedException(Sets.newHashSet(new String[]{}));
            }
            if(request.getMethod().equalsIgnoreCase("patch") && !entityDef.supportsPatch()) {
                throw new MethodNotAllowedException(Sets.newHashSet(new String[] {}));
            }
        }
    }

    return request;
}
 
Example 7
Source File: ContextValidator.java    From secure-data-service with Apache License 2.0 4 votes vote down vote up
private void validateUserHasContextToRequestedEntities(ContainerRequest request, SLIPrincipal principal) {

        List<PathSegment> segs = request.getPathSegments();
        segs = cleanEmptySegments(segs);

        if (segs.size() < 3) {
            return;
        }

        /*
         * If the URI being requested is a GET full of global entities, we do
         * not need to attempt validation Global entities include: ASSESSMENT,
         * LEARNING_OBJECTIVE, LEARNING_STANDARD, COMPETENCY_LEVEL_DESCRIPTOR,
         * SESSION, COURSE_OFFERING, GRADING_PERIOD, COURSE,
         * EDUCATION_ORGANIZATION, SCHOOL, SECITON, PROGRAM, GRADUATION_PLAN,
         * STUDENT_COMPETENCY_OBJECTIVE, and CUSTOM (custom entity exists under
         * another entity, they should not prevent classification of a call
         * being global)
         */
        boolean isGlobal = true;
        for (PathSegment seg : segs) {
            // First segment is always API version, skip it
            // Third segment is always the ID, skip it
            if (seg.equals(segs.get(0)) || seg.equals(segs.get(2))) {
                continue;
            }
            // Check if the segment is not global, if so break
            if (!GLOBAL_RESOURCES.contains(seg.getPath())) {
                isGlobal = false;
                break;
            }
        }
        // Only skip validation if method is a get, updates may still require
        // validation
        if (isGlobal && request.getMethod().equals("GET")) {
            // The entity has global context, just return and don't call the
            // validators
            LOG.debug("Call to {} is of global context, skipping validation", request.getAbsolutePath().toString());
            return;
        }

        String rootEntity = segs.get(1).getPath();

        EntityDefinition def = resourceHelper.getEntityDefinition(rootEntity);
        if (def == null || def.skipContextValidation()) {
            return;
        }

        /*
         * e.g.
         * !isTransitive - /v1/staff/<ID>/disciplineActions
         * isTransitive - /v1/staff/<ID> OR /v1/staff/<ID>/custom
         */
        boolean isTransitive = segs.size() == 3
                || (segs.size() == 4 && segs.get(3).getPath().equals(ResourceNames.CUSTOM));

        validateContextToCallUri(segs);
        String idsString = segs.get(2).getPath();
        Set<String> ids = new HashSet<String>(Arrays.asList(idsString.split(",")));
        validateContextToEntities(def, ids, isTransitive);
    }
 
Example 8
Source File: PreProcessFilter.java    From secure-data-service with Apache License 2.0 4 votes vote down vote up
private void injectObligations(ContainerRequest request) {
    // Create obligations
    SLIPrincipal prince = SecurityUtil.getSLIPrincipal();

    if (request.getPathSegments().size() > 3) {	// not applied on two parters

        String base = request.getPathSegments().get(1).getPath();
        String assoc = request.getPathSegments().get(3).getPath();

        if (CONTEXTERS.contains(base)) {
            LOG.info("Skipping date-based obligation injection because association {} is base level URI", base);
            return;
        }

        if(base.equals(ResourceNames.PROGRAMS) || base.equals(ResourceNames.COHORTS)) {
            if(assoc.equals(ResourceNames.STAFF_PROGRAM_ASSOCIATIONS) || assoc.equals(ResourceNames.STAFF_COHORT_ASSOCIATIONS)) {
                prince.setStudentAccessFlag(false);
            }
        }

        if(SecurityUtil.isStudent()) {
            List<NeutralQuery> oblong = construct("endDate");

            for(String entity : DATE_RESTRICTED_ENTITIES) {
                prince.addObligation(entity, oblong);
            }
        }

        for (PathSegment seg : request.getPathSegments()) {
            String resourceName = seg.getPath();
            if (ResourceNames.STUDENTS.equals(resourceName)) {	// once student is encountered,
                                                               // no more obligations
                break;
            }

            if (CONTEXTERS.contains(resourceName) && !request.getQueryParameters().containsKey("showAll")) {
                if (ResourceNames.STUDENT_SCHOOL_ASSOCIATIONS.equals(resourceName)) {
                    prince.addObligation(resourceName.replaceAll("s$", ""), construct("exitWithdrawDate"));
                } else {
                    prince.addObligation(resourceName.replaceAll("s$", ""), construct("endDate"));
                }

                LOG.info("Injected a date-based obligation on association: {}", resourceName);
            }
        }
    }
}