下面列出了javax.ws.rs.ext.Provider#javax.ws.rs.ApplicationPath 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
default void add(Element element) {
// JAX-RS
ApplicationPath applicationPath = element.getAnnotation(ApplicationPath.class);
if (applicationPath != null) {
HashMap<String, Object> map = new HashMap<>();
map.put(ApplicationPath.class.getName(), new HashMap<String, String>() {{
put("value", applicationPath.value());
}});
addAnnotationConfiguration(map);
}
if (element.getAnnotation(Path.class) != null) {
addAnnotationConfiguration(Collections.emptyMap());
}
// servlet
if (element.getAnnotation(WebServlet.class) != null) {
addAnnotationConfiguration(Collections.emptyMap());
}
}
@Override
default void addPropertyConfiguration(Map map) {
Session session = getSession();
Port port = detectHttpPort();
session.configurators().add(new AddPort(port));
//TODO add support for detecting microprofile-health and setting the liveness/readiness probes
if (map.containsKey(ApplicationPath.class.getName())) {
Object o = map.get(ApplicationPath.class.getName());
if (o instanceof Map) {
Map<String, Object> applicationPath = (Map) o;
if (applicationPath != null && applicationPath.containsKey("value")) {
String path = String.valueOf(applicationPath.get("value"));
session.configurators().add(new SetPortPath(port.getName(), path));
}
}
}
}
/**
* Initialize Mojarra.
*
* @param classes the classes.
* @param servletContext the Servlet context.
* @throws ServletException when a Servlet error occurs.
*/
@Override
public void onStartup(Set<Class<?>> classes, ServletContext servletContext) throws ServletException {
DefaultWebApplication context = (DefaultWebApplication) servletContext;
Set<Class<?>> jerseyClasses = new HashSet<>();
context.getAnnotationManager()
.getAnnotations(Path.class, Provider.class, ApplicationPath.class)
.stream()
.map(e -> e.getTarget())
.forEach(e -> addClass(e, jerseyClasses));
jerseyClasses.addAll(context.getAnnotationManager().getInstances(Application.class));
JerseyServletContainerInitializer containerInitializer = new JerseyServletContainerInitializer();
containerInitializer.onStartup(jerseyClasses, servletContext);
}
private List<Class<?>> scanJaxrsClass() throws Exception {
try (ScanResult scanResult = new ClassGraph().disableJarScanning().enableAnnotationInfo().scan()) {
SetUniqueList<Class<?>> classes = SetUniqueList.setUniqueList(new ArrayList<Class<?>>());
for (ClassInfo info : scanResult.getClassesWithAnnotation(ApplicationPath.class.getName())) {
Class<?> applicationPathClass = ClassUtils.getClass(info.getName());
for (Class<?> o : (Set<Class<?>>) MethodUtils.invokeMethod(applicationPathClass.newInstance(),
"getClasses")) {
Path path = o.getAnnotation(Path.class);
JaxrsDescribe jaxrsDescribe = o.getAnnotation(JaxrsDescribe.class);
if (null != path && null != jaxrsDescribe) {
classes.add(o);
}
}
}
return classes;
}
}
private List<Class<?>> scanJaxrsClass(String name) throws Exception {
// String pack = "com." + name.replaceAll("_", ".");
String pack = "";
if (StringUtils.startsWith(name, "o2_")) {
pack = name.replaceAll("_", ".");
} else {
pack = "com." + name.replaceAll("_", ".");
}
try (ScanResult scanResult = new ClassGraph().whitelistPackages(pack).enableAllInfo().scan()) {
SetUniqueList<Class<?>> classes = SetUniqueList.setUniqueList(new ArrayList<Class<?>>());
for (ClassInfo info : scanResult.getClassesWithAnnotation(ApplicationPath.class.getName())) {
Class<?> applicationPathClass = ClassUtils.getClass(info.getName());
for (Class<?> o : (Set<Class<?>>) MethodUtils.invokeMethod(applicationPathClass.newInstance(),
"getClasses")) {
Path path = o.getAnnotation(Path.class);
JaxrsDescribe jaxrsDescribe = o.getAnnotation(JaxrsDescribe.class);
if (null != path && null != jaxrsDescribe) {
classes.add(o);
}
}
}
return classes;
}
}
private List<Class<?>> scanJaxrsClass() throws Exception {
try (ScanResult scanResult = new ClassGraph().disableJarScanning().enableAnnotationInfo().scan()) {
SetUniqueList<Class<?>> classes = SetUniqueList.setUniqueList(new ArrayList<Class<?>>());
for (ClassInfo info : scanResult.getClassesWithAnnotation(ApplicationPath.class.getName())) {
Class<?> applicationPathClass = ClassUtils.getClass(info.getName());
for (Class<?> o : (Set<Class<?>>) MethodUtils.invokeMethod(applicationPathClass.newInstance(),
"getClasses")) {
Path path = o.getAnnotation(Path.class);
JaxrsDescribe jaxrsDescribe = o.getAnnotation(JaxrsDescribe.class);
if (null != path && null != jaxrsDescribe) {
classes.add(o);
}
}
}
return classes;
}
}
/**
* Returns the base URL of the mycore system.
*
* @param info the UriInfo
*
* @return base URL of the mycore system as string
*/
public static String getBaseURL(UriInfo info, Application app) {
String baseURL = info.getBaseUri().toString();
List<String> applicationPaths = MCRConfiguration2
.getOrThrow("MCR.Jersey.Resource.ApplicationPaths", MCRConfiguration2::splitValue)
.collect(Collectors.toList());
for (String path : applicationPaths) {
baseURL = removeAppPath(baseURL, path);
}
Optional<String> appPath = Optional.ofNullable(app)
.map(a -> a instanceof ResourceConfig ? ((ResourceConfig) a).getApplication() : a)
.map(Application::getClass)
.map(c -> c.getAnnotation(ApplicationPath.class))
.map(ApplicationPath::value)
.map(s -> s.startsWith("/") ? s.substring(1) : s);
if (appPath.isPresent()) {
baseURL = removeAppPath(baseURL, appPath.get());
}
return baseURL;
}
@SuppressWarnings("unchecked")
public <T> void collect(@Observes final ProcessBean< T > event) {
if (event.getAnnotated().isAnnotationPresent(ApplicationPath.class)) {
applicationBeans.add(event.getBean());
} else if (event.getAnnotated().isAnnotationPresent(Path.class)) {
serviceBeans.add(event.getBean());
} else if (event.getAnnotated().isAnnotationPresent(Provider.class)) {
providerBeans.add(event.getBean());
} else if (event.getBean().getTypes().contains(javax.ws.rs.core.Feature.class)) {
providerBeans.add(event.getBean());
} else if (event.getBean().getTypes().contains(Feature.class)) {
featureBeans.add((Bean< ? extends Feature >)event.getBean());
} else if (CdiBusBean.CXF.equals(event.getBean().getName())
&& Bus.class.isAssignableFrom(event.getBean().getBeanClass())) {
hasBus = true;
} else if (event.getBean().getQualifiers().contains(DEFAULT)) {
event.getBean().getTypes().stream()
.filter(e -> Object.class != e && InjectionUtils.STANDARD_CONTEXT_CLASSES.contains(e.getTypeName()))
.findFirst()
.ifPresent(type -> existingStandardClasses.add(type.getTypeName()));
}
}
public void setApplicationInfo(ApplicationInfo application) {
if (application != null && application.getProvider() != null) {
final Class<?> clazz = application.getProvider().getClass();
final ApplicationPath path = ResourceUtils.locateApplicationPath(clazz);
if (path != null) {
applicationPath = path.value();
if (!applicationPath.startsWith("/")) {
applicationPath = "/" + applicationPath;
}
if (applicationPath.endsWith("/")) {
applicationPath = applicationPath.substring(0, applicationPath.lastIndexOf('/'));
}
}
}
}
public static <T> T createRestClient(Class<T> clazz, String appContextRoot, String jwt) {
String resourcePackage = clazz.getPackage().getName();
// First check for a javax.ws.rs.core.Application in the same package as the resource
List<Class<?>> appClasses = ReflectionSupport.findAllClassesInPackage(resourcePackage,
c -> Application.class.isAssignableFrom(c) &&
AnnotationSupport.isAnnotated(c, ApplicationPath.class),
n -> true);
if (appClasses.size() == 0) {
// If not found, check under the 3rd package, so com.foo.bar.*
// Classpath scanning can be expensive, so we jump straight to the 3rd package from root instead
// of recursing up one package at a time and scanning the entire CP for each step
String[] pkgs = resourcePackage.split("(.*)\\.(.*)\\.(.*)\\.", 2);
if (pkgs.length > 0 && !pkgs[0].isEmpty() && !pkgs[0].equals(resourcePackage)) {
appClasses = ReflectionSupport.findAllClassesInPackage(pkgs[0],
c -> Application.class.isAssignableFrom(c) &&
AnnotationSupport.isAnnotated(c, ApplicationPath.class),
n -> true);
}
}
if (appClasses.size() == 0) {
LOGGER.info("No classes implementing 'javax.ws.rs.core.Application' found on classpath to set as context root for " + clazz +
". Defaulting context root to '/'");
return createRestClient(clazz, appContextRoot, "", jwt);
}
Class<?> selectedClass = appClasses.get(0);
if (appClasses.size() > 1) {
appClasses.sort((c1, c2) -> c1.getCanonicalName().compareTo(c2.getCanonicalName()));
LOGGER.warn("Found multiple classes implementing 'javax.ws.rs.core.Application' on classpath: " + appClasses +
". Setting context root to the first class discovered (" + selectedClass.getCanonicalName() + ")");
}
ApplicationPath appPath = AnnotationSupport.findAnnotation(selectedClass, ApplicationPath.class).get();
return createRestClient(clazz, appContextRoot, appPath.value(), jwt);
}
@PostConstruct
private void init() {
latestApiVersion = StreamSupport
.stream(Spliterators.spliteratorUnknownSize(applications.iterator(), Spliterator.IMMUTABLE), false)
.filter(a -> a.getClass().isAnnotationPresent(ApplicationPath.class))
.map(a -> a.getClass().getAnnotation(ApplicationPath.class).value())
.map(path -> path.replace("api/v", ""))
.mapToInt(Integer::parseInt)
.max()
.orElse(1);
startTime = new Date();
}
private int getApiVersion() {
return StreamSupport
.stream(Spliterators.spliteratorUnknownSize(applications.iterator(), Spliterator.IMMUTABLE), false)
.filter(a -> a.getClass().isAnnotationPresent(ApplicationPath.class))
.map(a -> a.getClass().getAnnotation(ApplicationPath.class).value())
.map(path -> path.replace("api/v", ""))
.mapToInt(Integer::parseInt)
.max()
.orElse(1);
}
private static String getApplicationPath(Application applicationConfig) {
if (applicationConfig == null) {
return null;
}
ApplicationPath ap = applicationConfig.getClass().getAnnotation(ApplicationPath.class);
if (ap == null) {
return null;
}
String applicationPath = ap.value();
if (isBlank(applicationPath)) {
return null;
}
while (applicationPath.startsWith("/")) {
applicationPath = applicationPath.substring(1);
}
// support Servlet configs
if (applicationPath.endsWith("/*")) {
applicationPath = applicationPath.substring(0, applicationPath.length() - 2);
}
while (applicationPath.endsWith("/")) {
applicationPath = applicationPath.substring(0, applicationPath.length() - 1);
}
if (isBlank(applicationPath)) {
return null;
}
return applicationPath;
}
/**
* Get the JAX-RS application path configured this deployment. If the IndexView is not available, or if there is no class
* that has the annotated @ApplicationPath, then this method will return an empty string.
*
* @return the JAX-RS application path configured this deployment.
*/
private String getRestApplicationPath() {
String path = "";
// Check to see if we have any class annotated with the @ApplicationPath. If found, ensure that we set the context path
// for Swagger resources to webAppContextPath + applicationPath.
if (indexView != null) {
DotName dotName = DotName.createSimple(ApplicationPath.class.getName());
Collection<AnnotationInstance> instances = indexView.getAnnotations(dotName);
Set<String> applicationPaths = new HashSet<>();
for (AnnotationInstance ai : instances) {
AnnotationTarget target = ai.target();
if (target.kind() == AnnotationTarget.Kind.CLASS) {
Object value = ai.value().value();
if (value != null) {
applicationPaths.add(String.valueOf(value));
}
}
}
if (applicationPaths.size() > 1) {
// We wouldn't know which application path to pick for serving the swagger resources. Let the deployment choose
// this value explicitly.
SwaggerMessages.MESSAGES.multipleApplicationPathsFound(applicationPaths);
} else if (!applicationPaths.isEmpty()) {
// Update the context path for swagger
path = applicationPaths.iterator().next();
}
}
return path;
}
@Override
public Result tryParse(SourceType<?> sourceType) {
if (!(sourceType.type instanceof Class<?>)) {
return null;
}
final Class<?> cls = (Class<?>) sourceType.type;
// application
if (Application.class.isAssignableFrom(cls)) {
final ApplicationPath applicationPathAnnotation = cls.getAnnotation(ApplicationPath.class);
if (applicationPathAnnotation != null) {
model.setApplicationPath(applicationPathAnnotation.value());
}
model.setApplicationName(cls.getSimpleName());
final List<SourceType<Type>> discoveredTypes = JaxrsApplicationScanner.scanJaxrsApplication(cls, isClassNameExcluded);
return new Result(discoveredTypes);
}
// resource
final Path path = cls.getAnnotation(Path.class);
if (path != null) {
TypeScriptGenerator.getLogger().verbose("Parsing JAX-RS resource: " + cls.getName());
final Result result = new Result();
parseResource(result, new ResourceContext(cls, path.value()), cls);
return result;
}
return null;
}
/**
* Extracts relevant beans from producers.
* @param event process bean event
* @param baseType base type of the producer
*/
private <T> void processProducer(final ProcessBean<T> event, final Type baseType) {
if (baseType instanceof Class<?>) {
final Class<?> clazz = (Class<?>)baseType;
if (clazz.isAnnotationPresent(Path.class)) {
serviceBeans.add(event.getBean());
} else if (clazz.isAnnotationPresent(Provider.class)) {
providerBeans.add(event.getBean());
} else if (clazz.isAnnotationPresent(ApplicationPath.class)) {
applicationBeans.add(event.getBean());
}
}
}
public static ApplicationPath locateApplicationPath(Class<?> appClass) {
ApplicationPath appPath = appClass.getAnnotation(ApplicationPath.class);
if (appPath == null && appClass.getSuperclass() != Application.class) {
return locateApplicationPath(appClass.getSuperclass());
}
return appPath;
}
@Produces
public ServletDescriptor jerseyServlet() {
String urlPattern = restServerConfiguration.getRestServletMapping();
if (!applicationInstance.isUnsatisfied() && !applicationInstance.isAmbiguous()) {
ApplicationPath annotation = ClassUtils.getAnnotation(applicationInstance.get().getClass(), ApplicationPath.class);
if(annotation != null) {
String path = annotation.value();
urlPattern = path.endsWith("/") ? path + "*" : path + "/*";
}
}
return new ServletDescriptor(SERVLET_NAME, null, new String[] { urlPattern }, 1, null, true, ServletContainer.class);
}
@Produces
public ServletDescriptor resteasyServlet() {
String path = restServerConfiguration.getRestServerUri();
if( !(applicationInstance.isUnsatisfied() || applicationInstance.isAmbiguous())) {
ApplicationPath appPath = ClassUtils.getAnnotation(applicationInstance.get().getClass(), ApplicationPath.class);
if(appPath != null) {
path = appPath.value();
}
}
String pattern = path.endsWith("/") ? path + "*" : path + "/*";
WebInitParam param = new WebParam("resteasy.servlet.mapping.prefix", path);
return new ServletDescriptor("ResteasyServlet",new String[]{pattern}, new String[]{pattern},
1,new WebInitParam[]{param},true,HttpServlet30Dispatcher.class);
}
public static Set<Class<?>> getApplicationConfigClasses(Archive<?> archive) {
WebArchive webArchive = (WebArchive) archive;
return webArchive.getContent(archivePath ->
archivePath.get().startsWith("/WEB-INF/classes/") &&
archivePath.get().endsWith(".class")
).values().stream()
.filter(node -> node.getAsset() instanceof ClassAsset)
.map(node -> ((ClassAsset)node.getAsset()).getSource())
.filter(clazz -> clazz.isAnnotationPresent(ApplicationPath.class))
.collect(Collectors.toSet());
}
private static String locateApplicationPath(Class<?> clazz) {
String resourcePackage = clazz.getPackage().getName();
// If the rest client directly extends Application, look for ApplicationPath on it
if (AnnotationSupport.isAnnotated(clazz, ApplicationPath.class))
return AnnotationSupport.findAnnotation(clazz, ApplicationPath.class).get().value();
// First check for a javax.ws.rs.core.Application in the same package as the resource
List<Class<?>> appClasses = ReflectionSupport.findAllClassesInPackage(resourcePackage,
c -> Application.class.isAssignableFrom(c) &&
AnnotationSupport.isAnnotated(c, ApplicationPath.class),
n -> true);
if (appClasses.size() == 0) {
LOG.debug("no classes implementing Application found in pkg: " + resourcePackage);
// If not found, check under the 3rd package, so com.foo.bar.*
// Classpath scanning can be expensive, so we jump straight to the 3rd package from root instead
// of recursing up one package at a time and scanning the entire CP for each step
String[] pkgs = resourcePackage.split("\\.");
if (pkgs.length > 3) {
String checkPkg = pkgs[0] + '.' + pkgs[1] + '.' + pkgs[2];
LOG.debug("checking in pkg: " + checkPkg);
appClasses = ReflectionSupport.findAllClassesInPackage(checkPkg,
c -> Application.class.isAssignableFrom(c) &&
AnnotationSupport.isAnnotated(c, ApplicationPath.class),
n -> true);
}
}
if (appClasses.size() == 0) {
LOG.info("No classes implementing 'javax.ws.rs.core.Application' found on classpath to set as context root for " + clazz +
". Defaulting context root to '/'");
return "";
}
Class<?> selectedClass = appClasses.stream()
.sorted((c1, c2) -> c1.getName().compareTo(c2.getName()))
.findFirst()
.get();
ApplicationPath appPath = AnnotationSupport.findAnnotation(selectedClass, ApplicationPath.class).get();
if (appClasses.size() > 1) {
LOG.warn("Found multiple classes implementing 'javax.ws.rs.core.Application' on classpath: " + appClasses +
". Setting context root to the first class discovered (" + selectedClass.getCanonicalName() + ") with path: " +
appPath.value());
}
LOG.debug("Using ApplicationPath of '" + appPath.value() + "'");
return appPath.value();
}
private boolean isJAXRSRootResource(String className) {
final Class<?> clazz = JavaUtils.loadClassFromName(className);
return clazz != null && (isAnnotationPresent(clazz, javax.ws.rs.Path.class) || isAnnotationPresent(clazz, ApplicationPath.class));
}
@Override
protected Server createJaxRsServer() {
JAXRSServerFactoryBean factoryBean = null;
String[] beanNames = applicationContext.getBeanNamesForAnnotation(ApplicationPath.class);
if (beanNames.length > 0) {
Set<String> componentScanPackagesSet = parseSetProperty(componentScanPackages);
Set<String> componentScanBeansSet = parseSetProperty(componentScanBeans);
for (String beanName : beanNames) {
if (isComponentMatched(beanName, componentScanPackagesSet, componentScanBeansSet)) {
Application app = applicationContext.getBean(beanName, Application.class);
factoryBean = createFactoryBeanFromApplication(app);
for (String cxfBeanName : applicationContext.getBeanNamesForAnnotation(
org.apache.cxf.annotations.Provider.class)) {
if (isComponentMatched(cxfBeanName, componentScanPackagesSet, componentScanBeansSet)) {
addCxfProvider(getProviderBean(cxfBeanName));
}
}
break;
}
}
}
if (!StringUtils.isEmpty(classesScanPackages)) {
try {
final Map< Class< ? extends Annotation >, Collection< Class< ? > > > appClasses =
ClasspathScanner.findClasses(classesScanPackages, ApplicationPath.class);
List<Application> apps = CastUtils.cast(JAXRSServerFactoryBeanDefinitionParser
.createBeansFromDiscoveredClasses(super.applicationContext,
appClasses.get(ApplicationPath.class), null));
if (!apps.isEmpty()) {
factoryBean = createFactoryBeanFromApplication(apps.get(0));
final Map< Class< ? extends Annotation >, Collection< Class< ? > > > cxfClasses =
ClasspathScanner.findClasses(classesScanPackages, org.apache.cxf.annotations.Provider.class);
addCxfProvidersFromClasses(cxfClasses.get(org.apache.cxf.annotations.Provider.class));
}
} catch (Exception ex) {
throw new ServiceConstructionException(ex);
}
}
if (factoryBean != null) {
setFactoryCxfProviders(factoryBean);
return factoryBean.create();
}
return super.createJaxRsServer();
}
@SuppressWarnings("unchecked")
public static JAXRSServerFactoryBean createApplication(Application app,
boolean ignoreAppPath,
boolean staticSubresourceResolution,
boolean useSingletonResourceProvider,
Bus bus) {
Set<Object> singletons = app.getSingletons();
verifySingletons(singletons);
List<Class<?>> resourceClasses = new ArrayList<>();
List<Object> providers = new ArrayList<>();
List<Feature> features = new ArrayList<>();
Map<Class<?>, ResourceProvider> map = new HashMap<>();
// Note, app.getClasses() returns a list of per-request classes
// or singleton provider classes
for (Class<?> cls : app.getClasses()) {
if (isValidApplicationClass(cls, singletons)) {
if (isValidProvider(cls)) {
providers.add(createProviderInstance(cls));
} else if (Feature.class.isAssignableFrom(cls)) {
features.add(createFeatureInstance((Class<? extends Feature>) cls));
} else {
resourceClasses.add(cls);
if (useSingletonResourceProvider) {
map.put(cls, new SingletonResourceProvider(createProviderInstance(cls)));
} else {
map.put(cls, new PerRequestResourceProvider(cls));
}
}
}
}
// we can get either a provider or resource class here
for (Object o : singletons) {
if (isValidProvider(o.getClass())) {
providers.add(o);
} else if (o instanceof Feature) {
features.add((Feature) o);
} else {
resourceClasses.add(o.getClass());
map.put(o.getClass(), new SingletonResourceProvider(o));
}
}
JAXRSServerFactoryBean bean = new JAXRSServerFactoryBean();
if (bus != null) {
bean.setBus(bus);
}
String address = "/";
if (!ignoreAppPath) {
ApplicationPath appPath = locateApplicationPath(app.getClass());
if (appPath != null) {
address = appPath.value();
}
}
if (!address.startsWith("/")) {
address = "/" + address;
}
bean.setAddress(address);
bean.setStaticSubresourceResolution(staticSubresourceResolution);
bean.setResourceClasses(resourceClasses);
bean.setProviders(providers);
bean.getFeatures().addAll(features);
for (Map.Entry<Class<?>, ResourceProvider> entry : map.entrySet()) {
bean.setResourceProvider(entry.getKey(), entry.getValue());
}
Map<String, Object> appProps = app.getProperties();
if (appProps != null) {
bean.getProperties(true).putAll(appProps);
}
bean.setApplication(app);
return bean;
}
private static String appPrefix(final WebAppInfo info, final Class<?> appClazz) {
StringBuilder builder = null;
// no annotation, try servlets
for (final ServletInfo s : info.servlets) {
if (s.mappings.isEmpty()) {
continue;
}
String mapping = null;
final String name = appClazz.getName();
if (name.equals(s.servletClass) || name.equals(s.servletName) || "javax.ws.rs.core.Application ".equals(s.servletName)) {
mapping = s.mappings.iterator().next();
} else {
for (final ParamValueInfo pvi : s.initParams) {
if ("javax.ws.rs.Application".equals(pvi.name) || Application.class.getName().equals(pvi.name)) {
mapping = s.mappings.iterator().next();
break;
}
}
}
if (mapping != null) {
if (mapping.endsWith("/*")) {
mapping = mapping.substring(0, mapping.length() - 2);
}
if (mapping.startsWith("/")) {
mapping = mapping.substring(1);
}
builder = new StringBuilder();
builder.append(mapping);
break;
}
}
if (builder != null) { // https://issues.apache.org/jira/browse/CXF-5702
return builder.toString();
}
// annotation
final ApplicationPath path = appClazz.getAnnotation(ApplicationPath.class);
if (path != null) {
String appPath = path.value();
if (appPath.endsWith("*")) {
appPath = appPath.substring(0, appPath.length() - 1);
}
builder = new StringBuilder();
if (appPath.startsWith("/")) {
builder.append(appPath.substring(1));
} else {
builder.append(appPath);
}
}
if (builder == null) {
return null;
}
return builder.toString();
}