List of usage examples for javax.naming Context lookup
public Object lookup(String name) throws NamingException;
From source file:com.funambol.server.db.DataSourceContextHelper.java
/** * Create all intermediate subcontexts.// www .j a va 2s.c o m */ private static void createSubcontexts(javax.naming.Context ctx, String name) throws NamingException { javax.naming.Context currentContext = ctx; StringTokenizer tokenizer = new StringTokenizer(name, "/"); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); if ((!token.equals("")) && (tokenizer.hasMoreTokens())) { try { currentContext = currentContext.createSubcontext(token); } catch (NamingException e) { // Silent catch. Probably an object is already bound in // the context. currentContext = (javax.naming.Context) currentContext.lookup(token); } } } }
From source file:org.apache.solr.core.SolrResourceLoader.java
/** * Finds the solrhome based on looking up the value in one of three places: * <ol>// w w w.jav a2 s. co m * <li>JNDI: via java:comp/env/solr/home</li> * <li>The system property solr.solr.home</li> * <li>Look in the current working directory for a solr/ directory</li> * </ol> * * The return value is normalized. Normalization essentially means it ends in a trailing slash. * @return A normalized solrhome * @see #normalizeDir(String) */ public static String locateSolrHome() { String home = null; // Try JNDI try { Context c = new InitialContext(); home = (String) c.lookup("java:comp/env/" + project + "/home"); log.info("Using JNDI solr.home: " + home); } catch (NoInitialContextException e) { log.info("JNDI not configured for " + project + " (NoInitialContextEx)"); } catch (NamingException e) { log.info("No /" + project + "/home in JNDI"); } catch (RuntimeException ex) { log.warn("Odd RuntimeException while testing for JNDI: " + ex.getMessage()); } // Now try system property if (home == null) { String prop = project + ".solr.home"; home = System.getProperty(prop); if (home != null) { log.info("using system property " + prop + ": " + home); } } // if all else fails, try if (home == null) { home = project + '/'; log.info(project + " home defaulted to '" + home + "' (could not find system property or JNDI)"); } return normalizeDir(home); }
From source file:com.alfaariss.oa.util.database.jdbc.DataSourceFactory.java
/** * Creates a DataSource object specified by the supplied properties: * //from w w w . j av a2s. c om * <ul> * <li>environment_context</li> * <li>resource-ref</li> * </ul> * * or: * *<ul> * <li>password</li> * <li>url</li> * <li>username</li> * <li>driverClassName</li> * <li>maxActive</li> * <li>maxIdle</li> * <li>maxWait</li> * <li>minIdle</li> * <li>defaultAutoCommit</li> * <li>defaultReadOnly</li> * <li>defaultTransactionIsolation</li> * <li>defaultCatalog</li> * <li>initialSize</li> * <li>testOnBorrow</li> * <li>testOnReturn</li> * <li>timeBetweenEvictionRunsMillis</li> * <li>numTestsPerEvictionRun</li> * <li>minEvictableIdleTimeMillis</li> * <li>testWhileIdle</li> * <li>validationQuery</li> * <li>accessToUnderlyingConnectionAllowed</li> * <li>removeAbandoned</li> * <li>removeAbandonedTimeout</li> * <li>logAbandoned</li> * <li>poolPreparedStatements</li> * <li>maxOpenPreparedStatements</li> * <li>connectionProperties</li> * </ul> * @param pConfig config properties * @return DataSource object * @throws DatabaseException if creation fails */ public static DataSource createDataSource(Properties pConfig) throws DatabaseException { DataSource ds = null; try { if (pConfig.containsKey("environment_context")) { String sContext = pConfig.getProperty("environment_context"); Context envCtx = null; try { envCtx = (Context) new InitialContext().lookup(sContext); } catch (NamingException e) { _logger.warn("Could not find context: " + sContext, e); throw new DatabaseException(SystemErrors.ERROR_INIT); } String sResourceRef = pConfig.getProperty("resource-ref"); try { ds = (DataSource) envCtx.lookup(sResourceRef); } catch (NamingException e) { _logger.warn("Could not find resource ref: " + sResourceRef, e); throw new DatabaseException(SystemErrors.ERROR_INIT); } _logger.info("Created DataSource by reading from context"); } else { ds = BasicDataSourceFactory.createDataSource(pConfig); _logger.info("Created DataSource by reading properties object"); } } catch (Exception e) { _logger.fatal("Could not initialize object", e); throw new DatabaseException(SystemErrors.ERROR_INTERNAL); } return ds; }
From source file:com.wegas.core.Helper.java
/** * @param <T>/* w w w . j a v a2 s .co m*/ * @param context * @param type * @param service * @return looked-up EJB instance * @throws NamingException */ public static <T> T lookupBy(Context context, Class<T> type, Class<?> service) throws NamingException { try { return (T) context.lookup("java:module/" + service.getSimpleName() + "!" + type.getName()); } catch (NamingException ex) { try { return (T) context.lookup("java:global/classes/" + service.getSimpleName() + "!" + type.getName()); } catch (NamingException ex3) { try { return (T) context .lookup("java:global/embed-classes/" + service.getSimpleName() + "!" + type.getName()); } catch (NamingException ex1) { try { return (T) context .lookup("java:global/cobertura/" + service.getSimpleName() + "!" + type.getName()); } catch (NamingException ex2) { logger.error("Unable to retrieve to do jndi lookup on class: {}", type.getSimpleName()); throw ex2; } } } } }
From source file:ece356.UserDBAO.java
public static Connection getConnection() throws ClassNotFoundException, SQLException, NamingException { InitialContext cxt = new InitialContext(); if (cxt == null) { throw new RuntimeException("Unable to create naming context!"); }/*from w w w . j av a 2s . c o m*/ Context dbContext = (Context) cxt.lookup("java:comp/env"); DataSource ds = (DataSource) dbContext.lookup("jdbc/myDatasource"); if (ds == null) { throw new RuntimeException("Data source not found!"); } Connection con = ds.getConnection(); /*Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection(url, user, pwd);*/ Statement stmt = null; try { con.createStatement(); stmt = con.createStatement(); stmt.execute("USE ece356db_" + nid); } finally { if (stmt != null) { stmt.close(); } } return con; }
From source file:com.cws.esolutions.core.utils.MQUtils.java
/** * Puts an MQ message on a specified queue and returns the associated * correlation ID for retrieval upon request. * * @param connName - The connection name to utilize * @param authData - The authentication data to utilize, if required * @param requestQueue - The request queue name to put the message on * @param targetHost - The target host for the message * @param value - The data to place on the request. MUST be <code>Serialiable</code> * @return <code>String</code> - the JMS correlation ID associated with the message * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing *//*from w w w . j a v a 2 s . com*/ public static final synchronized String sendMqMessage(final String connName, final List<String> authData, final String requestQueue, final String targetHost, final Serializable value) throws UtilityException { final String methodName = MQUtils.CNAME + "sendMqMessage(final String connName, final List<String> authData, final String requestQueue, final String targetHost, final Serializable value) throws UtilityException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", connName); DEBUGGER.debug("Value: {}", requestQueue); DEBUGGER.debug("Value: {}", targetHost); DEBUGGER.debug("Value: {}", value); } Connection conn = null; Session session = null; Context envContext = null; InitialContext initCtx = null; MessageProducer producer = null; ConnectionFactory connFactory = null; final String correlationId = RandomStringUtils.randomAlphanumeric(64); if (DEBUG) { DEBUGGER.debug("correlationId: {}", correlationId); } try { try { initCtx = new InitialContext(); envContext = (Context) initCtx.lookup(MQUtils.INIT_CONTEXT); connFactory = (ConnectionFactory) envContext.lookup(connName); } catch (NamingException nx) { // we're probably not in a container connFactory = new ActiveMQConnectionFactory(connName); } if (DEBUG) { DEBUGGER.debug("ConnectionFactory: {}", connFactory); } if (connFactory == null) { throw new UtilityException("Unable to create connection factory for provided name"); } // Create a Connection conn = connFactory.createConnection(authData.get(0), PasswordUtils.decryptText(authData.get(1), authData.get(2), authData.get(3), Integer.parseInt(authData.get(4)), Integer.parseInt(authData.get(5)), authData.get(6), authData.get(7), authData.get(8))); conn.start(); if (DEBUG) { DEBUGGER.debug("Connection: {}", conn); } // Create a Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); if (DEBUG) { DEBUGGER.debug("Session: {}", session); } // Create a MessageProducer from the Session to the Topic or Queue if (envContext != null) { try { producer = session.createProducer((Destination) envContext.lookup(requestQueue)); } catch (NamingException nx) { throw new UtilityException(nx.getMessage(), nx); } } else { Destination destination = session.createTopic(requestQueue); if (DEBUG) { DEBUGGER.debug("Destination: {}", destination); } producer = session.createProducer(destination); } if (producer == null) { throw new JMSException("Failed to create a producer object"); } producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); if (DEBUG) { DEBUGGER.debug("MessageProducer: {}", producer); } ObjectMessage message = session.createObjectMessage(true); message.setJMSCorrelationID(correlationId); message.setStringProperty("targetHost", targetHost); if (DEBUG) { DEBUGGER.debug("correlationId: {}", correlationId); } message.setObject(value); if (DEBUG) { DEBUGGER.debug("ObjectMessage: {}", message); } producer.send(message); } catch (JMSException jx) { throw new UtilityException(jx.getMessage(), jx); } finally { try { // Clean up if (!(session == null)) { session.close(); } if (!(conn == null)) { conn.close(); conn.stop(); } } catch (JMSException jx) { ERROR_RECORDER.error(jx.getMessage(), jx); } } return correlationId; }
From source file:org.eclipse.ecr.runtime.jtajca.NuxeoContainer.java
protected static void addDeepBinding(Context dir, CompositeName comp, Object obj) throws NamingException { Name name = comp.getPrefix(1); if (comp.size() == 1) { addBinding(dir, name, obj);/* w w w . jav a 2 s . c o m*/ return; } Context subdir; try { subdir = (Context) dir.lookup(name); } catch (NamingException e) { subdir = dir.createSubcontext(name); } addDeepBinding(subdir, (CompositeName) comp.getSuffix(1), obj); }
From source file:com.flexive.core.Database.java
/** * Return a connection for initializing the embedded default database. * * @param c the initial context for looking up the data source * @return an open connection, or null if the data source was not found * @throws SQLException if the connection could not be created *//* w w w.jav a2 s.c om*/ private static Connection getDefaultInitConnection(final Context c) throws SQLException { try { final DataSource initDs = (DataSource) c.lookup(GlobalConfigurationEngineBean.DEFAULT_DS_INIT); return initDs.getConnection(); } catch (NamingException e) { if (LOG.isErrorEnabled()) { LOG.error("Default configuration schema not initialized, but could not find " + GlobalConfigurationEngineBean.DEFAULT_DS_INIT); // continue, the caller will get a related exception when creating a connection anyway } return null; } }
From source file:de.highbyte_le.weberknecht.conf.ContextConfig.java
public ContextConfig() throws NamingException { Context ctx = new InitialContext(); envCtx = (Context) ctx.lookup("java:comp/env"); //$NON-NLS-1$ }
From source file:com.bank.config.code.JndiDataConfig.java
@Bean public DataSource dataSource() { try {// w w w. ja v a2 s . c om Context ctx = new InitialContext(); return (DataSource) ctx.lookup("java:comp/env/jdbc/datasource"); } catch (NamingException ex) { throw new RuntimeException(ex); } }