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

The following examples show how to use com.sun.jersey.spi.container.ContainerResponse. 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: NettyToJerseyBridge.java    From karyon with Apache License 2.0 6 votes vote down vote up
ContainerResponseWriter bridgeResponse(final HttpServerResponse<ByteBuf> serverResponse) {
    return new ContainerResponseWriter() {

        private final ByteBuf contentBuffer = serverResponse.getChannel().alloc().buffer();

        @Override
        public OutputStream writeStatusAndHeaders(long contentLength, ContainerResponse response) {
            int responseStatus = response.getStatus();
            serverResponse.setStatus(HttpResponseStatus.valueOf(responseStatus));
            HttpResponseHeaders responseHeaders = serverResponse.getHeaders();
            for(Map.Entry<String, List<Object>> header : response.getHttpHeaders().entrySet()){
                responseHeaders.setHeader(header.getKey(), header.getValue());
            }
            return new ByteBufOutputStream(contentBuffer);
        }

        @Override
        public void finish() {
            serverResponse.writeAndFlush(contentBuffer);
        }
    };
}
 
Example #2
Source File: ServerErrorResponseMetricsFilter.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Override
public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
    if (response.getStatusType().getFamily() == Response.Status.Family.SERVER_ERROR) {
        switch (response.getStatus()) {
            case 500:
                _meter500.mark();
                break;
            case 503:
                _meter503.mark();
                break;
            default:
                _meterOther.mark();
                break;
        }
    }
    return response;
}
 
Example #3
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 #4
Source File: StaashAuditFilter.java    From staash with Apache License 2.0 6 votes vote down vote up
/**
 * Private helper that adds the request-id to the response payload.
 * @param response
 */
private void addRequestIdToResponse(ContainerResponse response) {
	
	// The request-id to be injected in the response
	String requestId = StaashRequestContext.getRequestId();
	
	// The key response attributes
	int status = response.getStatus();
	MediaType mediaType = response.getMediaType();
	
	if (mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) {
		
		String message = (String)response.getEntity();
		JsonObject json = new JsonObject(message);
		json.putString("request-id", requestId);
		
		Response newJerseyResponse = Response.status(status).type(mediaType).entity(json.toString()).build();
		response.setResponse(newJerseyResponse);
	}
		
	// Add the request id to the response regardless of the media type, 
	// this allows non json responses to have a request id in the response
	response.getHttpHeaders().add("x-nflx-staash-request-id", requestId);
}
 
Example #5
Source File: ResponseCorsFilter.java    From semanticMDR with GNU General Public License v3.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(null)) {
		resp.header("Access-Control-Allow-Headers", reqHead);
	}

	contResp.setResponse(resp.build());
	return contResp;
}
 
Example #6
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 #7
Source File: DcCoreContainerFilterTest.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * filter(ContainerRequest req, ContainerResponse res): ContainerResponseのテスト.
 * レスポンスフィルタとしてログ出力をしていることを確認。
 */
@Ignore
@Test
public void testFilterContainerRequestContainerResponse() {
    // 被テストオブジェクトを準備
    DcCoreContainerFilter containerFilter = new DcCoreContainerFilter();
    // ContainerRequiestモックを準備
    ContainerRequest mockRequest = mock(ContainerRequest.class);
    HttpServletRequest mockServletRequest = mock(HttpServletRequest.class);
    when(mockServletRequest.getAttribute("requestTime")).thenReturn(System.currentTimeMillis());
    containerFilter.setHttpServletRequest(mockServletRequest);

    // ContainerResponseモックを準備
    ContainerResponse mockResponse = mock(ContainerResponse.class);
    when(mockResponse.getStatus()).thenReturn(HttpStatus.SC_OK);

    // 被テスト処理の実行
    ContainerResponse filteredResponse = containerFilter.filter(mockRequest, mockResponse);

    // 結果の検証。
    // ログ出力するだけなので、非Nullであることのみ検査.
    assertNotNull(filteredResponse);
}
 
Example #8
Source File: DcCoreContainerFilter.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * レスポンスログ出力.
 * @param response
 */
private void responseLog(final ContainerResponse response) {
    StringBuilder sb = new StringBuilder();
    sb.append("[" + DcCoreConfig.getCoreVersion() + "] " + "Completed. ");
    sb.append(response.getStatus());
    sb.append(" ");

    // レスポンスの時間を記録する
    long responseTime = System.currentTimeMillis();
    // セッションからリクエストの時間を取り出す
    long requestTime = (Long) this.httpServletRequest.getAttribute("requestTime");
    // レスポンスとリクエストの時間差を出力する
    sb.append((responseTime - requestTime) + "ms");
    log.info(sb.toString());
}
 
Example #9
Source File: NettyHandlerContainer.java    From recipes-rss with Apache License 2.0 5 votes vote down vote up
public OutputStream writeStatusAndHeaders(long contentLength, ContainerResponse cResponse) throws IOException {

			response = new DefaultHttpResponse(HttpVersion.HTTP_1_0, HttpResponseStatus.valueOf(cResponse.getStatus()));
			for (Map.Entry<String, List<Object>> e : cResponse.getHttpHeaders().entrySet()) {
				List<String> values = new ArrayList<String>();
				for (Object v : e.getValue())
					values.add(ContainerResponse.getHeaderValue(v));
				response.setHeader(e.getKey(), values);
			}
			ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
			response.setContent(buffer);
			return new ChannelBufferOutputStream(buffer);
		}
 
Example #10
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 #11
Source File: CORSFilter.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public ContainerResponse filter(ContainerRequest request,
		ContainerResponse response) {
	response.getHttpHeaders().add("Access-Control-Allow-Origin", "*");
	response.getHttpHeaders().add("Access-Control-Allow-Headers",
			"origin, content-type, accept, authorization");
	response.getHttpHeaders().add("Access-Control-Allow-Credentials", "true");
	response.getHttpHeaders().add("Access-Control-Allow-Methods",
			"GET, POST, PUT, DELETE, OPTIONS, HEAD");
	return response;
}
 
Example #12
Source File: DcCoreContainerFilter.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * 全てのレスポンスに共通するレスポンスヘッダーを追加する.
 * Access-Control-Allow-Origin, Access-Control-Allow-Headers<br/>
 * X-Dc-Version<br/>
 * @param request
 * @param response
 */
private void addResponseHeaders(final ContainerRequest request, final ContainerResponse response) {
    MultivaluedMap<String, Object> mm = response.getHttpHeaders();
    String acrh = request.getHeaderValue(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS);
    if (acrh != null) {
        mm.putSingle(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, acrh);
    } else {
        mm.remove(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS);
    }
    mm.putSingle(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, HttpHeaders.Value.ASTERISK);
    // X-Dc-Version
    mm.putSingle(HttpHeaders.X_DC_VERSION, DcCoreConfig.getCoreVersion());
}
 
Example #13
Source File: DcCoreContainerFilter.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * レスポンス全体に対してかけるフィルター.
 * @param request リクエスト
 * @param response フィルタ前レスポンス
 * @return フィルタ後レスポンス
 */
@Override
public ContainerResponse filter(final ContainerRequest request, final ContainerResponse response) {
    String cellId = (String) httpServletRequest.getAttribute("cellId");
    if (cellId != null) {
        CellLockManager.decrementReferenceCount(cellId);
    }

    // 全てのレスポンスに共通するヘッダを追加する
    addResponseHeaders(request, response);
    // レスポンスログを出力
    responseLog(response);
    return response;
}
 
Example #14
Source File: OperationExecutionJerseyServerInterceptor.java    From kieker with Apache License 2.0 5 votes vote down vote up
/**
 * Method to intercept outgoing response.
 *
 * @return value of the intercepted method
 */
@Around("execution(public void com.sun.jersey.spi.container.ContainerResponse.write())")
public Object operationWriteResponse(final ProceedingJoinPoint thisJoinPoint) throws Throwable { // NOCS (Throwable)
	if (!CTRLINST.isMonitoringEnabled()) {
		return thisJoinPoint.proceed();
	}
	final String signature = this.signatureToLongString(thisJoinPoint.getSignature());
	if (!CTRLINST.isProbeActivated(signature)) {
		return thisJoinPoint.proceed();
	}

	final long traceId = CF_REGISTRY.recallThreadLocalTraceId();

	if (traceId == -1) {
		// Kieker trace Id not registered. Should not happen, since this is a response message!
		LOGGER.warn("Kieker traceId not registered. Will unset all threadLocal variables and return.");
		return thisJoinPoint.proceed();
	}

	final String sessionId = SESSION_REGISTRY.recallThreadLocalSessionId();
	final ContainerResponse containerResponse = (ContainerResponse) thisJoinPoint.getTarget();
	final MultivaluedMap<String, Object> responseHeader = containerResponse.getHttpHeaders();

	// Pass back trace id, session id, eoi but not ess (use old value before the request)
	final List<Object> responseHeaderList = new ArrayList<>();
	responseHeaderList.add(Long.toString(traceId) + "," + sessionId + "," + Integer.toString(CF_REGISTRY.recallThreadLocalEOI()));
	responseHeader.put(JerseyHeaderConstants.OPERATION_EXECUTION_JERSEY_HEADER, responseHeaderList);
	LOGGER.debug("Sending response with header = {} to the request: {}", responseHeader.toString(), containerResponse.getContainerRequest().getRequestUri());

	return thisJoinPoint.proceed();
}
 
Example #15
Source File: HypermediaFilter.java    From Processor with Apache License 2.0 5 votes vote down vote up
@Override
public ContainerResponse filter(ContainerRequest request, ContainerResponse response)
{
    if (request == null) throw new IllegalArgumentException("ContainerRequest cannot be null");
    if (response == null) throw new IllegalArgumentException("ContainerResponse cannot be null");
    
    // do not process hypermedia if the response is a redirect or 201 Created or 404 Not Found
    if (response.getStatusType().getFamily().equals(REDIRECTION) || response.getStatusType().equals(CREATED) ||
            response.getStatusType().equals(NOT_FOUND) || response.getStatusType().equals(INTERNAL_SERVER_ERROR) || 
            response.getEntity() == null || (!(response.getEntity() instanceof Dataset)))
        return response;
    
    TemplateCall templateCall = getTemplateCall();
    if (templateCall == null) return response;
    
    Resource state = templateCall.build();
    Resource absolutePath = state.getModel().createResource(request.getAbsolutePath().toString());
    if (!state.equals(absolutePath)) state.addProperty(C.stateOf, absolutePath);

    Resource requestUri = state.getModel().createResource(request.getRequestUri().toString());
    if (!state.equals(requestUri)) // add hypermedia if there are query parameters
        state.addProperty(C.viewOf, requestUri). // needed to lookup response state by request URI without redirection
            addProperty(RDF.type, C.View);

    if (log.isDebugEnabled()) log.debug("Added Number of HATEOAS statements added: {}", state.getModel().size());
    Dataset newEntity = ((Dataset)response.getEntity());
    newEntity.getDefaultModel().add(state.getModel());
    response.setEntity(newEntity);
    
    return response;
}
 
Example #16
Source File: AuthenticationResourceFilter.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Override
public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
    Subject subject = ThreadContext.getSubject();
    if (subject != null) {
        if (subject.isAuthenticated()) {
            subject.logout();
        }
        ThreadContext.unbindSubject();
    }
    return response;
}
 
Example #17
Source File: RequestWrapper.java    From titan-web-example with Apache License 2.0 4 votes vote down vote up
/**
 * Executed after every servlet returns, even if there is an exception.
 */
@Override
public ContainerResponse filter(ContainerRequest containerRequest, ContainerResponse containerResponse) {
    g.tx().rollback(); // perform a rollback to clean up any dangling transactions
    return containerResponse;
}
 
Example #18
Source File: PostProcessFilter.java    From secure-data-service with Apache License 2.0 4 votes vote down vote up
@Override
public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
    if (isRead(request.getMethod()) && isSuccessfulRead(response.getStatus())) {
        if (contextValidator.isUrlBlocked(request)) {
            throw new APIAccessDeniedException(String.format("url %s is not accessible.", request.getAbsolutePath().toString()));
        }

        SLIPrincipal principal = (SLIPrincipal) SecurityContextHolder.getContext().getAuthentication()
                .getPrincipal();
        principal.setSubEdOrgHierarchy(edOrgHelper.getStaffEdOrgsAndChildren());
        contextValidator.validateContextToUri(request, principal);
    }

    SecurityContextHolder.clearContext();

    if ("true".equals(apiPerformanceTracking)) {
        logApiDataToDb(request, response);
    }
    TenantContext.cleanup();
    printElapsed(request);
    expireCache();

    String queryString = "";
    if (null != request.getRequestUri().getQuery()) {
        queryString = "?" + request.getRequestUri().getQuery();
    }
    String executedPath = request.getPath() + queryString;

    // Truncate the executed path to avoid issues with response header length being too long for the servlet container
    if (executedPath != null && executedPath.length() > maxResponseHeaderXexecutedPath) {
        executedPath = executedPath.substring(0, Math.min(executedPath.length(), maxResponseHeaderXexecutedPath));
    }

    response.getHttpHeaders().add("X-RequestedPath", request.getProperties().get("requestedPath"));
    response.getHttpHeaders().add("X-ExecutedPath", executedPath);

    //        Map<String,Object> body = (Map<String, Object>) response.getEntity();
    //        body.put("requestedPath", request.getProperties().get("requestedPath"));
    //        body.put("executedPath", request.getPath());

    return response;
}
 
Example #19
Source File: UnbufferedStreamResourceFilterFactory.java    From emodb with Apache License 2.0 4 votes vote down vote up
@Override
public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
    response.getHttpHeaders().putSingle(UnbufferedStreamFilter.UNBUFFERED_HEADER, "true");
    return response;
}
 
Example #20
Source File: ConcurrentRequestsThrottlingFilter.java    From emodb with Apache License 2.0 4 votes vote down vote up
@Override
public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
    _regulatorSupplier.forRequest(request).release(request);
    return response;
}
 
Example #21
Source File: StaashAuditFilter.java    From staash with Apache License 2.0 3 votes vote down vote up
public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
	
	Logger.info("StaashAuditFilter POST");
	
	StaashRequestContext.addContext("STATUS", String.valueOf(response.getStatus()));
	StaashRequestContext.recordRequestEnd();
	StaashRequestContext.flushRequestContext();
	
	// Add RequestId to response
	addRequestIdToResponse(response);
	
	return response;
}