News Ticker

What is javax.ws.rs.core.context? (Part 2)

JAX-RS and RESTful APIs

How to use the @Context annotation

In part 1 of What is javax.ws.rs.core.context? you learnt how to use the @Context annotation to retrieve HTTP Header information from an injected instance of the HttpHeaders class and how to retrieve URI information from the UriInfo instance such as URI parameters and variables.

In this article, you will learn about using the @Context annotation with the SecurityContext and the ResourceContext class.

Securing RESTful web services with SecurityContext

To secure a RESTful endpoint you can use the javax.ws.rs.core.SecurityContext interface which provides access to security-related information about the request. The SecurityContext instance enables you to access the following security-related information:

  • The authentication type used to secure the resource, such as CLIENT_CERT_AUTH, FORM_AUTH, and BASIC_AUTH
  • The java.security.Principal instance which is populated with the name of the user making the request
  • If the request was made using HTTPS
  • If the user is included in a given role

To get to the SecurityContext you inject an instance into an instance variable, setter method, or method parameter using the @Context annotation.

Let’s take a look at an example that checks if the current user is in the guest role.

@Path("/security-context")
public class SecurityContextResource {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response sayHello(
                      final @Context SecurityContext securityContext) {
        return Response.ok(securityContext.isUserInRole("guest")).build();
    }

}

This code snippet shows an instance of SecurityContext being injected into the securityContext parameter using the @Context annotation. Then it checks if the user is in the guest role and returns the result to the caller. A call to http://localhost:8080/rest-server/security-context will return true or false depending on the user involvement in the guest role. In this simple example, it should return false as no roles have been configured.

Retrieving a JAX-RS with ResourceContext

The javax.ws.rs.container.ResourseContext instance provides access to instances of other resource classes. It has two methods: the getResource() method with retrieves a resource or sub-resource and the initResource() which initializes a resource or sub-resource.

Let’s create an example that retrieves a resource that adds two number together.

First, you need calculator resource which has a resource method that adds two values.

@Path("/calculator")
public class CalculatorResource {

    @GET
    @Path("add")
    @Produces(MediaType.APPLICATION_JSON)
    public Integer add(@QueryParam("x") int x, @QueryParam("y") int y) {
        return x + y;
    }

}

This is a simple resource class with a single method that adds together two query parameters and returns the result. We are not going to use this resource directly, although we could via the URL http://localhost:8080/rest-server/calculator/add?x=10&y=50, instead, we are going to locate this resource within another resource method and use its add method.

@Path("/resource-context")
public class ResourceContextResource {

    @GET
    @Path("/add")
    @Produces(MediaType.APPLICATION_JSON)
    public Response get(final @Context ResourceContext resourceContext, 
                        final @Context UriInfo uriInfo) {
        final CalculatorResource calculatorResource = 
          resourceContext.getResource(CalculatorResource.class);
        int x = 
          Integer.valueOf(uriInfo.getQueryParameters().getFirst("x"));
        int y = 
          Integer.valueOf(uriInfo.getQueryParameters().getFirst("y"));
        return Response.ok(calculatorResource.add(x, y)).build();
    }

}

In this resource class, there is one resource method that takes the ResourceContext and UriInfo as parameters. The ResourceContext is used to retrieve the CalculatorResource.class and the UriInfo instance is used to retrieve the two query parameters. Then the add() method on the CalculatorResource class instance is called and the two parameters are passed to the method. The result is of the method is sent back to the caller.

To provoke this method make a call to the URL http://localhost:8080/rest-server/resource-context/add?x=10&y=50.

Code Repository

The source code for this and all my articles are in the readlearncode_articles Github repository.

What Next?

That is all for part 2, in part 3 of What is javax.ws.rs.core.context? you will learn how to use the @Context annotation to inject the RequestConfiguration, Providers, and Application classes.

Want to Learn More?

If like video training then why not check out the Java EE course on Lynda.com. There is a vast range of Java EE course covering all aspects of the eco-system for beginners to experts. If you are a beginner then my course Learning Java Enterprise Edition is perfect for you. It’s a complete two hrs course spanning the essential APIs in the Java EE platform.

Your learning continues with the other Java EE APIs where you can learn how to construct a RESTful APIs with JAX-RS, build a simple chat app with the WebSocket API and master JSON manipulation with the JSON-Processing API. The learning path is growing so get in now to get ahead.

Further Reading

I publish articles regularly on Java EE at readlearncode.com and have published a mini-series of posts looking at the JAX-RS API in detail. You will learn about how to handle bean validationMediaTypes and JAX-RS, and Resource Entities. I hope you enjoy.

3 Trackbacks / Pingbacks

  1. What is javax.ws.rs.core.context? [ Part 1 ] Java EE | Java SE | Design Patterns
  2. What is javax.ws.rs.core.context? [ Part 3 ] Java EE | Java SE | Design Patterns
  3. JAX-RS: What is @Context?

Leave a Reply

%d bloggers like this: