Search in sources :

Example 1 with Feature

use of javax.ws.rs.core.Feature in project jersey by jersey.

the class AbstractJsonOsgiIntegrationTest method testJson.

@Test
public void testJson() throws Exception {
    final Feature jsonProviderFeature = getJsonProviderFeature();
    final Client client = ClientBuilder.newClient();
    final ResourceConfig resourceConfig = new ResourceConfig(JsonResource.class);
    if (jsonProviderFeature != null) {
        client.register(jsonProviderFeature);
        resourceConfig.register(jsonProviderFeature);
    }
    HttpServer server = null;
    try {
        server = GrizzlyHttpServerFactory.createHttpServer(baseUri, resourceConfig);
        final String result = client.target(baseUri).path("/json").request(MediaType.APPLICATION_JSON).get(String.class);
        System.out.println("RESULT = " + result);
        assertThat(result, containsString("Jim"));
    } finally {
        if (server != null) {
            server.shutdownNow();
        }
    }
}
Also used : HttpServer(org.glassfish.grizzly.http.server.HttpServer) ResourceConfig(org.glassfish.jersey.server.ResourceConfig) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) Client(javax.ws.rs.client.Client) Feature(javax.ws.rs.core.Feature) Test(org.junit.Test)

Example 2 with Feature

use of javax.ws.rs.core.Feature in project jersey by jersey.

the class App method main.

/**
     * Main method that creates a {@link Client client} and initializes the OAuth support with
     * configuration needed to connect to the Twitter and retrieve statuses.
     * <p/>
     * Execute this method to demo
     *
     * @param args Command line arguments.
     * @throws Exception Thrown when error occurs.
     */
public static void main(final String[] args) throws Exception {
    // retrieve consumer key/secret and token/secret from the property file
    // or system properties
    loadSettings();
    final ConsumerCredentials consumerCredentials = new ConsumerCredentials(PROPERTIES.getProperty(PROPERTY_CONSUMER_KEY), PROPERTIES.getProperty(PROPERTY_CONSUMER_SECRET));
    final Feature filterFeature;
    if (PROPERTIES.getProperty(PROPERTY_TOKEN) == null) {
        // we do not have Access Token yet. Let's perfom the Authorization Flow first,
        // let the user approve our app and get Access Token.
        final OAuth1AuthorizationFlow authFlow = OAuth1ClientSupport.builder(consumerCredentials).authorizationFlow("https://api.twitter.com/oauth/request_token", "https://api.twitter.com/oauth/access_token", "https://api.twitter.com/oauth/authorize").build();
        final String authorizationUri = authFlow.start();
        System.out.println("Enter the following URI into a web browser and authorize me:");
        System.out.println(authorizationUri);
        System.out.print("Enter the authorization code: ");
        final String verifier;
        try {
            verifier = IN.readLine();
        } catch (final IOException ex) {
            throw new RuntimeException(ex);
        }
        final AccessToken accessToken = authFlow.finish(verifier);
        // store access token for next application execution
        PROPERTIES.setProperty(PROPERTY_TOKEN, accessToken.getToken());
        PROPERTIES.setProperty(PROPERTY_TOKEN_SECRET, accessToken.getAccessTokenSecret());
        // get the feature that will configure the client with consumer credentials and
        // received access token
        filterFeature = authFlow.getOAuth1Feature();
    } else {
        final AccessToken storedToken = new AccessToken(PROPERTIES.getProperty(PROPERTY_TOKEN), PROPERTIES.getProperty(PROPERTY_TOKEN_SECRET));
        // build a new feature from the stored consumer credentials and access token
        filterFeature = OAuth1ClientSupport.builder(consumerCredentials).feature().accessToken(storedToken).build();
    }
    // create a new Jersey client and register filter feature that will add OAuth signatures and
    // JacksonFeature that will process returned JSON data.
    final Client client = ClientBuilder.newBuilder().register(filterFeature).register(JacksonFeature.class).build();
    // make requests to protected resources
    // (no need to care about the OAuth signatures)
    final Response response = client.target(FRIENDS_TIMELINE_URI).request().get();
    if (response.getStatus() != 200) {
        String errorEntity = null;
        if (response.hasEntity()) {
            errorEntity = response.readEntity(String.class);
        }
        throw new RuntimeException("Request to Twitter was not successful. Response code: " + response.getStatus() + ", reason: " + response.getStatusInfo().getReasonPhrase() + ", entity: " + errorEntity);
    }
    // persist the current consumer key/secret and token/secret for future use
    storeSettings();
    final List<Status> statuses = response.readEntity(new GenericType<List<Status>>() {
    });
    System.out.println("Tweets:\n");
    for (final Status s : statuses) {
        System.out.println(s.getText());
        System.out.println("[posted by " + s.getUser().getName() + " at " + s.getCreatedAt() + "]");
    }
}
Also used : OAuth1AuthorizationFlow(org.glassfish.jersey.client.oauth1.OAuth1AuthorizationFlow) ConsumerCredentials(org.glassfish.jersey.client.oauth1.ConsumerCredentials) IOException(java.io.IOException) Feature(javax.ws.rs.core.Feature) JacksonFeature(org.glassfish.jersey.jackson.JacksonFeature) Response(javax.ws.rs.core.Response) JacksonFeature(org.glassfish.jersey.jackson.JacksonFeature) AccessToken(org.glassfish.jersey.client.oauth1.AccessToken) List(java.util.List) Client(javax.ws.rs.client.Client)

Example 3 with Feature

use of javax.ws.rs.core.Feature in project jersey by jersey.

the class OAuthClientServerTest method testRequestSigningWithExceedingCache.

/**
     * Tests configuration of the nonce cache on the server side.
     */
@Test
public void testRequestSigningWithExceedingCache() {
    final Feature filterFeature = OAuth1ClientSupport.builder(new ConsumerCredentials(CONSUMER_KEY, SECRET_CONSUMER_KEY)).feature().accessToken(new AccessToken(PROMETHEUS_TOKEN, PROMETHEUS_SECRET)).build();
    final Client client = ClientBuilder.newBuilder().register(filterFeature).build();
    final URI resourceUri = UriBuilder.fromUri(getBaseUri()).path("resource").build();
    final WebTarget target = client.target(resourceUri);
    Response response;
    for (int i = 0; i < 20; i++) {
        System.out.println("request: " + i);
        response = target.request().get();
        assertEquals(200, response.getStatus());
        assertEquals("prometheus", response.readEntity(String.class));
        i++;
        response = target.path("admin").request().get();
        assertEquals(200, response.getStatus());
        assertEquals(true, response.readEntity(boolean.class));
    }
    // now the nonce cache is full
    response = target.request().get();
    assertEquals(401, response.getStatus());
}
Also used : Response(javax.ws.rs.core.Response) ConsumerCredentials(org.glassfish.jersey.client.oauth1.ConsumerCredentials) AccessToken(org.glassfish.jersey.client.oauth1.AccessToken) WebTarget(javax.ws.rs.client.WebTarget) Client(javax.ws.rs.client.Client) Feature(javax.ws.rs.core.Feature) OAuth1ServerFeature(org.glassfish.jersey.server.oauth1.OAuth1ServerFeature) LoggingFeature(org.glassfish.jersey.logging.LoggingFeature) URI(java.net.URI) JerseyTest(org.glassfish.jersey.test.JerseyTest) Test(org.junit.Test)

Example 4 with Feature

use of javax.ws.rs.core.Feature in project jersey by jersey.

the class OAuthClientServerTest method testRequestSigning.

/**
     * Tests {@link org.glassfish.jersey.client.oauth1.OAuth1ClientFilter} already configured with Access Token for signature
     * purposes only.
     */
@Test
public void testRequestSigning() {
    final Feature filterFeature = OAuth1ClientSupport.builder(new ConsumerCredentials(CONSUMER_KEY, SECRET_CONSUMER_KEY)).feature().accessToken(new AccessToken(PROMETHEUS_TOKEN, PROMETHEUS_SECRET)).build();
    final Client client = ClientBuilder.newBuilder().register(filterFeature).build();
    final URI resourceUri = UriBuilder.fromUri(getBaseUri()).path("resource").build();
    final WebTarget target = client.target(resourceUri);
    Response response;
    for (int i = 0; i < 15; i++) {
        System.out.println("request: " + i);
        response = target.request().get();
        assertEquals(200, response.getStatus());
        assertEquals("prometheus", response.readEntity(String.class));
        i++;
        response = target.path("admin").request().get();
        assertEquals(200, response.getStatus());
        assertEquals(true, response.readEntity(boolean.class));
    }
}
Also used : Response(javax.ws.rs.core.Response) ConsumerCredentials(org.glassfish.jersey.client.oauth1.ConsumerCredentials) AccessToken(org.glassfish.jersey.client.oauth1.AccessToken) WebTarget(javax.ws.rs.client.WebTarget) Client(javax.ws.rs.client.Client) Feature(javax.ws.rs.core.Feature) OAuth1ServerFeature(org.glassfish.jersey.server.oauth1.OAuth1ServerFeature) LoggingFeature(org.glassfish.jersey.logging.LoggingFeature) URI(java.net.URI) JerseyTest(org.glassfish.jersey.test.JerseyTest) Test(org.junit.Test)

Example 5 with Feature

use of javax.ws.rs.core.Feature in project jersey by jersey.

the class OauthClientAuthorizationFlowTest method testOAuthClientFeature.

/**
     * Tests mainly the client functionality. The test client registers
     * {@link org.glassfish.jersey.client.oauth1.OAuth1ClientFilter} and uses the filter only to sign requests. So, it does not
     * use the filter to perform authorization flow. However, each request that this test performs is actually a request used
     * during the authorization flow.
     * <p/>
     * The server side of this test extracts header authorization values and tests that signatures are
     * correct for each request type.
     */
@Test
public void testOAuthClientFeature() {
    final URI baseUri = getBaseUri();
    // baseline for requests
    final OAuth1Builder oAuth1Builder = OAuth1ClientSupport.builder(new ConsumerCredentials("dpf43f3p2l4k3l03", "kd94hf93k423kf44")).timestamp("1191242090").nonce("hsu94j3884jdopsl").signatureMethod(PlaintextMethod.NAME).version("1.0");
    final Feature feature = oAuth1Builder.feature().build();
    final Client client = client();
    client.register(LoggingFeature.class);
    final WebTarget target = client.target(baseUri);
    // simulate request for Request Token (temporary credentials)
    String responseEntity = target.path("request_token").register(feature).request().post(Entity.entity("entity", MediaType.TEXT_PLAIN_TYPE), String.class);
    assertEquals(responseEntity, "oauth_token=hh5s93j4hdidpola&oauth_token_secret=hdhd0244k9j7ao03");
    final Feature feature2 = oAuth1Builder.timestamp("1191242092").nonce("dji430splmx33448").feature().accessToken(new AccessToken("hh5s93j4hdidpola", "hdhd0244k9j7ao03")).build();
    // simulate request for Access Token
    responseEntity = target.path("access_token").register(feature2).request().post(Entity.entity("entity", MediaType.TEXT_PLAIN_TYPE), String.class);
    assertEquals(responseEntity, "oauth_token=nnch734d00sl2jdk&oauth_token_secret=pfkkdhi9sl3r4s00");
    final Feature feature3 = oAuth1Builder.nonce("kllo9940pd9333jh").signatureMethod("HMAC-SHA1").timestamp("1191242096").feature().accessToken(new AccessToken("nnch734d00sl2jdk", "pfkkdhi9sl3r4s00")).build();
    // based on Access Token
    responseEntity = target.path("/photos").register(feature3).queryParam("file", "vacation.jpg").queryParam("size", "original").request().get(String.class);
    assertEquals(responseEntity, "PHOTO");
}
Also used : ConsumerCredentials(org.glassfish.jersey.client.oauth1.ConsumerCredentials) AccessToken(org.glassfish.jersey.client.oauth1.AccessToken) OAuth1Builder(org.glassfish.jersey.client.oauth1.OAuth1Builder) WebTarget(javax.ws.rs.client.WebTarget) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) Client(javax.ws.rs.client.Client) URI(java.net.URI) Feature(javax.ws.rs.core.Feature) OAuth1SignatureFeature(org.glassfish.jersey.oauth1.signature.OAuth1SignatureFeature) LoggingFeature(org.glassfish.jersey.logging.LoggingFeature) JerseyTest(org.glassfish.jersey.test.JerseyTest) Test(org.junit.Test)

Aggregations

Feature (javax.ws.rs.core.Feature)19 Response (javax.ws.rs.core.Response)9 Test (org.junit.Test)9 IOException (java.io.IOException)7 List (java.util.List)7 InputStream (java.io.InputStream)6 Annotation (java.lang.annotation.Annotation)6 Type (java.lang.reflect.Type)6 ArrayList (java.util.ArrayList)6 Map (java.util.Map)6 Priority (javax.annotation.Priority)6 WebApplicationException (javax.ws.rs.WebApplicationException)6 Client (javax.ws.rs.client.Client)6 MediaType (javax.ws.rs.core.MediaType)6 ExceptionMapper (javax.ws.rs.ext.ExceptionMapper)6 OutputStream (java.io.OutputStream)5 URI (java.net.URI)5 Arrays (java.util.Arrays)5 MultivaluedMap (javax.ws.rs.core.MultivaluedMap)5 MessageBodyWriter (javax.ws.rs.ext.MessageBodyWriter)5