com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider Java Examples

The following examples show how to use com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider. 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: JAXRSClientMetricsTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void usingClientStopIsCalledWhenServerReturnsNotFound() throws Exception {
    final Client client = ClientBuilder
            .newClient()
            .register(new MetricsFeature(provider))
            .register(JacksonJsonProvider.class);

    stubFor(get(urlEqualTo("/books/10"))
        .willReturn(aResponse()
            .withStatus(404)));

    try {
        expectedException.expect(ProcessingException.class);
        client
            .target("http://localhost:" + wireMockRule.port() + "/books/10")
            .request(MediaType.APPLICATION_JSON).get()
            .readEntity(Book.class);
    } finally {
        Mockito.verify(resourceContext, times(1)).start(any(Exchange.class));
        Mockito.verify(resourceContext, times(1)).stop(anyLong(), anyLong(), anyLong(), any(Exchange.class));
        Mockito.verify(endpointContext, times(1)).start(any(Exchange.class));
        Mockito.verify(endpointContext, times(1)).stop(anyLong(), anyLong(), anyLong(), any(Exchange.class));
        Mockito.verifyNoInteractions(operationContext);
    }
}
 
Example #2
Source File: JAXRSRxJava2ObservableTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetHelloWorldJson() throws Exception {
    String address = "http://localhost:" + PORT + "/rx2/observable/textJson";
    List<Object> providers = new LinkedList<>();
    providers.add(new JacksonJsonProvider());
    providers.add(new ObservableRxInvokerProvider());
    WebClient wc = WebClient.create(address, providers);
    Observable<HelloWorldBean> obs = wc.accept("application/json")
        .rx(ObservableRxInvoker.class)
        .get(HelloWorldBean.class);

    Holder<HelloWorldBean> holder = new Holder<>();
    Disposable d = obs.subscribe(v -> {
        holder.value = v;
    });
    if (d == null) {
        throw new IllegalStateException("Subscribe did not return a Disposable");
    }
    Thread.sleep(2000);
    assertEquals("Hello", holder.value.getGreeting());
    assertEquals("World", holder.value.getAudience());
}
 
Example #3
Source File: JAXRSJwsJsonTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testJweCompactJwsJsonBookBeanHmac() throws Exception {
    if (!SecurityTestUtil.checkUnrestrictedPoliciesInstalled()) {
        return;
    }
    String address = "https://localhost:" + PORT + "/jwejwsjsonhmac";
    List<?> extraProviders = Arrays.asList(new JacksonJsonProvider(),
                                           new JweWriterInterceptor(),
                                           new JweClientResponseFilter());
    String jwkStoreProperty = "org/apache/cxf/systest/jaxrs/security/secret.jwk.properties";
    Map<String, Object> props = new HashMap<>();
    props.put(JoseConstants.RSSEC_SIGNATURE_PROPS, jwkStoreProperty);
    props.put(JoseConstants.RSSEC_ENCRYPTION_PROPS, jwkStoreProperty);
    BookStore bs = createBookStore(address,
                                   props,
                                   extraProviders);
    Book book = bs.echoBook(new Book("book", 123L));
    assertEquals("book", book.getName());
    assertEquals(123L, book.getId());
}
 
Example #4
Source File: PersonsIT.java    From jaxrs-beanvalidation-javaee7 with Apache License 2.0 6 votes vote down vote up
@Test
@RunAsClient
@InSequence(30)
public void shouldReturnAnEmptyPerson(@ArquillianResource URL baseURL) {
    Client client = ClientBuilder.newBuilder()
            .register(JacksonJsonProvider.class)
            .build();
    Response response = client.target(baseURL + "r/persons/{id}")
            .resolveTemplate("id", "10")
            .request(MediaType.APPLICATION_JSON)
            .get();
    response.bufferEntity();

    logResponse("shouldReturnAnEmptyPerson", response);
    Assert.assertEquals(null, response.readEntity(Person.class));
}
 
Example #5
Source File: JweJwsAlgorithmTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testBadEncryptingKey() throws Exception {

    URL busFile = JweJwsAlgorithmTest.class.getResource("client.xml");

    List<Object> providers = new ArrayList<>();
    providers.add(new JacksonJsonProvider());
    providers.add(new JweWriterInterceptor());

    String address = "http://localhost:" + PORT + "/jweoaepgcm/bookstore/books";
    WebClient client =
        WebClient.create(address, providers, busFile.toString());
    client.type("application/json").accept("application/json");

    Map<String, Object> properties = new HashMap<>();
    properties.put("rs.security.keystore.type", "jwk");
    properties.put("rs.security.keystore.alias", "AliceCert");
    properties.put("rs.security.keystore.file", "org/apache/cxf/systest/jaxrs/security/certs/jwkPublicSet.txt");
    properties.put("rs.security.encryption.content.algorithm", "A128GCM");
    properties.put("rs.security.encryption.key.algorithm", "RSA-OAEP");
    WebClient.getConfig(client).getRequestContext().putAll(properties);

    Response response = client.post(new Book("book", 123L));
    assertNotEquals(response.getStatus(), 200);
}
 
Example #6
Source File: FluxReactorTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testFluxEmpty() throws Exception {
    String address = "http://localhost:" + PORT + "/reactor2/flux/empty";
    
    StepVerifier
        .create(ClientBuilder
            .newClient()
            .register(new JacksonJsonProvider())
            .register(new ReactorInvokerProvider())
            .target(address)
            .request(MediaType.APPLICATION_JSON)
            .rx(ReactorInvoker.class)
            .getFlux(HelloWorldBean.class))
        .expectComplete()
        .verify();
}
 
Example #7
Source File: FluxReactorTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testFluxErrorsResponse() throws Exception {
    String address = "http://localhost:" + PORT + "/reactor2/flux/errors";
    
    StepVerifier
        .create(ClientBuilder
            .newClient()
            .register(new JacksonJsonProvider())
            .register(new ReactorInvokerProvider())
            .target(address)
            .request(MediaType.APPLICATION_JSON)
            .rx(ReactorInvoker.class)
            .get())
        .expectNextMatches(r -> r.getStatus() == 500)
        .expectComplete()
        .verify();
}
 
Example #8
Source File: Swagger2NonAnnotatedServiceDescriptionTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
protected void run() {
    final JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();
    sf.setResourceClasses(BookStore.class);
    sf.setResourceClasses(BookStoreStylesheetsSwagger2.class);
    sf.setResourceProvider(BookStore.class,
        new SingletonResourceProvider(new BookStore()));
    sf.setProvider(new JacksonJsonProvider());
    final Swagger2Feature feature = createSwagger2Feature();
    //FIXME swagger-jaxrs 1.5.3 can't handle a self-recursive subresource like Book
    // so we need to exclude "org.apache.cxf.systest.jaxrs" for now.
    feature.setResourcePackage("org.apache.cxf.systest.jaxrs.description.group1");
    feature.setScanAllResources(true);
    sf.setFeatures(Arrays.asList(feature));
    sf.setAddress("http://localhost:" + port + "/");
    sf.create();
}
 
Example #9
Source File: Module.java    From usergrid with Apache License 2.0 6 votes vote down vote up
protected void configureServlets() {
    //noinspection unchecked
    install( new GuicyFigModule( ServletFig.class, CoordinatorFig.class ) );
    install( new ChopClientModule() );

    // Hook Jersey into Guice Servlet
    bind( GuiceContainer.class );

    // Hook Jackson into Jersey as the POJO <-> JSON mapper
    bind( JacksonJsonProvider.class ).asEagerSingleton();

    bind( IController.class ).to( Controller.class );
    bind( RunnerRegistry.class ).to( RunnerRegistryImpl.class );
    bind( RunManager.class ).to( RunManagerImpl.class );

    bind( ResetResource.class );
    bind( StopResource.class );
    bind( StartResource.class );
    bind( StatsResource.class );
    bind( StatusResource.class );

    Map<String, String> params = new HashMap<String, String>();
    params.put( PACKAGES_KEY, getClass().getPackage().toString() );
    serve( "/*" ).with( GuiceContainer.class, params );
}
 
Example #10
Source File: PersonsIT.java    From jaxrs-beanvalidation-javaee7 with Apache License 2.0 6 votes vote down vote up
@Test
@RunAsClient
@InSequence(20)
public void shouldReturnAValidationErrorWhenGettingAPerson(@ArquillianResource URL baseURL) {
    Client client = ClientBuilder.newBuilder()
            .register(JacksonJsonProvider.class)
            .build();
    Response response = client.target(baseURL + "r/persons/{id}")
            .resolveTemplate("id", "test")
            .request(MediaType.APPLICATION_JSON)
            .header("Accept-Language", "en")
            .get();
    response.bufferEntity();

    logResponse("shouldReturnAValidationErrorWhenGettingAPerson", response);
    Assert.assertEquals(HttpServletResponse.SC_BAD_REQUEST, response.getStatus());
}
 
Example #11
Source File: JAXRSServerMetricsTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void usingClientStopIsCalledWhenServerReturnSuccessfulResponse() throws Exception {
    final Client client = ClientBuilder
        .newClient()
        .register(JacksonJsonProvider.class);

    try {
        client
            .target("http://localhost:" + PORT + "/books/11")
            .request(MediaType.APPLICATION_JSON)
            .get()
            .readEntity(Book.class);
    } finally {
        Mockito.verify(resourceContext, times(1)).start(any(Exchange.class));
        Mockito.verify(resourceContext, times(1)).stop(anyLong(), anyLong(), anyLong(), any(Exchange.class));
        Mockito.verify(endpointContext, times(1)).start(any(Exchange.class));
        Mockito.verify(endpointContext, times(1)).stop(anyLong(), anyLong(), anyLong(), any(Exchange.class));
        Mockito.verifyNoInteractions(operationContext);
    }
}
 
Example #12
Source File: ApiClient.java    From forge-api-java-client with Apache License 2.0 6 votes vote down vote up
/**
 * Build the Client used to make HTTP requests with the latest settings,
 * i.e. objectMapper and debugging.
 * TODO: better to use the Builder Pattern?
 */
public ApiClient rebuildHttpClient() {
  // Add the JSON serialization support to Jersey
  JacksonJsonProvider jsonProvider = new JacksonJsonProvider(objectMapper);
  DefaultClientConfig conf = new DefaultClientConfig();
  conf.getSingletons().add(jsonProvider);
  Client client = Client.create(conf);
  if (debugging) {
    client.addFilter(new LoggingFilter());
  }
  
  //to solve the issue of GET:metadata/:guid with accepted encodeing is 'gzip' 
  //in the past, when clients use gzip header, actually it doesn't trigger a gzip encoding... So everything is fine 
  //After the release, the content is return in gzip, while the sdk doesn't handle it correctly
  client.addFilter(new GZIPContentEncodingFilter(false));

  this.httpClient = client;
  return this;
}
 
Example #13
Source File: Server.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected Server() throws Exception {
    org.eclipse.jetty.server.Server server = new org.eclipse.jetty.server.Server(9000);

    final ServletHolder servletHolder = new ServletHolder(new CXFNonSpringJaxrsServlet());
    final ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    context.addServlet(servletHolder, "/*");
    servletHolder.setInitParameter("jaxrs.serviceClasses", Sample.class.getName());
    servletHolder.setInitParameter("jaxrs.features",
        Swagger2Feature.class.getName());
    servletHolder.setInitParameter("jaxrs.providers", StringUtils.join(
        new String[] {
            MultipartProvider.class.getName(),
            JacksonJsonProvider.class.getName(),
            ApiOriginFilter.class.getName()
        }, ",")
    );

    server.setHandler(context);
    server.start();
    server.join();
}
 
Example #14
Source File: NulsResourceConfig.java    From nuls with MIT License 6 votes vote down vote up
public NulsResourceConfig() {
    register(io.swagger.jaxrs.listing.ApiListingResource.class);
    register(io.swagger.jaxrs.listing.AcceptHeaderApiListingResource.class);
    register(NulsSwaggerSerializers.class);
    register(MultiPartFeature.class);
    register(RpcServerFilter.class);
    register(JacksonJsonProvider.class);

    Collection<Object> list = SpringLiteContext.getAllBeanList();
    for (Object object : list) {
        if (object.getClass().getAnnotation(Path.class) != null) {
            Log.debug("register restFul resource:{}", object.getClass());
            register(object);
        }
    }
}
 
Example #15
Source File: MonoReactorTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testTextJsonImplicitListAsyncStream() throws Exception {
    String address = "http://localhost:" + PORT + "/reactor/mono/textJsonImplicitListAsyncStream";
    final BlockingQueue<HelloWorldBean> holder = new LinkedBlockingQueue<>();
    ClientBuilder.newClient()
            .register(new JacksonJsonProvider())
            .register(new ReactorInvokerProvider())
            .target(address)
            .request(MediaType.APPLICATION_JSON)
            .rx(ReactorInvoker.class)
            .get(HelloWorldBean.class)
            .doOnNext(holder::offer)
            .subscribe();
    HelloWorldBean bean = holder.poll(1L, TimeUnit.SECONDS);
    assertNotNull(bean);
    assertEquals("Hello", bean.getGreeting());
    assertEquals("World", bean.getAudience());
}
 
Example #16
Source File: ParaClient.java    From para with Apache License 2.0 6 votes vote down vote up
/**
 * Default constructor.
 * @param accessKey app access key
 * @param secretKey app secret key
 */
public ParaClient(String accessKey, String secretKey) {
	this.accessKey = accessKey;
	this.secretKey = secretKey;
	if (StringUtils.length(secretKey) < 6) {
		logger.warn("Secret key appears to be invalid. Make sure you call 'signIn()' first.");
	}
	this.throwExceptionOnHTTPError = false;
	ObjectMapper mapper = ParaObjectUtils.getJsonMapper();
	mapper.setSerializationInclusion(JsonInclude.Include.USE_DEFAULTS);
	ClientConfig clientConfig = new ClientConfig();
	clientConfig.register(GenericExceptionMapper.class);
	clientConfig.register(new JacksonJsonProvider(mapper));
	clientConfig.connectorProvider(new HttpUrlConnectorProvider().useSetMethodWorkaround());
	SSLContext sslContext = SslConfigurator.newInstance().createSSLContext();
	apiClient = ClientBuilder.newBuilder().
			sslContext(sslContext).
			withConfig(clientConfig).build();
}
 
Example #17
Source File: ForgeRestApplication.java    From fabric8-forge with Apache License 2.0 6 votes vote down vote up
@Override
    public Set<Object> getSingletons() {
        if (!preloaded) {
            preloaded = true;
            forgeInitialiser.preloadCommands(commandsResource);
        }

        return new HashSet<Object>(
                Arrays.asList(
                        rootResource,
                        commandsResource,
                        repositoriesResource,
                        new JacksonJsonProvider(),
                        new CamelCatalogRest()
/*
                        new SwaggerFeature(),
                        new EnableJMXFeature(),
*/
                )
        );
    }
 
Example #18
Source File: JweJwsAlgorithmTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testWrongKeyEncryptionAlgorithmKeyIncluded() throws Exception {

    URL busFile = JweJwsAlgorithmTest.class.getResource("client.xml");

    List<Object> providers = new ArrayList<>();
    providers.add(new JacksonJsonProvider());
    providers.add(new JweWriterInterceptor());

    String address = "http://localhost:" + PORT + "/jweoaepgcm/bookstore/books";
    WebClient client =
        WebClient.create(address, providers, busFile.toString());
    client.type("application/json").accept("application/json");

    Map<String, Object> properties = new HashMap<>();
    properties.put("rs.security.keystore.type", "jwk");
    properties.put("rs.security.keystore.alias", "2011-04-29");
    properties.put("rs.security.keystore.file", "org/apache/cxf/systest/jaxrs/security/certs/jwkPublicSet.txt");
    properties.put("rs.security.encryption.content.algorithm", "A128GCM");
    properties.put("rs.security.encryption.key.algorithm", "RSA1_5");
    properties.put("rs.security.encryption.include.public.key", "true");
    WebClient.getConfig(client).getRequestContext().putAll(properties);

    Response response = client.post(new Book("book", 123L));
    assertNotEquals(response.getStatus(), 200);
}
 
Example #19
Source File: RestFolderClient.java    From document-management-software with GNU Lesser General Public License v3.0 6 votes vote down vote up
public RestFolderClient(String endpoint, String username, String password, int timeout) {
	super(endpoint, username, password, timeout);

	JacksonJsonProvider provider = new JacksonJsonProvider();

	if ((username == null) || (password == null)) {
		proxy = JAXRSClientFactory.create(endpoint, FolderService.class, Arrays.asList(provider));
	} else {
		// proxy = JAXRSClientFactory.create(endpoint, FolderService.class,
		// Arrays.asList(provider));
		// create(String baseAddress, Class<T> cls, List<?> providers,
		// String username, String password, String configLocation)
		proxy = JAXRSClientFactory.create(endpoint, FolderService.class, Arrays.asList(provider), username,
				password, null);
	}

	if (timeout > 0) {
		HTTPConduit conduit = WebClient.getConfig(proxy).getHttpConduit();
		HTTPClientPolicy policy = new HTTPClientPolicy();
		policy.setReceiveTimeout(timeout);
		conduit.setClient(policy);
	}
}
 
Example #20
Source File: Server.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected Server() throws Exception {
    org.eclipse.jetty.server.Server server = new org.eclipse.jetty.server.Server(9000);

    final ServletHolder servletHolder = new ServletHolder(new CXFNonSpringJaxrsServlet());
    final ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    context.addServlet(servletHolder, "/*");
    servletHolder.setInitParameter("jaxrs.serviceClasses", Sample.class.getName());
    servletHolder.setInitParameter("jaxrs.features",
        OpenApiFeature.class.getName());
    servletHolder.setInitParameter("jaxrs.providers", StringUtils.join(
        new String[] {
            MultipartProvider.class.getName(),
            JacksonJsonProvider.class.getName(),
            ApiOriginFilter.class.getName()
        }, ",")
    );

    server.setHandler(context);
    server.start();
    server.join();
}
 
Example #21
Source File: JweJwsAlgorithmTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testWrongContentEncryptionAlgorithm() throws Exception {
    if (!SecurityTestUtil.checkUnrestrictedPoliciesInstalled()) {
        return;
    }

    URL busFile = JweJwsAlgorithmTest.class.getResource("client.xml");

    List<Object> providers = new ArrayList<>();
    providers.add(new JacksonJsonProvider());
    providers.add(new JweWriterInterceptor());

    String address = "http://localhost:" + PORT + "/jweoaepgcm/bookstore/books";
    WebClient client =
        WebClient.create(address, providers, busFile.toString());
    client.type("application/json").accept("application/json");

    Map<String, Object> properties = new HashMap<>();
    properties.put("rs.security.keystore.type", "jwk");
    properties.put("rs.security.keystore.alias", "2011-04-29");
    properties.put("rs.security.keystore.file", "org/apache/cxf/systest/jaxrs/security/certs/jwkPublicSet.txt");
    properties.put("rs.security.encryption.content.algorithm", "A192GCM");
    properties.put("rs.security.encryption.key.algorithm", "RSA-OAEP");
    WebClient.getConfig(client).getRequestContext().putAll(properties);

    Response response = client.post(new Book("book", 123L));
    assertNotEquals(response.getStatus(), 200);
}
 
Example #22
Source File: BaseRemoteAccessApiTest.java    From swaggy-jenkins with MIT License 5 votes vote down vote up
@Before
public void setup() {
    JacksonJsonProvider provider = new JacksonJsonProvider();
    List providers = new ArrayList();
    providers.add(provider);
    
    api = JAXRSClientFactory.create("http://localhost", BaseRemoteAccessApi.class, providers);
    org.apache.cxf.jaxrs.client.Client client = WebClient.client(api);
    
    ClientConfiguration config = WebClient.getConfig(client); 
}
 
Example #23
Source File: StatisticReportApiTest.java    From opencps-v2 with GNU Affero General Public License v3.0 5 votes vote down vote up
@Before
public void setup() {
    JacksonJsonProvider provider = new JacksonJsonProvider();
    List providers = new ArrayList();
    providers.add(provider);
    
    api = JAXRSClientFactory.create("https://virtserver.swaggerhub.com/binhthgc/opencps/1.0.0", StatisticReportApi.class, providers);
    org.apache.cxf.jaxrs.client.Client client = WebClient.client(api);
    
    ClientConfiguration config = WebClient.getConfig(client); 
}
 
Example #24
Source File: DossierDocumentsApiTest.java    From opencps-v2 with GNU Affero General Public License v3.0 5 votes vote down vote up
@Before
public void setup() {
    JacksonJsonProvider provider = new JacksonJsonProvider();
    List providers = new ArrayList();
    providers.add(provider);
    
    api = JAXRSClientFactory.create("https://virtserver.swaggerhub.com/binhthgc/opencps/1.0.0", DossierDocumentsApi.class, providers);
    org.apache.cxf.jaxrs.client.Client client = WebClient.client(api);
    
    ClientConfiguration config = WebClient.getConfig(client); 
}
 
Example #25
Source File: JWTAuthnAuthzTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testClaimsAuthorizationWeakClaims() throws Exception {

    URL busFile = JWTAuthnAuthzTest.class.getResource("client.xml");

    List<Object> providers = new ArrayList<>();
    providers.add(new JacksonJsonProvider());
    providers.add(new JwtAuthenticationClientFilter());

    String address = "https://localhost:" + PORT + "/signedjwtauthz/bookstore/booksclaims";
    WebClient client =
        WebClient.create(address, providers, busFile.toString());
    client.type("application/json").accept("application/json");

    // Create the JWT Token
    JwtClaims claims = new JwtClaims();
    claims.setSubject("alice");
    claims.setIssuer("DoubleItSTSIssuer");
    claims.setIssuedAt(Instant.now().getEpochSecond());
    claims.setAudiences(toList(address));
    // The endpoint requires a role of "boss"
    claims.setProperty("role", "boss");
    claims.setProperty("http://claims/authentication", "password");

    JwtToken token = new JwtToken(claims);

    Map<String, Object> properties = new HashMap<>();
    properties.put("rs.security.keystore.type", "jwk");
    properties.put("rs.security.keystore.alias", "2011-04-29");
    properties.put("rs.security.keystore.file",
                   "org/apache/cxf/systest/jaxrs/security/certs/jwkPrivateSet.txt");
    properties.put("rs.security.signature.algorithm", "RS256");
    properties.put(JwtConstants.JWT_TOKEN, token);
    WebClient.getConfig(client).getRequestContext().putAll(properties);

    Response response = client.post(new Book("book", 123L));
    assertEquals(response.getStatus(), 403);
}
 
Example #26
Source File: AbstractSwagger2ServiceDescriptionTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected WebClient createWebClient(final String url) {
    return WebClient
        .create("http://localhost:" + getPort() + url,
            Arrays.< Object >asList(new JacksonJsonProvider()),
            Arrays.< Feature >asList(new LoggingFeature()),
            null)
        .accept(MediaType.APPLICATION_JSON).accept("application/yaml");
}
 
Example #27
Source File: JWTAuthnAuthzTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testAuthorizationRolesAllowedAnnotationHEAD() throws Exception {

    URL busFile = JWTAuthnAuthzTest.class.getResource("client.xml");

    List<Object> providers = new ArrayList<>();
    providers.add(new JacksonJsonProvider());
    providers.add(new JwtAuthenticationClientFilter());

    String address = "https://localhost:" + PORT + "/signedjwtauthzannotations/bookstore/booksrolesallowed";
    WebClient client =
        WebClient.create(address, providers, busFile.toString());
    client.type("application/json").accept("application/json");

    // Create the JWT Token
    JwtClaims claims = new JwtClaims();
    claims.setSubject("alice");
    claims.setIssuer("DoubleItSTSIssuer");
    claims.setIssuedAt(Instant.now().getEpochSecond());
    claims.setAudiences(toList(address));
    // The endpoint requires a role of "boss"
    claims.setProperty("role", "boss");

    JwtToken token = new JwtToken(claims);

    Map<String, Object> properties = new HashMap<>();
    properties.put("rs.security.keystore.type", "jwk");
    properties.put("rs.security.keystore.alias", "2011-04-29");
    properties.put("rs.security.keystore.file",
                   "org/apache/cxf/systest/jaxrs/security/certs/jwkPrivateSet.txt");
    properties.put("rs.security.signature.algorithm", "RS256");
    properties.put(JwtConstants.JWT_TOKEN, token);
    WebClient.getConfig(client).getRequestContext().putAll(properties);

    Response response = client.head();
    assertEquals(response.getStatus(), 200);
}
 
Example #28
Source File: ResourceProducer.java    From gazpachoquest with GNU General Public License v3.0 5 votes vote down vote up
@Produces
@GazpachoResource
@RequestScoped
public QuestionnaireResource createQuestionnairResource(HttpServletRequest request) {
    RespondentAccount principal = (RespondentAccount) request.getUserPrincipal();
    String apiKey = principal.getApiKey();
    String secret = principal.getSecret();

    logger.info("Getting QuestionnaireResource using api key {}/{} ", apiKey, secret);

    JacksonJsonProvider jacksonProvider = new JacksonJsonProvider();
    ObjectMapper mapper = new ObjectMapper();
    // mapper.findAndRegisterModules();
    mapper.registerModule(new JSR310Module());
    mapper.setSerializationInclusion(Include.NON_EMPTY);
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

    jacksonProvider.setMapper(mapper);

    QuestionnaireResource resource = JAXRSClientFactory.create(BASE_URI, QuestionnaireResource.class,
            Collections.singletonList(jacksonProvider), null);
    // proxies
    // WebClient.client(resource).header("Authorization", "GZQ " + apiKey);

    Client client = WebClient.client(resource);
    ClientConfiguration config = WebClient.getConfig(client);
    config.getOutInterceptors().add(new HmacAuthInterceptor(apiKey, secret));
    return resource;
}
 
Example #29
Source File: RemoteAccessApiTest.java    From swaggy-jenkins with MIT License 5 votes vote down vote up
@Before
public void setup() {
    JacksonJsonProvider provider = new JacksonJsonProvider();
    List providers = new ArrayList();
    providers.add(provider);
    
    api = JAXRSClientFactory.create("http://localhost", RemoteAccessApi.class, providers);
    org.apache.cxf.jaxrs.client.Client client = WebClient.client(api);
    
    ClientConfiguration config = WebClient.getConfig(client); 
}
 
Example #30
Source File: DossierStatisticApiTest.java    From opencps-v2 with GNU Affero General Public License v3.0 5 votes vote down vote up
@Before
public void setup() {
    JacksonJsonProvider provider = new JacksonJsonProvider();
    List providers = new ArrayList();
    providers.add(provider);
    
    api = JAXRSClientFactory.create("https://virtserver.swaggerhub.com/binhthgc/opencps/1.0.0", DossierStatisticApi.class, providers);
    org.apache.cxf.jaxrs.client.Client client = WebClient.client(api);
    
    ClientConfiguration config = WebClient.getConfig(client); 
}