Search in sources :

Example 16 with SystemInstance

use of org.apache.openejb.loader.SystemInstance in project tomee by apache.

the class EjbTimerServiceImpl method getDefaultScheduler.

public static synchronized Scheduler getDefaultScheduler(final BeanContext deployment) {
    Scheduler scheduler = deployment.get(Scheduler.class);
    if (scheduler != null) {
        boolean valid;
        try {
            valid = !scheduler.isShutdown();
        } catch (final Exception ignored) {
            valid = false;
        }
        if (valid) {
            return scheduler;
        }
    }
    Scheduler thisScheduler;
    synchronized (deployment.getId()) {
        // should be done only once so no perf issues
        scheduler = deployment.get(Scheduler.class);
        if (scheduler != null) {
            return scheduler;
        }
        final Properties properties = new Properties();
        int quartzProps = 0;
        quartzProps += putAll(properties, SystemInstance.get().getProperties());
        quartzProps += putAll(properties, deployment.getModuleContext().getAppContext().getProperties());
        quartzProps += putAll(properties, deployment.getModuleContext().getProperties());
        quartzProps += putAll(properties, deployment.getProperties());
        // custom config -> don't use default/global scheduler
        // if one day we want to keep a global config for a global scheduler (SystemInstance.get().getProperties()) we'll need to manage resume/pause etc correctly by app
        // since we have a scheduler by ejb today in such a case we don't need
        final boolean newInstance = quartzProps > 0;
        final SystemInstance systemInstance = SystemInstance.get();
        scheduler = systemInstance.getComponent(Scheduler.class);
        if (scheduler == null || newInstance) {
            final boolean useTccl = "true".equalsIgnoreCase(properties.getProperty(OPENEJB_QUARTZ_USE_TCCL, "false"));
            defaultQuartzConfiguration(properties, deployment, newInstance, useTccl);
            try {
                // start in container context to avoid thread leaks
                final ClassLoader oldCl = Thread.currentThread().getContextClassLoader();
                if (useTccl) {
                    Thread.currentThread().setContextClassLoader(deployment.getClassLoader());
                } else {
                    Thread.currentThread().setContextClassLoader(EjbTimerServiceImpl.class.getClassLoader());
                }
                try {
                    thisScheduler = new StdSchedulerFactory(properties).getScheduler();
                    thisScheduler.start();
                } finally {
                    Thread.currentThread().setContextClassLoader(oldCl);
                }
                // durability is configured with true, which means that the job will be kept in the store even if no trigger is attached to it.
                // Currently, all the EJB beans share with the same job instance
                final JobDetail job = JobBuilder.newJob(EjbTimeoutJob.class).withIdentity(OPENEJB_TIMEOUT_JOB_NAME, OPENEJB_TIMEOUT_JOB_GROUP_NAME).storeDurably(true).requestRecovery(false).build();
                thisScheduler.addJob(job, true);
            } catch (final SchedulerException e) {
                throw new OpenEJBRuntimeException("Fail to initialize the default scheduler", e);
            }
            if (!newInstance) {
                systemInstance.setComponent(Scheduler.class, thisScheduler);
            }
        } else {
            thisScheduler = scheduler;
        }
        deployment.set(Scheduler.class, thisScheduler);
    }
    return thisScheduler;
}
Also used : StdSchedulerFactory(org.apache.openejb.quartz.impl.StdSchedulerFactory) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) JobDetail(org.apache.openejb.quartz.JobDetail) SchedulerException(org.apache.openejb.quartz.SchedulerException) Scheduler(org.apache.openejb.quartz.Scheduler) SystemInstance(org.apache.openejb.loader.SystemInstance) Properties(java.util.Properties) OpenEJBException(org.apache.openejb.OpenEJBException) EJBException(javax.ejb.EJBException) SchedulerException(org.apache.openejb.quartz.SchedulerException) ApplicationException(org.apache.openejb.ApplicationException) IOException(java.io.IOException) SystemException(javax.transaction.SystemException) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException)

Example 17 with SystemInstance

use of org.apache.openejb.loader.SystemInstance in project tomee by apache.

the class DefaultTimerThreadPoolAdapter method shutdown.

@Override
public synchronized void shutdown(final boolean waitForJobsToComplete) {
    if (threadPoolExecutorUsed) {
        final SystemInstance systemInstance = SystemInstance.get();
        final TimerExecutor te = systemInstance.getComponent(TimerExecutor.class);
        if (te != null) {
            if (te.executor == executor) {
                if (te.decr()) {
                    doShutdownExecutor(waitForJobsToComplete);
                    systemInstance.removeComponent(TimerExecutor.class);
                } else {
                    // flush jobs, maybe not all dedicated to this threadpool if shared but shouldn't be an issue
                    final ThreadPoolExecutor tpe = ThreadPoolExecutor.class.cast(executor);
                    if (waitForJobsToComplete) {
                        final Collection<Runnable> jobs = new ArrayList<>();
                        tpe.getQueue().drainTo(jobs);
                        for (final Runnable r : jobs) {
                            try {
                                r.run();
                            } catch (final Exception e) {
                                logger.warning(e.getMessage(), e);
                            }
                        }
                    }
                }
            } else {
                doShutdownExecutor(waitForJobsToComplete);
            }
        } else {
            doShutdownExecutor(waitForJobsToComplete);
        }
    }
}
Also used : SystemInstance(org.apache.openejb.loader.SystemInstance) ArrayList(java.util.ArrayList) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) SchedulerConfigException(org.apache.openejb.quartz.SchedulerConfigException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException)

Example 18 with SystemInstance

use of org.apache.openejb.loader.SystemInstance in project tomee by apache.

the class SingletonInstanceManager method initializeDependencies.

private void initializeDependencies(final BeanContext beanContext) throws OpenEJBException {
    final SystemInstance systemInstance = SystemInstance.get();
    final ContainerSystem containerSystem = systemInstance.getComponent(ContainerSystem.class);
    for (final String dependencyId : beanContext.getDependsOn()) {
        final BeanContext dependencyContext = containerSystem.getBeanContext(dependencyId);
        if (dependencyContext == null) {
            throw new OpenEJBException("Deployment does not exist. Deployment(id='" + dependencyContext + "')");
        }
        final Object containerData = dependencyContext.getContainerData();
        // managed by a different container implementation
        if (containerData instanceof Data) {
            final Data data = (Data) containerData;
            data.initialize();
        }
    }
}
Also used : ContainerSystem(org.apache.openejb.spi.ContainerSystem) BeanContext(org.apache.openejb.BeanContext) OpenEJBException(org.apache.openejb.OpenEJBException) SystemInstance(org.apache.openejb.loader.SystemInstance) InterceptorData(org.apache.openejb.core.interceptor.InterceptorData)

Example 19 with SystemInstance

use of org.apache.openejb.loader.SystemInstance in project tomee by apache.

the class CheckInvalidAsynchronousAnnotationsTest method setupTestCase.

@BeforeClass
public static void setupTestCase() {
    SystemInstance.reset();
    final SystemInstance system = SystemInstance.get();
    system.setProperty(VALIDATION_OUTPUT_LEVEL, "VERBOSE");
}
Also used : SystemInstance(org.apache.openejb.loader.SystemInstance) BeforeClass(org.junit.BeforeClass)

Example 20 with SystemInstance

use of org.apache.openejb.loader.SystemInstance in project tomee by apache.

the class DeploymentLoader method createWebModule.

public WebModule createWebModule(final String appId, final String warPath, final ClassLoader parentClassLoader, final String contextRoot, final String moduleName, final ExternalConfiguration config) throws OpenEJBException {
    File warFile = new File(warPath);
    if (!warFile.isDirectory()) {
        warFile = unpack(warFile);
    }
    // read web.xml file
    final Map<String, URL> descriptors;
    try {
        descriptors = getWebDescriptors(warFile);
    } catch (final IOException e) {
        throw new OpenEJBException("Unable to collect descriptors in web module: " + contextRoot, e);
    }
    final WebApp webApp;
    final URL webXmlUrl = descriptors.get("web.xml");
    if (webXmlUrl != null) {
        webApp = ReadDescriptors.readWebApp(webXmlUrl);
    } else {
        // no web.xml webapp - possible since Servlet 3.0
        webApp = new WebApp();
    }
    // determine war class path
    ensureContainerUrls();
    final List<URL> webUrls = new ArrayList<>(containerUrls);
    final SystemInstance systemInstance = SystemInstance.get();
    // add these urls first to ensure we load classes from here first
    final String externalRepos = systemInstance.getProperty("tomee." + warFile.getName().replace(".war", "") + ".externalRepositories");
    List<URL> externalUrls = null;
    if (externalRepos != null) {
        externalUrls = new ArrayList<>();
        for (final String additional : externalRepos.split(",")) {
            final String trim = additional.trim();
            if (!trim.isEmpty()) {
                try {
                    externalUrls.add(new File(trim).toURI().toURL());
                } catch (final MalformedURLException e) {
                    LOGGER.error(e.getMessage());
                }
            }
        }
        webUrls.addAll(externalUrls);
    }
    final Map<String, URL[]> urls = getWebappUrlsAndRars(warFile);
    webUrls.addAll(Arrays.asList(urls.get(URLS_KEY)));
    final List<URL> addedUrls = new ArrayList<>();
    for (final URL url : urls.get(RAR_URLS_KEY)) {
        // eager unpack to be able to use it in classloader
        final File[] files = unpack(URLs.toFile(url)).listFiles();
        if (files != null) {
            for (final File f : files) {
                if (f.getName().endsWith(".jar")) {
                    try {
                        addedUrls.add(f.toURI().toURL());
                    } catch (final MalformedURLException e) {
                        LOGGER.warning("War path bad: " + f.getAbsolutePath(), e);
                    }
                }
            }
        }
    }
    webUrls.addAll(addedUrls);
    // context.xml can define some additional libraries
    if (config != null) {
        // we don't test all !=null inline to show that config will get extra params in the future and that it is hierarchic
        if (config.getClasspath() != null && config.getClasspath().length > 0) {
            final Set<URL> contextXmlUrls = new LinkedHashSet<>();
            for (final String location : config.getClasspath()) {
                try {
                    webUrls.add(new File(location).toURI().toURL());
                } catch (final MalformedURLException e) {
                    throw new IllegalArgumentException(e);
                }
            }
            webUrls.addAll(contextXmlUrls);
        }
    }
    final ClassLoaderConfigurer configurer = QuickJarsTxtParser.parse(new File(warFile, "WEB-INF/" + QuickJarsTxtParser.FILE_NAME));
    if (configurer != null) {
        ClassLoaderConfigurer.Helper.configure(webUrls, configurer);
    }
    final URL[] webUrlsArray = webUrls.toArray(new URL[webUrls.size()]);
    // in TomEE this is done in init hook since we don't manage tomee webapp classloader
    // so here is not the best idea for tomee
    // if we want to manage it in a generic way
    // simply add a boolean shared between tomcat and openejb world
    // to know if we should fire it or not
    systemInstance.fireEvent(new BeforeDeploymentEvent(webUrlsArray, parentClassLoader));
    final ClassLoader warClassLoader = ClassLoaderUtil.createTempClassLoader(appId, webUrlsArray, parentClassLoader);
    // create web module
    final List<URL> scannableUrls = filterWebappUrls(webUrlsArray, config == null ? null : config.customerFilter, descriptors.get(NewLoaderLogic.EXCLUSION_FILE));
    // executable war will add war in scannable urls, we don't want it since it will surely contain tomee, cxf, ...
    if (Boolean.parseBoolean(systemInstance.getProperty("openejb.core.skip-war-in-loader", "true"))) {
        File archive = warFile;
        if (!archive.getName().endsWith(".war")) {
            archive = new File(warFile.getParentFile(), warFile.getName() + ".war");
            final String unpackDir = systemInstance.getProperty("tomee.unpack.dir");
            if (unpackDir != null && !archive.isFile()) {
                try {
                    archive = new File(systemInstance.getBase().getDirectory(unpackDir, false), warFile.getName());
                } catch (final IOException e) {
                // no-op
                }
            }
        }
        if (archive.isFile()) {
            try {
                scannableUrls.remove(archive.toURI().toURL());
            } catch (final MalformedURLException e) {
            // no-op
            }
        }
    }
    if (externalUrls != null) {
        for (final URL url : externalUrls) {
            if (scannableUrls.contains(url)) {
                scannableUrls.remove(url);
                scannableUrls.add(0, url);
            }
        }
    }
    SystemInstance.get().fireEvent(new EnhanceScannableUrlsEvent(scannableUrls));
    final WebModule webModule = new WebModule(webApp, contextRoot, warClassLoader, warFile.getAbsolutePath(), moduleName);
    webModule.setUrls(webUrls);
    webModule.setAddedUrls(addedUrls);
    webModule.setRarUrls(Arrays.asList(urls.get(RAR_URLS_KEY)));
    webModule.setScannableUrls(scannableUrls);
    webModule.setDefaultContextPath(webApp.getDefaultContextPath());
    webModule.getAltDDs().putAll(descriptors);
    webModule.getWatchedResources().add(warPath);
    webModule.getWatchedResources().add(warFile.getAbsolutePath());
    if (webXmlUrl != null && "file".equals(webXmlUrl.getProtocol())) {
        webModule.getWatchedResources().add(URLs.toFilePath(webXmlUrl));
    }
    // If webModule object is loaded by ejbModule or persitenceModule, no need to load tag libraries, web service and JSF related staffs.
    addTagLibraries(webModule);
    // load webservices descriptor
    addWebservices(webModule);
    // load faces configuration files
    addFacesConfigs(webModule);
    addBeansXmls(webModule);
    return webModule;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) OpenEJBException(org.apache.openejb.OpenEJBException) MalformedURLException(java.net.MalformedURLException) EnhanceScannableUrlsEvent(org.apache.openejb.config.event.EnhanceScannableUrlsEvent) ArrayList(java.util.ArrayList) IOException(java.io.IOException) ClassLoaderConfigurer(org.apache.openejb.classloader.ClassLoaderConfigurer) URL(java.net.URL) SystemInstance(org.apache.openejb.loader.SystemInstance) URLClassLoader(java.net.URLClassLoader) EmptyResourcesClassLoader(org.apache.openejb.core.EmptyResourcesClassLoader) JarFile(java.util.jar.JarFile) File(java.io.File) BeforeDeploymentEvent(org.apache.openejb.config.event.BeforeDeploymentEvent) WebApp(org.apache.openejb.jee.WebApp)

Aggregations

SystemInstance (org.apache.openejb.loader.SystemInstance)26 File (java.io.File)7 IOException (java.io.IOException)7 Properties (java.util.Properties)7 OpenEJBException (org.apache.openejb.OpenEJBException)7 MalformedURLException (java.net.MalformedURLException)5 ArrayList (java.util.ArrayList)5 URL (java.net.URL)4 NamingException (javax.naming.NamingException)4 BeanContext (org.apache.openejb.BeanContext)4 NoSuchApplicationException (org.apache.openejb.NoSuchApplicationException)4 OpenEJBRuntimeException (org.apache.openejb.OpenEJBRuntimeException)4 UndeployException (org.apache.openejb.UndeployException)4 InvalidObjectException (java.io.InvalidObjectException)3 ObjectStreamException (java.io.ObjectStreamException)3 URISyntaxException (java.net.URISyntaxException)3 ExecutionException (java.util.concurrent.ExecutionException)3 TimeoutException (java.util.concurrent.TimeoutException)3 DefinitionException (javax.enterprise.inject.spi.DefinitionException)3 DeploymentException (javax.enterprise.inject.spi.DeploymentException)3