Search in sources :

Example 11 with Options

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

the class ConfigurationFactory method getOpenEjbConfiguration.

public OpenEjbConfiguration getOpenEjbConfiguration(final Openejb providedConf) throws OpenEJBException {
    if (sys != null) {
        return sys;
    }
    if (providedConf != null) {
        openejb = providedConf;
    } else if (configLocation != null) {
        openejb = JaxbOpenejb.readConfig(configLocation);
    } else {
        openejb = JaxbOpenejb.createOpenejb();
    }
    for (final SystemProperty sp : openejb.getSystemProperties()) {
        final String name = sp.getName();
        final String value = sp.getValue();
        SystemInstance.get().setProperty(name, value);
        JavaSecurityManagers.setSystemProperty(name, value);
    }
    loadPropertiesDeclaredConfiguration(openejb);
    sys = new OpenEjbConfiguration();
    sys.containerSystem = new ContainerSystemInfo();
    sys.facilities = new FacilitiesInfo();
    // listener + some config can be defined as service
    for (final Service service : openejb.getServices()) {
        final ServiceInfo info = configureService(service, ServiceInfo.class);
        sys.facilities.services.add(info);
    }
    for (final JndiProvider provider : openejb.getJndiProvider()) {
        final JndiContextInfo info = configureService(provider, JndiContextInfo.class);
        sys.facilities.remoteJndiContexts.add(info);
    }
    sys.facilities.securityService = configureService(openejb.getSecurityService(), SecurityServiceInfo.class);
    sys.facilities.transactionService = configureService(openejb.getTransactionManager(), TransactionServiceInfo.class);
    List<ResourceInfo> resources = new ArrayList<>();
    for (final Resource resource : openejb.getResource()) {
        final ResourceInfo resourceInfo = configureService(resource, ResourceInfo.class);
        resources.add(resourceInfo);
    }
    resources = sort(resources, null);
    sys.facilities.resources.addAll(resources);
    if (openejb.getProxyFactory() != null) {
        sys.facilities.intraVmServer = configureService(openejb.getProxyFactory(), ProxyFactoryInfo.class);
    }
    for (final Container declaration : openejb.getContainer()) {
        final ContainerInfo info = createContainerInfo(declaration);
        sys.containerSystem.containers.add(info);
    }
    final List<File> declaredApps = getDeclaredApps();
    for (final File jarFile : declaredApps) {
        try {
            final AppInfo appInfo = configureApplication(jarFile);
            sys.containerSystem.applications.add(appInfo);
        } catch (final OpenEJBException alreadyHandled) {
            final DeploymentExceptionManager exceptionManager = SystemInstance.get().getComponent(DeploymentExceptionManager.class);
            if (exceptionManager != null) {
                exceptionManager.pushDelpoymentException(alreadyHandled);
            }
        }
    }
    final boolean embedded = SystemInstance.get().hasProperty(EJBContainer.class.getName());
    final Options options = SystemInstance.get().getOptions();
    if (options.get("openejb.system.apps", false)) {
        try {
            final boolean extended = SystemApps.isExtended();
            final AppInfo appInfo;
            if (!extended) {
                // do it manually, we know what we need and can skip a bunch of processing
                appInfo = SystemAppInfo.preComputedInfo(this);
            } else {
                appInfo = configureApplication(new AppModule(SystemApps.getSystemModule()));
            }
            sys.containerSystem.applications.add(appInfo);
        } catch (final OpenEJBException e) {
            logger.error("Unable to load the system applications.", e);
        }
    } else if (options.get(DEPLOYMENTS_CLASSPATH_PROPERTY, !embedded)) {
        final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        final ArrayList<File> jarFiles = getModulesFromClassPath(declaredApps, classLoader);
        final String appId = "classpath.ear";
        final boolean classpathAsEar = options.get(CLASSPATH_AS_EAR, true);
        try {
            if (classpathAsEar && !jarFiles.isEmpty()) {
                final AppInfo appInfo = configureApplication(classLoader, appId, jarFiles);
                sys.containerSystem.applications.add(appInfo);
            } else {
                for (final File jarFile : jarFiles) {
                    final AppInfo appInfo = configureApplication(jarFile);
                    sys.containerSystem.applications.add(appInfo);
                }
            }
            if (jarFiles.size() == 0) {
                logger.warning("config.noModulesFoundToDeploy");
            }
        } catch (final OpenEJBException alreadyHandled) {
            logger.debug("config.alreadyHandled");
        }
    }
    for (final Deployments deployments : openejb.getDeployments()) {
        if (deployments.isAutoDeploy()) {
            if (deployments.getDir() != null) {
                sys.containerSystem.autoDeploy.add(deployments.getDir());
            }
        }
    }
    final OpenEjbConfiguration finished = sys;
    sys = null;
    openejb = null;
    return finished;
}
Also used : OpenEJBException(org.apache.openejb.OpenEJBException) Options(org.apache.openejb.loader.Options) ArrayList(java.util.ArrayList) AdditionalDeployments(org.apache.openejb.config.sys.AdditionalDeployments) Deployments(org.apache.openejb.config.sys.Deployments) OpenEjbConfiguration(org.apache.openejb.assembler.classic.OpenEjbConfiguration) TransactionServiceInfo(org.apache.openejb.assembler.classic.TransactionServiceInfo) SecurityServiceInfo(org.apache.openejb.assembler.classic.SecurityServiceInfo) ServiceInfo(org.apache.openejb.assembler.classic.ServiceInfo) EJBContainer(javax.ejb.embeddable.EJBContainer) Container(org.apache.openejb.config.sys.Container) JndiContextInfo(org.apache.openejb.assembler.classic.JndiContextInfo) EJBContainer(javax.ejb.embeddable.EJBContainer) ContainerSystemInfo(org.apache.openejb.assembler.classic.ContainerSystemInfo) SecurityServiceInfo(org.apache.openejb.assembler.classic.SecurityServiceInfo) DeploymentExceptionManager(org.apache.openejb.assembler.classic.DeploymentExceptionManager) ResourceInfo(org.apache.openejb.assembler.classic.ResourceInfo) JndiProvider(org.apache.openejb.config.sys.JndiProvider) Resource(org.apache.openejb.config.sys.Resource) AbstractService(org.apache.openejb.config.sys.AbstractService) SecurityService(org.apache.openejb.config.sys.SecurityService) Service(org.apache.openejb.config.sys.Service) AppInfo(org.apache.openejb.assembler.classic.AppInfo) WebAppInfo(org.apache.openejb.assembler.classic.WebAppInfo) FacilitiesInfo(org.apache.openejb.assembler.classic.FacilitiesInfo) ProxyFactoryInfo(org.apache.openejb.assembler.classic.ProxyFactoryInfo) TransactionServiceInfo(org.apache.openejb.assembler.classic.TransactionServiceInfo) ManagedContainerInfo(org.apache.openejb.assembler.classic.ManagedContainerInfo) BmpEntityContainerInfo(org.apache.openejb.assembler.classic.BmpEntityContainerInfo) StatelessSessionContainerInfo(org.apache.openejb.assembler.classic.StatelessSessionContainerInfo) CmpEntityContainerInfo(org.apache.openejb.assembler.classic.CmpEntityContainerInfo) StatefulSessionContainerInfo(org.apache.openejb.assembler.classic.StatefulSessionContainerInfo) SingletonSessionContainerInfo(org.apache.openejb.assembler.classic.SingletonSessionContainerInfo) MdbContainerInfo(org.apache.openejb.assembler.classic.MdbContainerInfo) ContainerInfo(org.apache.openejb.assembler.classic.ContainerInfo) File(java.io.File)

Example 12 with Options

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

the class StatelessInstanceManager method deploy.

@SuppressWarnings("unchecked")
public void deploy(final BeanContext beanContext) throws OpenEJBException {
    final Options options = new Options(beanContext.getProperties());
    final Duration accessTimeout = getDuration(options, "AccessTimeout", // default timeout
    getDuration(options, "Timeout", this.accessTimeout, TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS);
    final Duration closeTimeout = getDuration(options, "CloseTimeout", this.closeTimeout, TimeUnit.MINUTES);
    final ObjectRecipe recipe = PassthroughFactory.recipe(new Pool.Builder(poolBuilder));
    recipe.allow(Option.CASE_INSENSITIVE_FACTORY);
    recipe.allow(Option.CASE_INSENSITIVE_PROPERTIES);
    recipe.allow(Option.IGNORE_MISSING_PROPERTIES);
    recipe.setAllProperties(beanContext.getProperties());
    final Pool.Builder builder = (Pool.Builder) recipe.create();
    setDefault(builder.getMaxAge(), TimeUnit.HOURS);
    setDefault(builder.getIdleTimeout(), TimeUnit.MINUTES);
    setDefault(builder.getInterval(), TimeUnit.MINUTES);
    final StatelessSupplier supplier = new StatelessSupplier(beanContext);
    builder.setSupplier(supplier);
    builder.setExecutor(executor);
    builder.setScheduledExecutor(scheduledExecutor);
    final Data data = new Data(builder.build(), accessTimeout, closeTimeout);
    beanContext.setContainerData(data);
    beanContext.set(EJBContext.class, data.sessionContext);
    try {
        final Context context = beanContext.getJndiEnc();
        context.bind("comp/EJBContext", data.sessionContext);
        context.bind("comp/WebServiceContext", new EjbWsContext(data.sessionContext));
        context.bind("comp/TimerService", new TimerServiceWrapper());
    } catch (final NamingException e) {
        throw new OpenEJBException("Failed to bind EJBContext/WebServiceContext/TimerService", e);
    }
    final int min = builder.getMin();
    final long maxAge = builder.getMaxAge().getTime(TimeUnit.MILLISECONDS);
    final double maxAgeOffset = builder.getMaxAgeOffset();
    final ObjectNameBuilder jmxName = new ObjectNameBuilder("openejb.management");
    jmxName.set("J2EEServer", "openejb");
    jmxName.set("J2EEApplication", null);
    jmxName.set("EJBModule", beanContext.getModuleID());
    jmxName.set("StatelessSessionBean", beanContext.getEjbName());
    jmxName.set("name", beanContext.getEjbName());
    final MBeanServer server = LocalMBeanServer.get();
    // Create stats interceptor
    if (StatsInterceptor.isStatsActivated()) {
        StatsInterceptor stats = null;
        for (final InterceptorInstance interceptor : beanContext.getUserAndSystemInterceptors()) {
            if (interceptor.getInterceptor() instanceof StatsInterceptor) {
                stats = (StatsInterceptor) interceptor.getInterceptor();
            }
        }
        if (stats == null) {
            // normally useless
            stats = new StatsInterceptor(beanContext.getBeanClass());
            beanContext.addFirstSystemInterceptor(stats);
        }
        // register the invocation stats interceptor
        try {
            final ObjectName objectName = jmxName.set("j2eeType", "Invocations").build();
            if (server.isRegistered(objectName)) {
                server.unregisterMBean(objectName);
            }
            server.registerMBean(new ManagedMBean(stats), objectName);
            data.add(objectName);
        } catch (final Exception e) {
            logger.error("Unable to register MBean ", e);
        }
    }
    // register the pool
    try {
        final ObjectName objectName = jmxName.set("j2eeType", "Pool").build();
        if (server.isRegistered(objectName)) {
            server.unregisterMBean(objectName);
        }
        server.registerMBean(new ManagedMBean(data.pool), objectName);
        data.add(objectName);
    } catch (final Exception e) {
        logger.error("Unable to register MBean ", e);
    }
    // Finally, fill the pool and start it
    if (!options.get("BackgroundStartup", false) && min > 0) {
        final ExecutorService es = Executors.newFixedThreadPool(min);
        for (int i = 0; i < min; i++) {
            es.submit(new InstanceCreatorRunnable(maxAge, i, min, maxAgeOffset, data, supplier));
        }
        es.shutdown();
        try {
            es.awaitTermination(5, TimeUnit.MINUTES);
        } catch (final InterruptedException e) {
            logger.error("can't fill the stateless pool", e);
        }
    }
    data.getPool().start();
}
Also used : Options(org.apache.openejb.loader.Options) OpenEJBException(org.apache.openejb.OpenEJBException) ObjectNameBuilder(org.apache.openejb.monitoring.ObjectNameBuilder) TimerServiceWrapper(org.apache.openejb.core.timer.TimerServiceWrapper) ObjectRecipe(org.apache.xbean.recipe.ObjectRecipe) Pool(org.apache.openejb.util.Pool) NamingException(javax.naming.NamingException) MBeanServer(javax.management.MBeanServer) LocalMBeanServer(org.apache.openejb.monitoring.LocalMBeanServer) SessionContext(javax.ejb.SessionContext) BeanContext(org.apache.openejb.BeanContext) Context(javax.naming.Context) EJBContext(javax.ejb.EJBContext) InstanceContext(org.apache.openejb.core.InstanceContext) ThreadContext(org.apache.openejb.core.ThreadContext) StatsInterceptor(org.apache.openejb.monitoring.StatsInterceptor) Duration(org.apache.openejb.util.Duration) InterceptorData(org.apache.openejb.core.interceptor.InterceptorData) InterceptorInstance(org.apache.openejb.core.interceptor.InterceptorInstance) TimeoutException(java.util.concurrent.TimeoutException) NamingException(javax.naming.NamingException) ConcurrentAccessTimeoutException(javax.ejb.ConcurrentAccessTimeoutException) OpenEJBException(org.apache.openejb.OpenEJBException) InvocationTargetException(java.lang.reflect.InvocationTargetException) RemoteException(java.rmi.RemoteException) SystemException(org.apache.openejb.SystemException) ApplicationException(org.apache.openejb.ApplicationException) IOException(java.io.IOException) ObjectName(javax.management.ObjectName) ObjectNameBuilder(org.apache.openejb.monitoring.ObjectNameBuilder) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ExecutorService(java.util.concurrent.ExecutorService) ManagedMBean(org.apache.openejb.monitoring.ManagedMBean)

Example 13 with Options

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

the class OptionsTest method setUp.

public void setUp() {
    properties = new Properties();
    options = new Options(properties);
    log = new TestLog();
    options.setLogger(log);
}
Also used : Options(org.apache.openejb.loader.Options) Properties(java.util.Properties)

Example 14 with Options

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

the class AsynchronousPool method create.

public static AsynchronousPool create(final AppContext appContext) {
    final Options options = appContext.getOptions();
    final ExecutorBuilder builder = new ExecutorBuilder().prefix("AsynchronousPool").size(options.get("AsynchronousPool.Size", 5)).threadFactory(new DaemonThreadFactory("@Asynchronous", appContext.getId()));
    return new AsynchronousPool(builder.build(options), options.get("AsynchronousPool.ShutdownWaitDuration", new Duration(1, TimeUnit.MINUTES)));
}
Also used : Options(org.apache.openejb.loader.Options) ExecutorBuilder(org.apache.openejb.util.ExecutorBuilder) DaemonThreadFactory(org.apache.openejb.util.DaemonThreadFactory) Duration(org.apache.openejb.util.Duration)

Example 15 with Options

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

the class NewLoaderLogic method _loadFromClasspath.

@SuppressWarnings("UseOfSystemOutOrSystemErr")
public static void _loadFromClasspath(final FileUtils base, final List<URL> jarList, final ClassLoader classLoader) {
    final PerformanceTimer timer = new PerformanceTimer();
    timer.event("create filters");
    final Options options = SystemInstance.get().getOptions();
    final String include = "";
    final String exclude = "";
    final PatternFilter classpathInclude = new PatternFilter(options.get(DeploymentFilterable.CLASSPATH_INCLUDE, ".*"));
    final PatternFilter classpathExclude = new PatternFilter(options.get(DeploymentFilterable.CLASSPATH_EXCLUDE, ""));
    final Filter classpathFilter = new ExcludeIncludeFilter(classpathInclude, classpathExclude);
    final PatternFilter packageInclude = new PatternFilter(options.get(DeploymentFilterable.PACKAGE_INCLUDE, ".*"));
    final PatternFilter packageExclude = new PatternFilter(options.get(DeploymentFilterable.PACKAGE_EXCLUDE, ""));
    final IncludeExcludeFilter packageFilter;
    if (classpathInclude.getPattern().pattern().equals(".*") && packageInclude.getPattern().pattern().equals(".*")) {
        timer.event("callers");
        final Set<String> callers = callers();
        timer.event("parse packages");
        callers.size();
        final Set<String> packages = new HashSet<>();
        for (final String caller : callers) {
            String[] parts = caller.split("\\.");
            if (parts.length > 2) {
                parts = new String[] { parts[0], parts[1] };
            }
            packages.add(Join.join(".", parts));
        }
        final Filter includes = Filters.packages(packages.toArray(new String[packages.size()]));
        packageFilter = new IncludeExcludeFilter(includes, packageExclude);
    } else {
        packageFilter = new IncludeExcludeFilter(packageInclude, packageExclude);
    }
    timer.event("urlset");
    final Set<RequireDescriptors> requireDescriptors = options.getAll(DeploymentFilterable.CLASSPATH_REQUIRE_DESCRIPTOR, RequireDescriptors.CLIENT);
    try {
        UrlSet urlSet = new UrlSet(classLoader);
        timer.event("exclude system urls");
        urlSet = URLs.cullSystemJars(urlSet);
        timer.event("classpath filter");
        final UrlSet beforeFiltering = urlSet;
        urlSet = urlSet.filter(classpathFilter);
        // If the user filtered out too much, that's a problem
        if (urlSet.size() == 0) {
            final String message = String.format("Classpath Include/Exclude resulted in zero URLs.  There were %s possible URLs before filtering and 0 after: include=\"%s\", exclude=\"%s\"", beforeFiltering.size(), include, exclude);
            logger.error(message);
            logger.info("Eligible Classpath before filtering:");
            for (final URL url : beforeFiltering) {
                logger.info(String.format("   %s", url.toExternalForm()));
            }
        }
        // If they are the same size, than nothing was filtered
        // and we know the user did not take action to change the default
        final boolean userSuppliedClasspathFilter = beforeFiltering.size() != urlSet.size();
        if (!userSuppliedClasspathFilter) {
            logger.info("Applying buildin classpath excludes");
            timer.event("buildin excludes");
            urlSet = applyBuiltinExcludes(urlSet);
        }
        DeploymentsResolver.processUrls("NewLoaderLogic1", urlSet.getUrls(), classLoader, EnumSet.allOf(RequireDescriptors.class), base, jarList);
        timer.event("package filter");
        urlSet = filterArchives(packageFilter, classLoader, urlSet);
        timer.event("process urls");
        final List<URL> urls = urlSet.getUrls();
        final long begin = System.currentTimeMillis();
        DeploymentsResolver.processUrls("NewLoaderLogic2", urls, classLoader, requireDescriptors, base, jarList);
        final long end = System.currentTimeMillis();
        final long time = end - begin;
        timer.stop(System.out);
        final UrlSet unchecked = new UrlSet();
        DeploymentsResolver.processUrls("NewLoaderLogic3", unchecked.getUrls(), classLoader, EnumSet.allOf(RequireDescriptors.class), base, jarList);
        if (logger.isDebugEnabled()) {
            final int urlCount = urlSet.getUrls().size() + unchecked.getUrls().size();
            logger.debug("URLs after filtering: " + urlCount);
            for (final URL url : urlSet.getUrls()) {
                logger.debug("Annotations path: " + url);
            }
            for (final URL url : unchecked.getUrls()) {
                logger.debug("Descriptors path: " + url);
            }
        }
        if (urls.size() == 0) {
            return;
        }
        if (time < 1000) {
            logger.debug("Searched " + urls.size() + " classpath urls in " + time + " milliseconds.  Average " + time / urls.size() + " milliseconds per url.");
        } else if (time < 4000 || urls.size() < 3) {
            logger.info("Searched " + urls.size() + " classpath urls in " + time + " milliseconds.  Average " + time / urls.size() + " milliseconds per url.");
        } else if (time < 10000) {
            logger.warning("Searched " + urls.size() + " classpath urls in " + time + " milliseconds.  Average " + time / urls.size() + " milliseconds per url.");
            logger.warning("Consider adjusting your " + DeploymentFilterable.CLASSPATH_EXCLUDE + " and " + DeploymentFilterable.CLASSPATH_INCLUDE + " settings.  Current settings: exclude='" + exclude + "', include='" + include + "'");
        } else {
            logger.fatal("Searched " + urls.size() + " classpath urls in " + time + " milliseconds.  Average " + time / urls.size() + " milliseconds per url.  TOO LONG!");
            logger.fatal("ADJUST THE EXCLUDE/INCLUDE!!!.  Current settings: " + DeploymentFilterable.CLASSPATH_EXCLUDE + "='" + exclude + "', " + DeploymentFilterable.CLASSPATH_INCLUDE + "='" + include + "'");
            final List<String> list = new ArrayList<>();
            for (final URL url : urls) {
                list.add(url.toExternalForm());
            }
            Collections.sort(list);
            for (final String url : list) {
                logger.info("Matched: " + url);
            }
        }
    } catch (final IOException e1) {
        e1.printStackTrace();
        logger.warning("Unable to search classpath for modules: Received Exception: " + e1.getClass().getName() + " " + e1.getMessage(), e1);
    }
}
Also used : Options(org.apache.openejb.loader.Options) PatternFilter(org.apache.xbean.finder.filter.PatternFilter) ArrayList(java.util.ArrayList) ExcludeIncludeFilter(org.apache.xbean.finder.filter.ExcludeIncludeFilter) IOException(java.io.IOException) URL(java.net.URL) PerformanceTimer(org.apache.openejb.util.PerformanceTimer) IncludeExcludeFilter(org.apache.xbean.finder.filter.IncludeExcludeFilter) PatternFilter(org.apache.xbean.finder.filter.PatternFilter) Filter(org.apache.xbean.finder.filter.Filter) ExcludeIncludeFilter(org.apache.xbean.finder.filter.ExcludeIncludeFilter) UrlSet(org.apache.xbean.finder.UrlSet) IncludeExcludeFilter(org.apache.xbean.finder.filter.IncludeExcludeFilter) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Aggregations

Options (org.apache.openejb.loader.Options)21 IOException (java.io.IOException)7 OpenEJBException (org.apache.openejb.OpenEJBException)5 Properties (java.util.Properties)4 NamingException (javax.naming.NamingException)4 InvocationTargetException (java.lang.reflect.InvocationTargetException)3 ArrayList (java.util.ArrayList)3 TimeoutException (java.util.concurrent.TimeoutException)3 MBeanServer (javax.management.MBeanServer)3 MalformedObjectNameException (javax.management.MalformedObjectNameException)3 ObjectName (javax.management.ObjectName)3 ApplicationException (org.apache.openejb.ApplicationException)3 SystemException (org.apache.openejb.SystemException)3 OptionsLog (org.apache.openejb.util.OptionsLog)3 URL (java.net.URL)2 RemoteException (java.rmi.RemoteException)2 HashSet (java.util.HashSet)2 LinkedHashSet (java.util.LinkedHashSet)2 AttributeNotFoundException (javax.management.AttributeNotFoundException)2 InstanceNotFoundException (javax.management.InstanceNotFoundException)2