Example usage for javax.naming Context bind

List of usage examples for javax.naming Context bind

Introduction

In this page you can find the example usage for javax.naming Context bind.

Prototype

public void bind(String name, Object obj) throws NamingException;

Source Link

Document

Binds a name to an object.

Usage

From source file:mitm.application.djigzo.james.service.DjigzoServiceImpl.java

@Override
public void service(ServiceManager serviceManager) throws ServiceException {
    try {//  www  .  j  av a  2s  . c  o  m
        Context context = new InitialContext();

        /*
         * We will bind the avalon service manager to the JNDI context so we can get a hold of the
         * service manager from spring using a JndiObjectFactoryBean.  
         */
        context = context.createSubcontext("djigzo");
        context.bind("avalonServiceManager", serviceManager);
    } catch (NamingException e) {
        throw new ServiceException("DjigzoService", "Unable to register James service manager.", e);
    }
}

From source file:com.ritchey.naming.InitialContextFactory.java

/**
 * Get Context that has access to default Namespace. This method won't be
 * called if a name URL beginning with java: is passed to an InitialContext.
 *
 * @see org.mortbay.naming.java.javaURLContextFactory
 * @param env a <code>Hashtable</code> value
 * @return a <code>Context</code> value
 */// w ww .j a  v  a 2 s  .  co m
public Context getInitialContext(Hashtable env) {
    Log.debug("InitialContext loaded");
    Context ctx = new localContextRoot(env);

    Properties properties = new Properties();
    try {
        properties.load(new FileInputStream("build.properties"));
    } catch (Exception e1) {
        e1.printStackTrace();
    }

    Context jdbc = null;
    try {
        jdbc = ctx.createSubcontext("jdbc");
    } catch (NamingException e) {
        try {
            jdbc = (Context) ctx.lookup("jdbc");
        } catch (NamingException e1) {
            e1.printStackTrace();
        }
    }
    Context ldap = null;
    try {
        ldap = ctx.createSubcontext("ldap");
    } catch (NamingException e) {
        try {
            ldap = (Context) ctx.lookup("ldap");
        } catch (NamingException e1) {
            e1.printStackTrace();
        }
    }

    Log.debug("getInitialContext");

    String databaseNames = properties.getProperty("database.jndi.names");
    if (databaseNames == null) {
        Log.warn(new RuntimeException("database.jndi.names is not defined"
                + " in build.properties as a comma separated list in " + "build.properties"));
        return ctx;
    }

    for (String database : databaseNames.split(" *, *")) {
        Log.debug("create " + database);
        try {
            createDs(database, properties, jdbc);
        } catch (NamingException e) {
            e.printStackTrace();
        }
    }

    try {
        createLdapStrings(properties, ldap);
    } catch (NamingException e1) {
        e1.printStackTrace();
    }

    String url = getValue(false, "picture", null, properties);
    try {
        ctx.bind("picture", url);
    } catch (NamingException ex) {
        Logger.getLogger(InitialContextFactory.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        Log.debug("jdbc initial context = " + ctx.listBindings("jdbc"));
        NamingEnumeration<Binding> ldapBindings = ctx.listBindings("ldap");
        Log.debug("ldap initial context = " + ctx.listBindings("ldap"));
        while (ldapBindings.hasMore()) {
            Binding binding = ldapBindings.next();
            Log.debug("binding: " + binding.getName());
        }
    } catch (NamingException e) {
        e.printStackTrace();
    }
    return ctx;
}

From source file:blueprint.sdk.experimental.florist.db.ConnectionListener.java

public void contextInitialized(final ServletContextEvent arg0) {
    Properties poolProp = new Properties();
    try {//  w  w w. ja  v a2  s .  c o m
        Context initContext = new InitialContext();

        // load pool properties file (from class path)
        poolProp.load(ConnectionListener.class.getResourceAsStream("/jdbc_pools.properties"));
        StringTokenizer stk = new StringTokenizer(poolProp.getProperty("PROP_LIST"));

        // process all properties files list in pool properties (from class
        // path)
        while (stk.hasMoreTokens()) {
            try {
                String propName = stk.nextToken();
                LOGGER.info(this, "loading jdbc properties - " + propName);

                Properties prop = new Properties();
                prop.load(ConnectionListener.class.getResourceAsStream(propName));

                DataSource dsr;
                if (prop.containsKey("JNDI_NAME")) {
                    // lookup DataSource from JNDI
                    // FIXME JNDI support is not tested yet. SPI or Factory
                    // is needed here.
                    LOGGER.warn(this, "JNDI DataSource support needs more hands on!");
                    dsr = (DataSource) initContext.lookup(prop.getProperty("JNDI_NAME"));
                } else {
                    // create new BasicDataSource
                    BasicDataSource bds = new BasicDataSource();
                    bds.setMaxActive(Integer.parseInt(prop.getProperty("MAX_ACTIVE")));
                    bds.setMaxIdle(Integer.parseInt(prop.getProperty("MAX_IDLE")));
                    bds.setMaxWait(Integer.parseInt(prop.getProperty("MAX_WAIT")));
                    bds.setInitialSize(Integer.parseInt(prop.getProperty("INITIAL")));
                    bds.setDriverClassName(prop.getProperty("CLASS_NAME"));
                    bds.setUrl(prop.getProperty("URL"));
                    bds.setUsername(prop.getProperty("USER"));
                    bds.setPassword(prop.getProperty("PASSWORD"));
                    bds.setValidationQuery(prop.getProperty("VALIDATION"));
                    dsr = bds;
                }
                boundDsrs.put(prop.getProperty("POOL_NAME"), dsr);
                initContext.bind(prop.getProperty("POOL_NAME"), dsr);
            } catch (RuntimeException e) {
                LOGGER.trace(e);
            }
        }
    } catch (IOException | NamingException e) {
        LOGGER.trace(e);
    }
}

From source file:org.apache.juddi.rmi.JNDIRegistration.java

/**
 * Registers the Publish and Inquiry Services to JNDI and instantiates a
 * instance of each so we can remotely attach to it later.
 *//*  www .  j  a  va  2  s. c  o m*/
public void register(int port) {
    try {
        Context juddiContext = context.createSubcontext(JUDDI);

        securityService = new UDDISecurityService(port);
        if (log.isDebugEnabled())
            log.debug("Setting " + UDDI_SECURITY_SERVICE + ", " + securityService.getClass());
        juddiContext.bind(UDDI_SECURITY_SERVICE, securityService);

        publicationService = new UDDIPublicationService(port);
        if (log.isDebugEnabled())
            log.debug("Setting " + UDDI_PUBLICATION_SERVICE + ", " + publicationService.getClass());
        juddiContext.bind(UDDI_PUBLICATION_SERVICE, publicationService);

        inquiryService = new UDDIInquiryService(port);
        if (log.isDebugEnabled())
            log.debug("Setting " + UDDI_INQUIRY_SERVICE + ", " + inquiryService.getClass());
        juddiContext.bind(UDDI_INQUIRY_SERVICE, inquiryService);

        subscriptionService = new UDDISubscriptionService(port);
        if (log.isDebugEnabled())
            log.debug("Setting " + UDDI_SUBSCRIPTION_SERVICE + ", " + subscriptionService.getClass());
        juddiContext.bind(UDDI_SUBSCRIPTION_SERVICE, subscriptionService);

        subscriptionListenerService = new UDDISubscriptionListenerService(port);
        if (log.isDebugEnabled())
            log.debug("Setting " + UDDI_SUBSCRIPTION_LISTENER_SERVICE + ", "
                    + subscriptionListenerService.getClass());
        juddiContext.bind(UDDI_SUBSCRIPTION_LISTENER_SERVICE, subscriptionListenerService);

        custodyTransferService = new UDDICustodyTransferService(port);
        if (log.isDebugEnabled())
            log.debug("Setting " + UDDI_CUSTODY_TRANSFER_SERVICE + ", " + custodyTransferService.getClass());
        juddiContext.bind(UDDI_CUSTODY_TRANSFER_SERVICE, custodyTransferService);

        owl_SInquiryService = new OWL_SInquiryService(port);
        if (log.isDebugEnabled()) {
            log.debug("Setting " + OWL_S_INQUERY_SERVICE + ", " + owl_SInquiryService.getClass());
        }
        juddiContext.bind(OWL_S_INQUERY_SERVICE, owl_SInquiryService);

        owl_SPublicationService = new OWL_SPublicationService(port);
        if (log.isDebugEnabled()) {
            log.debug("Setting " + OWL_S_Publication_SERVICE + ", " + owl_SPublicationService.getClass());
        }
        juddiContext.bind(OWL_S_Publication_SERVICE, owl_SInquiryService);

        publisherService = new JUDDIApiService(port);
        if (log.isDebugEnabled())
            log.debug("Setting " + JUDDI_PUBLISHER_SERVICE + ", " + publisherService.getClass());
        juddiContext.bind(JUDDI_PUBLISHER_SERVICE, publisherService);

    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
}

From source file:org.apache.openejb.assembler.classic.Assembler.java

public AppContext createApplication(AppInfo appInfo, ClassLoader classLoader, boolean start)
        throws OpenEJBException, IOException, NamingException {
    // The path is used in the UrlCache, command line deployer, JNDI name templates, tomcat integration and a few other places
    if (appInfo.appId == null)
        throw new IllegalArgumentException("AppInfo.appId cannot be null");
    if (appInfo.path == null)
        appInfo.path = appInfo.appId;/*ww  w  .  j  av  a2s . co m*/

    logger.info("createApplication.start", appInfo.path);

    //        try {
    //            Thread.sleep(5000);
    //        } catch (InterruptedException e) {
    //            e.printStackTrace();
    //            Thread.interrupted();
    //        }

    // To start out, ensure we don't already have any beans deployed with duplicate IDs.  This
    // is a conflict we can't handle.
    List<String> used = new ArrayList<String>();
    for (EjbJarInfo ejbJarInfo : appInfo.ejbJars) {
        for (EnterpriseBeanInfo beanInfo : ejbJarInfo.enterpriseBeans) {
            if (containerSystem.getBeanContext(beanInfo.ejbDeploymentId) != null) {
                used.add(beanInfo.ejbDeploymentId);
            }
        }
    }

    if (used.size() > 0) {
        String message = logger.error("createApplication.appFailedDuplicateIds", appInfo.path);
        for (String id : used) {
            logger.debug("createApplication.deploymentIdInUse", id);
            message += "\n    " + id;
        }
        throw new DuplicateDeploymentIdException(message);
    }

    //Construct the global and app jndi contexts for this app
    final InjectionBuilder injectionBuilder = new InjectionBuilder(classLoader);

    Set<Injection> injections = new HashSet<Injection>();
    injections.addAll(injectionBuilder.buildInjections(appInfo.globalJndiEnc));
    injections.addAll(injectionBuilder.buildInjections(appInfo.appJndiEnc));

    final JndiEncBuilder globalBuilder = new JndiEncBuilder(appInfo.globalJndiEnc, injections, null, null,
            GLOBAL_UNIQUE_ID, classLoader);
    final Map<String, Object> globalBindings = globalBuilder.buildBindings(JndiEncBuilder.JndiScope.global);
    final Context globalJndiContext = globalBuilder.build(globalBindings);

    final JndiEncBuilder appBuilder = new JndiEncBuilder(appInfo.appJndiEnc, injections, appInfo.appId, null,
            appInfo.appId, classLoader);
    final Map<String, Object> appBindings = appBuilder.buildBindings(JndiEncBuilder.JndiScope.app);
    final Context appJndiContext = appBuilder.build(appBindings);

    try {
        // Generate the cmp2/cmp1 concrete subclasses
        CmpJarBuilder cmpJarBuilder = new CmpJarBuilder(appInfo, classLoader);
        File generatedJar = cmpJarBuilder.getJarFile();
        if (generatedJar != null) {
            classLoader = ClassLoaderUtil.createClassLoader(appInfo.path,
                    new URL[] { generatedJar.toURI().toURL() }, classLoader);
        }

        final AppContext appContext = new AppContext(appInfo.appId, SystemInstance.get(), classLoader,
                globalJndiContext, appJndiContext, appInfo.standaloneModule);
        appContext.getInjections().addAll(injections);
        appContext.getBindings().putAll(globalBindings);
        appContext.getBindings().putAll(appBindings);

        containerSystem.addAppContext(appContext);

        final Context containerSystemContext = containerSystem.getJNDIContext();

        if (!SystemInstance.get().hasProperty("openejb.geronimo")) {
            // Bean Validation
            // ValidatorFactory needs to be put in the map sent to the entity manager factory
            // so it has to be constructed before
            final List<CommonInfoObject> vfs = new ArrayList<CommonInfoObject>();
            for (ClientInfo clientInfo : appInfo.clients) {
                vfs.add(clientInfo);
            }
            for (ConnectorInfo connectorInfo : appInfo.connectors) {
                vfs.add(connectorInfo);
            }
            for (EjbJarInfo ejbJarInfo : appInfo.ejbJars) {
                vfs.add(ejbJarInfo);
            }
            for (WebAppInfo webAppInfo : appInfo.webApps) {
                vfs.add(webAppInfo);
            }

            final Map<String, ValidatorFactory> validatorFactories = new HashMap<String, ValidatorFactory>();
            for (CommonInfoObject info : vfs) {
                ValidatorFactory factory = null;
                try {
                    factory = ValidatorBuilder.buildFactory(classLoader, info.validationInfo);
                } catch (ValidationException ve) {
                    logger.warning("can't build the validation factory for module " + info.uniqueId, ve);
                }
                if (factory != null) {
                    validatorFactories.put(info.uniqueId, factory);
                }
            }
            moduleIds.addAll(validatorFactories.keySet());

            // validators bindings
            for (Entry<String, ValidatorFactory> validatorFactory : validatorFactories.entrySet()) {
                String id = validatorFactory.getKey();
                ValidatorFactory factory = validatorFactory.getValue();
                try {
                    containerSystemContext.bind(VALIDATOR_FACTORY_NAMING_CONTEXT + id, factory);
                    containerSystemContext.bind(VALIDATOR_NAMING_CONTEXT + id,
                            factory.usingContext().getValidator());
                } catch (NameAlreadyBoundException e) {
                    throw new OpenEJBException("ValidatorFactory already exists for module " + id, e);
                } catch (Exception e) {
                    throw new OpenEJBException(e);
                }
            }
        }

        // JPA - Persistence Units MUST be processed first since they will add ClassFileTransformers
        // to the class loader which must be added before any classes are loaded
        Map<String, String> units = new HashMap<String, String>();
        PersistenceBuilder persistenceBuilder = new PersistenceBuilder(persistenceClassLoaderHandler);
        for (PersistenceUnitInfo info : appInfo.persistenceUnits) {
            ReloadableEntityManagerFactory factory;
            try {
                factory = persistenceBuilder.createEntityManagerFactory(info, classLoader);
                containerSystem.getJNDIContext().bind(PERSISTENCE_UNIT_NAMING_CONTEXT + info.id, factory);
                units.put(info.name, PERSISTENCE_UNIT_NAMING_CONTEXT + info.id);
            } catch (NameAlreadyBoundException e) {
                throw new OpenEJBException("PersistenceUnit already deployed: " + info.persistenceUnitRootUrl);
            } catch (Exception e) {
                throw new OpenEJBException(e);
            }

            factory.register();
        }

        // Connectors
        for (ConnectorInfo connector : appInfo.connectors) {
            ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
            Thread.currentThread().setContextClassLoader(classLoader);
            try {
                // todo add undeployment code for these
                if (connector.resourceAdapter != null) {
                    createResource(connector.resourceAdapter);
                }
                for (ResourceInfo outbound : connector.outbound) {
                    createResource(outbound);
                }
                for (MdbContainerInfo inbound : connector.inbound) {
                    createContainer(inbound);
                }
                for (ResourceInfo adminObject : connector.adminObject) {
                    createResource(adminObject);
                }
            } finally {
                Thread.currentThread().setContextClassLoader(oldClassLoader);
            }
        }

        List<BeanContext> allDeployments = new ArrayList<BeanContext>();

        // EJB
        EjbJarBuilder ejbJarBuilder = new EjbJarBuilder(props, appContext);
        for (EjbJarInfo ejbJar : appInfo.ejbJars) {
            HashMap<String, BeanContext> deployments = ejbJarBuilder.build(ejbJar, injections);

            JaccPermissionsBuilder jaccPermissionsBuilder = new JaccPermissionsBuilder();
            PolicyContext policyContext = jaccPermissionsBuilder.build(ejbJar, deployments);
            jaccPermissionsBuilder.install(policyContext);

            TransactionPolicyFactory transactionPolicyFactory = createTransactionPolicyFactory(ejbJar,
                    classLoader);
            for (BeanContext beanContext : deployments.values()) {

                beanContext.setTransactionPolicyFactory(transactionPolicyFactory);
            }

            MethodTransactionBuilder methodTransactionBuilder = new MethodTransactionBuilder();
            methodTransactionBuilder.build(deployments, ejbJar.methodTransactions);

            MethodConcurrencyBuilder methodConcurrencyBuilder = new MethodConcurrencyBuilder();
            methodConcurrencyBuilder.build(deployments, ejbJar.methodConcurrency);

            for (BeanContext beanContext : deployments.values()) {
                containerSystem.addDeployment(beanContext);
            }

            //bind ejbs into global jndi
            jndiBuilder.build(ejbJar, deployments);

            // setup timers/asynchronous methods - must be after transaction attributes are set
            for (BeanContext beanContext : deployments.values()) {
                if (beanContext.getComponentType() != BeanType.STATEFUL) {
                    Method ejbTimeout = beanContext.getEjbTimeout();
                    boolean timerServiceRequired = false;
                    if (ejbTimeout != null) {
                        // If user set the tx attribute to RequiresNew change it to Required so a new transaction is not started
                        if (beanContext.getTransactionType(ejbTimeout) == TransactionType.RequiresNew) {
                            beanContext.setMethodTransactionAttribute(ejbTimeout, TransactionType.Required);
                        }
                        timerServiceRequired = true;
                    }
                    for (Iterator<Map.Entry<Method, MethodContext>> it = beanContext.iteratorMethodContext(); it
                            .hasNext();) {
                        Map.Entry<Method, MethodContext> entry = it.next();
                        MethodContext methodContext = entry.getValue();
                        if (methodContext.getSchedules().size() > 0) {
                            timerServiceRequired = true;
                            Method method = entry.getKey();
                            //TODO Need ?
                            if (beanContext.getTransactionType(method) == TransactionType.RequiresNew) {
                                beanContext.setMethodTransactionAttribute(method, TransactionType.Required);
                            }
                        }
                    }
                    if (timerServiceRequired) {
                        // Create the timer
                        EjbTimerServiceImpl timerService = new EjbTimerServiceImpl(beanContext);
                        //Load auto-start timers
                        TimerStore timerStore = timerService.getTimerStore();
                        for (Iterator<Map.Entry<Method, MethodContext>> it = beanContext
                                .iteratorMethodContext(); it.hasNext();) {
                            Map.Entry<Method, MethodContext> entry = it.next();
                            MethodContext methodContext = entry.getValue();
                            for (ScheduleData scheduleData : methodContext.getSchedules()) {
                                timerStore.createCalendarTimer(timerService,
                                        (String) beanContext.getDeploymentID(), null, entry.getKey(),
                                        scheduleData.getExpression(), scheduleData.getConfig());
                            }
                        }
                        beanContext.setEjbTimerService(timerService);
                    } else {
                        beanContext.setEjbTimerService(new NullEjbTimerServiceImpl());
                    }
                }
                //set asynchronous methods transaction
                //TODO ???
                for (Iterator<Entry<Method, MethodContext>> it = beanContext.iteratorMethodContext(); it
                        .hasNext();) {
                    Entry<Method, MethodContext> entry = it.next();
                    if (entry.getValue().isAsynchronous()
                            && beanContext.getTransactionType(entry.getKey()) == TransactionType.RequiresNew) {
                        beanContext.setMethodTransactionAttribute(entry.getKey(), TransactionType.Required);
                    }
                }
            }
            // process application exceptions
            for (ApplicationExceptionInfo exceptionInfo : ejbJar.applicationException) {
                try {
                    Class exceptionClass = classLoader.loadClass(exceptionInfo.exceptionClass);
                    for (BeanContext beanContext : deployments.values()) {
                        beanContext.addApplicationException(exceptionClass, exceptionInfo.rollback,
                                exceptionInfo.inherited);
                    }
                } catch (ClassNotFoundException e) {
                    logger.error("createApplication.invalidClass", e, exceptionInfo.exceptionClass,
                            e.getMessage());
                }
            }

            allDeployments.addAll(deployments.values());
        }

        allDeployments = sort(allDeployments);

        appContext.getBeanContexts().addAll(allDeployments);

        new CdiBuilder().build(appInfo, appContext, allDeployments);

        ensureWebBeansContext(appContext);

        appJndiContext.bind("app/BeanManager", appContext.getBeanManager());
        appContext.getBindings().put("app/BeanManager", appContext.getBeanManager());

        // now that everything is configured, deploy to the container
        if (start) {
            // deploy
            for (BeanContext deployment : allDeployments) {
                try {
                    Container container = deployment.getContainer();
                    container.deploy(deployment);
                    if (!((String) deployment.getDeploymentID()).endsWith(".Comp") && !deployment.isHidden()) {
                        logger.info("createApplication.createdEjb", deployment.getDeploymentID(),
                                deployment.getEjbName(), container.getContainerID());
                    }
                    if (logger.isDebugEnabled()) {
                        for (Map.Entry<Object, Object> entry : deployment.getProperties().entrySet()) {
                            logger.info("createApplication.createdEjb.property", deployment.getEjbName(),
                                    entry.getKey(), entry.getValue());
                        }
                    }
                } catch (Throwable t) {
                    throw new OpenEJBException("Error deploying '" + deployment.getEjbName() + "'.  Exception: "
                            + t.getClass() + ": " + t.getMessage(), t);
                }
            }

            // start
            for (BeanContext deployment : allDeployments) {
                try {
                    Container container = deployment.getContainer();
                    container.start(deployment);
                    if (!((String) deployment.getDeploymentID()).endsWith(".Comp") && !deployment.isHidden()) {
                        logger.info("createApplication.startedEjb", deployment.getDeploymentID(),
                                deployment.getEjbName(), container.getContainerID());
                    }
                } catch (Throwable t) {
                    throw new OpenEJBException("Error starting '" + deployment.getEjbName() + "'.  Exception: "
                            + t.getClass() + ": " + t.getMessage(), t);
                }
            }
        }

        // App Client
        for (ClientInfo clientInfo : appInfo.clients) {
            // determine the injections
            List<Injection> clientInjections = injectionBuilder.buildInjections(clientInfo.jndiEnc);

            // build the enc
            JndiEncBuilder jndiEncBuilder = new JndiEncBuilder(clientInfo.jndiEnc, clientInjections, "Bean",
                    clientInfo.moduleId, null, clientInfo.uniqueId, classLoader);
            // if there is at least a remote client classes
            // or if there is no local client classes
            // then, we can set the client flag
            if ((clientInfo.remoteClients.size() > 0) || (clientInfo.localClients.size() == 0)) {
                jndiEncBuilder.setClient(true);

            }
            jndiEncBuilder.setUseCrossClassLoaderRef(false);
            Context context = jndiEncBuilder.build(JndiEncBuilder.JndiScope.comp);

            //                Debug.printContext(context);

            containerSystemContext.bind("openejb/client/" + clientInfo.moduleId, context);

            if (clientInfo.path != null) {
                context.bind("info/path", clientInfo.path);
            }
            if (clientInfo.mainClass != null) {
                context.bind("info/mainClass", clientInfo.mainClass);
            }
            if (clientInfo.callbackHandler != null) {
                context.bind("info/callbackHandler", clientInfo.callbackHandler);
            }
            context.bind("info/injections", clientInjections);

            for (String clientClassName : clientInfo.remoteClients) {
                containerSystemContext.bind("openejb/client/" + clientClassName, clientInfo.moduleId);
            }

            for (String clientClassName : clientInfo.localClients) {
                containerSystemContext.bind("openejb/client/" + clientClassName, clientInfo.moduleId);
                logger.getChildLogger("client").info("createApplication.createLocalClient", clientClassName,
                        clientInfo.moduleId);
            }
        }

        SystemInstance systemInstance = SystemInstance.get();

        // WebApp

        WebAppBuilder webAppBuilder = systemInstance.getComponent(WebAppBuilder.class);
        if (webAppBuilder != null) {
            webAppBuilder.deployWebApps(appInfo, classLoader);
        }

        if (start) {
            EjbResolver globalEjbResolver = systemInstance.getComponent(EjbResolver.class);
            globalEjbResolver.addAll(appInfo.ejbJars);
        }

        // bind all global values on global context
        for (Map.Entry<String, Object> value : appContext.getBindings().entrySet()) {
            String path = value.getKey();
            if (!path.startsWith("global") || path.equalsIgnoreCase("global/dummy")) { // dummy bound for each app
                continue;
            }

            // a bit weird but just to be consistent if user doesn't lookup directly the resource
            Context lastContext = ContextUtil.mkdirs(containerSystemContext, path);
            try {
                lastContext.bind(path.substring(path.lastIndexOf("/") + 1, path.length()), value.getValue());
            } catch (NameAlreadyBoundException nabe) {
                nabe.printStackTrace();
            }
            containerSystemContext.rebind(path, value.getValue());
        }

        logger.info("createApplication.success", appInfo.path);

        deployedApplications.put(appInfo.path, appInfo);
        fireAfterApplicationCreated(appInfo);

        return appContext;
    } catch (ValidationException ve) {
        throw ve;
    } catch (Throwable t) {
        try {
            destroyApplication(appInfo);
        } catch (Exception e1) {
            logger.debug("createApplication.undeployFailed", e1, appInfo.path);
        }
        throw new OpenEJBException(messages.format("createApplication.failed", appInfo.path), t);
    }
}

From source file:org.apache.torque.dsfactory.JndiDataSourceFactory.java

/**
 *
 * @param ctx/*from w ww . j  a  va  2s  .c om*/
 * @param path
 * @param ds
 * @throws Exception
 */
private void bindDStoJndi(Context ctx, String path, Object ds) throws Exception {
    debugCtx(ctx);

    // add subcontexts, if not added already
    int start = path.indexOf(':') + 1;
    if (start > 0) {
        path = path.substring(start);
    }
    StringTokenizer st = new StringTokenizer(path, "/");
    while (st.hasMoreTokens()) {
        String subctx = st.nextToken();
        if (st.hasMoreTokens()) {
            try {
                ctx.createSubcontext(subctx);
                log.debug("Added sub context: " + subctx);
            } catch (NameAlreadyBoundException nabe) {
                // ignore
                log.debug("Sub context " + subctx + " already exists");
            } catch (NamingException ne) {
                log.debug("Naming exception caught " + "when creating subcontext" + subctx, ne);
                // even though there is a specific exception
                // for this condition, some implementations
                // throw the more general one.
                /*
                 *                      if (ne.getMessage().indexOf("already bound") == -1 )
                 *                      {
                 *                      throw ne;
                 *                      }
                 */
                // ignore
            }
            ctx = (Context) ctx.lookup(subctx);
        } else {
            // not really a subctx, it is the ds name
            ctx.bind(subctx, ds);
        }
    }
}

From source file:org.apache.torque.JndiConfigurationTest.java

/**
 * creates and binds a BasicDataSource into jndi.
 * @throws Exception if DataSource creation or binding fails.
 *///  ww w  .  j  a  va2  s. c om
protected void bindDataSource() throws Exception {
    BasicDataSource dataSource = getDataSource();
    Context context = getInitialContext();
    context.createSubcontext(JNDI_SUBCONTEXT);
    context.bind(JNDI_PATH, dataSource);
}

From source file:org.bibsonomy.lucene.util.JNDITestDatabaseBinder.java

private static void bindLuceneConfig(String contextName, String fileName) {
    Context ctx;

    final Properties props;
    try {// w  w  w.  j a  v a2 s. c o m
        props = openPropertyFile(fileName);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }

    LuceneConfig config = new LuceneConfig();

    // get properties
    for (Object key : props.keySet()) {
        if (!present((key.toString())) || !(key.toString()).startsWith(CONTEXT_CONFIG_BEAN))
            continue;

        String propertyName = getPropertyName((String) key);
        String propertyValue = props.getProperty((String) key);
        try {
            PropertyUtils.setNestedProperty(config, propertyName, propertyValue);
            log.debug("Set lucene configuration property " + propertyName + " to " + propertyValue);
        } catch (Exception e) {
            log.warn("Error setting lucene configuration property " + propertyName + " to " + propertyValue
                    + "('" + e.getMessage() + "')");
        }
    }

    // bind bean in context
    try {
        MockContextFactory.setAsInitial();
        ctx = new InitialContext();
        ctx.bind(contextName + CONTEXT_CONFIG_BEAN, config);
    } catch (NamingException ex) {
        log.error("Error binding environment variable:'" + contextName + "' via JNDI ('" + ex.getMessage()
                + "')");
    }
}

From source file:org.eclipse.ecr.runtime.jtajca.NuxeoContainer.java

protected static void addBinding(Context dir, Name name, Object obj) throws NamingException {
    try {// www  .  j a  v a 2 s  .c  o  m
        dir.rebind(name, obj);
    } catch (NamingException e) {
        dir.bind(name, obj);
    }
}

From source file:org.grouter.common.jndi.JNDIUtils.java

public static void createInMemoryJndiProvider(List<BindingItem> bindings) {
    if (bindings == null) {
        throw new IllegalArgumentException("Can not bind null to jndi tree.");
    }/*from w  ww .j  a v a 2 s.c  o m*/
    try {
        System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
                "org.apache.commons.naming.java.javaURLContextFactory");
        System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");

        Iterator<BindingItem> bindingItemIterator = bindings.iterator();
        while (bindingItemIterator.hasNext()) {
            BindingItem item = bindingItemIterator.next();
            InitialContext initialContext = new InitialContext();
            logger.debug("Creating component context : " + item.getJndipath()[0]);
            Context compContext = initialContext.createSubcontext(item.getJndipath()[0]);
            logger.debug("Creating environment context : " + item.getJndipath()[1]);
            Context envContext = compContext.createSubcontext(item.getJndipath()[1]);
            logger.debug("Bidning : " + item.getJndiName() + " to implementation : " + item.getImplemenation());
            envContext.bind(item.getJndiName(), item.getImplemenation());
            printJNDI(envContext, logger);
            //logger.debug(envContext.listBindings(initialContext.getNameInNamespace()));
        }

    } catch (NamingException e) {
        logger.error(e, e);
    }

}