-1

Using: Java EE + JAX-RS (Apache Wink) + WAS.

Let say I have Rest API declared by class Hello, path "/hello"

@Path("/hello")
public class Hello{

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response sayHello() {
        Map<String, String> myMap = new LinkedHashMap<String, String>();
        myMap.put("firstName", "To");
        myMap.put("lastName", "Kra");
        myMap.put("message", "Hello World!");
        Gson gson = new Gson(); 
        String json = gson.toJson(myMap);       
        return Response.status(200).entity(json).build();
   }
}

How can I get that path from Hello.class without using reflections ? I can see example in javax.ws.rs.core.UriBuilder method path(Class clazz) which can get it somehow, could not find the sources of it.

To Kra
  • 3,344
  • 3
  • 38
  • 45

2 Answers2

1

Add @Context to either method call or class and inject either HttpServletRequest or UriInfo, whatever will be more useful, like this:

// as class fields
@Context
private HttpServletRequest request;

@Context
private UriInfo uriInfo;
...

// or as param in method
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response sayHello(@Context UriInfo uriInfo) {
....

System.out.println(request.getRequestURI());
System.out.println("uri: " + uriInfo.getPath());
System.out.println("uri: " + uriInfo.getBaseUri());
Gas
  • 17,601
  • 4
  • 46
  • 93
  • this is not really what I meant in my question. but thx – To Kra Dec 11 '14 at 09:33
  • @ToKra so how about this `UriBuilder.fromResource(Hello.class).build().toString()` is it more what you were looking for ? – Gas Dec 11 '14 at 14:10
0

Solution with reflections:

/**
 * Gets rest api path from its resource class
 * @param apiClazz
 * @return String rest api path
 */
public static String getRestApiPath(Class<?> apiClazz){
    Annotation[] annotations = apiClazz.getAnnotations();
    for(Annotation annotation : annotations){
        if(annotation instanceof Path){
            Path pathAnnotation = (Path) annotation;
            return pathAnnotation.value();
        }
    }
    return "";
}
To Kra
  • 3,344
  • 3
  • 38
  • 45