HavenNo7
HavenNo7

Reputation: 107

Jersey getting template path

Im using Jersey 2 and I want to get the URI template. The reason is that Im creating an auth system that validates based on the URI. I managed to work:

    @Override
    public void filter(ContainerRequestContext containerRequest) throws IOException {

        String method = containerRequest.getMethod();
        String uri = containerRequest.getUriInfo().getPath();
    }

The problem is that getPath returns something like:

/companies/1

And I want it to return

/companies/{id}

Which is how I declared with:

@Path("{id}")

thank you

EDIT I thought I found it here:

@Context
private ExtendedUriInfo uriInfo;

//...
Resource matchedModelResource = uriInfo.getMatchedModelResource();
System.out.println(matchedModelResource.getPathPattern().getTemplate().getTemplate());

buut guess what? matchedModelResource is null.

Also, this:

List<UriTemplate> matchedTemplates = uriInfo.getMatchedTemplates();

Returns an Empty List of UriTemplate. :( Why are the data not beeing set?

Upvotes: 3

Views: 1242

Answers (1)

HavenNo7
HavenNo7

Reputation: 107

Ok. So the answer is to use:

 uriInfo.getMatchedTemplates();

Where uriInfo is actually ExtendedUriInfo.

This is the code I've made to get the correct syntax:

    List<UriTemplate> matchedTemplates = uriInfo.getMatchedTemplates();

    StringBuilder builder = new StringBuilder();

    for (int i = matchedTemplates.size() - 1; i >= 0; i--) {
        builder.append(matchedTemplates.get(i).getTemplate().substring(1));
    }

    System.out.println("Permission is: " + builder.toString());
   // Prints:
   // Permission is: sig/companies/{id}

The reason the data was null or empty before is because I had an @PreMatching annotation in my filter class. Please dont ask why.

Hope this helps someone.

Upvotes: 4

Related Questions