use of javax.ws.rs.core.Application in project jersey by jersey.
the class ConstrainedToServerTest method testSpecificApplication.
@Test
public void testSpecificApplication() throws ExecutionException, InterruptedException {
Application app = new Application() {
@Override
public Set<Class<?>> getClasses() {
final HashSet<Class<?>> classes = new HashSet<>();
classes.add(Resource.class);
classes.add(MyClientFilter.class);
classes.add(MyServerWrongFilter.class);
return classes;
}
};
ApplicationHandler handler = new ApplicationHandler(app);
final ContainerResponse response = handler.apply(RequestContextBuilder.from("/resource", "GET").build()).get();
assertEquals(200, response.getStatus());
}
use of javax.ws.rs.core.Application in project tomee by apache.
the class CheckRestMethodArePublic method validate.
@Override
public void validate(final AppModule appModule) {
// valid standalone classes
final Collection<String> standAloneClasses = new ArrayList<String>();
final ClassLoader loader = Thread.currentThread().getContextClassLoader();
try {
for (final EjbModule ejb : appModule.getEjbModules()) {
Thread.currentThread().setContextClassLoader(ejb.getClassLoader());
for (final EnterpriseBean bean : ejb.getEjbJar().getEnterpriseBeans()) {
if (bean instanceof SessionBean && ((SessionBean) bean).isRestService()) {
standAloneClasses.add(bean.getEjbClass());
valid(ejb.getValidation(), ejb.getClassLoader(), bean.getEjbClass());
}
}
}
for (final WebModule web : appModule.getWebModules()) {
Thread.currentThread().setContextClassLoader(web.getClassLoader());
// build the list of classes to validate
final Collection<String> classes = new ArrayList<String>();
classes.addAll(web.getRestClasses());
classes.addAll(web.getEjbRestServices());
for (final String app : web.getRestApplications()) {
final Class<?> clazz;
try {
clazz = web.getClassLoader().loadClass(app);
} catch (final ClassNotFoundException e) {
// managed elsewhere, here we just check methods
continue;
}
final Application appInstance;
try {
appInstance = (Application) clazz.newInstance();
} catch (final Exception e) {
// managed elsewhere
continue;
}
try {
for (final Class<?> rsClass : appInstance.getClasses()) {
classes.add(rsClass.getName());
}
/* don't do it or ensure you have cdi activated! + CXF will catch it later
for (final Object rsSingleton : appInstance.getSingletons()) {
classes.add(rsSingleton.getClass().getName());
}
*/
} catch (final RuntimeException npe) {
if (appInstance == null) {
throw npe;
}
// if app relies on cdi it is null here
}
}
// try to avoid to valid twice the same classes
final Iterator<String> it = classes.iterator();
while (it.hasNext()) {
final String current = it.next();
if (standAloneClasses.contains(current)) {
it.remove();
}
}
// valid
for (final String classname : classes) {
valid(web.getValidation(), web.getClassLoader(), classname);
}
classes.clear();
}
} finally {
Thread.currentThread().setContextClassLoader(loader);
}
standAloneClasses.clear();
}
use of javax.ws.rs.core.Application in project tomee by apache.
the class RESTService method fullServletDeployment.
private void fullServletDeployment(final AppInfo appInfo, final WebAppInfo webApp, final WebContext webContext, final Map<String, EJBRestServiceInfo> restEjbs, final ClassLoader classLoader, final Collection<Injection> injections, final WebBeansContext owbCtx, final Context context, final Collection<Object> additionalProviders, final Collection<IdPropertiesInfo> initPojoConfigurations) {
// The spec says:
//
// "The resources and providers that make up a JAX-RS application are configured via an application-supplied
// subclass of Application. An implementation MAY provide alternate mechanisms for locating resource
// classes and providers (e.g. runtime class scanning) but use of Application is the only portable means of
// configuration."
//
// The choice here is to deploy using the Application if it exists or to use the scanned classes
// if there is no Application.
//
// Like this providing an Application subclass user can totally control deployed services.
Collection<IdPropertiesInfo> pojoConfigurations = null;
boolean useApp = false;
String appPrefix = webApp.contextRoot;
for (final String app : webApp.restApplications) {
// if multiple application classes reinit it
appPrefix = webApp.contextRoot;
if (!appPrefix.endsWith("/")) {
appPrefix += "/";
}
final Application appInstance;
final Class<?> appClazz;
try {
appClazz = classLoader.loadClass(app);
appInstance = Application.class.cast(appClazz.newInstance());
if (owbCtx.getBeanManagerImpl().isInUse()) {
try {
webContext.inject(appInstance);
} catch (final Exception e) {
// not important since not required by the spec
}
}
} catch (final Exception e) {
throw new OpenEJBRestRuntimeException("can't create class " + app, e);
}
final String path = appPrefix(webApp, appClazz);
if (path != null) {
appPrefix += path;
}
final Set<Class<?>> classes = appInstance.getClasses();
final Set<Object> singletons = appInstance.getSingletons();
// look for providers
for (final Class<?> clazz : classes) {
if (isProvider(clazz)) {
additionalProviders.add(clazz);
}
}
for (final Object obj : singletons) {
if (obj != null && isProvider(obj.getClass())) {
additionalProviders.add(obj);
}
}
for (final Object o : singletons) {
if (o == null || additionalProviders.contains(o)) {
continue;
}
if (hasEjbAndIsNotAManagedBean(restEjbs, o.getClass().getName())) {
// no more a singleton if the ejb is not a singleton...but it is a weird case
deployEJB(appInfo.appId, webApp.contextRoot, appPrefix, restEjbs.get(o.getClass().getName()).context, additionalProviders, appInfo.services);
} else {
pojoConfigurations = PojoUtil.findPojoConfig(pojoConfigurations, appInfo, webApp);
deploySingleton(appInfo.appId, webApp.contextRoot, appPrefix, o, appInstance, classLoader, additionalProviders, new ServiceConfiguration(PojoUtil.findConfiguration(pojoConfigurations, o.getClass().getName()), appInfo.services));
}
}
for (final Class<?> clazz : classes) {
if (additionalProviders.contains(clazz)) {
continue;
}
if (hasEjbAndIsNotAManagedBean(restEjbs, clazz.getName())) {
deployEJB(appInfo.appId, webApp.contextRoot, appPrefix, restEjbs.get(clazz.getName()).context, additionalProviders, appInfo.services);
} else {
pojoConfigurations = PojoUtil.findPojoConfig(pojoConfigurations, appInfo, webApp);
deployPojo(appInfo.appId, webApp.contextRoot, appPrefix, clazz, appInstance, classLoader, injections, context, owbCtx, additionalProviders, new ServiceConfiguration(PojoUtil.findConfiguration(pojoConfigurations, clazz.getName()), appInfo.services));
}
}
useApp = useApp || classes.size() + singletons.size() > 0;
LOGGER.info("REST application deployed: " + app);
}
if (!useApp) {
if (webApp.restApplications.isEmpty() || webApp.restApplications.size() > 1) {
appPrefix = webApp.contextRoot;
}
// else keep application prefix
final Set<String> restClasses = new HashSet<>(webApp.restClass);
restClasses.addAll(webApp.ejbRestServices);
for (final String clazz : restClasses) {
if (restEjbs.containsKey(clazz)) {
final BeanContext ctx = restEjbs.get(clazz).context;
if (hasEjbAndIsNotAManagedBean(restEjbs, clazz)) {
deployEJB(appInfo.appId, webApp.contextRoot, appPrefix, restEjbs.get(clazz).context, additionalProviders, appInfo.services);
} else {
deployPojo(appInfo.appId, webApp.contextRoot, appPrefix, ctx.getBeanClass(), null, ctx.getClassLoader(), ctx.getInjections(), context, owbCtx, additionalProviders, new ServiceConfiguration(ctx.getProperties(), appInfo.services));
}
} else {
try {
final Class<?> loadedClazz = classLoader.loadClass(clazz);
pojoConfigurations = PojoUtil.findPojoConfig(pojoConfigurations, appInfo, webApp);
deployPojo(appInfo.appId, webApp.contextRoot, appPrefix, loadedClazz, null, classLoader, injections, context, owbCtx, additionalProviders, new ServiceConfiguration(PojoUtil.findConfiguration(pojoConfigurations, loadedClazz.getName()), appInfo.services));
} catch (final ClassNotFoundException e) {
throw new OpenEJBRestRuntimeException("can't find class " + clazz, e);
}
}
}
}
}
use of javax.ws.rs.core.Application in project tomee by apache.
the class RESTService method afterApplicationCreated.
public void afterApplicationCreated(final AppInfo appInfo, final WebAppInfo webApp) {
final WebContext webContext = containerSystem.getWebContextByHost(webApp.moduleId, webApp.host != null ? webApp.host : virtualHost);
if (webContext == null) {
return;
}
if (!deployedWebApps.add(webApp)) {
return;
}
final Map<String, EJBRestServiceInfo> restEjbs = getRestEjbs(appInfo, webApp.moduleId);
final ClassLoader classLoader = getClassLoader(webContext.getClassLoader());
final Collection<Injection> injections = webContext.getInjections();
final WebBeansContext owbCtx;
if (webContext.getWebbeansContext() != null) {
owbCtx = webContext.getWebbeansContext();
} else {
owbCtx = webContext.getAppContext().getWebBeansContext();
}
Context context = webContext.getJndiEnc();
if (context == null) {
// usually true since it is set in org.apache.tomee.catalina.TomcatWebAppBuilder.afterStart() and lookup(comp) fails
context = webContext.getAppContext().getAppJndiContext();
}
final ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
final Collection<Object> additionalProviders = new HashSet<>();
addAppProvidersIfNeeded(appInfo, webApp, classLoader, additionalProviders);
// done lazily
Collection<IdPropertiesInfo> pojoConfigurations = null;
try {
boolean deploymentWithApplication = "true".equalsIgnoreCase(appInfo.properties.getProperty(OPENEJB_USE_APPLICATION_PROPERTY, APPLICATION_DEPLOYMENT));
if (deploymentWithApplication) {
Class<?> appClazz;
for (final String app : webApp.restApplications) {
Application application;
boolean appSkipped = false;
String prefix = "/";
try {
appClazz = classLoader.loadClass(app);
application = Application.class.cast(appClazz.newInstance());
if (owbCtx != null && owbCtx.getBeanManagerImpl().isInUse()) {
try {
webContext.inject(application);
} catch (final Exception e) {
// not important since not required by the spec
}
}
} catch (final Exception e) {
throw new OpenEJBRestRuntimeException("can't create class " + app, e);
}
application = "true".equalsIgnoreCase(appInfo.properties.getProperty("openejb.cxf-rs.cache-application", "true")) ? new InternalApplication(application) : /* caches singletons and classes */
application;
final Set<Class<?>> classes = new HashSet<>(application.getClasses());
final Set<Object> singletons = application.getSingletons();
if (classes.size() + singletons.size() == 0) {
appSkipped = true;
} else {
for (final Class<?> clazz : classes) {
if (isProvider(clazz)) {
additionalProviders.add(clazz);
} else if (!hasEjbAndIsNotAManagedBean(restEjbs, clazz.getName())) {
pojoConfigurations = PojoUtil.findPojoConfig(pojoConfigurations, appInfo, webApp);
if (PojoUtil.findConfiguration(pojoConfigurations, clazz.getName()) != null) {
deploymentWithApplication = false;
logOldDeploymentUsage(clazz.getName());
}
}
}
if (deploymentWithApplication) {
// don't do it if we detected we should use old deployment
for (final Object o : singletons) {
final Class<?> clazz = o.getClass();
if (isProvider(clazz)) {
additionalProviders.add(o);
} else if (!hasEjbAndIsNotAManagedBean(restEjbs, clazz.getName())) {
pojoConfigurations = PojoUtil.findPojoConfig(pojoConfigurations, appInfo, webApp);
if (PojoUtil.findConfiguration(pojoConfigurations, clazz.getName()) != null) {
deploymentWithApplication = false;
logOldDeploymentUsage(clazz.getName());
}
}
}
}
}
if (deploymentWithApplication) {
// don't do it if we detected we should use old deployment
final String path = appPrefix(webApp, appClazz);
if (path != null) {
prefix += path + wildcard;
} else {
prefix += wildcard;
}
}
if (deploymentWithApplication) {
// don't do it if we detected we should use old deployment
if (appSkipped || application == null) {
application = !InternalApplication.class.isInstance(application) ? new InternalApplication(application) : application;
for (final String clazz : webApp.restClass) {
try {
final Class<?> loaded = classLoader.loadClass(clazz);
if (!isProvider(loaded)) {
pojoConfigurations = PojoUtil.findPojoConfig(pojoConfigurations, appInfo, webApp);
if (PojoUtil.findConfiguration(pojoConfigurations, loaded.getName()) != null) {
deploymentWithApplication = false;
logOldDeploymentUsage(loaded.getName());
break;
}
application.getClasses().add(loaded);
} else {
additionalProviders.add(loaded);
}
} catch (final Exception e) {
throw new OpenEJBRestRuntimeException("can't load class " + clazz, e);
}
}
if (deploymentWithApplication) {
addEjbToApplication(application, restEjbs);
if (!prefix.endsWith(wildcard)) {
prefix += wildcard;
}
}
}
if (!application.getClasses().isEmpty() || !application.getSingletons().isEmpty()) {
pojoConfigurations = PojoUtil.findPojoConfig(pojoConfigurations, appInfo, webApp);
deployApplication(appInfo, webApp.contextRoot, restEjbs, classLoader, injections, owbCtx, context, additionalProviders, pojoConfigurations, application, prefix);
}
}
if (!deploymentWithApplication) {
fullServletDeployment(appInfo, webApp, webContext, restEjbs, classLoader, injections, owbCtx, context, additionalProviders, pojoConfigurations);
}
}
if (webApp.restApplications.isEmpty()) {
final Application application = new InternalApplication(null);
for (final String clazz : webApp.restClass) {
try {
final Class<?> loaded = classLoader.loadClass(clazz);
if (!isProvider(loaded)) {
pojoConfigurations = PojoUtil.findPojoConfig(pojoConfigurations, appInfo, webApp);
if (PojoUtil.findConfiguration(pojoConfigurations, loaded.getName()) != null) {
deploymentWithApplication = false;
logOldDeploymentUsage(loaded.getName());
break;
}
application.getClasses().add(loaded);
} else {
additionalProviders.add(loaded);
}
} catch (final Exception e) {
throw new OpenEJBRestRuntimeException("can't load class " + clazz, e);
}
}
addEjbToApplication(application, restEjbs);
if (deploymentWithApplication) {
if (!application.getClasses().isEmpty() || !application.getSingletons().isEmpty()) {
final String path = appPrefix(webApp, application.getClass());
final String prefix;
if (path != null) {
prefix = "/" + path + wildcard;
} else {
prefix = "/" + wildcard;
}
pojoConfigurations = PojoUtil.findPojoConfig(pojoConfigurations, appInfo, webApp);
deployApplication(appInfo, webApp.contextRoot, restEjbs, classLoader, injections, owbCtx, context, additionalProviders, pojoConfigurations, application, prefix);
}
} else {
fullServletDeployment(appInfo, webApp, webContext, restEjbs, classLoader, injections, owbCtx, context, additionalProviders, pojoConfigurations);
}
}
} else {
fullServletDeployment(appInfo, webApp, webContext, restEjbs, classLoader, injections, owbCtx, context, additionalProviders, pojoConfigurations);
}
} finally {
Thread.currentThread().setContextClassLoader(oldLoader);
}
}
use of javax.ws.rs.core.Application in project che by eclipse.
the class ProjectServiceTest method setUp.
@BeforeMethod
public void setUp() throws Exception {
WorkspaceProjectsSyncer workspaceHolder = new WsAgentTestBase.TestWorkspaceHolder();
File root = new File(FS_PATH);
if (root.exists()) {
IoUtil.deleteRecursive(root);
}
root.mkdir();
File indexDir = new File(INDEX_PATH);
if (indexDir.exists()) {
IoUtil.deleteRecursive(indexDir);
}
indexDir.mkdir();
Set<PathMatcher> filters = new HashSet<>();
filters.add(path -> {
for (java.nio.file.Path pathElement : path) {
if (pathElement == null || EXCLUDE_SEARCH_PATH.equals(pathElement.toString())) {
return true;
}
}
return false;
});
FSLuceneSearcherProvider sProvider = new FSLuceneSearcherProvider(indexDir, filters);
vfsProvider = new LocalVirtualFileSystemProvider(root, sProvider);
final EventService eventService = new EventService();
// PTs for test
ProjectTypeDef chuck = new ProjectTypeDef("chuck_project_type", "chuck_project_type", true, false) {
{
addConstantDefinition("x", "attr description", new AttributeValue(Arrays.asList("a", "b")));
}
};
Set<ProjectTypeDef> projectTypes = new HashSet<>();
final LocalProjectType myProjectType = new LocalProjectType("my_project_type", "my project type");
projectTypes.add(myProjectType);
projectTypes.add(new LocalProjectType("module_type", "module type"));
projectTypes.add(chuck);
ptRegistry = new ProjectTypeRegistry(projectTypes);
phRegistry = new ProjectHandlerRegistry(new HashSet<>());
importerRegistry = new ProjectImporterRegistry(Collections.<ProjectImporter>emptySet());
projectServiceLinksInjector = new ProjectServiceLinksInjector();
projectRegistry = new ProjectRegistry(workspaceHolder, vfsProvider, ptRegistry, phRegistry, eventService);
projectRegistry.initProjects();
FileWatcherNotificationHandler fileWatcherNotificationHandler = new DefaultFileWatcherNotificationHandler(vfsProvider);
FileTreeWatcher fileTreeWatcher = new FileTreeWatcher(root, new HashSet<>(), fileWatcherNotificationHandler);
pm = new ProjectManager(vfsProvider, ptRegistry, projectRegistry, phRegistry, importerRegistry, fileWatcherNotificationHandler, fileTreeWatcher, workspaceHolder, fileWatcherManager);
pm.initWatcher();
HttpJsonRequest httpJsonRequest = mock(HttpJsonRequest.class, new SelfReturningAnswer());
//List<ProjectConfigDto> modules = new ArrayList<>();
projects = new ArrayList<>();
addMockedProjectConfigDto(myProjectType, "my_project");
when(httpJsonRequestFactory.fromLink(any())).thenReturn(httpJsonRequest);
when(httpJsonRequest.request()).thenReturn(httpJsonResponse);
when(httpJsonResponse.asDto(WorkspaceDto.class)).thenReturn(usersWorkspaceMock);
when(usersWorkspaceMock.getConfig()).thenReturn(workspaceConfigMock);
when(workspaceConfigMock.getProjects()).thenReturn(projects);
// verify(httpJsonRequestFactory).fromLink(eq(DtoFactory.newDto(Link.class)
// .withHref(apiEndpoint + "/workspace/" + workspace + "/project")
// .withMethod(PUT)));
DependencySupplierImpl dependencies = new DependencySupplierImpl();
dependencies.addInstance(ProjectTypeRegistry.class, ptRegistry);
dependencies.addInstance(UserDao.class, userDao);
dependencies.addInstance(ProjectManager.class, pm);
dependencies.addInstance(ProjectImporterRegistry.class, importerRegistry);
dependencies.addInstance(ProjectHandlerRegistry.class, phRegistry);
dependencies.addInstance(EventService.class, eventService);
dependencies.addInstance(ProjectServiceLinksInjector.class, projectServiceLinksInjector);
ResourceBinder resources = new ResourceBinderImpl();
ProviderBinder providers = ProviderBinder.getInstance();
EverrestProcessor processor = new EverrestProcessor(new EverrestConfiguration(), dependencies, new RequestHandlerImpl(new RequestDispatcher(resources), providers), null);
launcher = new ResourceLauncher(processor);
processor.addApplication(new Application() {
@Override
public Set<Class<?>> getClasses() {
return java.util.Collections.<Class<?>>singleton(ProjectService.class);
}
@Override
public Set<Object> getSingletons() {
return new HashSet<>(Arrays.asList(new ApiExceptionMapper()));
}
});
ApplicationContext.setCurrent(anApplicationContext().withProviders(providers).build());
env = org.eclipse.che.commons.env.EnvironmentContext.getCurrent();
}
Aggregations