Search in sources :

Example 26 with OpenEJBRuntimeException

use of org.apache.openejb.OpenEJBRuntimeException 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 27 with OpenEJBRuntimeException

use of org.apache.openejb.OpenEJBRuntimeException in project tomee by apache.

the class ApplicationComposers method run.

public static void run(final Class<?> type, final String... args) {
    final ApplicationComposers composer = new ApplicationComposers(type);
    try {
        Object instance;
        try {
            final Constructor<?> constructor = type.getConstructor(String[].class);
            instance = constructor.newInstance(new Object[] { args });
        } catch (final Exception e) {
            instance = type.newInstance();
        }
        composer.before(instance);
        // fix this workaround used for tests but breaking standalone mode
        composer.testClassFinders.remove(composer);
        final CountDownLatch latch = new CountDownLatch(1);
        final Thread hook = new Thread() {

            @Override
            public void run() {
                try {
                    composer.after();
                } catch (final Exception e) {
                // no-op
                }
            }
        };
        Runtime.getRuntime().addShutdownHook(hook);
        composer.afterRunnables.add(new Runnable() {

            @Override
            public void run() {
                Runtime.getRuntime().removeShutdownHook(hook);
                latch.countDown();
            }
        });
        // do it after having added the latch countdown hook to avoid to block if start and stop very fast
        composer.handleLifecycle(type, instance);
        latch.await();
    } catch (final InterruptedException ie) {
        Thread.interrupted();
    } catch (final Exception e) {
        throw new OpenEJBRuntimeException(e);
    }
}
Also used : OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) CountDownLatch(java.util.concurrent.CountDownLatch) InvocationTargetException(java.lang.reflect.InvocationTargetException) IOException(java.io.IOException) NamingException(javax.naming.NamingException) OpenEJBException(org.apache.openejb.OpenEJBException) MalformedURLException(java.net.MalformedURLException) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException)

Example 28 with OpenEJBRuntimeException

use of org.apache.openejb.OpenEJBRuntimeException in project tomee by apache.

the class ListConfigurator method getList.

public static <T> List<T> getList(final Properties properties, final String key, final ClassLoader classloader, final Class<T> filter) {
    if (properties == null) {
        return null;
    }
    final String features = properties.getProperty(key);
    if (features == null) {
        return null;
    }
    final List<T> list = new ArrayList<T>();
    final String[] split = features.trim().split(",");
    for (final String feature : split) {
        if (feature == null || feature.trim().isEmpty()) {
            continue;
        }
        final String prefix = key + "." + feature + ".";
        final ObjectRecipe recipe = new ObjectRecipe(feature);
        for (final Map.Entry<Object, Object> entry : properties.entrySet()) {
            final String current = entry.getKey().toString();
            if (current.startsWith(prefix)) {
                final String property = current.substring(prefix.length());
                recipe.setProperty(property, entry.getValue());
            }
        }
        final Object instance = recipe.create(classloader);
        if (!filter.isInstance(instance)) {
            throw new OpenEJBRuntimeException(feature + " is not an abstract feature");
        }
        list.add(filter.cast(instance));
    }
    if (list.isEmpty()) {
        return null;
    }
    return list;
}
Also used : OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) ObjectRecipe(org.apache.xbean.recipe.ObjectRecipe) ArrayList(java.util.ArrayList) Map(java.util.Map)

Example 29 with OpenEJBRuntimeException

use of org.apache.openejb.OpenEJBRuntimeException in project tomee by apache.

the class ActiveMQFactory method init.

private static void init() {
    synchronized (initialized) {
        if (!initialized.getAndSet(true)) {
            Class tmp;
            try {
                tmp = Class.forName("org.apache.openejb.resource.activemq.ActiveMQ5Factory");
                brokerPrefix = "amq5factory:";
            } catch (final Throwable t1) {
                try {
                    tmp = Class.forName("org.apache.openejb.resource.activemq.ActiveMQ4Factory");
                    brokerPrefix = "amq4factory:";
                } catch (final Throwable t2) {
                    throw new OpenEJBRuntimeException("Unable to load ActiveMQFactory: Check ActiveMQ jar files are on classpath", t1);
                }
            }
            final Class clazz = tmp;
            try {
                instance = clazz.newInstance();
            } catch (final InstantiationException e) {
                throw new OpenEJBRuntimeException("Unable to create ActiveMQFactory instance", e);
            } catch (final IllegalAccessException e) {
                throw new OpenEJBRuntimeException("Unable to access ActiveMQFactory instance", e);
            }
            try {
                setThreadProperties = clazz.getDeclaredMethod("setThreadProperties", new Class[] { Properties.class });
            } catch (final NoSuchMethodException e) {
                throw new OpenEJBRuntimeException("Unable to create ActiveMQFactory setThreadProperties method", e);
            }
            try {
                createBroker = clazz.getDeclaredMethod("createBroker", new Class[] { URI.class });
            } catch (final NoSuchMethodException e) {
                throw new OpenEJBRuntimeException("Unable to create ActiveMQFactory createBroker method", e);
            }
            try {
                getBrokers = clazz.getDeclaredMethod("getBrokers", (Class[]) null);
            } catch (final NoSuchMethodException e) {
                throw new OpenEJBRuntimeException("Unable to create ActiveMQFactory createBroker method", e);
            }
        }
    }
}
Also used : OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) Properties(java.util.Properties) URI(java.net.URI)

Example 30 with OpenEJBRuntimeException

use of org.apache.openejb.OpenEJBRuntimeException in project tomee by apache.

the class EjbTimerServiceImpl method schedule.

/**
 * Called from TimerData and start when a timer should be scheduled with the java.util.Timer.
 *
 * @param timerData the timer to schedule
 */
public void schedule(final TimerData timerData) throws TimerStoreException {
    start();
    if (scheduler == null) {
        throw new TimerStoreException("Scheduler is not configured properly");
    }
    timerData.setScheduler(scheduler);
    final Trigger trigger = timerData.getTrigger();
    if (null == trigger) {
        try {
            if (!scheduler.isShutdown()) {
                log.warning("Failed to schedule: " + timerData.getInfo());
            }
        } catch (final SchedulerException e) {
        // Ignore
        }
    }
    final AbstractTrigger<?> atrigger;
    if (trigger instanceof AbstractTrigger) {
        // is the case
        atrigger = (AbstractTrigger<?>) trigger;
        atrigger.setJobName(OPENEJB_TIMEOUT_JOB_NAME);
        atrigger.setJobGroup(OPENEJB_TIMEOUT_JOB_GROUP_NAME);
    } else {
        throw new OpenEJBRuntimeException("the trigger was not an AbstractTrigger - Should not be possible: " + trigger);
    }
    final JobDataMap triggerDataMap = trigger.getJobDataMap();
    triggerDataMap.put(EjbTimeoutJob.EJB_TIMERS_SERVICE, this);
    triggerDataMap.put(EjbTimeoutJob.TIMER_DATA, timerData);
    try {
        final TriggerKey triggerKey = new TriggerKey(atrigger.getName(), atrigger.getGroup());
        if (!scheduler.checkExists(triggerKey)) {
            scheduler.scheduleJob(trigger);
        } else if (Trigger.TriggerState.PAUSED.equals(scheduler.getTriggerState(triggerKey))) {
            // redeployment
            // more consistent in the semantic than a resume but resume would maybe be more relevant here
            scheduler.unscheduleJob(triggerKey);
            scheduler.scheduleJob(trigger);
        }
    } catch (final Exception e) {
        // TODO Any other actions we could do ?
        log.error("Could not schedule timer " + timerData, e);
    }
}
Also used : OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) TriggerKey(org.apache.openejb.quartz.TriggerKey) JobDataMap(org.apache.openejb.quartz.JobDataMap) Trigger(org.apache.openejb.quartz.Trigger) AbstractTrigger(org.apache.openejb.quartz.impl.triggers.AbstractTrigger) SchedulerException(org.apache.openejb.quartz.SchedulerException) AbstractTrigger(org.apache.openejb.quartz.impl.triggers.AbstractTrigger) 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)

Aggregations

OpenEJBRuntimeException (org.apache.openejb.OpenEJBRuntimeException)55 IOException (java.io.IOException)20 OpenEJBException (org.apache.openejb.OpenEJBException)17 ArrayList (java.util.ArrayList)13 Properties (java.util.Properties)12 NamingException (javax.naming.NamingException)9 MalformedURLException (java.net.MalformedURLException)8 BeanContext (org.apache.openejb.BeanContext)8 ObjectStreamException (java.io.ObjectStreamException)6 URISyntaxException (java.net.URISyntaxException)6 HashMap (java.util.HashMap)6 Map (java.util.Map)6 File (java.io.File)5 InvocationTargetException (java.lang.reflect.InvocationTargetException)4 Method (java.lang.reflect.Method)4 URL (java.net.URL)4 ApplicationException (org.apache.openejb.ApplicationException)4 InvalidObjectException (java.io.InvalidObjectException)3 AccessException (java.rmi.AccessException)3 RemoteException (java.rmi.RemoteException)3