Search in sources :

Example 1 with Openejb

use of org.apache.openejb.config.sys.Openejb in project tomee by apache.

the class EffectiveTomEEXml method main.

public static void main(final String[] args) throws Exception {
    final CommandLine line = parseCommand(args);
    if (line == null) {
        return;
    }
    final Openejb openejb = JaxbOpenejb.readConfig(findXml(line).getCanonicalPath());
    final ConfigurationFactory configFact = new ConfigurationFactory();
    for (final Resource r : openejb.getResource()) {
        final ResourceInfo ri = configFact.configureService(r, ResourceInfo.class);
        if (!ri.properties.containsKey("SkipImplicitAttributes")) {
            ri.properties.put("SkipImplicitAttributes", "false");
        }
        r.getProperties().clear();
        r.getProperties().putAll(ri.properties);
    }
    // TODO: others
    final Marshaller marshaller = JaxbOpenejb.getContext(Openejb.class).createMarshaller();
    marshaller.setProperty("jaxb.formatted.output", true);
    marshaller.marshal(openejb, System.out);
}
Also used : ResourceInfo(org.apache.openejb.assembler.classic.ResourceInfo) CommandLine(org.apache.commons.cli.CommandLine) Marshaller(javax.xml.bind.Marshaller) Resource(org.apache.openejb.config.sys.Resource) Openejb(org.apache.openejb.config.sys.Openejb) JaxbOpenejb(org.apache.openejb.config.sys.JaxbOpenejb)

Example 2 with Openejb

use of org.apache.openejb.config.sys.Openejb 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 3 with Openejb

use of org.apache.openejb.config.sys.Openejb in project tomee by apache.

the class WebServiceInjectionConfigurator method getServices.

private Collection<ServiceInfo> getServices(final Properties properties) {
    final ConfigurationFactory cf = SystemInstance.get().getComponent(ConfigurationFactory.class);
    if (cf == null || !ConfigurationFactory.class.isInstance(cf)) {
        return Collections.emptyList();
    }
    final Openejb openejb = new Openejb();
    ConfigurationFactory.fillOpenEjb(openejb, properties);
    final List<Service> services = openejb.getServices();
    if (services.isEmpty()) {
        return Collections.emptyList();
    }
    final Collection<ServiceInfo> info = new ArrayList<>(services.size());
    for (final Service s : services) {
        final String prefix = s.getId() + ".";
        for (final String key : properties.stringPropertyNames()) {
            if (key.startsWith(prefix)) {
                s.getProperties().put(key.substring(prefix.length()), properties.getProperty(key));
            }
        }
        try {
            info.add(cf.configureService(s, ServiceInfo.class));
        } catch (final OpenEJBException e) {
            throw new IllegalArgumentException(e);
        }
    }
    return info;
}
Also used : ServiceInfo(org.apache.openejb.assembler.classic.ServiceInfo) OpenEJBException(org.apache.openejb.OpenEJBException) ConfigurationFactory(org.apache.openejb.config.ConfigurationFactory) ArrayList(java.util.ArrayList) Service(org.apache.openejb.config.sys.Service) Openejb(org.apache.openejb.config.sys.Openejb)

Example 4 with Openejb

use of org.apache.openejb.config.sys.Openejb in project tomee by apache.

the class AbstractTomEEMojo method ensureAppsFolderExistAndIsConfiguredByDefault.

private void ensureAppsFolderExistAndIsConfiguredByDefault(final File file) throws IOException {
    if ("openejb".equals(container.toLowerCase(Locale.ENGLISH)) || (file.exists() && ((apps != null && !apps.isEmpty()) || (!"pom".equals(packaging) && !"war".equals(packaging))))) {
        // webapps doesn't need apps folder in tomee
        final String rootTag = container.toLowerCase(Locale.ENGLISH);
        if (file.isFile()) {
            // can be not existing since we dont always deploy tomee but shouldn't since then apps/ is not guaranteed to work
            try {
                final Openejb jaxb = JaxbOpenejb.readConfig(file.getAbsolutePath());
                boolean needAdd = true;
                for (final Deployments d : jaxb.getDeployments()) {
                    if ("apps".equals(d.getDir())) {
                        needAdd = false;
                        break;
                    }
                }
                if (needAdd) {
                    final String content = IO.slurp(file);
                    final FileWriter writer = new FileWriter(file);
                    final String end = "</" + rootTag + ">";
                    writer.write(content.replace(end, "  <Deployments dir=\"apps\" />\n" + end));
                    writer.close();
                }
            } catch (final OpenEJBException e) {
                throw new IllegalStateException("illegal tomee.xml:\n" + IO.slurp(file), e);
            }
        } else {
            final FileWriter writer = new FileWriter(file);
            writer.write("<?xml version=\"1.0\"?>\n" + "<" + rootTag + ">\n" + "  <Deployments dir=\"apps\" />\n" + "</" + rootTag + ">\n");
            writer.close();
        }
        final File appsFolder = new File(catalinaBase, "apps");
        if (!appsFolder.exists() && !appsFolder.mkdirs()) {
            throw new RuntimeException("Failed to create: " + appsFolder);
        }
    }
}
Also used : OpenEJBException(org.apache.openejb.OpenEJBException) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) FileWriter(java.io.FileWriter) Deployments(org.apache.openejb.config.sys.Deployments) ZipFile(java.util.zip.ZipFile) File(java.io.File) Openejb(org.apache.openejb.config.sys.Openejb) JaxbOpenejb(org.apache.openejb.config.sys.JaxbOpenejb)

Example 5 with Openejb

use of org.apache.openejb.config.sys.Openejb in project tomee by apache.

the class ServiceClasspathTest method test.

@Test
public void test() throws Exception {
    final String className = "org.superbiz.foo.Orange";
    final File jar = subclass(Color.class, className);
    System.setProperty(javax.naming.Context.INITIAL_CONTEXT_FACTORY, InitContextFactory.class.getName());
    final Openejb openejb = new Openejb();
    final Resource resource = new Resource();
    openejb.getResource().add(resource);
    resource.setClassName(className);
    resource.setType(className);
    resource.setId("Orange");
    resource.getProperties().put("red", "FF");
    resource.getProperties().put("green", "99");
    resource.getProperties().put("blue", "00");
    resource.setClasspath(jar.getAbsolutePath());
    createEnvrt();
    final ConfigurationFactory config = new ConfigurationFactory();
    final Assembler assembler = new Assembler();
    assembler.createTransactionManager(config.configureService(TransactionServiceInfo.class));
    assembler.createSecurityService(config.configureService(SecurityServiceInfo.class));
    final ResourceInfo serviceInfo = config.configureService(resource, ResourceInfo.class);
    //        serviceInfo.classpath = new URI[]{jar.toURI()};
    assembler.createResource(serviceInfo);
    final InitialContext initialContext = new InitialContext();
    final Color color = (Color) initialContext.lookup("openejb:Resource/Orange");
    assertNotNull(color);
    assertEquals("Orange.FF", color.getRed());
    assertEquals("Orange.99", color.getGreen());
    assertEquals("Orange.00", color.getBlue());
}
Also used : ResourceInfo(org.apache.openejb.assembler.classic.ResourceInfo) TransactionServiceInfo(org.apache.openejb.assembler.classic.TransactionServiceInfo) Resource(org.apache.openejb.config.sys.Resource) InitContextFactory(org.apache.openejb.core.ivm.naming.InitContextFactory) Assembler(org.apache.openejb.assembler.classic.Assembler) File(java.io.File) SecurityServiceInfo(org.apache.openejb.assembler.classic.SecurityServiceInfo) Openejb(org.apache.openejb.config.sys.Openejb) InitialContext(javax.naming.InitialContext) Test(org.junit.Test)

Aggregations

Openejb (org.apache.openejb.config.sys.Openejb)7 JaxbOpenejb (org.apache.openejb.config.sys.JaxbOpenejb)4 Resource (org.apache.openejb.config.sys.Resource)4 Test (org.junit.Test)3 File (java.io.File)2 ArrayList (java.util.ArrayList)2 OpenEJBException (org.apache.openejb.OpenEJBException)2 OpenEJBRuntimeException (org.apache.openejb.OpenEJBRuntimeException)2 Assembler (org.apache.openejb.assembler.classic.Assembler)2 ResourceInfo (org.apache.openejb.assembler.classic.ResourceInfo)2 ConfigurationFactory (org.apache.openejb.config.ConfigurationFactory)2 InputSource (org.xml.sax.InputSource)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 FileWriter (java.io.FileWriter)1 InputStream (java.io.InputStream)1 Field (java.lang.reflect.Field)1 Method (java.lang.reflect.Method)1 URL (java.net.URL)1 Arrays.asList (java.util.Arrays.asList)1 HashMap (java.util.HashMap)1