Search in sources :

Example 6 with ClassFinder

use of org.apache.xbean.finder.ClassFinder in project tomee by apache.

the class ApplicationComposers method startContainer.

public void startContainer(final Object instance) throws Exception {
    originalProperties = (Properties) JavaSecurityManagers.getSystemProperties().clone();
    originalLoader = Thread.currentThread().getContextClassLoader();
    fixFakeClassFinder(instance);
    // For the moment we just take the first @Configuration method
    // maybe later we can add something fancy to allow multiple configurations using a qualifier
    // as a sort of altDD/altConfig concept.  Say for example the altDD prefix might be "foo",
    // we can then imagine something like this:
    // @Foo @Configuration public Properties alternateConfig(){...}
    // @Foo @Module  public Properties alternateModule(){...}
    // anyway, one thing at a time ....
    final Properties configuration = new Properties();
    configuration.put(DEPLOYMENTS_CLASSPATH_PROPERTY, "false");
    final EnableServices annotation = testClass.getAnnotation(EnableServices.class);
    if (annotation != null && annotation.httpDebug()) {
        configuration.setProperty("httpejbd.print", "true");
        configuration.setProperty("httpejbd.indent.xml", "true");
        configuration.setProperty("logging.level.OpenEJB.server.http", "FINE");
    }
    final org.apache.openejb.junit.EnableServices annotationOld = testClass.getAnnotation(org.apache.openejb.junit.EnableServices.class);
    if (annotationOld != null && annotationOld.httpDebug()) {
        configuration.setProperty("httpejbd.print", "true");
        configuration.setProperty("httpejbd.indent.xml", "true");
        configuration.setProperty("logging.level.OpenEJB.server.http", "FINE");
    }
    final WebResource webResource = testClass.getAnnotation(WebResource.class);
    if (webResource != null && webResource.value().length > 0) {
        configuration.setProperty("openejb.embedded.http.resources", Join.join(",", webResource.value()));
    }
    Openejb openejb = null;
    final Map<Object, List<Method>> configs = new HashMap<>();
    findAnnotatedMethods(configs, Configuration.class);
    findAnnotatedMethods(configs, org.apache.openejb.junit.Configuration.class);
    for (final Map.Entry<Object, List<Method>> method : configs.entrySet()) {
        for (final Method m : method.getValue()) {
            final Object o = m.invoke(method.getKey());
            if (o instanceof Properties) {
                final Properties properties = (Properties) o;
                configuration.putAll(properties);
            } else if (Openejb.class.isInstance(o)) {
                openejb = Openejb.class.cast(o);
            } else if (String.class.isInstance(o)) {
                final String path = String.class.cast(o);
                final URL url = Thread.currentThread().getContextClassLoader().getResource(path);
                if (url == null) {
                    throw new IllegalArgumentException(o.toString() + " not found");
                }
                final InputStream in = url.openStream();
                try {
                    if (path.endsWith(".json")) {
                        openejb = JSonConfigReader.read(Openejb.class, in);
                    } else {
                        openejb = JaxbOpenejb.readConfig(new InputSource(in));
                    }
                } finally {
                    IO.close(in);
                }
            }
        }
    }
    if (SystemInstance.isInitialized()) {
        SystemInstance.reset();
    }
    Collection<String> propertiesToSetAgain = null;
    final ContainerProperties configAnnot = testClass.getAnnotation(ContainerProperties.class);
    if (configAnnot != null) {
        for (final ContainerProperties.Property p : configAnnot.value()) {
            final String value = p.value();
            if (ContainerProperties.Property.IGNORED.equals(value)) {
                // enforces some clean up since we can't set null in a hash table
                System.clearProperty(p.name());
                continue;
            }
            final String name = p.name();
            configuration.put(name, value);
            if (value.contains("${")) {
                if (propertiesToSetAgain == null) {
                    propertiesToSetAgain = new LinkedList<>();
                }
                propertiesToSetAgain.add(name);
            }
        }
    }
    SystemInstance.init(configuration);
    if (SystemInstance.get().getComponent(ThreadSingletonService.class) == null) {
        CdiBuilder.initializeOWB();
    }
    for (final Map.Entry<Object, ClassFinder> finder : testClassFinders.entrySet()) {
        for (final Field field : finder.getValue().findAnnotatedFields(RandomPort.class)) {
            if (!field.isAccessible()) {
                field.setAccessible(true);
            }
            final String service = field.getAnnotation(RandomPort.class).value();
            final String key = ("http".equals(service) ? "httpejbd" : service) + ".port";
            final String existing = SystemInstance.get().getProperty(key);
            final int random;
            if (existing == null) {
                random = NetworkUtil.getNextAvailablePort();
                SystemInstance.get().setProperty(key, Integer.toString(random));
            } else {
                random = Integer.parseInt(existing);
            }
            if (int.class == field.getType()) {
                field.set(finder.getKey(), random);
            } else if (URL.class == field.getType()) {
                field.set(finder.getKey(), new URL("http://localhost:" + random + "/"));
            }
        }
    }
    for (final Map.Entry<Object, ClassFinder> finder : testClassFinders.entrySet()) {
        if (!finder.getValue().findAnnotatedClasses(SimpleLog.class).isEmpty()) {
            SystemInstance.get().setProperty("openejb.jul.forceReload", "true");
            break;
        }
    }
    final CdiExtensions cdiExtensions = testClass.getAnnotation(CdiExtensions.class);
    if (cdiExtensions != null) {
        SystemInstance.get().setComponent(LoaderService.class, new ExtensionAwareOptimizedLoaderService(cdiExtensions.value()));
    }
    // save the test under test to be able to retrieve it from extensions
    // /!\ has to be done before all other init
    SystemInstance.get().setComponent(TestInstance.class, new TestInstance(testClass, instance));
    // call the mock injector before module method to be able to use mocked classes
    // it will often use the TestInstance so
    final Map<Object, List<Method>> mockInjectors = new HashMap<>();
    findAnnotatedMethods(mockInjectors, MockInjector.class);
    findAnnotatedMethods(mockInjectors, org.apache.openejb.junit.MockInjector.class);
    if (!mockInjectors.isEmpty() && !mockInjectors.values().iterator().next().isEmpty()) {
        final Map.Entry<Object, List<Method>> methods = mockInjectors.entrySet().iterator().next();
        Object o = methods.getValue().iterator().next().invoke(methods.getKey());
        if (o instanceof Class<?>) {
            o = ((Class<?>) o).newInstance();
        }
        if (o instanceof FallbackPropertyInjector) {
            SystemInstance.get().setComponent(FallbackPropertyInjector.class, (FallbackPropertyInjector) o);
        }
    }
    for (final Map.Entry<Object, List<Method>> method : findAnnotatedMethods(new HashMap<Object, List<Method>>(), Component.class).entrySet()) {
        for (final Method m : method.getValue()) {
            setComponent(method.getKey(), m);
        }
    }
    for (final Map.Entry<Object, List<Method>> method : findAnnotatedMethods(new HashMap<Object, List<Method>>(), org.apache.openejb.junit.Component.class).entrySet()) {
        for (final Method m : method.getValue()) {
            setComponent(method.getKey(), m);
        }
    }
    final ConfigurationFactory config = new ConfigurationFactory();
    config.init(SystemInstance.get().getProperties());
    SystemInstance.get().setComponent(ConfigurationFactory.class, config);
    assembler = new Assembler();
    SystemInstance.get().setComponent(Assembler.class, assembler);
    final OpenEjbConfiguration openEjbConfiguration;
    if (openejb != null) {
        openEjbConfiguration = config.getOpenEjbConfiguration(openejb);
    } else {
        openEjbConfiguration = config.getOpenEjbConfiguration();
    }
    assembler.buildContainerSystem(openEjbConfiguration);
    if ("true".equals(configuration.getProperty(OpenEjbContainer.OPENEJB_EMBEDDED_REMOTABLE, "false")) || annotation != null || annotationOld != null) {
        try {
            if (annotation != null) {
                final List<String> value = new ArrayList<>(asList(annotation.value()));
                if (annotation.jaxrs()) {
                    value.add("jaxrs");
                }
                if (annotation.jaxws()) {
                    value.add("jaxws");
                }
                initFilteredServiceManager(value.toArray(new String[value.size()]));
            }
            if (annotationOld != null) {
                initFilteredServiceManager(annotationOld.value());
            }
            serviceManager = new ServiceManagerProxy(false);
            serviceManager.start();
        } catch (final ServiceManagerProxy.AlreadyStartedException e) {
            throw new OpenEJBRuntimeException(e);
        }
    }
    if (propertiesToSetAgain != null) {
        for (final String name : propertiesToSetAgain) {
            final String value = PropertyPlaceHolderHelper.simpleValue(SystemInstance.get().getProperty(name));
            configuration.put(name, value);
            // done lazily to support placeholders so container will not do it here
            JavaSecurityManagers.setSystemProperty(name, value);
        }
        propertiesToSetAgain.clear();
    }
}
Also used : InputSource(org.xml.sax.InputSource) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Properties(java.util.Properties) URL(java.net.URL) OpenEjbConfiguration(org.apache.openejb.assembler.classic.OpenEjbConfiguration) Field(java.lang.reflect.Field) ClassFinder(org.apache.xbean.finder.ClassFinder) ConfigurationFactory(org.apache.openejb.config.ConfigurationFactory) Arrays.asList(java.util.Arrays.asList) ArrayList(java.util.ArrayList) List(java.util.List) LinkedList(java.util.LinkedList) Openejb(org.apache.openejb.config.sys.Openejb) JaxbOpenejb(org.apache.openejb.config.sys.JaxbOpenejb) InputStream(java.io.InputStream) Method(java.lang.reflect.Method) ThreadSingletonService(org.apache.openejb.cdi.ThreadSingletonService) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) FallbackPropertyInjector(org.apache.openejb.injection.FallbackPropertyInjector) Assembler(org.apache.openejb.assembler.classic.Assembler) Map(java.util.Map) HashMap(java.util.HashMap) ServiceManagerProxy(org.apache.openejb.util.ServiceManagerProxy)

Example 7 with ClassFinder

use of org.apache.xbean.finder.ClassFinder in project tomee by apache.

the class ApplicationComposers method deployApp.

public void deployApp(final Object inputTestInstance) throws Exception {
    final ClassFinder testClassFinder = fixFakeClassFinder(inputTestInstance);
    final ClassLoader loader = testClass.getClassLoader();
    AppModule appModule = new AppModule(loader, testClass.getSimpleName());
    // Add the test case as an @ManagedBean
    final ManagedBean testBean;
    {
        final EjbJar ejbJar = new EjbJar();
        final OpenejbJar openejbJar = new OpenejbJar();
        testBean = ejbJar.addEnterpriseBean(new ManagedBean(testClass.getSimpleName(), testClass.getName(), true));
        testBean.localBean();
        testBean.setTransactionType(TransactionType.BEAN);
        final EjbDeployment ejbDeployment = openejbJar.addEjbDeployment(testBean);
        ejbDeployment.setDeploymentId(testClass.getName());
        final EjbModule ejbModule = new EjbModule(ejbJar, openejbJar);
        ejbModule.getProperties().setProperty("openejb.cdi.activated", "false");
        final FinderFactory.OpenEJBAnnotationFinder finder = new FinderFactory.OpenEJBAnnotationFinder(new ClassesArchive(ancestors(testClass)));
        ejbModule.setFinder(finder);
        if (finder.findMetaAnnotatedFields(Inject.class).size() + finder.findMetaAnnotatedMethods(Inject.class).size() > 0) {
            // "activate" cdi to avoid WARNINGs
            ejbModule.setBeans(new Beans());
        }
        appModule.getEjbModules().add(ejbModule);
    }
    final Map<String, URL> additionalDescriptors = descriptorsToMap(testClass.getAnnotation(org.apache.openejb.junit.Descriptors.class));
    final Map<String, URL> additionalDescriptorsNew = descriptorsToMap(testClass.getAnnotation(Descriptors.class));
    additionalDescriptors.putAll(additionalDescriptorsNew);
    Application application = null;
    int webModulesNb = 0;
    final Jars globalJarsAnnotation = testClass.getAnnotation(Jars.class);
    // Invoke the @Module producer methods to build out the AppModule
    int moduleNumber = 0;
    // we dont consider resources.xml to set an app as standalone or not
    int notBusinessModuleNumber = 0;
    final Map<Object, List<Method>> moduleMethods = new HashMap<>();
    findAnnotatedMethods(moduleMethods, Module.class);
    findAnnotatedMethods(moduleMethods, org.apache.openejb.junit.Module.class);
    for (final Map.Entry<Object, List<Method>> methods : moduleMethods.entrySet()) {
        moduleNumber += methods.getValue().size();
        for (final Method method : methods.getValue()) {
            final Object obj = method.invoke(methods.getKey());
            final Jars jarsAnnotation = method.getAnnotation(Jars.class);
            final Classes classesAnnotation = method.getAnnotation(Classes.class);
            final org.apache.openejb.junit.Classes classesAnnotationOld = method.getAnnotation(org.apache.openejb.junit.Classes.class);
            final boolean defaultConfig = method.getAnnotation(Default.class) != null;
            Class<?>[] classes = null;
            String[] excludes = null;
            Class<?>[] cdiInterceptors = null;
            Class<?>[] cdiAlternatives = null;
            Class<?>[] cdiStereotypes = null;
            Class<?>[] cdiDecorators = null;
            boolean cdi = false;
            boolean innerClassesAsBean = false;
            if (classesAnnotation != null) {
                classes = classesAnnotation.value();
                excludes = classesAnnotation.excludes();
                innerClassesAsBean = classesAnnotation.innerClassesAsBean();
                cdiInterceptors = classesAnnotation.cdiInterceptors();
                cdiDecorators = classesAnnotation.cdiDecorators();
                cdiAlternatives = classesAnnotation.cdiAlternatives();
                cdiStereotypes = classesAnnotation.cdiStereotypes();
                cdi = isCdi(classesAnnotation.cdi(), cdiInterceptors, cdiAlternatives, cdiStereotypes, cdiDecorators);
            } else if (classesAnnotationOld != null) {
                classes = classesAnnotationOld.value();
            }
            if (obj instanceof WebApp) {
                // will add the ejbmodule too
                final WebApp webApp = WebApp.class.cast(obj);
                if (webApp.getContextRoot() == null && classesAnnotation != null) {
                    webApp.contextRoot(classesAnnotation.context());
                }
                webModulesNb++;
                addWebApp(appModule, testBean, additionalDescriptors, method.getAnnotation(Descriptors.class), method.getAnnotation(JaxrsProviders.class), webApp, globalJarsAnnotation, jarsAnnotation, classes, excludes, cdiInterceptors, cdiAlternatives, cdiDecorators, cdiStereotypes, cdi, innerClassesAsBean, defaultConfig);
            } else if (obj instanceof WebModule) {
                // will add the ejbmodule too
                webModulesNb++;
                final WebModule webModule = (WebModule) obj;
                webModule.getAltDDs().putAll(additionalDescriptors);
                webModule.getAltDDs().putAll(descriptorsToMap(method.getAnnotation(Descriptors.class)));
                final EjbModule ejbModule = DeploymentLoader.addWebModule(webModule, appModule);
                ejbModule.getProperties().put(CdiScanner.OPENEJB_CDI_FILTER_CLASSLOADER, "false");
                if (cdi) {
                    ejbModule.setBeans(beans(new Beans(), cdiDecorators, cdiInterceptors, cdiAlternatives, cdiStereotypes));
                }
                Collection<File> files = findFiles(jarsAnnotation);
                if (defaultConfig) {
                    (files == null ? files = new LinkedList<>() : files).add(jarLocation(testClass));
                }
                webModule.setFinder(finderFromClasses(webModule, classes, files, excludes));
                ejbModule.setFinder(webModule.getFinder());
            } else if (obj instanceof EjbModule) {
                final EjbModule ejbModule = (EjbModule) obj;
                ejbModule.getAltDDs().putAll(additionalDescriptors);
                ejbModule.getAltDDs().putAll(descriptorsToMap(method.getAnnotation(Descriptors.class)));
                ejbModule.initAppModule(appModule);
                appModule.getEjbModules().add(ejbModule);
                if (cdi) {
                    ejbModule.setBeans(beans(new Beans(), cdiDecorators, cdiInterceptors, cdiAlternatives, cdiStereotypes));
                }
                Collection<File> files = findFiles(jarsAnnotation);
                if (defaultConfig) {
                    (files == null ? files = new LinkedList<>() : files).add(jarLocation(testClass));
                }
                ejbModule.setFinder(finderFromClasses(ejbModule, classes, files, excludes));
            } else if (obj instanceof EjbJar) {
                final EjbJar ejbJar = (EjbJar) obj;
                setId(ejbJar, method);
                final EjbModule ejbModule = new EjbModule(ejbJar);
                ejbModule.getAltDDs().putAll(additionalDescriptors);
                ejbModule.getAltDDs().putAll(descriptorsToMap(method.getAnnotation(Descriptors.class)));
                appModule.getEjbModules().add(ejbModule);
                if (cdi) {
                    ejbModule.setBeans(beans(new Beans(), cdiDecorators, cdiInterceptors, cdiAlternatives, cdiStereotypes));
                }
                Collection<File> files = findFiles(jarsAnnotation);
                if (defaultConfig) {
                    (files == null ? files = new LinkedList<>() : files).add(jarLocation(testClass));
                }
                ejbModule.setFinder(finderFromClasses(ejbModule, classes, files, excludes));
            } else if (obj instanceof EnterpriseBean) {
                final EnterpriseBean bean = (EnterpriseBean) obj;
                final EjbJar ejbJar = new EjbJar(method.getName());
                ejbJar.addEnterpriseBean(bean);
                final EjbModule ejbModule = new EjbModule(ejbJar);
                final Beans beans = new Beans();
                beans.addManagedClass(bean.getEjbClass());
                ejbModule.setBeans(beans);
                appModule.getEjbModules().add(ejbModule);
                if (cdi) {
                    ejbModule.setBeans(beans(new Beans(), cdiDecorators, cdiInterceptors, cdiAlternatives, cdiStereotypes));
                }
                Collection<File> files = findFiles(jarsAnnotation);
                if (defaultConfig) {
                    (files == null ? files = new LinkedList<>() : files).add(jarLocation(testClass));
                }
                ejbModule.setFinder(finderFromClasses(ejbModule, classes, files, excludes));
            } else if (obj instanceof Application) {
                application = (Application) obj;
                setId(application, method);
            } else if (obj instanceof Connector) {
                final Connector connector = (Connector) obj;
                setId(connector, method);
                appModule.getConnectorModules().add(new ConnectorModule(connector));
            } else if (obj instanceof Persistence) {
                final Persistence persistence = (Persistence) obj;
                appModule.addPersistenceModule(new PersistenceModule(appModule, implicitRootUrl(method.getAnnotation(PersistenceRootUrl.class)), persistence));
                notBusinessModuleNumber++;
            } else if (obj instanceof PersistenceUnit) {
                final PersistenceUnit unit = (PersistenceUnit) obj;
                appModule.addPersistenceModule(new PersistenceModule(appModule, implicitRootUrl(method.getAnnotation(PersistenceRootUrl.class)), new Persistence(unit)));
                notBusinessModuleNumber++;
            } else if (obj instanceof Beans) {
                final Beans beans = (Beans) obj;
                final EjbModule ejbModule = new EjbModule(new EjbJar(method.getName()));
                ejbModule.setBeans(beans);
                appModule.getEjbModules().add(ejbModule);
                if (cdi) {
                    ejbModule.setBeans(beans(beans, cdiDecorators, cdiInterceptors, cdiAlternatives, cdiStereotypes));
                }
                Collection<File> files = findFiles(jarsAnnotation);
                if (defaultConfig) {
                    (files == null ? files = new LinkedList<>() : files).add(jarLocation(testClass));
                }
                ejbModule.setFinder(finderFromClasses(ejbModule, classes, files, excludes));
            } else if (obj instanceof Class[]) {
                final Class[] beans = (Class[]) obj;
                final EjbModule ejbModule = new EjbModule(new EjbJar(method.getName()));
                ejbModule.setFinder(new AnnotationFinder(new ClassesArchive(beans)).link());
                ejbModule.setBeans(new Beans());
                appModule.getEjbModules().add(ejbModule);
            } else if (obj instanceof Class) {
                final Class bean = (Class) obj;
                final EjbModule ejbModule = new EjbModule(new EjbJar(method.getName()));
                ejbModule.setFinder(new AnnotationFinder(new ClassesArchive(bean)).link());
                ejbModule.setBeans(new Beans());
                appModule.getEjbModules().add(ejbModule);
            } else if (obj instanceof IAnnotationFinder) {
                final EjbModule ejbModule = new EjbModule(new EjbJar(method.getName()));
                ejbModule.setFinder((IAnnotationFinder) obj);
                ejbModule.setBeans(new Beans());
                appModule.getEjbModules().add(ejbModule);
            } else if (obj instanceof ClassesArchive) {
                final EjbModule ejbModule = new EjbModule(new EjbJar(method.getName()));
                ejbModule.setFinder(new AnnotationFinder((Archive) obj).link());
                ejbModule.setBeans(new Beans());
                appModule.getEjbModules().add(ejbModule);
            } else if (obj instanceof Resources) {
                final Resources asResources = Resources.class.cast(obj);
                appModule.getResources().addAll(asResources.getResource());
                appModule.getContainers().addAll(asResources.getContainer());
                notBusinessModuleNumber++;
            } else if (obj instanceof AppModule) {
                // we can probably go further here
                final AppModule module = (AppModule) obj;
                module.getAltDDs().putAll(additionalDescriptors);
                module.getAltDDs().putAll(descriptorsToMap(method.getAnnotation(Descriptors.class)));
                if (module.getWebModules().size() > 0) {
                    webModulesNb++;
                }
                appModule.getEjbModules().addAll(module.getEjbModules());
                appModule.getPersistenceModules().addAll(module.getPersistenceModules());
                appModule.getAdditionalLibMbeans().addAll(module.getAdditionalLibMbeans());
                appModule.getWebModules().addAll(module.getWebModules());
                appModule.getConnectorModules().addAll(module.getConnectorModules());
                appModule.getResources().addAll(module.getResources());
                appModule.getServices().addAll(module.getServices());
                appModule.getPojoConfigurations().putAll(module.getPojoConfigurations());
                appModule.getAdditionalLibraries().addAll(module.getAdditionalLibraries());
                appModule.getAltDDs().putAll(module.getAltDDs());
                appModule.getProperties().putAll(module.getProperties());
            } else {
                moduleNumber--;
            }
        }
    }
    final Classes classClasses = testClass.getAnnotation(Classes.class);
    if (classClasses != null) {
        final WebApp webapp = new WebApp();
        webapp.setContextRoot(classClasses.context());
        addWebApp(appModule, testBean, additionalDescriptors, null, null, webapp, globalJarsAnnotation, null, classClasses.value(), classClasses.excludes(), classClasses.cdiInterceptors(), classClasses.cdiAlternatives(), classClasses.cdiDecorators(), classClasses.cdiStereotypes(), classClasses.cdi(), classClasses.innerClassesAsBean(), testClass.getAnnotation(Default.class) != null);
        webModulesNb++;
        moduleNumber++;
    }
    // Application is final in AppModule, which is fine, so we'll create a new one and move everything
    if (application != null) {
        final AppModule newModule = new AppModule(appModule.getClassLoader(), appModule.getModuleId(), application, false);
        newModule.getClientModules().addAll(appModule.getClientModules());
        newModule.addPersistenceModules(appModule.getPersistenceModules());
        newModule.getEjbModules().addAll(appModule.getEjbModules());
        newModule.getConnectorModules().addAll(appModule.getConnectorModules());
        appModule = newModule;
    }
    // config for the app
    for (final Map.Entry<Object, List<Method>> method : findAnnotatedMethods(new HashMap<Object, List<Method>>(), ApplicationConfiguration.class).entrySet()) {
        for (final Method m : method.getValue()) {
            final Object o = m.invoke(method.getKey());
            if (Properties.class.isInstance(o)) {
                appModule.getProperties().putAll(Properties.class.cast(o));
            }
        }
    }
    // copy ejb into beans if cdi is activated and init finder
    for (final EjbModule ejb : appModule.getEjbModules()) {
        final EnterpriseBean[] enterpriseBeans = ejb.getEjbJar().getEnterpriseBeans();
        final Beans beans = ejb.getBeans();
        if (beans != null && ejb.getEjbJar() != null) {
            for (final EnterpriseBean bean : enterpriseBeans) {
                boolean found = false;
                for (final List<String> mc : beans.getManagedClasses().values()) {
                    if (mc.contains(bean.getEjbClass())) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    beans.addManagedClass(bean.getEjbClass());
                }
            }
        }
    }
    if (moduleNumber - notBusinessModuleNumber == 1 && webModulesNb == 1) {
        appModule.setStandloneWebModule();
    }
    if (webModulesNb > 0 && SystemInstance.get().getComponent(WebAppBuilder.class) == null) {
        SystemInstance.get().setComponent(WebAppBuilder.class, new LightweightWebAppBuilder());
    }
    final Context jndiContext = SystemInstance.get().getComponent(ContainerSystem.class).getJNDIContext();
    for (final EnvEntry entry : testBean.getEnvEntry()) {
        // set it in global jndi context since that's "app" entries and otherwise when we are no more in test bean context lookup fails
        final String name = entry.getName();
        final String jndi;
        if (name.startsWith("java:") || name.startsWith("comp/env")) {
            jndi = name;
        } else {
            jndi = "java:comp/env/" + name;
        }
        jndiContext.bind(jndi, entry.getEnvEntryValue());
    }
    appInfo = SystemInstance.get().getComponent(ConfigurationFactory.class).configureApplication(appModule);
    appContext = assembler.createApplication(appInfo);
    if (mockCdiContexts() && appContext.getWebBeansContext() != null) {
        ScopeHelper.startContexts(appContext.getWebBeansContext().getContextsService(), servletContext, session);
    }
    final BeanContext context = SystemInstance.get().getComponent(ContainerSystem.class).getBeanContext(testClass.getName());
    enrich(inputTestInstance, context);
    JavaSecurityManagers.setSystemProperty(Context.INITIAL_CONTEXT_FACTORY, InitContextFactory.class.getName());
    JavaSecurityManagers.setSystemProperty(OPENEJB_APPLICATION_COMPOSER_CONTEXT, appContext.getGlobalJndiContext());
    final List<Field> fields = new ArrayList<>(testClassFinder.findAnnotatedFields(AppResource.class));
    fields.addAll(testClassFinder.findAnnotatedFields(org.apache.openejb.junit.AppResource.class));
    for (final Field field : fields) {
        final Class<?> type = field.getType();
        if (AppModule.class.isAssignableFrom(type)) {
            field.setAccessible(true);
            field.set(inputTestInstance, appModule);
        } else if (Context.class.isAssignableFrom(type)) {
            field.setAccessible(true);
            field.set(inputTestInstance, new InitialContext(new Properties() {

                {
                    setProperty(Context.INITIAL_CONTEXT_FACTORY, LocalInitialContextFactory.class.getName());
                }
            }));
        } else if (ApplicationComposers.class.isAssignableFrom(type)) {
            field.setAccessible(true);
            field.set(inputTestInstance, this);
        } else if (ContextProvider.class.isAssignableFrom(type)) {
            RESTResourceFinder finder = SystemInstance.get().getComponent(RESTResourceFinder.class);
            if (finder == null || !ContextProvider.class.isInstance(finder)) {
                finder = new ContextProvider(finder);
                SystemInstance.get().setComponent(RESTResourceFinder.class, finder);
            }
            field.setAccessible(true);
            field.set(inputTestInstance, finder);
        } else {
            throw new IllegalArgumentException("can't find value for type " + type.getName());
        }
    }
    previous = ThreadContext.enter(new ThreadContext(context, null, Operation.BUSINESS));
    // switch back since next test will use another instance
    testClassFinders.put(this, testClassFinder);
}
Also used : ContainerSystem(org.apache.openejb.spi.ContainerSystem) AppModule(org.apache.openejb.config.AppModule) FilteredArchive(org.apache.xbean.finder.archive.FilteredArchive) ClassesArchive(org.apache.xbean.finder.archive.ClassesArchive) FileArchive(org.apache.xbean.finder.archive.FileArchive) JarArchive(org.apache.xbean.finder.archive.JarArchive) CompositeArchive(org.apache.xbean.finder.archive.CompositeArchive) Archive(org.apache.xbean.finder.archive.Archive) HashMap(java.util.HashMap) EjbModule(org.apache.openejb.config.EjbModule) ArrayList(java.util.ArrayList) Arrays.asList(java.util.Arrays.asList) ArrayList(java.util.ArrayList) List(java.util.List) LinkedList(java.util.LinkedList) RESTResourceFinder(org.apache.openejb.rest.RESTResourceFinder) Method(java.lang.reflect.Method) WebModule(org.apache.openejb.config.WebModule) ContextProvider(org.apache.openejb.testing.rest.ContextProvider) LinkedList(java.util.LinkedList) Persistence(org.apache.openejb.jee.jpa.unit.Persistence) BeanContext(org.apache.openejb.BeanContext) Collection(java.util.Collection) EjbDeployment(org.apache.openejb.jee.oejb3.EjbDeployment) Resources(org.apache.openejb.config.sys.Resources) ManagedBean(org.apache.openejb.jee.ManagedBean) Application(org.apache.openejb.jee.Application) Map(java.util.Map) HashMap(java.util.HashMap) File(java.io.File) AnnotationFinder(org.apache.xbean.finder.AnnotationFinder) IAnnotationFinder(org.apache.xbean.finder.IAnnotationFinder) Connector(org.apache.openejb.jee.Connector) EnterpriseBean(org.apache.openejb.jee.EnterpriseBean) IAnnotationFinder(org.apache.xbean.finder.IAnnotationFinder) InitContextFactory(org.apache.openejb.core.ivm.naming.InitContextFactory) Properties(java.util.Properties) URL(java.net.URL) ConnectorModule(org.apache.openejb.config.ConnectorModule) Field(java.lang.reflect.Field) OpenejbJar(org.apache.openejb.jee.oejb3.OpenejbJar) PersistenceUnit(org.apache.openejb.jee.jpa.unit.PersistenceUnit) ClassFinder(org.apache.xbean.finder.ClassFinder) EjbJar(org.apache.openejb.jee.EjbJar) EnvEntry(org.apache.openejb.jee.EnvEntry) WebContext(org.apache.openejb.core.WebContext) InitialContext(javax.naming.InitialContext) MockServletContext(org.apache.webbeans.web.lifecycle.test.MockServletContext) BeanContext(org.apache.openejb.BeanContext) Context(javax.naming.Context) ThreadContext(org.apache.openejb.core.ThreadContext) AppContext(org.apache.openejb.AppContext) ThreadContext(org.apache.openejb.core.ThreadContext) FinderFactory(org.apache.openejb.config.FinderFactory) PersistenceModule(org.apache.openejb.config.PersistenceModule) InitialContext(javax.naming.InitialContext) Beans(org.apache.openejb.jee.Beans) LightweightWebAppBuilder(org.apache.openejb.web.LightweightWebAppBuilder) ClassesArchive(org.apache.xbean.finder.archive.ClassesArchive) WebApp(org.apache.openejb.jee.WebApp)

Example 8 with ClassFinder

use of org.apache.xbean.finder.ClassFinder in project tomee by apache.

the class ApplicationComposers method findAnnotatedMethods.

private Map<Object, List<Method>> findAnnotatedMethods(final Map<Object, List<Method>> map, final Class<? extends Annotation> annotation) {
    for (final Map.Entry<Object, ClassFinder> finder : testClassFinders.entrySet()) {
        final Object key = finder.getKey();
        final List<Method> newAnnotatedMethods = finder.getValue().findAnnotatedMethods(annotation);
        List<Method> annotatedMethods = map.get(key);
        if (annotatedMethods == null) {
            annotatedMethods = newAnnotatedMethods;
            map.put(key, annotatedMethods);
        } else {
            for (final Method m : newAnnotatedMethods) {
                if (!annotatedMethods.contains(m)) {
                    annotatedMethods.add(m);
                }
            }
        }
    }
    return map;
}
Also used : ClassFinder(org.apache.xbean.finder.ClassFinder) Method(java.lang.reflect.Method) Map(java.util.Map) HashMap(java.util.HashMap)

Example 9 with ClassFinder

use of org.apache.xbean.finder.ClassFinder in project tomee by apache.

the class SingletonContainer method invokeWebService.

private Object invokeWebService(final Object[] args, final BeanContext beanContext, final Method runMethod, final Instance instance) throws Exception {
    if (args.length < 2) {
        throw new IllegalArgumentException("WebService calls must follow format {messageContext, interceptor, [arg...]}.");
    }
    final Object messageContext = args[0];
    if (messageContext == null) {
        throw new IllegalArgumentException("MessageContext is null.");
    }
    // This object will be used as an interceptor in the stack and will be responsible
    // for unmarshalling the soap message parts into an argument list that will be
    // used for the actual method invocation.
    //
    // We just need to make it an interceptor in the OpenEJB sense and tack it on the end
    // of our stack.
    final Object interceptor = args[1];
    if (interceptor == null) {
        throw new IllegalArgumentException("Interceptor instance is null.");
    }
    final Class<?> interceptorClass = interceptor.getClass();
    //  Add the webservice interceptor to the list of interceptor instances
    final Map<String, Object> interceptors = new HashMap<String, Object>(instance.interceptors);
    {
        interceptors.put(interceptorClass.getName(), interceptor);
    }
    //  Create an InterceptorData for the webservice interceptor to the list of interceptorDatas for this method
    final List<InterceptorData> interceptorDatas = new ArrayList<InterceptorData>();
    {
        final InterceptorData providerData = new InterceptorData(interceptorClass);
        List<Method> aroundInvokes = interceptorCache.get(interceptorClass);
        if (aroundInvokes == null) {
            aroundInvokes = new ClassFinder(interceptorClass).findAnnotatedMethods(AroundInvoke.class);
            if (SingletonContainer.class.getClassLoader() == interceptorClass.getClassLoader()) {
                // use cache only for server classes
                final List<Method> value = new CopyOnWriteArrayList<Method>(aroundInvokes);
                // ensure it to be thread safe
                aroundInvokes = interceptorCache.putIfAbsent(interceptorClass, value);
                if (aroundInvokes == null) {
                    aroundInvokes = value;
                }
            }
        }
        providerData.getAroundInvoke().addAll(aroundInvokes);
        interceptorDatas.add(0, providerData);
        interceptorDatas.addAll(beanContext.getMethodInterceptors(runMethod));
    }
    final InterceptorStack interceptorStack = new InterceptorStack(instance.bean, runMethod, Operation.BUSINESS_WS, interceptorDatas, interceptors);
    final Object[] params = new Object[runMethod.getParameterTypes().length];
    if (messageContext instanceof javax.xml.rpc.handler.MessageContext) {
        ThreadContext.getThreadContext().set(javax.xml.rpc.handler.MessageContext.class, (javax.xml.rpc.handler.MessageContext) messageContext);
        return interceptorStack.invoke((javax.xml.rpc.handler.MessageContext) messageContext, params);
    } else if (messageContext instanceof javax.xml.ws.handler.MessageContext) {
        AddressingSupport wsaSupport = NoAddressingSupport.INSTANCE;
        for (int i = 2; i < args.length; i++) {
            if (args[i] instanceof AddressingSupport) {
                wsaSupport = (AddressingSupport) args[i];
            }
        }
        ThreadContext.getThreadContext().set(AddressingSupport.class, wsaSupport);
        ThreadContext.getThreadContext().set(javax.xml.ws.handler.MessageContext.class, (javax.xml.ws.handler.MessageContext) messageContext);
        return interceptorStack.invoke((javax.xml.ws.handler.MessageContext) messageContext, params);
    }
    throw new IllegalArgumentException("Uknown MessageContext type: " + messageContext.getClass().getName());
}
Also used : HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ArrayList(java.util.ArrayList) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Method(java.lang.reflect.Method) InterceptorData(org.apache.openejb.core.interceptor.InterceptorData) InterceptorStack(org.apache.openejb.core.interceptor.InterceptorStack) ClassFinder(org.apache.xbean.finder.ClassFinder) EJBObject(javax.ejb.EJBObject) EJBLocalObject(javax.ejb.EJBLocalObject) ArrayList(java.util.ArrayList) List(java.util.List) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) NoAddressingSupport(org.apache.openejb.core.webservices.NoAddressingSupport) AddressingSupport(org.apache.openejb.core.webservices.AddressingSupport)

Example 10 with ClassFinder

use of org.apache.xbean.finder.ClassFinder in project tomee by apache.

the class TestClient method processFieldInjections.

protected final void processFieldInjections() {
    Object home = null;
    ClassFinder finder = null;
    List<Field> fieldList = null;
    finder = new ClassFinder(getClassPath());
    fieldList = finder.findAnnotatedFields(EJB.class);
    for (final Iterator fields = fieldList.iterator(); fields.hasNext(); ) {
        final Field field = (Field) fields.next();
        final EJB ejbAnnotation = field.getAnnotation(EJB.class);
        if ((ejbAnnotation.name() != null) && (ejbAnnotation.name() != "") && (ejbAnnotation.beanInterface() != null)) {
            try {
                home = initialContext.lookup(ejbAnnotation.name());
                // home = ejbAnnotation.beanInterface().cast(home;
                home = cast(home, ejbAnnotation.beanInterface());
                field.setAccessible(true);
                field.set(this, home);
            } catch (final Exception ex) {
                // TODO - MNour : Needs better exception handling
                ex.printStackTrace();
            }
        }
    }
}
Also used : Field(java.lang.reflect.Field) ClassFinder(org.apache.xbean.finder.ClassFinder) Iterator(java.util.Iterator) EJB(javax.ejb.EJB)

Aggregations

ClassFinder (org.apache.xbean.finder.ClassFinder)24 Method (java.lang.reflect.Method)10 ArrayList (java.util.ArrayList)10 URL (java.net.URL)8 File (java.io.File)6 HashMap (java.util.HashMap)6 Field (java.lang.reflect.Field)5 List (java.util.List)5 MojoFailureException (org.apache.maven.plugin.MojoFailureException)5 URLClassLoader (java.net.URLClassLoader)4 Map (java.util.Map)4 Arrays.asList (java.util.Arrays.asList)3 LinkedList (java.util.LinkedList)3 Properties (java.util.Properties)3 MalformedURLException (java.net.MalformedURLException)2 Iterator (java.util.Iterator)2 TreeSet (java.util.TreeSet)2 CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)2 EJB (javax.ejb.EJB)2 NamingException (javax.naming.NamingException)2