我使用 Jersey 1.17 提供 REST Web 服务。
我知道 Jersey“知道”所有资源是什么,那么有没有办法让 Jersey 给我它已发现的资源的完整列表?
背景:我希望增强用户在资源级别配置用户/权限的能力。为此,我想枚举 Jersey 发现的所有资源,以填充用户界面,以便为用户设置安全性。然后我会将用户/URL 权限保留在数据库中。
解决方案
static class ResourceListBuilder
{
private List<ResourceInfo> resourceInfos = new ArrayList<ResourceInfo>();
public List<ResourceInfo> getResourceInfos()
{
return resourceInfos;
}
private void build( Application application )
{
for ( Class<?> aClass : application.getClasses() )
{
if ( isAnnotatedResourceClass( aClass ) )
{
AbstractResource resource = IntrospectionModeller.createResource( aClass );
buildResource( resource, resource.getPath().getValue() );
}
}
}
private void buildResource( AbstractResource resource, String uriPrefix )
{
for ( AbstractSubResourceMethod srm : resource.getSubResourceMethods() )
{
String uri = uriPrefix + srm.getPath().getValue();
resourceInfos.add( new ResourceInfo( uri, srm.getHttpMethod(), srm.getMethod().getName() ) );
}
for ( AbstractResourceMethod srm : resource.getResourceMethods() )
{
resourceInfos.add( new ResourceInfo( uriPrefix, srm.getHttpMethod(), srm.getMethod().getName() ) );
}
for ( AbstractSubResourceLocator locator : resource.getSubResourceLocators() )
{
AbstractResource locatorResource = IntrospectionModeller.createResource( locator.getMethod().getReturnType() );
buildResource( locatorResource, uriPrefix + locator.getPath().getValue() );
}
}
private boolean isAnnotatedResourceClass( Class rc )
{
if ( rc.isAnnotationPresent( Path.class ) )
{
return true;
}
for ( Class i : rc.getInterfaces() )
{
if ( i.isAnnotationPresent( Path.class ) )
{
return true;
}
}
return false;
}
}
static class ResourceInfo
{
private String url;
private String method;
private String description;
ResourceInfo( String url, String method, String description )
{
this.url = url;
this.method = method;
this.description = description;
}
public String getUrl()
{
return url;
}
public String getMethod()
{
return method;
}
public String getDescription()
{
return description;
}
}
我是一名优秀的程序员,十分优秀!