Search in sources :

Example 56 with Binding

use of javax.naming.Binding in project tomee by apache.

the class Assembler method destroy.

@Override
public void destroy() {
    final ReentrantLock l = lock;
    l.lock();
    try {
        final SystemInstance systemInstance = SystemInstance.get();
        systemInstance.fireEvent(new ContainerSystemPreDestroy());
        try {
            EjbTimerServiceImpl.shutdown();
        } catch (final Exception e) {
            logger.warning("Unable to shutdown scheduler", e);
        } catch (final NoClassDefFoundError ncdfe) {
        // no-op
        }
        logger.debug("Undeploying Applications");
        final Assembler assembler = this;
        final List<AppInfo> deployedApps = new ArrayList<>(assembler.getDeployedApplications());
        // if an app relies on the previous one it surely relies on it too at undeploy time
        Collections.reverse(deployedApps);
        for (final AppInfo appInfo : deployedApps) {
            try {
                assembler.destroyApplication(appInfo.path);
            } catch (final UndeployException e) {
                logger.error("Undeployment failed: " + appInfo.path, e);
            } catch (final NoSuchApplicationException e) {
            // Ignore
            }
        }
        final Iterator<ObjectName> it = containerObjectNames.iterator();
        final MBeanServer server = LocalMBeanServer.get();
        while (it.hasNext()) {
            try {
                server.unregisterMBean(it.next());
            } catch (final Exception ignored) {
            // no-op
            }
            it.remove();
        }
        try {
            remoteResourceMonitor.unregister();
        } catch (final Exception ignored) {
        // no-op
        }
        NamingEnumeration<Binding> namingEnumeration = null;
        try {
            namingEnumeration = containerSystem.getJNDIContext().listBindings("openejb/Resource");
        } catch (final NamingException ignored) {
        // no resource adapters were created
        }
        destroyResourceTree("", namingEnumeration);
        try {
            containerSystem.getJNDIContext().unbind("java:global");
        } catch (final NamingException ignored) {
        // no-op
        }
        systemInstance.removeComponent(OpenEjbConfiguration.class);
        systemInstance.removeComponent(JtaEntityManagerRegistry.class);
        systemInstance.removeComponent(TransactionSynchronizationRegistry.class);
        systemInstance.removeComponent(EjbResolver.class);
        systemInstance.removeComponent(ThreadSingletonService.class);
        systemInstance.fireEvent(new AssemblerDestroyed());
        systemInstance.removeObservers();
        if (DestroyableResource.class.isInstance(this.securityService)) {
            DestroyableResource.class.cast(this.securityService).destroyResource();
        }
        if (DestroyableResource.class.isInstance(this.transactionManager)) {
            DestroyableResource.class.cast(this.transactionManager).destroyResource();
        }
        for (final Container c : this.containerSystem.containers()) {
            if (DestroyableResource.class.isInstance(c)) {
                // TODO: should we use auto closeable there?
                DestroyableResource.class.cast(c).destroyResource();
            }
        }
        SystemInstance.reset();
    } finally {
        l.unlock();
    }
}
Also used : ReentrantLock(java.util.concurrent.locks.ReentrantLock) Binding(javax.naming.Binding) DestroyableResource(org.apache.openejb.api.resource.DestroyableResource) ArrayList(java.util.ArrayList) InvalidObjectException(java.io.InvalidObjectException) NameAlreadyBoundException(javax.naming.NameAlreadyBoundException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ObjectStreamException(java.io.ObjectStreamException) ResourceAdapterInternalException(javax.resource.spi.ResourceAdapterInternalException) URISyntaxException(java.net.URISyntaxException) UndeployException(org.apache.openejb.UndeployException) DefinitionException(javax.enterprise.inject.spi.DefinitionException) ConstructionException(org.apache.xbean.recipe.ConstructionException) MBeanRegistrationException(javax.management.MBeanRegistrationException) InstanceNotFoundException(javax.management.InstanceNotFoundException) ValidationException(javax.validation.ValidationException) MalformedObjectNameException(javax.management.MalformedObjectNameException) DuplicateDeploymentIdException(org.apache.openejb.DuplicateDeploymentIdException) TimeoutException(java.util.concurrent.TimeoutException) NamingException(javax.naming.NamingException) OpenEJBException(org.apache.openejb.OpenEJBException) DeploymentException(javax.enterprise.inject.spi.DeploymentException) NoSuchApplicationException(org.apache.openejb.NoSuchApplicationException) MalformedURLException(java.net.MalformedURLException) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) ObjectName(javax.management.ObjectName) JMXContainer(org.apache.openejb.assembler.monitoring.JMXContainer) Container(org.apache.openejb.Container) SystemInstance(org.apache.openejb.loader.SystemInstance) ContainerSystemPreDestroy(org.apache.openejb.assembler.classic.event.ContainerSystemPreDestroy) NamingException(javax.naming.NamingException) NoSuchApplicationException(org.apache.openejb.NoSuchApplicationException) UndeployException(org.apache.openejb.UndeployException) LocalMBeanServer(org.apache.openejb.monitoring.LocalMBeanServer) MBeanServer(javax.management.MBeanServer) AssemblerDestroyed(org.apache.openejb.assembler.classic.event.AssemblerDestroyed)

Example 57 with Binding

use of javax.naming.Binding in project tomee by apache.

the class JndiTreeBrowser method runOnTree.

private void runOnTree(final JndiNodeWorker worker) throws NamingException {
    final NamingEnumeration<Binding> ne = context.listBindings(ROOT);
    while (ne.hasMoreElements()) {
        final Binding current = ne.next();
        final Object obj = current.getObject();
        worker.doWork(path, current.getName(), obj);
        if (obj instanceof Context) {
            runOnJndiTree((Context) obj, worker, path + '/' + current.getName());
        }
    }
}
Also used : Binding(javax.naming.Binding) InitialContext(javax.naming.InitialContext) Context(javax.naming.Context)

Example 58 with Binding

use of javax.naming.Binding in project tomee by apache.

the class HsqlService method init.

@Override
public void init(final Properties p) throws Exception {
    final Properties properties = new Properties();
    for (final Map.Entry<Object, Object> entry : p.entrySet()) {
        // Sometimes the properties object has non string values
        if (!(entry.getKey() instanceof String))
            continue;
        if (!(entry.getValue() instanceof String))
            continue;
        final String property = (String) entry.getKey();
        final String value = (String) entry.getValue();
        if (property.startsWith(sc_key_dbname + ".") || property.startsWith(sc_key_database + ".")) {
            throw new ServiceException("Databases cannot be declared in the hsql.properties.  " + "Instead declare a database connection in the openejb.conf file");
        }
        if ("port".equals(property)) {
            properties.setProperty(sc_key_port, value);
        } else if ("bind".equals(property)) {
            properties.setProperty(sc_key_address, value);
        } else {
            properties.setProperty(property, value);
        }
    }
    properties.setProperty(sc_key_no_system_exit, "true");
    final boolean disabled = Boolean.parseBoolean(properties.getProperty("disabled"));
    final ContainerSystem containerSystem = SystemInstance.get().getComponent(ContainerSystem.class);
    if (!disabled && containerSystem != null) {
        final NamingEnumeration<Binding> bindings;
        try {
            bindings = containerSystem.getJNDIContext().listBindings("openejb/Resource/");
            final Set<String> dbnames = new TreeSet<String>();
            for (final Binding binding : Collections.list(bindings)) {
                final Object value = binding.getObject();
                if (value instanceof DataSource) {
                    final DataSource jdbc = (DataSource) value;
                    Connection connection = null;
                    String path = null;
                    try {
                        connection = jdbc.getConnection();
                        final DatabaseMetaData meta = connection.getMetaData();
                        path = getPath(meta.getDriverName(), meta.getURL());
                    } catch (Throwable t) {
                        continue;
                    } finally {
                        if (connection != null) {
                            try {
                                connection.close();
                            } catch (SQLException sqlEx) {
                            // no-op
                            }
                        }
                    }
                    if (path != null) {
                        if (dbnames.size() > 9) {
                            throw new ServiceException("Hsql Server can only host 10 database instances");
                        }
                        String dbname = path.substring(path.lastIndexOf(':') + 1);
                        dbname = dbname.substring(dbname.lastIndexOf('/') + 1);
                        if (!dbnames.contains(dbname)) {
                            properties.put(sc_key_dbname + "." + dbnames.size(), dbname);
                            properties.put(sc_key_database + "." + dbnames.size(), path);
                            dbnames.add(dbname);
                        }
                    }
                }
            }
        } catch (NameNotFoundException e) {
        // Ignore
        }
        // create the server
        server = new Server();
        // add the silent property
        properties.setProperty(sc_key_silent, "true");
        // set the log and error writers
        server.setLogWriter(new HsqlPrintWriter(false));
        server.setErrWriter(new HsqlPrintWriter(true));
        server.setProperties(new HsqlProperties(properties));
        // get the port
        port = server.getPort();
        // get the Address
        final String ipString = server.getAddress();
        if (ipString != null && ipString.length() > 0) {
            this.ip = ipString;
        }
    }
}
Also used : ContainerSystem(org.apache.openejb.spi.ContainerSystem) Binding(javax.naming.Binding) Server(org.hsqldb.Server) SQLException(java.sql.SQLException) NameNotFoundException(javax.naming.NameNotFoundException) Connection(java.sql.Connection) Properties(java.util.Properties) HsqlProperties(org.hsqldb.persist.HsqlProperties) HsqlDatabaseProperties(org.hsqldb.persist.HsqlDatabaseProperties) DatabaseMetaData(java.sql.DatabaseMetaData) DataSource(javax.sql.DataSource) ServiceException(org.apache.openejb.server.ServiceException) TreeSet(java.util.TreeSet) HsqlProperties(org.hsqldb.persist.HsqlProperties) Map(java.util.Map)

Example 59 with Binding

use of javax.naming.Binding in project tomee by apache.

the class JndiTest method assertBindings.

private void assertBindings(NamingEnumeration<Binding> namingEnumeration) {
    assertNotNull("namingEnumeration", namingEnumeration);
    Map<String, Object> map = new HashMap<String, Object>();
    while (namingEnumeration.hasMoreElements()) {
        Binding pair = namingEnumeration.nextElement();
        map.put(pair.getName(), pair.getObject());
    }
    assertTrue("OrangeRemote", map.containsKey("OrangeRemote"));
    assertTrue("OrangeRemote is FruitRemote", map.get("OrangeRemote") instanceof FruitRemote);
    assertTrue("AppleRemote", map.containsKey("AppleRemote"));
    assertTrue("AppleRemote is FruitRemote", map.get("AppleRemote") instanceof FruitRemote);
    assertTrue("PeachRemote", map.containsKey("PeachRemote"));
    assertTrue("PeachRemote is FruitRemote", map.get("PeachRemote") instanceof FruitRemote);
    assertTrue("PearRemote", map.containsKey("PearRemote"));
    assertTrue("PearRemote is FruitRemote", map.get("PearRemote") instanceof FruitRemote);
    assertTrue("PlumRemote", map.containsKey("PlumRemote"));
    assertTrue("PlumRemote is FruitRemote", map.get("PlumRemote") instanceof FruitRemote);
}
Also used : Binding(javax.naming.Binding) HashMap(java.util.HashMap)

Example 60 with Binding

use of javax.naming.Binding in project tomee by apache.

the class TomcatJndiBuilder method mergeJava.

public static void mergeJava(final StandardContext standardContext) {
    final ContainerSystem cs = SystemInstance.get().getComponent(ContainerSystem.class);
    final String name = standardContext.getNamingContextListener().getName();
    final Object namingToken = standardContext.getNamingToken();
    ContextAccessController.setWritable(name, namingToken);
    Context root = null;
    try {
        root = ContextBindings.getClassLoader();
    } catch (final NamingException ignored) {
    // shouldn't occur
    // no-op
    }
    // classical deployment - needed because can be overriden through META-INF/context.xml
    final String hostname = org.apache.tomee.catalina.Contexts.getHostname(standardContext);
    String path = standardContext.findParameter(TomcatWebAppBuilder.OPENEJB_WEBAPP_MODULE_ID);
    if (path == null) {
        // standardContext not created by OpenEJB
        path = hostname;
        if (standardContext.getPath().startsWith("/")) {
            path += standardContext.getPath();
        } else {
            path += "/" + standardContext.getPath();
        }
    }
    WebContext webContext = cs.getWebContextByHost(path, hostname);
    if (webContext == null) {
        // tomee-embedded deployment
        webContext = cs.getWebContextByHost(standardContext.getPath().replaceFirst("/", ""), hostname);
        if (webContext == null) {
            webContext = cs.getWebContextByHost(standardContext.getPath(), hostname);
        }
    }
    final TomcatWebAppBuilder builder = (TomcatWebAppBuilder) SystemInstance.get().getComponent(WebAppBuilder.class);
    TomcatWebAppBuilder.ContextInfo contextInfo = null;
    if (builder != null) {
        contextInfo = builder.getContextInfo(standardContext);
        if (webContext == null && contextInfo != null && contextInfo.appInfo != null) {
            // can happen if deployed from apps/
            for (final WebAppInfo webAppInfo : contextInfo.appInfo.webApps) {
                if (webAppInfo.path != null && webAppInfo.path.replace(File.separatorChar, '/').equals(standardContext.getDocBase())) {
                    webContext = cs.getWebContextByHost(webAppInfo.moduleId, hostname);
                    if (webContext != null) {
                        break;
                    }
                }
            }
        }
    }
    Collection<String> ignoreNames = null;
    if (contextInfo != null) {
        ignoreNames = contextInfo.resourceNames;
    }
    if (webContext != null && webContext.getBindings() != null && root != null) {
        for (final Map.Entry<String, Object> entry : webContext.getBindings().entrySet()) {
            try {
                final String key = entry.getKey();
                if (key.startsWith("global/")) {
                    // will be done later
                    continue;
                }
                final Object value = normalize(entry.getValue());
                if (ignoreNames.contains(removeCompEnv(key))) {
                    // keep tomcat resources
                    try {
                        // tomcat can get the reference but the bound value
                        // can come from OpenEJB (ejb-jar.xml for instance)
                        // so check the lookup can be resolved before skipping it
                        root.lookup(key);
                        continue;
                    } catch (final NameNotFoundException nnfe) {
                    // no-op: let it be rebound or bound
                    }
                }
                Contexts.createSubcontexts(root, key);
                root.rebind(key, value);
            } catch (final NamingException e) {
                e.printStackTrace();
            }
        }
    }
    // merge global: we bind our global to be able to get a real global context and not a local one (bindigns)
    if (root != null) {
        try {
            root.bind("global", SystemInstance.get().getComponent(ContainerSystem.class).getJNDIContext().lookup("global"));
        } catch (final NamingException e) {
            // bind only global bindings
            if (webContext != null && webContext.getBindings() != null) {
                for (final Map.Entry<String, Object> entry : webContext.getBindings().entrySet()) {
                    try {
                        final String key = entry.getKey();
                        if (!key.startsWith("global/")) {
                            continue;
                        }
                        final Object value = normalize(entry.getValue());
                        Contexts.createSubcontexts(root, key);
                        root.rebind(key, value);
                    } catch (final NamingException ignored) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    // try to force some binding which probably failed earlier (see in TomcatWebappBuilder)
    try {
        final Context comp = (Context) ContextBindings.getClassLoader().lookup("comp");
        final TransactionManager transactionManager = SystemInstance.get().getComponent(TransactionManager.class);
        comp.rebind("TransactionManager", transactionManager);
        // bind TransactionSynchronizationRegistry
        final TransactionSynchronizationRegistry synchronizationRegistry = SystemInstance.get().getComponent(TransactionSynchronizationRegistry.class);
        comp.rebind("TransactionSynchronizationRegistry", synchronizationRegistry);
        try {
            comp.rebind("ORB", new SystemComponentReference(TomcatJndiBuilder.class.getClassLoader().loadClass("org.omg.CORBA.ORB")));
        } catch (final NoClassDefFoundError | ClassNotFoundException ncdfe) {
        // no-op
        }
        comp.rebind("HandleDelegate", new SystemComponentReference(HandleDelegate.class));
        if (webContext != null && webContext.getWebbeansContext() != null) {
            comp.rebind("BeanManager", new InjectableBeanManager(webContext.getWebbeansContext().getBeanManagerImpl()));
        } else if (contextInfo != null) {
            final WebBeansContext webBeansContext = cs.getAppContext(contextInfo.appInfo.appId).getWebBeansContext();
            if (webBeansContext != null) {
                // can be null if cdi is inhibited
                comp.rebind("BeanManager", new InjectableBeanManager(webBeansContext.getBeanManagerImpl()));
            }
        }
    } catch (final Exception ignored) {
        ignored.printStackTrace();
    // no-op
    }
    // merge comp/env in app if available (some users are doing it, JBoss habit?)
    try {
        final Context app = (Context) ContextBindings.getClassLoader().lookup("app");
        final Context ctx = (Context) ContextBindings.getClassLoader().lookup("comp/env");
        final List<Binding> bindings = Collections.list(ctx.listBindings("app"));
        for (final Binding binding : bindings) {
            try {
                app.bind(binding.getName(), binding.getObject());
            } catch (final NamingException ne) {
            // we don't want to rebind
            // no-op
            }
        }
    } catch (final Exception ne) {
    // no-op
    }
    ContextAccessController.setReadOnly(name);
}
Also used : ContainerSystem(org.apache.openejb.spi.ContainerSystem) WebContext(org.apache.openejb.core.WebContext) InjectableBeanManager(org.apache.webbeans.container.InjectableBeanManager) WebAppBuilder(org.apache.openejb.assembler.classic.WebAppBuilder) WebAppInfo(org.apache.openejb.assembler.classic.WebAppInfo) WebBeansContext(org.apache.webbeans.config.WebBeansContext) NamingException(javax.naming.NamingException) WebContext(org.apache.openejb.core.WebContext) WebBeansContext(org.apache.webbeans.config.WebBeansContext) StandardContext(org.apache.catalina.core.StandardContext) Context(javax.naming.Context) Binding(javax.naming.Binding) NameNotFoundException(javax.naming.NameNotFoundException) SystemComponentReference(org.apache.openejb.core.ivm.naming.SystemComponentReference) NamingException(javax.naming.NamingException) OpenEJBException(org.apache.openejb.OpenEJBException) NameNotFoundException(javax.naming.NameNotFoundException) MalformedURLException(java.net.MalformedURLException) HandleDelegate(javax.ejb.spi.HandleDelegate) TransactionManager(javax.transaction.TransactionManager) TransactionSynchronizationRegistry(javax.transaction.TransactionSynchronizationRegistry) Map(java.util.Map)

Aggregations

Binding (javax.naming.Binding)70 NamingException (javax.naming.NamingException)37 Context (javax.naming.Context)31 InitialContext (javax.naming.InitialContext)29 NameNotFoundException (javax.naming.NameNotFoundException)22 NameAlreadyBoundException (javax.naming.NameAlreadyBoundException)20 Name (javax.naming.Name)19 NotContextException (javax.naming.NotContextException)18 OperationNotSupportedException (javax.naming.OperationNotSupportedException)18 Reference (javax.naming.Reference)17 CompoundName (javax.naming.CompoundName)16 IOException (java.io.IOException)12 ArrayList (java.util.ArrayList)10 NamingContext (org.eclipse.jetty.jndi.NamingContext)9 CompositeName (javax.naming.CompositeName)8 Test (org.junit.Test)8 HashMap (java.util.HashMap)7 NamingEnumeration (javax.naming.NamingEnumeration)5 ServletContext (javax.servlet.ServletContext)5 MalformedURLException (java.net.MalformedURLException)4