Search in sources :

Example 6 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 7 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 8 with Feature

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

the class CommonConfig method processFeatureRegistration.

private void processFeatureRegistration(final Object component, final Class<?> componentClass) {
    final ContractProvider model = componentBag.getModel(componentClass);
    if (model.getContracts().contains(Feature.class)) {
        @SuppressWarnings("unchecked") final FeatureRegistration registration = (component != null) ? new FeatureRegistration((Feature) component) : new FeatureRegistration((Class<? extends Feature>) componentClass);
        newFeatureRegistrations.add(registration);
    }
}
Also used : ContractProvider(org.glassfish.jersey.model.ContractProvider) Feature(javax.ws.rs.core.Feature)

Aggregations

Feature (javax.ws.rs.core.Feature)8 Client (javax.ws.rs.client.Client)6 AccessToken (org.glassfish.jersey.client.oauth1.AccessToken)4 ConsumerCredentials (org.glassfish.jersey.client.oauth1.ConsumerCredentials)4 LoggingFeature (org.glassfish.jersey.logging.LoggingFeature)4 Test (org.junit.Test)4 URI (java.net.URI)3 WebTarget (javax.ws.rs.client.WebTarget)3 Response (javax.ws.rs.core.Response)3 JerseyTest (org.glassfish.jersey.test.JerseyTest)3 OAuth1ServerFeature (org.glassfish.jersey.server.oauth1.OAuth1ServerFeature)2 CoreMatchers.containsString (org.hamcrest.CoreMatchers.containsString)2 IOException (java.io.IOException)1 List (java.util.List)1 Logger (java.util.logging.Logger)1 ClientBuilder (javax.ws.rs.client.ClientBuilder)1 BonitaAuthFilter (org.apache.camel.component.bonita.api.filter.BonitaAuthFilter)1 JsonClientFilter (org.apache.camel.component.bonita.api.filter.JsonClientFilter)1 HttpServer (org.glassfish.grizzly.http.server.HttpServer)1 ClientConfig (org.glassfish.jersey.client.ClientConfig)1