當前位置: 首頁>>代碼示例>>Java>>正文


Java RequestInfo類代碼示例

本文整理匯總了Java中com.nike.riposte.server.http.RequestInfo的典型用法代碼示例。如果您正苦於以下問題:Java RequestInfo類的具體用法?Java RequestInfo怎麽用?Java RequestInfo使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


RequestInfo類屬於com.nike.riposte.server.http包,在下文中一共展示了RequestInfo類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: filterResponse

import com.nike.riposte.server.http.RequestInfo; //導入依賴的package包/類
@Override
public <T> ResponseInfo<T> filterResponse(ResponseInfo<T> currentResponseInfo, RequestInfo<?> requestInfo,
                                          ChannelHandlerContext ctx) {
    try {
        if (requestInfo != null && requestInfo.getRequestAttributes() != null) {
            HystrixRequestContext context = (HystrixRequestContext) requestInfo.getRequestAttributes().get(HYSTRIX_REQUEST_CONTEXT);
            if (context != null) {
                context.shutdown();
            }
        }
    } catch (Throwable t) {
        logger.error("An unexpected error occurred trying to shutdown the HystrixRequestContext for this request.", t);
    }

    // Returning null just means use the passed-in response, which is what we want.
    return null;
}
 
開發者ID:Nike-Inc,項目名稱:cerberus-management-service,代碼行數:18,代碼來源:HystrixRequestAndResponseFilter.java

示例2: doExecute

import com.nike.riposte.server.http.RequestInfo; //導入依賴的package包/類
@Override
public CompletableFuture<ResponseInfo<Void>> doExecute(final RequestInfo<CleanUpRequest> request,
                                                       final Executor longRunningTaskExecutor,
                                                       final ChannelHandlerContext ctx,
                                                       final SecurityContext securityContext) {

    final VaultAuthPrincipal vaultAuthPrincipal = (VaultAuthPrincipal) securityContext.getUserPrincipal();
    final String principal = vaultAuthPrincipal.getName();

    log.info("Clean Up Event: the principal {} is attempting to clean up kms keys", principal);

    longRunningTaskExecutor.execute(AsyncNettyHelper.runnableWithTracingAndMdc(
            () -> cleanUpService.cleanUp(request.getContent()),
            ctx
    ));

    return CompletableFuture.completedFuture(
            ResponseInfo.<Void>newBuilder()
                    .withHttpStatusCode(HttpResponseStatus.NO_CONTENT.code())
                    .build()
    );
}
 
開發者ID:Nike-Inc,項目名稱:cerberus-management-service,代碼行數:23,代碼來源:CleanUpInactiveOrOrphanedRecords.java

示例3: processError

import com.nike.riposte.server.http.RequestInfo; //導入依賴的package包/類
/**
 * Attempts to process the given error using the "normal" error handler {@link #riposteErrorHandler} to produce the
 * most specific error response possible for the given error. If that fails for any reason then the unhandled error
 * handler will take over to guarantee the user gets a generic error response that still follows our error contract.
 * If you already know your error is a non-normal unhandled error of the "how did we get here, this should never
 * happen" variety you can (and should) directly call {@link #processUnhandledError(HttpProcessingState, Object,
 * Throwable)} instead.
 */
protected ResponseInfo<ErrorResponseBody> processError(HttpProcessingState state,
                                                       Object msg,
                                                       Throwable cause) throws JsonProcessingException {
    RequestInfo<?> requestInfo = getRequestInfo(state, msg);

    try {
        ErrorResponseInfo contentFromErrorHandler = riposteErrorHandler.maybeHandleError(cause, requestInfo);
        if (contentFromErrorHandler != null) {
            // The regular error handler did handle the error. Setup our ResponseInfo.
            ResponseInfo<ErrorResponseBody> responseInfo = new FullResponseInfo<>();
            setupResponseInfoBasedOnErrorResponseInfo(responseInfo, contentFromErrorHandler);
            return responseInfo;
        }
    }
    catch (Throwable errorHandlerFailed) {
        logger.error("An unexpected problem occurred while trying to handle an error.", errorHandlerFailed);
    }

    // If we reach here then it means the regular handler didn't handle the error (or blew up trying to handle it),
    //      so the riposteUnhandledErrorHandler should take care of it.
    return processUnhandledError(state, msg, cause);
}
 
開發者ID:Nike-Inc,項目名稱:riposte,代碼行數:31,代碼來源:ExceptionHandlingHandler.java

示例4: execute

import com.nike.riposte.server.http.RequestInfo; //導入依賴的package包/類
@Override
public CompletableFuture<ResponseInfo<String>> execute(RequestInfo<SerializableObject> request, Executor longRunningTaskExecutor, ChannelHandlerContext ctx) {
    if (request.getContent() == null) {
        throw new IllegalStateException(
            "getContent() should return a non-null value for deserializable content. getRawContent(): " + request.getRawContent());
    }

    verifyIncomingPayloadByteHash(request, true);

    try {
        SerializableObject widget = request.getContent();
        String widgetAsString = objectMapper.writeValueAsString(widget);
        if (!widgetAsString.equals(request.getRawContent())) {
            throw new IllegalArgumentException("Expected serialized widget to match getRawContent(), but it didn't. serialized widget string: " +
                                               widgetAsString + ", getRawContent(): " + request.getRawContent());
        }
    } catch (JsonProcessingException e) {
        throw new RuntimeException(e);
    }

    return CompletableFuture.completedFuture(ResponseInfo.newBuilder(responseMessage()).build());
}
 
開發者ID:Nike-Inc,項目名稱:riposte,代碼行數:23,代碼來源:VerifyPayloadHandlingComponentTest.java

示例5: validateSecureRequestForEndpoint_does_nothing_if_validationMap_returns_null_or_empty

import com.nike.riposte.server.http.RequestInfo; //導入依賴的package包/類
@DataProvider(value = {
    "true",
    "false"
}, splitBy = "\\|")
@Test
public void validateSecureRequestForEndpoint_does_nothing_if_validationMap_returns_null_or_empty(boolean useNull) {
    // given
    setupMultipleEndpointsAndMultipleValidators();
    List<RequestSecurityValidator> mappedValidators = (useNull) ? null : Collections.emptyList();
    validator.validationMap.put(mockEndpoint, mappedValidators);
    reset(innerValidatorOne);
    reset(innerValidatorTwo);

    // when
    validator.validateSecureRequestForEndpoint(mock(RequestInfo.class), mockEndpoint);

    // then
    verifyZeroInteractions(innerValidatorOne);
    verifyZeroInteractions(innerValidatorTwo);
}
 
開發者ID:Nike-Inc,項目名稱:riposte,代碼行數:21,代碼來源:PolymorphicSecurityValidatorTest.java

示例6: verifyIncomingPayloadByteHash

import com.nike.riposte.server.http.RequestInfo; //導入依賴的package包/類
public static void verifyIncomingPayloadByteHash(RequestInfo<?> request, boolean verifyRawStringMatchesByteHashAlso) {
    String expectedPayloadHash = request.getHeaders().get(REQUEST_PAYLOAD_HASH_HEADER_KEY);
    if (expectedPayloadHash == null)
        throw new IllegalArgumentException("Expected to receive " + REQUEST_PAYLOAD_HASH_HEADER_KEY + " header, but none was found.");

    String actualBytesHash = getHashForPayload(request.getRawContentBytes());
    if (!actualBytesHash.equals(expectedPayloadHash)) {
        throw new IllegalArgumentException(
            String.format("Actual byte[] payload hash (%s) did not match expected payload hash (%s)", actualBytesHash, expectedPayloadHash));
    }

    if (verifyRawStringMatchesByteHashAlso) {
        String actualRawStringHash = getHashForPayload(request.getRawContent().getBytes(CharsetUtil.UTF_8));
        if (!actualRawStringHash.equals(expectedPayloadHash)) {
            throw new IllegalArgumentException(
                String.format("Actual raw string payload hash (%s) did not match expected payload hash (%s)", actualRawStringHash, expectedPayloadHash));
        }
    }
}
 
開發者ID:Nike-Inc,項目名稱:riposte,代碼行數:20,代碼來源:VerifyPayloadHandlingComponentTest.java

示例7: getRequestInfo

import com.nike.riposte.server.http.RequestInfo; //導入依賴的package包/類
/**
 * Tries to extract the {@link RequestInfo} associated with the current request using the given arguments. First it
 * will try to get it from the given state. If that fails, it will try to create a new one based on the given msg
 * (which only works if the msg is a {@link HttpRequest}). If that also fails then a new dummy instance for an
 * unknown request will be created via {@link RequestInfoImpl#dummyInstanceForUnknownRequests()} and returned.
 */
RequestInfo<?> getRequestInfo(HttpProcessingState state, Object msg) {
    // Try to get the RequestInfo from the state variable first.
    RequestInfo requestInfo = state.getRequestInfo();

    // If the state did not have a request info, see if we can build one from the msg
    if (requestInfo == null && msg != null && (msg instanceof HttpRequest))
        requestInfo = new RequestInfoImpl((HttpRequest) msg);

    // If requestInfo is still null then something major blew up, and we just need to create a dummy one for an
    //      unknown request
    if (requestInfo == null)
        requestInfo = RequestInfoImpl.dummyInstanceForUnknownRequests();

    return requestInfo;
}
 
開發者ID:Nike-Inc,項目名稱:riposte,代碼行數:22,代碼來源:ExceptionHandlingHandler.java

示例8: onEvent_should_short_circuit_for_RESPONSE_SENT_if_request_start_time_is_null

import com.nike.riposte.server.http.RequestInfo; //導入依賴的package包/類
@Test
public void onEvent_should_short_circuit_for_RESPONSE_SENT_if_request_start_time_is_null() {
    // given
    state.setRequestStartTime(null);

    // when
    listener.onEvent(ServerMetricsEvent.RESPONSE_SENT, state);

    // then
    // Inflight requests and processed requests counters should still be adjusted properly
    verify(listener.inflightRequests).dec();
    verify(listener.processedRequests).inc();
    // But we should short circuit immediately afterward
    verifyZeroInteractions(listener.requestSizes, listener.responseSizes);
    verify(endpointMetricsHandlerMock, never()).handleRequest(
        any(RequestInfo.class), any(ResponseInfo.class), any(HttpProcessingState.class), anyInt(), anyInt(), anyLong()
    );
}
 
開發者ID:Nike-Inc,項目名稱:riposte,代碼行數:19,代碼來源:CodahaleMetricsListenerTest.java

示例9: matchesMethod_works_as_expected_for_known_data

import com.nike.riposte.server.http.RequestInfo; //導入依賴的package包/類
@Test
@DataProvider(value = {
        "GET,POST   |   GET     |   true",
        "GET,POST   |   POST    |   true",
        "GET,POST   |   PUT     |   false",
        "GET,POST   |   null    |   false"
}, splitBy = "\\|")
public void matchesMethod_works_as_expected_for_known_data(String matcherMethodStrings, String requestMethodString, boolean expectedMatchValue) {
    // given
    List<HttpMethod> matcherMethods = Arrays.asList(matcherMethodStrings.split(",")).stream().map(HttpMethod::valueOf).collect(Collectors.toList());
    Collection<String> paths = new ArrayList<String>() {{ add("/foo"); }};
    MultiMatcher matcher = MultiMatcher.match(paths, matcherMethods);
    RequestInfo<?> requestInfo = RequestInfoImpl.dummyInstanceForUnknownRequests();
    if (requestMethodString == null)
        Whitebox.setInternalState(requestInfo, "method", null);
    else
        Whitebox.setInternalState(requestInfo, "method", HttpMethod.valueOf(requestMethodString));

    // expect
    assertThat(matcher.matchesMethod(requestInfo), is(expectedMatchValue));
}
 
開發者ID:Nike-Inc,項目名稱:riposte,代碼行數:22,代碼來源:MultiMatcherTest.java

示例10: filterResponse

import com.nike.riposte.server.http.RequestInfo; //導入依賴的package包/類
@Override
public <T> ResponseInfo<T> filterResponse(ResponseInfo<T> responseInfo, RequestInfo<?> requestInfo, ChannelHandlerContext ctx) {
    // Indicate whether or not the first/last chunk request methods were executed for this filter
    //      so that the caller can assert based on what it expects.
    setHeader(responseInfo,
              firstChunkReqMethodExecutedKey,
              requestAttributeIsSetToTrue(requestInfo, firstChunkReqMethodExecutedKey));

    setHeader(responseInfo,
              lastChunkReqMethodExecutedKey,
              requestAttributeIsSetToTrue(requestInfo, lastChunkReqMethodExecutedKey));

    // Indicate whether or not the security validator was called, and whether or not it threw an exception.
    setHeader(responseInfo,
              SECURITY_VALIDATOR_EXECUTED_HEADER_KEY,
              requestAttributeIsSetToTrue(requestInfo, SECURITY_VALIDATOR_EXECUTED_HEADER_KEY));
    setHeader(responseInfo,
              SECURITY_VALIDATOR_THREW_ERROR_HEADER_KEY,
              requestAttributeIsSetToTrue(requestInfo, SECURITY_VALIDATOR_THREW_ERROR_HEADER_KEY));

    // Add a header so the caller knows the response method for this filter was executed.
    setHeader(responseInfo, responseMethodExecutedKey, responseMethodExecutedPayload);
    return responseInfo;
}
 
開發者ID:Nike-Inc,項目名稱:riposte,代碼行數:25,代碼來源:VerifyBeforeAndAfterSecurityRequestAndResponseFiltersComponentTest.java

示例11: test_validateSecureRequestForEndpoint_adds_security_context_to_request

import com.nike.riposte.server.http.RequestInfo; //導入依賴的package包/類
@Test
public void test_validateSecureRequestForEndpoint_adds_security_context_to_request() {
    final RequestInfo<Void> requestInfo = mock(RequestInfo.class);
    when(requestInfo.getUri()).thenReturn("https://localhost");
    final HttpHeaders httpHeaders = new DefaultHttpHeaders();
    httpHeaders.add(CmsRequestSecurityValidator.HEADER_X_VAULT_TOKEN, vaultToken);
    when(requestInfo.getHeaders()).thenReturn(httpHeaders);

    final Map<String, String> meta = Maps.newHashMap();
    meta.put(VaultAuthPrincipal.METADATA_KEY_IS_ADMIN, Boolean.TRUE.toString());
    meta.put(VaultAuthPrincipal.METADATA_KEY_USERNAME, "username");
    meta.put(VaultAuthPrincipal.METADATA_KEY_GROUPS, "group1,group2");
    final VaultClientTokenResponse clientTokenResponse = new VaultClientTokenResponse()
            .setId(vaultToken)
            .setMeta(meta);
    when(vaultAdminClient.lookupToken(vaultToken)).thenReturn(clientTokenResponse);

    subject.validateSecureRequestForEndpoint(requestInfo, securedEndpoint);

    verify(requestInfo).addRequestAttribute(eq(SECURITY_CONTEXT_ATTR_KEY), any(SecurityContext.class));
}
 
開發者ID:Nike-Inc,項目名稱:cerberus-management-service,代碼行數:22,代碼來源:CmsRequestSecurityValidatorTest.java

示例12: test_getSecurityContextForRequest_returns_optional_populated_with_security_context

import com.nike.riposte.server.http.RequestInfo; //導入依賴的package包/類
@Test
public void test_getSecurityContextForRequest_returns_optional_populated_with_security_context() {
    final RequestInfo<?> requestInfo = mock(RequestInfo.class);
    final Map<String, Object> requestAttributes = Maps.newHashMap();
    final Map<String, String> meta = Maps.newHashMap();
    meta.put(VaultAuthPrincipal.METADATA_KEY_IS_ADMIN, Boolean.TRUE.toString());
    meta.put(VaultAuthPrincipal.METADATA_KEY_USERNAME, "username");
    meta.put(VaultAuthPrincipal.METADATA_KEY_GROUPS, "group1,group2");
    final VaultAuthPrincipal authPrincipal = new VaultAuthPrincipal(new VaultClientTokenResponse().setMeta(meta));
    requestAttributes.put(SECURITY_CONTEXT_ATTR_KEY,
            new VaultSecurityContext(authPrincipal, "https"));

    when(requestInfo.getRequestAttributes()).thenReturn(requestAttributes);

    final Optional<SecurityContext> securityContext =
            CmsRequestSecurityValidator.getSecurityContextForRequest(requestInfo);

    assertThat(securityContext).isPresent();
    assertThat(securityContext.get()).isInstanceOf(VaultSecurityContext.class);
}
 
開發者ID:Nike-Inc,項目名稱:cerberus-management-service,代碼行數:21,代碼來源:CmsRequestSecurityValidatorTest.java

示例13: beforeMethod

import com.nike.riposte.server.http.RequestInfo; //導入依賴的package包/類
@Before
public void beforeMethod() {
    stateMock = mock(HttpProcessingState.class);
    ctxMock = mock(ChannelHandlerContext.class);
    channelMock = mock(Channel.class);
    stateAttrMock = mock(Attribute.class);
    metricsListenerMock = mock(MetricsListener.class);
    msgMock = mock(HttpRequest.class);
    responseSenderMock = mock(ResponseSender.class);
    responseInfo = ResponseInfo.newBuilder(UUID.randomUUID().toString()).build();
    endpointExecutedMock = mock(Endpoint.class);
    customSerializerMock = mock(ObjectMapper.class);

    doReturn(channelMock).when(ctxMock).channel();
    doReturn(stateAttrMock).when(channelMock).attr(ChannelAttributes.HTTP_PROCESSING_STATE_ATTRIBUTE_KEY);
    doReturn(stateMock).when(stateAttrMock).get();
    doReturn(responseInfo).when(stateMock).getResponseInfo();
    doReturn(endpointExecutedMock).when(stateMock).getEndpointForExecution();
    doReturn(customSerializerMock).when(endpointExecutedMock).customResponseContentSerializer(any(RequestInfo.class));

    handlerSpy = spy(new ResponseSenderHandler(responseSenderMock));
}
 
開發者ID:Nike-Inc,項目名稱:riposte,代碼行數:23,代碼來源:ResponseSenderHandlerTest.java

示例14: doReturn

import com.nike.riposte.server.http.RequestInfo; //導入依賴的package包/類
@DataProvider(value = {
    "OPTIONS    |   true",
    "GET        |   false",
    "POST       |   false",
    "PUT        |   false"
}, splitBy = "\\|")
@Test
public void filterRequestFirstChunkWithOptionalShortCircuitResponse_short_circuits_on_CORS_preflight_OPTIONS_request(String httpMethodString, boolean expectShortCircuit) {
    // given
    HttpMethod method = HttpMethod.valueOf(httpMethodString);
    doReturn(method).when(requestMock).getMethod();

    // when
    Pair<RequestInfo<?>, Optional<ResponseInfo<?>>> result = filter.filterRequestFirstChunkWithOptionalShortCircuitResponse(requestMock, ctxMock);

    // then
    if (expectShortCircuit) {
        assertThat(result).isNotNull();
        assertThat(result.getLeft()).isSameAs(requestMock);
        assertThat(result.getRight()).isPresent();
        assertThat(result.getRight().get().getHttpStatusCode()).isEqualTo(200);
    }
    else
        assertThat(result).isNull();
}
 
開發者ID:Nike-Inc,項目名稱:riposte,代碼行數:26,代碼來源:AllowAllTheThingsCORSFilterTest.java

示例15: execute_validates_user_is_admin

import com.nike.riposte.server.http.RequestInfo; //導入依賴的package包/類
@Test
public void execute_validates_user_is_admin() {
    final Map<String, Object> requestAttributes = Maps.newHashMap();
    final Map<String, String> meta = Maps.newHashMap();
    meta.put(VaultAuthPrincipal.METADATA_KEY_IS_ADMIN, Boolean.TRUE.toString());
    meta.put(VaultAuthPrincipal.METADATA_KEY_USERNAME, "username");
    meta.put(VaultAuthPrincipal.METADATA_KEY_GROUPS, "group1,group2");
    final VaultAuthPrincipal authPrincipal = new VaultAuthPrincipal(new VaultClientTokenResponse().setMeta(meta));
    requestAttributes.put(CmsRequestSecurityValidator.SECURITY_CONTEXT_ATTR_KEY,
            new VaultSecurityContext(authPrincipal, "https"));
    final RequestInfo<Void> requestInfo = mock(RequestInfo.class);
    when(requestInfo.getRequestAttributes()).thenReturn(requestAttributes);

    final CompletableFuture<ResponseInfo<Void>> completableFuture = subject.execute(requestInfo, executor, null);
    final ResponseInfo<Void> responseInfo = completableFuture.join();

    assertThat(responseInfo.getHttpStatusCode()).isEqualTo(HttpResponseStatus.OK.code());
}
 
開發者ID:Nike-Inc,項目名稱:cerberus-management-service,代碼行數:19,代碼來源:AdminStandardEndpointTest.java


注:本文中的com.nike.riposte.server.http.RequestInfo類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。