Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

DZone's Guide to

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

Continue your journey into the @Context annotation. Here we'll see it used with the SecurityContext and ResourceContext classes.

· Java Zone
Free Resource

Managing a MongoDB deployment? Take a load off and live migrate to MongoDB Atlas, the official automated service, with little to no downtime.

In part 1 of What is javax.ws.rs.core.context?, you learned 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 classes.

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, which 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 numbers together.

First, you need a calculator resource that 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 UriInfoinstance 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 Request, Configuration, Providers, and Application classes.

MongoDB Atlas is the easiest way to run the fastest-growing database for modern applications — no installation, setup, or configuration required. Easily live migrate an existing workload or start with 512MB of storage for free.

Topics:
java ,jax-rs ,java ee ,restful web services ,tutorial

Published at DZone with permission of Alex Theedom, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}