com.sun.jersey.spi.container.ContainerRequest Java Examples

The following examples show how to use com.sun.jersey.spi.container.ContainerRequest. 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: DcCoreContainerFilter.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * リクエストヘッダーの値をチェックする.
 * 現在は、Acceptヘッダーのみ(US-ASCII文字以外かどうか)をチェックする
 * @param request フィルター前リクエスト
 */
private void checkRequestHeader(ContainerRequest request) {
    // ヘッダーのキー名に全角文字が含まれる場合は、その文字を含めたキー名となるため、実際にはこの指定は無視される。
    // Jersey1.10では、Acceptヘッダーのキー名と値にUS-ASCII文字以外が含まれる場合に異常終了するため以下を対処
    // (Acceptを含む他のヘッダーにも同様の処理が行われるが、上記理由により動作上は問題ないと判断)
    // -キー名に含まれる場合は、その指定を無効(Accept:*/*)とする(Jerseryで組み込み済み)。
    // -値に含まれる場合は、400エラーとする。
    InBoundHeaders newHeaders = new InBoundHeaders();
    MultivaluedMap<String, String> headers = request.getRequestHeaders();
    for (String header : headers.keySet()) {
        if (header.contains(org.apache.http.HttpHeaders.ACCEPT)
                && !acceptHeaderValueRegex.matcher(header).matches()) {
            continue;
        } else {
            newHeaders.put(header, request.getRequestHeader(header));
        }
    }
    request.setHeaders(newHeaders);
    String acceptValue = request.getHeaderValue(org.apache.http.HttpHeaders.ACCEPT);
    if (acceptValue != null && !acceptHeaderValueRegex.matcher(acceptValue).matches()) {
        DcCoreException exception = DcCoreException.OData.BAD_REQUEST_HEADER_VALUE.params(
                org.apache.http.HttpHeaders.ACCEPT, acceptValue);
        throw exception;
    }
}
 
Example #2
Source File: ResponseCorsFilter.java    From nextreports-server with Apache License 2.0 6 votes vote down vote up
@Override
public ContainerResponse filter(ContainerRequest req, ContainerResponse contResp) {
 
    ResponseBuilder resp = Response.fromResponse(contResp.getResponse());
    resp.header("Access-Control-Allow-Origin", "*")
        .header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
 
    String reqHead = req.getHeaderValue("Access-Control-Request-Headers");
 
    if(null != reqHead && !reqHead.equals("")){
        resp.header("Access-Control-Allow-Headers", reqHead);
    }
 
    contResp.setResponse(resp.build());
    return contResp;
}
 
Example #3
Source File: TestRedirectResourceFilter.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testController() throws Exception {

    ContainerRequest request = mock(ContainerRequest.class);
    String path = "controller";
    String baseUri = "http://example.com:8080/nifi-api/";
    when(request.getPath()).thenReturn(path);
    when(request.getBaseUri()).thenReturn(new URI(baseUri));
    when(request.getRequestUri()).thenReturn(new URI(baseUri + path));

    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            assertEquals("base uri should be retained", new URI(baseUri), invocation.getArguments()[0]);
            assertEquals("request uri should be redirected", new URI(baseUri + "site-to-site"), invocation.getArguments()[1]);
            return null;
        }
    }).when(request).setUris(any(URI.class), any(URI.class));

    RedirectResourceFilter filter = new RedirectResourceFilter();
    filter.filter(request);

}
 
Example #4
Source File: DateSearchFilter.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that if a date range is specified that the request URI
 * is allowed to be searched via date ranges
 * @param request
 */
private void validateDateSearchUri(ContainerRequest request) {

    String requestPath = request.getPath();

    Matcher m = ID_REPLACEMENT_PATTERN.matcher(requestPath);

    if (m.matches()){
        // transform requestPath from "v1.x/foo/2344,3453,5345/bar" to "v1.x/foo/{id}/bar"
        requestPath = m.group(1) + PathConstants.ID_PLACEHOLDER + m.group(2);
    }

    if (this.resourceEndPoint.getDateRangeDisallowedEndPoints().contains(requestPath)) {

        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: TestRedirectResourceFilter.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testControllerWithParams() throws Exception {

    ContainerRequest request = mock(ContainerRequest.class);
    String path = "controller";
    String baseUri = "http://example.com:8080/nifi-api/";
    String query = "?a=1&b=23&cde=456";
    when(request.getPath()).thenReturn(path);
    when(request.getBaseUri()).thenReturn(new URI(baseUri));
    when(request.getRequestUri()).thenReturn(new URI(baseUri + path + query));

    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            assertEquals("base uri should be retained", new URI(baseUri), invocation.getArguments()[0]);
            assertEquals("request uri should be redirected with query parameters",
                    new URI(baseUri + "site-to-site" + query), invocation.getArguments()[1]);
            return null;
        }
    }).when(request).setUris(any(URI.class), any(URI.class));

    RedirectResourceFilter filter = new RedirectResourceFilter();
    filter.filter(request);

}
 
Example #6
Source File: VersionFilter.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
private ContainerRequest updateContainerRequest(ContainerRequest containerRequest, List<PathSegment> segments, String newVersion) {
    //add the new version
    UriBuilder builder = containerRequest.getBaseUriBuilder().path(newVersion);

    //add the rest of the request
    for (PathSegment segment : segments) {
        builder.path(segment.getPath());
    }

    if (containerRequest.getRequestUri().getQuery() != null &&
            !containerRequest.getRequestUri().getQuery().isEmpty()) {
        builder.replaceQuery(containerRequest.getRequestUri().getQuery());
    }

    containerRequest.getProperties().put(REQUESTED_PATH, containerRequest.getPath());
    containerRequest.setUris(containerRequest.getBaseUri(), builder.build());

    return containerRequest;
}
 
Example #7
Source File: PreProcessFilter.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
/**
 * Validate the request URL is not blocked
 *
 * @param request
 */
private void validateNotBlockGetRequest(ContainerRequest request) {
    if (!request.getMethod().equals(RequestMethod.GET.name())) {
        return;
    }

    String requestPath = request.getPath();
    Matcher m = ID_REPLACEMENT_PATTERN.matcher(requestPath);

    if (m.matches()) {
        // transform requestPath from "v1.x/foo/2344,3453,5345/bar" to
        // "v1.x/foo/{id}/bar"
        requestPath = m.group(1) + PathConstants.ID_PLACEHOLDER + m.group(2);
    }

    if (this.resourceEndPoint.getBlockGetRequestEndPoints().contains(requestPath)) {
        throw new RequestBlockedException(request.getPath());
    }
}
 
Example #8
Source File: EndpointMutatorTest.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
@Test(expected = NotFoundException.class)
public void testNoPathSegments() throws URISyntaxException {
    // Test /api/rest with no additional path segments.
    SLIPrincipal principle = mock(SLIPrincipal.class);
    ClientToken clientToken = mock(ClientToken.class);
    when(clientToken.getClientId()).thenReturn("theAppId");
    OAuth2Authentication auth = mock(OAuth2Authentication.class);
    when(auth.getPrincipal()).thenReturn(principle);
    when(auth.getClientAuthentication()).thenReturn(clientToken);

    ContainerRequest request = mock(ContainerRequest.class);
    List<PathSegment> segments = Collections.emptyList();
    when(request.getPathSegments()).thenReturn(segments);
    when(request.getMethod()).thenReturn("GET");
    when(request.getRequestUri()).thenReturn(new URI("http://not.valid.inbloom.org"));
    
    endpointMutator.mutateURI(auth, request);
}
 
Example #9
Source File: DateFilterCriteriaGeneratorTest.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
@Test
public void testGenerate() throws Exception {
    ContainerRequest request = mock(ContainerRequest.class);
    MultivaluedMap<String,String> parameters = mock(MultivaluedMap.class);
    List<String> schoolYears = new ArrayList<String>();
    schoolYears.add("begin");
    schoolYears.add("end");
    SessionDateInfo sessionDateInfo = new SessionDateInfo("01-01-2010","01-31-2012",
            new HashSet<String>());
    EntityFilterInfo entityFilterInfo =  new EntityFilterInfo();
    entityFilterInfo.setEntityName("testEntity");
    entityFilterInfo.setBeginDateAttribute("beginDate");
    entityFilterInfo.setEndDateAttribute("endDate");

    Mockito.when(request.getQueryParameters()).thenReturn(parameters);
    Mockito.when(parameters.get(ParameterConstants.SCHOOL_YEARS)).thenReturn(schoolYears);
    Mockito.when(sessionRangeCalculator.findDateRange(anyString())).thenReturn(sessionDateInfo);
    Mockito.when(entityIdentifier.findEntity(anyString())).thenReturn(entityFilterInfo);

    dateFilterCriteriaGenerator.generate(request);

}
 
Example #10
Source File: TestRedirectResourceFilter.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnmatched() throws Exception {

    ContainerRequest request = mock(ContainerRequest.class);
    String path = "unmatched";
    String baseUri = "http://example.com:8080/nifi-api/";
    when(request.getPath()).thenReturn(path);
    when(request.getBaseUri()).thenReturn(new URI(baseUri));
    when(request.getRequestUri()).thenReturn(new URI(baseUri + path));

    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            fail("setUris shouldn't be called");
            return null;
        }
    }).when(request).setUris(any(URI.class), any(URI.class));

    RedirectResourceFilter filter = new RedirectResourceFilter();
    filter.filter(request);

}
 
Example #11
Source File: DateSearchFilter.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
@Override
public ContainerRequest filter(ContainerRequest request) {

    // sets the startTime in the case that an exception is thrown
    // so that the PostProcessFilter can process correctly
    request.getProperties().put("startTime", System.currentTimeMillis());

    List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS);

    // only check conditions if query parameter exists
    if (schoolYears != null ){

        validateNotVersionOneZero(request);
        validateDateSearchUri(request);
        validateNonTwoPartUri(request);
    }


    return request;
}
 
Example #12
Source File: ContextValidator.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
/**
 * white list student accessible URL. Can't do it in validateUserHasContextToRequestedEntity
 * because we must also block some url that only has 2 segment, i.e.
 * disciplineActions/disciplineIncidents
 *
 * @param request
 * @return if url is accessible to students principals
 */
public boolean isUrlBlocked(ContainerRequest request) {
    List<PathSegment> segs = cleanEmptySegments(request.getPathSegments());

    if (isSystemCall(segs)) {
        // do not block system calls
        return false;
    }

    if (SecurityUtil.isStudent()) {
        return !studentAccessValidator.isAllowed(request);
    } else if (SecurityUtil.isParent()) {
        return !parentAccessValidator.isAllowed(request);
    }

    return false;
}
 
Example #13
Source File: AuthorizationResourceFilter.java    From emodb with Apache License 2.0 6 votes vote down vote up
/**
 * Resolves permissions based on the request.  For example, if the annotation's permission is
 * "get|{thing}" and the method's @Path annotation is "/resources/{thing}" then a request to
 * "/resources/table" will resolve to the permission "get|table".
 */
private String[] resolvePermissions(ContainerRequest request) {
    String[] values = _permissions;

    if (_substitutions.isEmpty()) {
        return values;
    }

    String[] permissions = new String[values.length];
    System.arraycopy(values, 0, permissions, 0, values.length);

    for (Map.Entry<String, Function<HttpRequestContext, String>> entry : _substitutions.entrySet()) {
        String key = Pattern.quote(entry.getKey());
        String substitution = Matcher.quoteReplacement(MatchingPermission.escape(entry.getValue().apply(request)));

        for (int i=0; i < values.length; i++) {
            permissions[i] = permissions[i].replaceAll(key, substitution);
        }
    }

    return permissions;
}
 
Example #14
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 #15
Source File: AdHocThrottleTest.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    // Create a unique base path for each test so each tests ZooKeeper data is independent.
    _zkNamespace = "emodb/test" + (_nextBaseIndex++);
    _curator = _rootCurator.usingNamespace(_zkNamespace);

    _mapStore = new ZkMapStore<>(_curator, "adhoc-throttle", new ZkAdHocThrottleSerializer());
    _mapStore.start();

    _adHocThrottleManager = new AdHocThrottleManager(_mapStore);

    // Set up the regulator supplier provided to Jersey to defer an instance created specifically for this test.
    final AdHocConcurrentRequestRegulatorSupplier regulatorSupplier =
            new AdHocConcurrentRequestRegulatorSupplier(_adHocThrottleManager, new MetricRegistry());
    when(_deferringRegulatorSupplier.forRequest(any(ContainerRequest.class))).thenAnswer(
            new Answer<ConcurrentRequestRegulator>() {
                @Override
                public ConcurrentRequestRegulator answer(InvocationOnMock invocation) throws Throwable {
                    ContainerRequest request = (ContainerRequest) invocation.getArguments()[0];
                    return regulatorSupplier.forRequest(request);
                }
            });
}
 
Example #16
Source File: RightCheckFilterFactory.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
/**
 * Enforces the rights.
 *
 * Causes a InsufficientAuthenticationException (401) if the user isn't authenticated
 * Causes an {@link AccessDeniedException} if the user doesn't have the necessary rights,
 * and a security event is logged.
 */
@Override
public ContainerRequest filter(ContainerRequest request) {

    SecurityUtil.ensureAuthenticated();

    //If annotation user uses @RightsAllowed(any=true),
    //we just check that the user is authenticated and nothing else
    if (rightList.size() == 0) {
        return request;
    }

    for (Right right : rightList) {
        if (SecurityUtil.hasRight(right)) {
            LOG.info("User has needed right {} to access {}.", right, request.getPath());
            return request;
        }
    }


    throw new APIAccessDeniedException("Failed to access URL because of insufficient rights.");
}
 
Example #17
Source File: RangerRESTAPIFilter.java    From ranger with Apache License 2.0 6 votes vote down vote up
@Override
public ContainerRequest filter(ContainerRequest request) {
	if (!initDone) {
		init();
	}
	if (logStdOut) {
		String path = request.getRequestUri().getPath();

		if ((request.getMediaType() == null || !"multipart".equals(request.getMediaType()
				.getType()))
				&& !path.endsWith("/service/general/logs")) {
			try {
				request = super.filter(request);
			} catch (Throwable t) {
				logger.error("Error FILTER logging. path=" + path, t);
			}
		}
	}

	return request;
}
 
Example #18
Source File: RangerRESTAPIFilter.java    From ranger with Apache License 2.0 6 votes vote down vote up
@Override
public ContainerResponse filter(ContainerRequest request,
		ContainerResponse response) {
	if (logStdOut) {
		// If it is image, then don't call super
		if (response.getMediaType() == null) {
			logger.info("DELETE ME: Response= mediaType is null");
		}
		if (response.getMediaType() == null
				|| !"image".equals(response.getMediaType().getType())) {

			response = super.filter(request, response);
		}
	}

	return response;
}
 
Example #19
Source File: DcCoreContainerFilter.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * リクエスト全体に対してかけるフィルター.
 * @param request フィルタ前リクエスト
 * @return フィルタ後リクエスト
 */
@Override
public ContainerRequest filter(ContainerRequest request) {
    requestLog(request);

    // リクエストの時間を記録する
    long requestTime = System.currentTimeMillis();
    // リクエストの時間をセッションに保存する
    this.httpServletRequest.setAttribute("requestTime", requestTime);

    methodOverride(request);
    headerOverride(request);
    uriOverride(request);
    responseOptionsMethod(request);

    // リクエストヘッダーの不正値をチェックする
    checkRequestHeader(request);

    // DcCoreConfig.setUnitRootIfNotSet(this.httpServletRequest);

    // PCSの動作モードがReadDeleteOnlyモードの場合は、参照系リクエストのみ許可する
    // 許可されていない場合は例外を発生させてExceptionMapperにて処理する
    DcReadDeleteModeManager.checkReadDeleteOnlyMode(request.getMethod(), request.getPathSegments());

    return request;
}
 
Example #20
Source File: DateSearchFilterTest.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
private ContainerRequest createRequest(String requestPath, String schoolYearsQuery) {
    ContainerRequest request = Mockito.mock(ContainerRequest.class);
    String[] pathParts = requestPath.split("/");
    List<PathSegment> segments = new ArrayList<PathSegment>();
    for (String pathPart : pathParts) {
        segments.add(segmentFor(pathPart));
    }
    
    MultivaluedMap queryParameters = new MultivaluedMapImpl();
    
    String[] schoolYearParts = schoolYearsQuery.split("=");
    if (schoolYearParts.length == 2) {
        queryParameters.add(schoolYearParts[0], schoolYearParts[1]);
    }
    
    Mockito.when(request.getQueryParameters()).thenReturn(queryParameters);
    Mockito.when(request.getPathSegments()).thenReturn(segments);
    Mockito.when(request.getPath()).thenReturn(requestPath);
    return request;
}
 
Example #21
Source File: AuthenticationResourceFilter.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Override
public ContainerRequest filter(ContainerRequest request) {
    Subject subject = new Subject.Builder(_securityManager).buildSubject();
    ThreadContext.bind(subject);

    AuthenticationToken token = _tokenGenerator.createToken(request);
    if (token == null) {
        token = AnonymousToken.getInstance();
    }
    subject.login(token);

    // The user has been successfully logged in.  Update the container authentication.
    setJettyAuthentication(subject);

    return request;
}
 
Example #22
Source File: HttpRequestAdapter.java    From jerseyoauth2 with MIT License 6 votes vote down vote up
public HttpRequestAdapter(ContainerRequest containerRequest) {
	this.containerRequest = containerRequest;
	
	MultivaluedMap<String, String> queryParams = containerRequest.getQueryParameters();
	for (Entry<String, List<String>> entry : queryParams.entrySet())
	{
		StringBuffer values = new StringBuffer();
		for (String val : entry.getValue())
		{
			if (values.length()>0) {
				values.append(",");
			}
			values.append(val);
		}
		this.queryParameters.put(entry.getKey(), values.toString());
	}
}
 
Example #23
Source File: RequestDecoder.java    From jersey-hmac-auth with Apache License 2.0 6 votes vote down vote up
/**
 * Under normal circumstances, the body of the request can only be read once, because it is
 * backed by an {@code InputStream}, and thus is not easily consumed multiple times. This
 * method gets the request content and resets it so it can be read again later if necessary.
 */
private byte[] safelyGetContent(HttpRequestContext request) {
    ContainerRequest containerRequest = (ContainerRequest) request;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    InputStream in = containerRequest.getEntityInputStream();

    try {
        ReaderWriter.writeTo(in, out);
        byte[] content = out.toByteArray();

        // Reset the input stream so that it can be read again by another filter or resource
        containerRequest.setEntityInputStream(new ByteArrayInputStream(content));
        return content;

    } catch (IOException ex) {
        throw new ContainerException(ex);
    }
}
 
Example #24
Source File: DcCoreContainerFilter.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * 認証なしOPTIONメソッドのレスポンスを返却する.
 * @param request フィルタ前リクエスト
 */
private void responseOptionsMethod(ContainerRequest request) {
    String authValue = request.getHeaderValue(org.apache.http.HttpHeaders.AUTHORIZATION);
    String methodName = request.getMethod();
    if (authValue == null && HttpMethod.OPTIONS.equals(methodName)) {
        Response res = DcCoreUtils.responseBuilderForOptions(
                HttpMethod.GET,
                HttpMethod.POST,
                HttpMethod.PUT,
                HttpMethod.DELETE,
                HttpMethod.HEAD,
                com.fujitsu.dc.common.utils.DcCoreUtils.HttpMethod.MERGE,
                com.fujitsu.dc.common.utils.DcCoreUtils.HttpMethod.MKCOL,
                com.fujitsu.dc.common.utils.DcCoreUtils.HttpMethod.MOVE,
                com.fujitsu.dc.common.utils.DcCoreUtils.HttpMethod.PROPFIND,
                com.fujitsu.dc.common.utils.DcCoreUtils.HttpMethod.PROPPATCH,
                com.fujitsu.dc.common.utils.DcCoreUtils.HttpMethod.ACL
                ).build();

        // 例外を発行することでServletへ制御を渡さない
        throw new WebApplicationException(res);
    }
}
 
Example #25
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 #26
Source File: ResponseCorsFilter.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
@Override
public ContainerResponse filter( ContainerRequest req, ContainerResponse contResp ) {

	ResponseBuilder resp = Response.fromResponse( contResp.getResponse());
	Map<String,String> headers = buildHeaders(
			req.getHeaderValue( CORS_REQ_HEADERS ),
			req.getHeaderValue( ORIGIN ));

	for( Map.Entry<String,String> h : headers.entrySet())
		resp.header( h.getKey(), h.getValue());

	contResp.setResponse( resp.build());
	return contResp;
}
 
Example #27
Source File: StudentAccessValidatorTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    request = Mockito.mock(ContainerRequest.class);
    when(request.getPathSegments()).thenAnswer(new Answer<List<PathSegment>>() {
        @Override
        public List<PathSegment> answer(InvocationOnMock invocation) throws Throwable {
            return buildSegment();
        }
    });
    when(request.getQueryParameters()).thenReturn(new MultivaluedMapImpl());
    when(request.getMethod()).thenReturn("GET");
}
 
Example #28
Source File: VersionFilterTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testBulkExtractNoApiVersion() throws URISyntaxException {
    UriBuilder builder = mock(UriBuilder.class);
    when(builder.path(anyString())).thenReturn(builder);

    String latestApiVersion = versionFilter.getLatestApiVersion("v1.1");

    URI uri = new URI("http://api/rest/bulk");

    PathSegment segment1 = mock(PathSegment.class);
    when(segment1.getPath()).thenReturn("bulk");

    List<PathSegment> segments = new ArrayList<PathSegment>();
    segments.add(segment1);

    when(containerRequest.getPathSegments()).thenReturn(segments);
    when(containerRequest.getBaseUriBuilder()).thenReturn(builder);
    when(containerRequest.getRequestUri()).thenReturn(uri);
    when(containerRequest.getPath()).thenReturn("http://api/rest/bulk");
    when(containerRequest.getProperties()).thenReturn(new HashMap<String, Object>());

    ContainerRequest request = versionFilter.filter(containerRequest);
    verify(containerRequest).setUris((URI) any(), (URI) any());
    verify(builder).build();
    verify(builder, times(1)).path(latestApiVersion);
    verify(builder, times(1)).path("bulk");
    assertEquals("Should match", "http://api/rest/bulk", request.getProperties().get(REQUESTED_PATH));
}
 
Example #29
Source File: NettyToJerseyBridge.java    From karyon with Apache License 2.0 5 votes vote down vote up
ContainerRequest bridgeRequest(final HttpServerRequest<ByteBuf> nettyRequest, InputStream requestData ) {
    try {
        URI baseUri = new URI("/"); // Since the netty server does not have a context path element as such, so base uri is always /
        URI uri = new URI(nettyRequest.getUri());
        return new ContainerRequest(application, nettyRequest.getHttpMethod().name(),
                                    baseUri, uri, new JerseyRequestHeadersAdapter(nettyRequest.getHeaders()),
                                    requestData );
    } catch (URISyntaxException e) {
        logger.error(String.format("Invalid request uri: %s", nettyRequest.getUri()), e);
        throw new IllegalArgumentException(e);
    }
}
 
Example #30
Source File: SessionUtil.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
public static void checkAccess(Authentication auth, ContainerRequest request, Repository<Entity> repo) {
    
    String clientId = ((OAuth2Authentication) auth).getClientAuthentication().getClientId();

    if(isAdminApp(clientId, repo)==false&&isAdminRequest(request.getRequestUri().toString())==true) {
        throw new APIAccessDeniedException(String.format("url %s is not accessible to non-Admin Applications.", request.getRequestUri().toString()));
    }
}