List of usage examples for javax.naming Context rebind
public void rebind(String name, Object obj) throws NamingException;
From source file:NonSerializableFactory.java
/** A convenience method that simplifies the process of rebinding a non-serializable object into a JNDI context. //from ww w. j a v a 2 s.c o m @param ctx the JNDI context to rebind to. @param key the key to use in both the NonSerializableFactory map and JNDI. It must be a valid name for use in ctx.bind(). @param target the non-Serializable object to bind. @throws NamingException thrown on failure to rebind key into ctx. */ public static synchronized void rebind(Context ctx, String key, Object target) throws NamingException { NonSerializableFactory.rebind(key, target); // Bind a reference to target using NonSerializableFactory as the ObjectFactory String className = target.getClass().getName(); String factory = NonSerializableFactory.class.getName(); StringRefAddr addr = new StringRefAddr("nns", key); Reference memoryRef = new Reference(className, addr, factory, null); ctx.rebind(key, memoryRef); }
From source file:net.fender.sql.ManagedConnectionDataSource.java
/** * Sub-classes that implement init() should make sure to call super.init() * to ensure JNDI publication./* w w w. j a va2s . c o m*/ * * @throws Exception */ public void init() throws Exception { if (jndiName != null) { Context context = null; try { if (jndiProperties == null) { context = new InitialContext(); } else { context = new InitialContext(jndiProperties); } context.rebind(jndiName, this); } finally { if (context != null) { try { context.close(); } catch (NamingException ignore) { // ignore } } } } }
From source file:net.sf.ehcache.distribution.JNDIRMICacheManagerPeerListener.java
/** * {@inheritDoc}/*from w w w . j a v a 2 s. co m*/ */ public void init() throws CacheException { RMICachePeer rmiCachePeer = null; String peerName = null; int counter = 0; try { Context initialContext = getInitialContext(); populateListOfRemoteCachePeers(); synchronized (cachePeers) { for (Iterator iterator = cachePeers.values().iterator(); iterator.hasNext();) { rmiCachePeer = (RMICachePeer) iterator.next(); peerName = rmiCachePeer.getName(); LOG.debug("binding " + peerName); initialContext.rebind(peerName, rmiCachePeer); counter++; } } LOG.debug(counter + " RMICachePeers bound in JNDI for RMI listener"); } catch (Exception e) { throw new CacheException( "Problem starting listener for RMICachePeer " + peerName + " .Error was " + e.getMessage(), e); } }
From source file:com.caricah.iotracah.datastore.IotDataSource.java
public void setupDatasource(String driver, String dbUrl, String username, String password) throws NamingException { System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory"); System.setProperty(Context.PROVIDER_URL, "file:////tmp"); Context ctx = new InitialContext(); // Construct DriverAdapterCPDS reference Reference cpdsRef = new Reference("org.apache.commons.dbcp2.cpdsadapter.DriverAdapterCPDS", "org.apache.commons.dbcp2.cpdsadapter.DriverAdapterCPDS", null); cpdsRef.add(new StringRefAddr("driver", driver)); cpdsRef.add(new StringRefAddr("url", dbUrl)); cpdsRef.add(new StringRefAddr("user", username)); cpdsRef.add(new StringRefAddr("password", password)); ctx.rebind("jdbc_cpds", cpdsRef); Reference ref = new Reference("org.apache.commons.dbcp2.datasources.SharedPoolDataSource", "org.apache.commons.dbcp2.datasources.SharedPoolDataSourceFactory", null); ref.add(new StringRefAddr("dataSourceName", "jdbc_cpds")); ref.add(new StringRefAddr("defaultMaxTotal", "100")); ref.add(new StringRefAddr("defaultMaxIdle", "30")); ref.add(new StringRefAddr("defaultMaxWaitMillis", "10000")); ctx.rebind("jdbc_commonpool", ref); }
From source file:com.silverpeas.jcrutil.model.impl.AbstractJcrTestCase.java
/** * Workaround to be able to use Sun's JNDI file system provider on Unix * * @param ic : the JNDI initial context * @param jndiName : the binding name//from w w w . java 2 s .c om * @param ref : the reference to be bound * @throws NamingException */ protected void rebind(InitialContext ic, String jndiName, Object ref) throws NamingException { Context currentContext = ic; StringTokenizer tokenizer = new StringTokenizer(jndiName, "/", false); while (tokenizer.hasMoreTokens()) { String name = tokenizer.nextToken(); if (tokenizer.hasMoreTokens()) { try { currentContext = (Context) currentContext.lookup(name); } catch (javax.naming.NameNotFoundException nnfex) { currentContext = currentContext.createSubcontext(name); } } else { currentContext.rebind(name, ref); } } }
From source file:com.stratelia.silverpeas.versioning.jcr.impl.AbstractJcrTestCase.java
/** * Workaround to be able to use Sun's JNDI file system provider on Unix * @param ic : the JNDI initial context//from w w w . j a v a2 s. c om * @param jndiName : the binding name * @param ref : the reference to be bound * @throws NamingException */ protected void rebind(InitialContext ic, String jndiName, Reference ref) throws NamingException { Context currentContext = ic; StringTokenizer tokenizer = new StringTokenizer(jndiName, "/", false); while (tokenizer.hasMoreTokens()) { String name = tokenizer.nextToken(); if (tokenizer.hasMoreTokens()) { try { currentContext = (Context) currentContext.lookup(name); } catch (javax.naming.NameNotFoundException nnfex) { currentContext = currentContext.createSubcontext(name); } } else { currentContext.rebind(name, ref); } } }
From source file:jdao.JDAO.java
public static Context bind(Context ctx, String nameStr, Object obj) throws NamingException { log("binding " + nameStr); Name name = ctx.getNameParser("").parse(nameStr); //no name, nothing to do if (name.size() == 0) return null; Context subCtx = ctx; //last component of the name will be the name to bind for (int i = 0; i < name.size() - 1; i++) { try {//from w w w. jav a 2 s . co m subCtx = (Context) subCtx.lookup(name.get(i)); log("Subcontext " + name.get(i) + " already exists"); } catch (NameNotFoundException e) { subCtx = subCtx.createSubcontext(name.get(i)); log("Subcontext " + name.get(i) + " created"); } } subCtx.rebind(name.get(name.size() - 1), obj); log("Bound object to " + name.get(name.size() - 1)); return subCtx; }
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 ava 2s .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.compass.core.jndi.NamingHelper.java
/** * Bind val to name in ctx, and make sure that all intermediate contexts * exist.//from ww w . j a v a 2 s.co m * * @param ctx * the root context * @param name * the name as a string * @param val * the object to be bound * @throws javax.naming.NamingException */ public static void bind(Context ctx, String name, Object val) throws NamingException { try { ctx.rebind(name, val); } catch (Exception e) { Name n = ctx.getNameParser("").parse(name); while (n.size() > 1) { String ctxName = n.get(0); Context subctx = null; try { subctx = (Context) ctx.lookup(ctxName); } catch (NameNotFoundException nfe) { // don't do nothing } if (subctx != null) { ctx = subctx; } else { ctx = ctx.createSubcontext(ctxName); } n = n.getSuffix(1); } ctx.rebind(n, val); } }
From source file:org.eclipse.ecr.runtime.jtajca.NuxeoContainer.java
protected static void addBinding(Context dir, Name name, Object obj) throws NamingException { try {//from w w w. j a v a 2 s .com dir.rebind(name, obj); } catch (NamingException e) { dir.bind(name, obj); } }