javax.ws.rs.client.ClientRequestFilter Java Examples

The following examples show how to use javax.ws.rs.client.ClientRequestFilter. 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: RestClientProcessor.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@BuildStep
@Record(ExecutionTime.STATIC_INIT)
void setup(BuildProducer<FeatureBuildItem> feature,
        BuildProducer<AdditionalBeanBuildItem> additionalBeans,
        BuildProducer<ReflectiveClassBuildItem> reflectiveClass,
        RestClientRecorder restClientRecorder) {

    feature.produce(new FeatureBuildItem(Feature.REST_CLIENT));

    restClientRecorder.setRestClientBuilderResolver();

    additionalBeans.produce(new AdditionalBeanBuildItem(RestClient.class));

    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false,
            DefaultResponseExceptionMapper.class.getName(),
            AsyncInterceptorRxInvokerProvider.class.getName(),
            ResteasyProviderFactoryImpl.class.getName(),
            ProxyBuilderImpl.class.getName(),
            ClientRequestFilter[].class.getName(),
            ClientResponseFilter[].class.getName(),
            javax.ws.rs.ext.ReaderInterceptor[].class.getName()));

    reflectiveClass.produce(new ReflectiveClassBuildItem(true, false,
            ResteasyClientBuilder.class.getName()));
}
 
Example #2
Source File: JAXRS20ClientServerBookTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetSetEntityStreamLambda() {
    String address = "http://localhost:" + PORT + "/bookstore/entityecho";
    String entity = "BOOKSTORE";

    Client client = ClientBuilder.newClient();
    client.register((ClientRequestFilter) context -> {
        context.setEntityStream(new ReplacingOutputStream(context.getEntityStream(), 'X', 'O'));
    });

    WebTarget target = client.target(address);

    Response response = target.request().post(
            Entity.entity(entity.replace('O', 'X'), "text/plain"));
    assertEquals(entity, response.readEntity(String.class));
}
 
Example #3
Source File: JAXRS20ClientServerBookTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetSetEntityStream() {
    String address = "http://localhost:" + PORT + "/bookstore/entityecho";
    String entity = "BOOKSTORE";

    Client client = ClientBuilder.newClient();
    client.register(new ClientRequestFilter() {
        @Override
        public void filter(ClientRequestContext context) throws IOException {
            context.setEntityStream(new ReplacingOutputStream(
                             context.getEntityStream(), 'X', 'O'));
        }
    });

    WebTarget target = client.target(address);

    Response response = target.request().post(
            Entity.entity(entity.replace('O', 'X'), "text/plain"));
    assertEquals(entity, response.readEntity(String.class));
}
 
Example #4
Source File: JAXRS20ClientServerBookTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testClientFiltersLocalResponseLambdas() {
    String address = "http://localhost:" + PORT + "/bookstores";
    WebClient wc = WebClient.create(address, Arrays.asList(
        (ClientRequestFilter) ctx -> {
            ctx.abortWith(Response.status(201).entity(ctx.getEntity()).type(MediaType.TEXT_XML_TYPE).build());
        },
        (ClientResponseFilter) (reqContext, respContext) -> {
            MultivaluedMap<String, String> headers = respContext.getHeaders();
            headers.putSingle(HttpHeaders.LOCATION, "http://localhost/redirect");
        }));
    Book theBook = new Book("Echo", 123L);
    Response r = wc.post(theBook);
    assertEquals(201, r.getStatus());
    assertEquals("http://localhost/redirect", r.getHeaderString(HttpHeaders.LOCATION));
    Book responseBook = r.readEntity(Book.class);
    assertSame(theBook, responseBook);
}
 
Example #5
Source File: EtcdV2ProxyImpl.java    From etcd-viewer with Apache License 2.0 6 votes vote down vote up
private WebTarget getWebTarget() {
    if (client == null) {
        client = ClientBuilder.newClient();
        client.register(JacksonJsonProvider.class);

        // register the basic authentication filter if authentication information is provided
        if (authenticationToken != null) {
            client.register(new ClientRequestFilter() {
                @Override
                public void filter(ClientRequestContext requestContext) throws IOException {
                    requestContext.getHeaders().add("Authorization", "Basic " + authenticationToken);
                }
            });
        }

    }

    WebTarget target = client.target(targetUrl);

    return target;
}
 
Example #6
Source File: JerseyJaxRsClientFactory.java    From vespa with Apache License 2.0 6 votes vote down vote up
public JerseyJaxRsClientFactory(SSLContext sslContext, HostnameVerifier hostnameVerifier, String userAgent) {
    /*
     * Configure client with some workarounds for HTTP/JAX-RS/Jersey issues. See:
     *   https://jersey.java.net/apidocs/latest/jersey/org/glassfish/jersey/client/ClientProperties.html#SUPPRESS_HTTP_COMPLIANCE_VALIDATION
     *   https://jersey.java.net/apidocs/latest/jersey/org/glassfish/jersey/client/HttpUrlConnectorProvider.html#SET_METHOD_WORKAROUND
     */
    ClientBuilder builder = ClientBuilder.newBuilder()
                                         .property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true) // Allow empty PUT. TODO: Fix API.
                                         .property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true) // Allow e.g. PATCH method.
                                         .property(ClientProperties.FOLLOW_REDIRECTS, true);
    if (sslContext != null) {
        builder.sslContext(sslContext);
    }
    if (hostnameVerifier != null) {
        builder.hostnameVerifier(hostnameVerifier);
    }
    if (userAgent != null) {
        builder.register((ClientRequestFilter) context -> context.getHeaders().put(HttpHeaders.USER_AGENT, Collections.singletonList(userAgent)));
    }
    this.client = builder.build();
}
 
Example #7
Source File: TwitterShowUserServlet.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private TwitterOAuthResponse getTwitterOAuthResponse(final HttpServletRequest req) {
    ClientRequestFilter authFilter = new ClientRequestFilter() {
        @Override
        public void filter(ClientRequestContext requestContext) throws IOException {
            KeycloakSecurityContext securityContext = (KeycloakSecurityContext) req.getAttribute(KeycloakSecurityContext.class.getName());
            String accessToken = securityContext.getTokenString();

            requestContext.getHeaders().add(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken);
        }
    };

    Client client = ClientBuilder.newBuilder().register(authFilter).build();
    WebTarget target = client.target(getIdentityProviderTokenUrl());

    return target.request().get().readEntity(TwitterOAuthResponse.class);
}
 
Example #8
Source File: AdditionalRegistrationTest.java    From microprofile-rest-client with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRegisterAMultiTypedProviderClassWithPriorities() {
    Map<Class<?>, Integer> priorities = new HashMap<>();
    priorities.put(ClientRequestFilter.class, 500);
    priorities.put(ClientResponseFilter.class, 501);
    priorities.put(MessageBodyReader.class, 502);
    priorities.put(MessageBodyWriter.class, 503);
    priorities.put(ReaderInterceptor.class, 504);
    priorities.put(WriterInterceptor.class, 505);
    priorities.put(ResponseExceptionMapper.class, 506);
    priorities.put(ParamConverterProvider.class, 507);
    RestClientBuilder builder = RestClientBuilder.newBuilder().register(MultiTypedProvider.class, priorities);
    Configuration configuration = builder.getConfiguration();
    assertTrue(configuration.isRegistered(MultiTypedProvider.class), MultiTypedProvider.class + " should be registered");
    Map<Class<?>, Integer> contracts = configuration.getContracts(MultiTypedProvider.class);
    assertEquals(contracts.size(), priorities.size(),
        "There should be "+priorities.size()+" provider types registered");
    for(Map.Entry<Class<?>, Integer> priority : priorities.entrySet()) {
        Integer contractPriority = contracts.get(priority.getKey());
        assertEquals(contractPriority, priority.getValue(), "The priority for "+priority.getKey()+" should be "+priority.getValue());
    }
}
 
Example #9
Source File: AdditionalRegistrationTest.java    From microprofile-rest-client with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRegisterAMultiTypedProviderInstanceWithPriorities() {
    MultiTypedProvider provider = new MultiTypedProvider();
    Map<Class<?>, Integer> priorities = new HashMap<>();
    priorities.put(ClientRequestFilter.class, 500);
    priorities.put(ClientResponseFilter.class, 501);
    priorities.put(MessageBodyReader.class, 502);
    priorities.put(MessageBodyWriter.class, 503);
    priorities.put(ReaderInterceptor.class, 504);
    priorities.put(WriterInterceptor.class, 505);
    priorities.put(ResponseExceptionMapper.class, 506);
    priorities.put(ParamConverterProvider.class, 507);
    RestClientBuilder builder = RestClientBuilder.newBuilder().register(provider, priorities);
    Configuration configuration = builder.getConfiguration();
    assertTrue(configuration.isRegistered(MultiTypedProvider.class), MultiTypedProvider.class + " should be registered");
    assertTrue(configuration.isRegistered(provider), MultiTypedProvider.class + " should be registered");
    Map<Class<?>, Integer> contracts = configuration.getContracts(MultiTypedProvider.class);
    assertEquals(contracts.size(), priorities.size(),
        "There should be "+priorities.size()+" provider types registered");
    for(Map.Entry<Class<?>, Integer> priority : priorities.entrySet()) {
        Integer contractPriority = contracts.get(priority.getKey());
        assertEquals(contractPriority, priority.getValue(), "The priority for "+priority.getKey()+" should be "+priority.getValue());
    }
}
 
Example #10
Source File: OAuthResource.java    From clouditor with Apache License 2.0 5 votes vote down vote up
private TokenResponse retrieveAccessToken(String code) {
  var tokenUrl = this.engine.getOAuthTokenUrl();

  LOGGER.info("Trying to retrieve access token from {}", tokenUrl);

  var uri =
      UriBuilder.fromUri(tokenUrl)
          .queryParam("grant_type", "authorization_code")
          .queryParam("code", code)
          .build();

  var client =
      ClientBuilder.newClient()
          .register(
              (ClientRequestFilter)
                  requestContext -> {
                    var headers = requestContext.getHeaders();
                    headers.add(
                        "Authorization",
                        "Basic "
                            + Base64.getEncoder()
                                .encodeToString(
                                    (this.engine.getOAuthClientId()
                                            + ":"
                                            + this.engine.getOAuthClientSecret())
                                        .getBytes()));
                  })
          .register(
              (ClientResponseFilter)
                  (requestContext, responseContext) -> {
                    // stupid workaround because some oauth servers incorrectly sends two
                    // Content-Type
                    // headers! fix it!
                    var contentType = responseContext.getHeaders().getFirst("Content-Type");
                    responseContext.getHeaders().putSingle("Content-Type", contentType);
                  });

  return client.target(uri).request().post(null, TokenResponse.class);
}
 
Example #11
Source File: ConfigurationImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testClientFilterWithNestedInterfacesIsAccepted() {
    try (ConfigurableImpl<Client> configurable 
            = new ConfigurableImpl<>(createClientProxy(), RuntimeType.CLIENT)) {
        Configuration config = configurable.getConfiguration();
        configurable.register(NestedInterfaceTestFilter.class);
        Map<Class<?>, Integer> contracts = config.getContracts(NestedInterfaceTestFilter.class);
        assertTrue(contracts.containsKey(ClientRequestFilter.class));
        assertTrue(contracts.containsKey(ClientResponseFilter.class));
    }
}
 
Example #12
Source File: ConfigurationImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testServerFilterContractsOnClientIsRejected() {
    try (ConfigurableImpl<Client> configurable 
            = new ConfigurableImpl<>(createClientProxy(), RuntimeType.CLIENT)) {
        Configuration config = configurable.getConfiguration();
        configurable.register(TestFilter.class);
        Map<Class<?>, Integer> contracts = config.getContracts(TestFilter.class);
        assertTrue(contracts.containsKey(ClientRequestFilter.class));
        assertTrue(contracts.containsKey(ClientResponseFilter.class));
        assertFalse(contracts.containsKey(ContainerRequestFilter.class));
        assertFalse(contracts.containsKey(ContainerResponseFilter.class));
    }
}
 
Example #13
Source File: ClientSetup.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Produces
@ApplicationScoped
@Http(Http.Type.TALEND_COMPONENT_KIT)
public Client serverClient(@Http(Http.Type.TALEND_COMPONENT_KIT) final ExecutorService executor) {
    ClientBuilder builder = createClient(executor, serverKeystoreLocation, serverKeystoreType,
            serverKeystorePassword, serverTruststoreType, serverHostnames);
    if (serverToken.isPresent()) {
        final String token = serverToken.get();
        builder = builder
                .register((ClientRequestFilter) requestContext -> requestContext
                        .getHeaders()
                        .putSingle(HttpHeaders.AUTHORIZATION, token));
    }
    return builder.build();
}
 
Example #14
Source File: AdditionalRegistrationTest.java    From microprofile-rest-client with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRegisterInstanceWithPriority() {
    Integer priority = 1000;
    TestClientRequestFilter instance = new TestClientRequestFilter();
    RestClientBuilder builder = RestClientBuilder.newBuilder().register(instance, priority);
    Configuration configuration = builder.getConfiguration();
    assertTrue(configuration.isRegistered(TestClientRequestFilter.class), TestClientRequestFilter.class + " should be registered");
    assertTrue(configuration.isRegistered(instance), TestClientRequestFilter.class + " should be registered");
    Map<Class<?>, Integer> contracts = configuration.getContracts(TestClientRequestFilter.class);
    assertEquals(contracts.size(), 1, "There should be a registered contract for "+TestClientRequestFilter.class);
    assertEquals(contracts.get(ClientRequestFilter.class), priority, "The priority for "+TestClientRequestFilter.class+" should be 1000");
}
 
Example #15
Source File: ConfigurationImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testClientFilterContractsOnServerFeatureIsRejected() {
    FeatureContextImpl featureContext = new FeatureContextImpl();
    Configurable<FeatureContext> configurable = new ConfigurableImpl<>(featureContext, RuntimeType.SERVER);
    featureContext.setConfigurable(configurable);
    featureContext.register(TestFilter.class);
    Configuration config = configurable.getConfiguration();
    Map<Class<?>, Integer> contracts = config.getContracts(TestFilter.class);
    assertFalse(contracts.containsKey(ClientRequestFilter.class));
    assertFalse(contracts.containsKey(ClientResponseFilter.class));
    assertTrue(contracts.containsKey(ContainerRequestFilter.class));
    assertTrue(contracts.containsKey(ContainerResponseFilter.class));
}
 
Example #16
Source File: MicroProfileClientFactoryBean.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Set<Object> processProviders() {
    Set<Object> providers = new LinkedHashSet<>();
    for (Object provider : configuration.getInstances()) {
        Class<?> providerCls = ClassHelper.getRealClass(getBus(), provider);
        if (provider instanceof ClientRequestFilter || provider instanceof ClientResponseFilter) {
            FilterProviderInfo<Object> filter = new FilterProviderInfo<>(providerCls, providerCls,
                    provider, getBus(), configuration.getContracts(providerCls));
            providers.add(filter);
        } else {
            providers.add(provider);
        }
    }
    return providers;
}
 
Example #17
Source File: ClientProviderFactory.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
protected void setProviders(boolean custom, boolean busGlobal, Object... providers) {
    List<ProviderInfo<? extends Object>> theProviders =
        prepareProviders(custom, busGlobal, providers, null);
    super.setCommonProviders(theProviders);
    for (ProviderInfo<? extends Object> provider : theProviders) {
        Class<?> providerCls = ClassHelper.getRealClass(getBus(), provider.getProvider());
        if (providerCls == Object.class) {
            // If the provider is a lambda, ClassHelper.getRealClass returns Object.class
            providerCls = provider.getProvider().getClass();
        }
        if (filterContractSupported(provider, providerCls, ClientRequestFilter.class)) {
            addProviderToList(clientRequestFilters, provider);
        }

        if (filterContractSupported(provider, providerCls, ClientResponseFilter.class)) {
            addProviderToList(clientResponseFilters, provider);
        }

        if (ResponseExceptionMapper.class.isAssignableFrom(providerCls)) {
            addProviderToList(responseExceptionMappers, provider);
        }

        if (RxInvokerProvider.class.isAssignableFrom(providerCls)) {
            this.rxInvokerProvider = RxInvokerProvider.class.cast(provider.getProvider());
        }
    }
    Collections.sort(clientRequestFilters,
                     new BindingPriorityComparator(ClientRequestFilter.class, true));
    Collections.sort(clientResponseFilters,
                     new BindingPriorityComparator(ClientResponseFilter.class, false));

    injectContextProxies(responseExceptionMappers, clientRequestFilters, clientResponseFilters);
}
 
Example #18
Source File: AdditionalRegistrationTest.java    From microprofile-rest-client with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRegisterAMultiTypedProviderInstance() {
    MultiTypedProvider provider = new MultiTypedProvider();
    Class<?>[] providerTypes = {ClientRequestFilter.class, ClientResponseFilter.class,
        MessageBodyReader.class, MessageBodyWriter.class, ReaderInterceptor.class, WriterInterceptor.class,
        ResponseExceptionMapper.class, ParamConverterProvider.class};
    RestClientBuilder builder = RestClientBuilder.newBuilder().register(provider, providerTypes);
    Configuration configuration = builder.getConfiguration();
    assertTrue(configuration.isRegistered(MultiTypedProvider.class), MultiTypedProvider.class + " should be registered");
    assertTrue(configuration.isRegistered(provider), MultiTypedProvider.class + " should be registered");
    assertEquals(configuration.getContracts(MultiTypedProvider.class).size(), providerTypes.length,
        "There should be "+providerTypes.length+" provider types registered");
}
 
Example #19
Source File: VespaJerseyJaxRsClientFactory.java    From vespa with Apache License 2.0 5 votes vote down vote up
public VespaJerseyJaxRsClientFactory(String userAgent) {
    this.client = clientBuilder.newBuilder()
            .property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true) // Allow empty PUT
            .property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true) // Allow e.g. PATCH method.
            .property(ClientProperties.FOLLOW_REDIRECTS, true)
            .register((ClientRequestFilter) context -> context.getHeaders().put(HttpHeaders.USER_AGENT, List.of(userAgent)))
            .build();
}
 
Example #20
Source File: ConfigConvergenceChecker.java    From vespa with Apache License 2.0 5 votes vote down vote up
private Client createClient(Duration timeout) {
    return clientBuilderFactory.newBuilder()
                        .register(
                                (ClientRequestFilter) ctx ->
                                        ctx.getHeaders().put(HttpHeaders.USER_AGENT, List.of("config-convergence-checker")))
                        .property(ClientProperties.CONNECT_TIMEOUT, (int) timeout.toMillis())
                        .property(ClientProperties.READ_TIMEOUT, (int) timeout.toMillis())
                        .build();
}
 
Example #21
Source File: AdditionalRegistrationTest.java    From microprofile-rest-client with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRegisterProvidersWithPriority() {
    Integer priority = 1000;
    RestClientBuilder builder = RestClientBuilder.newBuilder().register(TestClientRequestFilter.class, priority);
    Configuration configuration = builder.getConfiguration();
    assertTrue(configuration.isRegistered(TestClientRequestFilter.class), TestClientRequestFilter.class + " should be registered");
    Map<Class<?>, Integer> contracts = configuration.getContracts(TestClientRequestFilter.class);
    assertEquals(contracts.size(), 1, "There should be a registered contract for "+TestClientRequestFilter.class);
    assertEquals(contracts.get(ClientRequestFilter.class), priority, "The priority for "+TestClientRequestFilter.class+" should be 1000");
}
 
Example #22
Source File: AdditionalRegistrationTest.java    From microprofile-rest-client with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRegisterAMultiTypedProviderClass() {
    Class<?>[] providerTypes = {ClientRequestFilter.class, ClientResponseFilter.class,
        MessageBodyReader.class, MessageBodyWriter.class, ReaderInterceptor.class, WriterInterceptor.class,
        ResponseExceptionMapper.class, ParamConverterProvider.class};
    RestClientBuilder builder = RestClientBuilder.newBuilder().register(MultiTypedProvider.class, providerTypes);
    Configuration configuration = builder.getConfiguration();
    assertTrue(configuration.isRegistered(MultiTypedProvider.class), MultiTypedProvider.class + " should be registered");
    assertEquals(configuration.getContracts(MultiTypedProvider.class).size(), providerTypes.length,
        "There should be "+providerTypes.length+" provider types registered");
}
 
Example #23
Source File: ClientProviderFactory.java    From cxf with Apache License 2.0 4 votes vote down vote up
public List<ProviderInfo<ClientRequestFilter>> getClientRequestFilters() {
    return Collections.unmodifiableList(clientRequestFilters);
}
 
Example #24
Source File: ClientRequestFilterInterceptor.java    From cxf with Apache License 2.0 4 votes vote down vote up
public void handleMessage(Message outMessage) throws Fault {
    ClientProviderFactory pf = ClientProviderFactory.getInstance(outMessage);
    if (pf == null) {
        return;
    }

    // create an empty proxy output stream that the filter can interact with
    // and save a reference for later
    ProxyOutputStream pos = new ProxyOutputStream();
    outMessage.setContent(OutputStream.class, pos);
    outMessage.setContent(ProxyOutputStream.class, pos);

    List<ProviderInfo<ClientRequestFilter>> filters = pf.getClientRequestFilters();
    if (!filters.isEmpty()) {

        final Exchange exchange = outMessage.getExchange();
        final ClientRequestContext context = new ClientRequestContextImpl(outMessage, false);
        for (ProviderInfo<ClientRequestFilter> filter : filters) {
            InjectionUtils.injectContexts(filter.getProvider(), filter, outMessage);
            try {
                filter.getProvider().filter(context);

                @SuppressWarnings("unchecked")
                Map<String, List<Object>> headers = CastUtils.cast((Map<String, List<Object>>) 
                                                                   outMessage.get(Message.PROTOCOL_HEADERS));
                HttpUtils.convertHeaderValuesToString(headers, false);

                Response response = outMessage.getExchange().get(Response.class);
                if (response != null) {
                    outMessage.getInterceptorChain().abort();

                    Message inMessage = new MessageImpl();
                    inMessage.setExchange(exchange);
                    inMessage.put(Message.RESPONSE_CODE, response.getStatus());
                    inMessage.put(Message.PROTOCOL_HEADERS, response.getMetadata());
                    exchange.setInMessage(inMessage);

                    MessageObserver observer = exchange.get(MessageObserver.class);
                    observer.onMessage(inMessage);
                    return;
                }
            } catch (IOException ex) {
                throw new ProcessingException(ex);
            }
        }
    }
}
 
Example #25
Source File: ThreadLocalUserCrnWebTargetBuilder.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
public ThreadLocalUserCrnWebTargetBuilder withClientRequestFilter(ClientRequestFilter clientRequestFilter) {
    this.clientRequestFilter = clientRequestFilter;
    return this;
}
 
Example #26
Source File: AbstractAdvancedBrokerTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
/**
 * Refers to in old test suite: org.keycloak.testsuite.broker.AbstractKeycloakIdentityProviderTest#testTokenStorageAndRetrievalByApplication
 */
@Test
public void testRetrieveToken() throws Exception {
    updateExecutions(AbstractBrokerTest::enableRequirePassword);
    updateExecutions(AbstractBrokerTest::disableUpdateProfileOnFirstLogin);
    IdentityProviderRepresentation idpRep = identityProviderResource.toRepresentation();

    idpRep.setStoreToken(true);

    identityProviderResource.update(idpRep);

    driver.navigate().to(getAccountUrl(getConsumerRoot(), bc.consumerRealmName()));
    logInWithBroker(bc);
    updatePasswordPage.updatePasswords("password", "password");
    waitForAccountManagementTitle();
    accountUpdateProfilePage.assertCurrent();

    String username = bc.getUserLogin();

    testingClient.server(bc.consumerRealmName()).run(grantReadTokenRole(username));

    OAuthClient.AccessTokenResponse accessTokenResponse = oauth.realm(bc.consumerRealmName()).clientId("broker-app").doGrantAccessTokenRequest("broker-app-secret", bc.getUserLogin(), bc.getUserPassword());
    AtomicReference<String> accessToken = (AtomicReference<String>) new AtomicReference<>(accessTokenResponse.getAccessToken());
    Client client = javax.ws.rs.client.ClientBuilder.newBuilder().register((ClientRequestFilter) request -> request.getHeaders().add(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken.get())).build();

    try {
        WebTarget target = client.target(Urls.identityProviderRetrieveToken(URI.create(getConsumerRoot() + "/auth"), bc.getIDPAlias(), bc.consumerRealmName()));

        try (Response response = target.request().get()) {
            assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
            assertNotNull(response.readEntity(String.class));
        }

        testingClient.server(bc.consumerRealmName()).run(revokeReadTokenRole(username));

        accessTokenResponse = oauth.realm(bc.consumerRealmName()).clientId("broker-app").doGrantAccessTokenRequest("broker-app-secret", bc.getUserLogin(), bc.getUserPassword());
        accessToken.set(accessTokenResponse.getAccessToken());

        try (Response response = target.request().get()) {
            assertEquals(Response.Status.FORBIDDEN.getStatusCode(), response.getStatus());
        }
    } finally {
        client.close();
    }
}
 
Example #27
Source File: JerseyDockerHttpClient.java    From docker-java with Apache License 2.0 4 votes vote down vote up
public Builder clientRequestFilters(ClientRequestFilter[] value) {
    this.clientRequestFilters = value;
    return this;
}
 
Example #28
Source File: JerseyDockerCmdExecFactory.java    From docker-java with Apache License 2.0 4 votes vote down vote up
public JerseyDockerCmdExecFactory withClientRequestFilters(ClientRequestFilter... clientRequestFilters) {
    clientBuilder = clientBuilder.clientRequestFilters(clientRequestFilters);
    return this;
}
 
Example #29
Source File: DatabricksJobExecutor.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Override
public List<Stage.ConfigIssue> init() {
  List<Stage.ConfigIssue> issues = new ArrayList<>();

  Optional
      .ofNullable(databricksConfigBean.init(getContext(), PREFIX))
      .ifPresent(issues::addAll);

  baseUrl = databricksConfigBean.baseUrl.endsWith("/") ?
      databricksConfigBean.baseUrl.substring(0, databricksConfigBean.baseUrl.length() - 1) :
      databricksConfigBean.baseUrl;

  HttpProxyConfigBean proxyConf = databricksConfigBean.proxyConfigBean;
  String proxyUsername = null;
  String proxyPassword = null;
  if(databricksConfigBean.useProxy) {
    proxyUsername = proxyConf.resolveUsername(getContext(), "PROXY", "conf.proxyConfigBean.", issues);
    proxyPassword = proxyConf.resolvePassword(getContext(), "PROXY", "conf.proxyConfigBean.", issues);
  }

  if(issues.isEmpty()) {
    ClientConfig clientConfig = new ClientConfig()
        .property(ClientProperties.ASYNC_THREADPOOL_SIZE, 1)
        .property(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.BUFFERED);

    if (databricksConfigBean.useProxy) {
      clientConfig = clientConfig.connectorProvider(new GrizzlyConnectorProvider(new GrizzlyClientCustomizer(
          true,
          proxyUsername,
          proxyPassword
      )));
    }

    ClientBuilder builder = getClientBuilder()
        .withConfig(clientConfig)
        .register(JacksonJsonProvider.class);
    HttpAuthenticationFeature auth = null;
    if (databricksConfigBean.credentialsConfigBean.credentialType == CredentialType.PASSWORD) {
      String username = databricksConfigBean.credentialsConfigBean.resolveUsername(
          getContext(),
          "CREDENTIALS",
          "conf.credentialsConfigBean.",
          issues
      );
      String password = databricksConfigBean.credentialsConfigBean.resolvePassword(
          getContext(),
          "CREDENTIALS",
          "conf.credentialsConfigBean.",
          issues
      );
      auth = HttpAuthenticationFeature.basic(username, password);
      builder.register(auth);
    } else {
      String token = databricksConfigBean.credentialsConfigBean.resolveToken(
          getContext(),
          "CREDENTIALS",
          "conf.credentialsConfigBean.",
          issues
      );

      builder.register((ClientRequestFilter) requestContext ->
          requestContext.getHeaders().add("Authorization", "Bearer " + token)
      );
    }

    JerseyClientUtil.configureSslContext(databricksConfigBean.tlsConfigBean, builder);

    if(databricksConfigBean.useProxy) {
      JerseyClientUtil.configureProxy(
          proxyConf.uri,
          proxyUsername,
          proxyPassword,
          builder
      );
    }

    client = builder.build();
    validateWithDatabricks(getContext(), issues);
  }
  return issues;
}
 
Example #30
Source File: JaxRSClientDistributionProvider.java    From JaxRSProviders with Apache License 2.0 4 votes vote down vote up
protected void unbindClientRequestFilter(ClientRequestFilter instance) {
	this.removeJaxComponent(instance);
}