Java Code Examples for org.apache.openejb.loader.SystemInstance#get()

The following examples show how to use org.apache.openejb.loader.SystemInstance#get() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TomcatWebAppBuilder.java    From tomee with Apache License 2.0 6 votes vote down vote up
private static boolean isExcludedBySystemProperty(final StandardContext standardContext) {
    String name = standardContext.getName();
    if (name == null) {
        name = standardContext.getPath();
        if (name == null) { // possible ?
            name = "";
        }
    }

    if (name.startsWith("/")) {
        name = name.substring(1);
    }

    final SystemInstance systemInstance = SystemInstance.get();
    return "true".equalsIgnoreCase(systemInstance.getProperty(name + ".tomcat-only", systemInstance.getProperty("tomcat-only", "false")));
}
 
Example 2
Source File: DeploymentIndexTest.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws SystemException {
    method = Method.class.getMethods()[0];
    beanContext = new BeanContext("aDeploymentId",
        null,
        new ModuleContext("", null, "", new AppContext("", SystemInstance.get(), null, null, null, false), null, null),
        DeploymentIndexTest.class,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        false, false);
    deploymentIndex = new DeploymentIndex(new BeanContext[]{beanContext, beanContext});
}
 
Example 3
Source File: BasicClusterableRequestHandlerTest.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
protected void setUp() throws Exception {
    requestHandler = new BasicClusterableRequestHandler();
    request = (ClusterableRequest) mock(ClusterableRequest.class);
    response = (ClusterableResponse) mock(ClusterableResponse.class);
    clusteredContainer = (ClusteredRPCContainer) mock(ClusteredRPCContainer.class);
    beanContext = new BeanContext("aDeploymentId",
        null,
        new ModuleContext("", null, "", new AppContext("", SystemInstance.get(), null, null, null, false), null, null),
        BasicClusterableRequestHandlerTest.class,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        false, false);
}
 
Example 4
Source File: ConfUtils.java    From tomee with Apache License 2.0 6 votes vote down vote up
public static File install(final URL resource, final String name, final boolean overwrite) throws IOException {
    if (resource == null) {
        return null;
    }
    final SystemInstance system = SystemInstance.get();
    final File conf = system.getConf(null);
    if (conf != null && !conf.exists()) {
        return null;
    }
    final File file = new File(conf, name);
    if (file.exists() && !overwrite) {
        return file;
    }
    IO.copy(IO.read(resource), file);
    return file;
}
 
Example 5
Source File: SingletonInstanceManager.java    From tomee with Apache License 2.0 6 votes vote down vote up
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();

        // Bean may not be a singleton or may be a singleton
        // managed by a different container implementation
        if (containerData instanceof Data) {
            final Data data = (Data) containerData;

            data.initialize();
        }
    }
}
 
Example 6
Source File: TomcatWebAppBuilder.java    From tomee with Apache License 2.0 5 votes vote down vote up
private void setComponentsUsedByCDI() {
    final SystemInstance systemInstance = SystemInstance.get();
    if (systemInstance.getComponent(HttpServletRequest.class) == null) {
        systemInstance.setComponent(HttpServletRequest.class, Proxys.threadLocalProxy(HttpServletRequest.class, OpenEJBSecurityListener.requests, null));
    }
    if (systemInstance.getComponent(HttpSession.class) == null) {
        systemInstance.setComponent(javax.servlet.http.HttpSession.class, Proxys.threadLocalRequestSessionProxy(OpenEJBSecurityListener.requests, null));
    }
    if (systemInstance.getComponent(ServletContext.class) == null) {
        systemInstance.setComponent(ServletContext.class, Proxys.handlerProxy(servletContextHandler, ServletContext.class, CdiAppContextsService.FiredManually.class));
    }
}
 
Example 7
Source File: TomeeJaxRsService.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public void init(final Properties props) throws Exception {
    final SystemInstance system = SystemInstance.get();

    TomcatRsRegistry tomcatRestHandler = (TomcatRsRegistry) system.getComponent(RsRegistry.class);
    if (tomcatRestHandler == null) {
        tomcatRestHandler = new TomcatRsRegistry();
        system.setComponent(RsRegistry.class, tomcatRestHandler);
    }

    system.addObserver(this);
}
 
Example 8
Source File: TomeeJaxWsService.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public void init(final Properties props) throws Exception {
    // Install the Tomcat webservice registry
    final SystemInstance system = SystemInstance.get();

    TomcatWsRegistry tomcatSoapHandler = (TomcatWsRegistry) system.getComponent(WsRegistry.class);
    if (tomcatSoapHandler == null) {
        tomcatSoapHandler = new TomcatWsRegistry();
        system.setComponent(WsRegistry.class, tomcatSoapHandler);
    }

    system.addObserver(this);
}
 
Example 9
Source File: DefaultTimerThreadPoolAdapter.java    From tomee with Apache License 2.0 5 votes vote down vote up
@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);
        }
    }
}
 
Example 10
Source File: AppNamingReadOnlyTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
private List<BeanContext> getMockBeanContextsList() throws SystemException, URISyntaxException {
	IvmContext context = new IvmContext();
	
	AppContext mockAppContext = new AppContext("appId", SystemInstance.get(),  this.getClass().getClassLoader(), context, context, false);
	ModuleContext mockModuleContext =  new ModuleContext("moduleId", new URI(""), "uniqueId", mockAppContext, context, this.getClass().getClassLoader());
	BeanContext mockBeanContext = new BeanContext("test", context, mockModuleContext, this.getClass(), this.getClass(), new HashMap<>());
	
	List<BeanContext> beanContextsList = new ArrayList<>();
	beanContextsList.add(mockBeanContext);
	
	return beanContextsList;
}
 
Example 11
Source File: CxfUtil.java    From tomee with Apache License 2.0 5 votes vote down vote up
public void destroy(@Observes final AssemblerDestroyed ignored) {
    final SystemInstance systemInstance = SystemInstance.get();
    final Bus bus = getBus();
    if ("true".equalsIgnoreCase(systemInstance.getProperty("openejb.cxf.jmx", "true"))) {
        final InstrumentationManager mgr = bus.getExtension(InstrumentationManager.class);
        if (InstrumentationManagerImpl.class.isInstance(mgr)) {
            mgr.shutdown();
        }
    }
    systemInstance.removeObserver(this);
}
 
Example 12
Source File: CxfUtil.java    From tomee with Apache License 2.0 5 votes vote down vote up
public void destroy(@Observes final AssemblerBeforeApplicationDestroyed ignored) {
    final SystemInstance systemInstance = SystemInstance.get();
    final Bus bus = getBus();

    // avoid to leak, we can enhance it to remove endpoints by app but not sure it does worth the effort
    // alternative can be a bus per app but would enforce us to change some deeper part of our config/design
    if ("true".equalsIgnoreCase(systemInstance.getProperty("openejb.cxf.monitoring.jmx.clear-on-undeploy", "true"))) {
        final CounterRepository repo = bus.getExtension(CounterRepository.class);
        if (repo != null) {
            repo.getCounters().clear();
        }
    }
}
 
Example 13
Source File: LocalClientRunner.java    From tomee with Apache License 2.0 5 votes vote down vote up
private BeanContext createDeployment(final Class<?> testClass) {
    try {
        final AppContext appContext = new AppContext("", SystemInstance.get(), testClass.getClassLoader(), new IvmContext(), new IvmContext(), false);
        final ModuleContext moduleContext = new ModuleContext("", null, "", appContext, new IvmContext(), null);
        return new BeanContext(null, new IvmContext(), moduleContext, testClass, null, null, null, null, null, null, null, null, null, BeanType.MANAGED, false, false);
    } catch (final SystemException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 14
Source File: TransactionSynchronizationRegistryWrapper.java    From tomee with Apache License 2.0 4 votes vote down vote up
public TransactionSynchronizationRegistryWrapper() {
    final SystemInstance system = SystemInstance.get();
    this.registry = system.getComponent(TransactionSynchronizationRegistry.class);
    this.system = system;
}
 
Example 15
Source File: AbstractDataSourcePlugin.java    From tomee with Apache License 2.0 4 votes vote down vote up
public boolean isActive() {
    final SystemInstance systemInstance = SystemInstance.get();
    return "true".equals(systemInstance.getProperty(
        "openejb.datasource.plugin." + getClass().getSimpleName().replace("DataSourcePlugin", "") + ".activaed",
        systemInstance.getProperty("openejb.datasource.plugin.activated", "true")));
}
 
Example 16
Source File: ServiceManager.java    From tomee with Apache License 2.0 4 votes vote down vote up
private void overrideProperties(final String serviceName, final Properties serviceProperties) throws IOException {
    final SystemInstance systemInstance = SystemInstance.get();
    final FileUtils base = systemInstance.getBase();

    // Override with file from conf dir
    final File conf = base.getDirectory("conf");
    if (conf.exists()) {

        final String legacy = System.getProperty("openejb.conf.schema.legacy");
        boolean legacySchema = Boolean.parseBoolean((null != legacy ? legacy : "false"));

        if (null == legacy) {
            //Legacy is not configured either way, so make an educated guess.
            //If we find at least 2 known service.properties files then assume legacy
            final File[] files = conf.listFiles(new FilenameFilter() {
                @Override
                public boolean accept(final File dir, String name) {
                    name = name.toLowerCase(Locale.ENGLISH);
                    return name.equals("ejbd.properties")
                        || name.equals("ejbds.properties")
                        || name.equals("admin.properties")
                        || name.equals("httpejbd.properties");
                }
            });

            if (null != files && files.length > 1) {
                legacySchema = true;
            }
        }

        addProperties(conf, legacySchema, new File(conf, serviceName + ".properties"), serviceProperties, true);
        addProperties(conf, legacySchema, new File(conf, SystemInstance.get().currentProfile() + "." + serviceName + ".properties"), serviceProperties, false);
    }

    holdsWithUpdate(serviceProperties);

    // Override with system properties
    final String prefix = serviceName + ".";
    final Properties sysProps = new Properties(System.getProperties());
    sysProps.putAll(systemInstance.getProperties());
    for (final Map.Entry<Object, Object> entry : sysProps.entrySet()) {
        final Map.Entry entry1 = (Map.Entry) entry;
        final Object value = entry1.getValue();
        String key = (String) entry1.getKey();
        if (value instanceof String && key.startsWith(prefix)) {
            key = key.replaceFirst(prefix, "");
            serviceProperties.setProperty(key, (String) value);
        }
    }

}
 
Example 17
Source File: EjbTimerServiceImpl.java    From tomee with Apache License 2.0 4 votes vote down vote up
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;
}
 
Example 18
Source File: CheckInvalidAsynchronousAnnotationsTest.java    From tomee with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void setupTestCase() {
    SystemInstance.reset();
    final SystemInstance system = SystemInstance.get();
    system.setProperty(VALIDATION_OUTPUT_LEVEL, "VERBOSE");
}
 
Example 19
Source File: ReloadingLoaderTest.java    From tomee with Apache License 2.0 4 votes vote down vote up
@Before
public void initContext() throws LifecycleException {
    final OpenEjbConfiguration configuration = new OpenEjbConfiguration();
    configuration.facilities = new FacilitiesInfo();

    final CoreContainerSystem containerSystem = new CoreContainerSystem(new IvmJndiFactory());

    SystemInstance.get().setComponent(OpenEjbConfiguration.class, configuration);
    SystemInstance.get().setComponent(ContainerSystem.class, containerSystem);
    SystemInstance.get().setComponent(WebAppEnricher.class, new WebAppEnricher() {
        @Override
        public URL[] enrichment(final ClassLoader webappClassLaoder) {
            return new URL[0];
        }
    });

    parentInstance = new AtomicReference<>(ParentClassLoaderFinder.Helper.get());
    loader = new TomEEWebappClassLoader(parentInstance.get()) {
        @Override
        public ClassLoader getInternalParent() {
            return parentInstance.get();
        }

        @Override
        protected void clearReferences() {
            // no-op: this test should be reworked to support it but in real life a loader is not stopped/started
        }
    };
    loader.init();
    final StandardRoot resources = new StandardRoot();
    loader.setResources(resources);
    resources.setContext(new StandardContext() {
        @Override
        public String getDocBase() {
            final File file = new File("target/foo");
            file.mkdirs();
            return file.getAbsolutePath();
        }

        @Override
        public String getMBeanKeyProperties() {
            return "foo";
        }
    {}});
    resources.start();
    loader.start();

    info = new AppInfo();
    info.appId = "test";
    context = new AppContext(info.appId, SystemInstance.get(), loader, new IvmContext(), new IvmContext(), true);
    containerSystem.addAppContext(context);

    final WebContext webDeployment = new WebContext(context);
    webDeployment.setId(context.getId());
    webDeployment.setClassLoader(loader);
    containerSystem.addWebContext(webDeployment);
}
 
Example 20
Source File: Assembler.java    From tomee with Apache License 2.0 3 votes vote down vote up
public Assembler(final JndiFactory jndiFactory) {
    logger = Logger.getInstance(LogCategory.OPENEJB_STARTUP, Assembler.class);
    skipLoaderIfPossible = "true".equalsIgnoreCase(SystemInstance.get().getProperty("openejb.classloader.skip-app-loader-if-possible", "true"));
    resourceDestroyTimeout = SystemInstance.get().getProperty("openejb.resources.destroy.timeout");
    threadStackOnTimeout = "true".equals(SystemInstance.get().getProperty("openejb.resources.destroy.stack-on-timeout", "false"));
    persistenceClassLoaderHandler = new PersistenceClassLoaderHandlerImpl();

    installNaming();

    final SystemInstance system = SystemInstance.get();

    system.setComponent(org.apache.openejb.spi.Assembler.class, this);
    system.setComponent(Assembler.class, this);

    containerSystem = new CoreContainerSystem(jndiFactory);
    system.setComponent(ContainerSystem.class, containerSystem);

    jndiBuilder = new JndiBuilder(containerSystem.getJNDIContext());

    setConfiguration(new OpenEjbConfiguration());

    final ApplicationServer appServer = system.getComponent(ApplicationServer.class);
    if (appServer == null) {
        system.setComponent(ApplicationServer.class, new ServerFederation());
    }

    system.setComponent(EjbResolver.class, new EjbResolver(null, EjbResolver.Scope.GLOBAL));

    installExtensions();

    system.fireEvent(new AssemblerCreated());

    initBValFiltering();
}