Example usage for javax.naming Context lookup

List of usage examples for javax.naming Context lookup

Introduction

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

Prototype

public Object lookup(String name) throws NamingException;

Source Link

Document

Retrieves the named object.

Usage

From source file:de.sqlcoach.db.jdbc.DBConnection.java

/**
 * Gets the pool connection./*from  www  . java2  s .  c o  m*/
 * 
 * @return the pool connection
 * 
 * @throws NamingException
 *           the naming exception
 * @throws SQLException
 *           the SQL exception
 */
protected static DBConnection getPoolConnection(String dataSourceName) throws NamingException, SQLException {
    final Context initCtx = new InitialContext();
    final Context envCtx = (Context) initCtx.lookup("java:comp/env");

    final String name = "jdbc/" + dataSourceName;

    DBConnection dbconn = null;

    Integer connectionCnt = DBConnection.connectionCounter.get(dataSourceName);
    if (connectionCnt == null)
        connectionCnt = 0;

    if (log.isInfoEnabled()) {
        log.info("getPoolConnection ENTER [dataSource=" + dataSourceName + " connectionCnt=" + connectionCnt
                + "]");
    }

    // final DataSource ds = (DataSource)envCtx.lookup(name);
    // if (ds == null) {
    // log.error ("getPoolConnection : No DataSource for "+ name+ " !");
    // return null;
    // } else {
    // if (log.isDebugEnabled())
    // log.debug("getPoolConnection : DataSource: "+ds.toString());
    // }

    // final Connection cn = ds.getConnection();
    final Connection cn = getSimpleConnection(dataSourceName);
    if (cn == null) { // Failed !
        log.error("getPoolConnection : No Connection for " + name + " ! (connectionCnt:" + connectionCnt + ")");
        return null;
    } else { // Success
        DBConnection.connectionCounter.put(dataSourceName, connectionCnt++);
        dbconn = new DBConnection(cn, connectionCnt, dataSourceName);
        if (log.isDebugEnabled())
            log.debug("getPoolConnection : Connection: " + cn.toString());
    }

    cn.setAutoCommit(false);

    // Set Oracle date format to YYYY-MM-DD
    // final java.sql.DatabaseMetaData dm = cn.getMetaData();
    // final String prodname = dm.getDatabaseProductName();
    // if (prodname.equalsIgnoreCase("Oracle")) { // Only for Oracle !!
    // try (Statement s = cn.createStatement()) {
    // s.execute("ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD'");
    // if (log.isDebugEnabled())
    // log.debug("getPoolConnection : ProductName=" + prodname + "\nALTER
    // SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD'");
    // } catch (SQLException e) {
    // log.warn("getPoolConnection : ProductName="+prodname+"\nALTER SESSION SET
    // NLS_DATE_FORMAT = 'YYYY-MM-DD': ", e);
    // }
    // } else {
    // if (log.isDebugEnabled())
    // log.debug("getPoolConnection : Kein Oracle cn= "+cn+ "
    // ProductName="+prodname);
    // }

    if (log.isInfoEnabled())
        log.info("getPoolConnection LEAVE dbconn=" + dbconn);

    return dbconn;
}

From source file:com.wso2telco.util.DbUtil.java

private static void initializeDatasources() throws AuthenticatorException {
    if (mConnectDatasource != null) {
        return;//from   w  ww .  j  a  va 2s . c o m
    }

    String dataSourceName = null;
    try {
        Context ctx = new InitialContext();
        dataSourceName = configurationService.getDataHolder().getMobileConnectConfig().getDataSourceName();
        mConnectDatasource = (DataSource) ctx.lookup(dataSourceName);
    } catch (NamingException e) {
        handleException("Error while looking up the data source: " + dataSourceName, e);
    }
}

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

/**
 * get runtime configuration from context
 *///from ww w.j av  a  2 s  .  c om
public static void initRuntimeConfiguration() {
    try {
        final Context initContext = new InitialContext();
        final Context envContext = (Context) initContext.lookup(CONTEXT_ENV_NAME);
        final LuceneConfig config = (LuceneConfig) envContext.lookup(CONTEXT_CONFIG_BEAN);

        // index base path
        setIndexBasePath(config.getIndexPath());
        // search mode
        if (present(config.getSearchMode())) {
            searchMode = config.getSearchMode();
        }

        // db driver name
        if (present(config.getDbDriverName())) {
            dbDriverName = config.getDbDriverName();
        }

        // maximum field length in the lucene index
        if (present(config.getMaximumFieldLength())) {
            String mflIn = config.getMaximumFieldLength();
            if (KEY_UNLIMITED.equals(mflIn)) {
                maximumFieldLength = IndexWriter.MaxFieldLength.UNLIMITED;
            } else if (KEY_LIMITED.equals(mflIn)) {
                maximumFieldLength = IndexWriter.MaxFieldLength.LIMITED;
            } else {
                Integer value;
                try {
                    value = Integer.parseInt(mflIn);
                } catch (NumberFormatException e) {
                    value = IndexWriter.DEFAULT_MAX_FIELD_LENGTH;
                }
                maximumFieldLength = new IndexWriter.MaxFieldLength(value);
            }
        }

        // nr. of redundant indeces
        if (present(config.getRedundantCnt())) {
            Integer value;
            try {
                value = Integer.parseInt(config.getRedundantCnt());
            } catch (NumberFormatException e) {
                value = IndexWriter.DEFAULT_MAX_FIELD_LENGTH;
            }
            redundantCnt = value;
        }

        // enable/disable tag cloud on search pages
        setEnableTagClouds(Boolean.valueOf(config.getEnableTagClouds()));

        // limit number of posts to consider for building the tag cloud
        setTagCloudLimit(Integer.valueOf(config.getTagCloudLimit()));

        setEnableUpdater(Boolean.valueOf(config.getEnableUpdater()));
        loadIndexIntoRam = Boolean.valueOf(config.getLoadIndexIntoRam());
    } catch (Exception e) {
        log.error("Error requesting JNDI environment variables", e);
    }

    // done - print out debug information
    log.debug("\t indexBasePath    : " + getIndexBasePath());
    log.debug("\t searchMode       : " + searchMode);
    log.debug("\t enableUpdater    : " + getEnableUpdater());
    log.debug("\t loadIndexIntoRam : " + loadIndexIntoRam);
}

From source file:com.wso2telco.refund.utils.DbUtils.java

/**
 * Initialize datasources.//from ww w.j a  v  a2s .  c o  m
 *
 * @throws SQLException the SQL exception
 * @throws DBUtilException the axata db util exception
 */
public static void initializeDatasources() throws SQLException, DBUtilException {
    if (Datasource != null) {
        return;
    }

    try {
        Context ctx = new InitialContext();
        Datasource = (DataSource) ctx.lookup(DATA_SOURCE);
    } catch (NamingException e) {
        handleException("Error while looking up the data source: " + DATA_SOURCE, e);
    }
}

From source file:de.zib.gndms.infra.GridConfig.java

/**
 * @see #findSharedContext(javax.naming.Context, String)
 *//*from   www .j  a va 2  s.c o m*/
@NotNull
public static Context findSharedContext(@NotNull Context startContext, @NotNull Name name)
        throws NamingException {
    Context resultContext;

    try {
        resultContext = startContext.createSubcontext(name);
    } catch (NameAlreadyBoundException e) {
        resultContext = (Context) startContext.lookup(name);
    }
    return resultContext;
}

From source file:de.zib.gndms.infra.GridConfig.java

/**
 * Returns the {@code Subcontext} of {@code startContext}, which is bounded to {@code name}.
 * If it does not exist, a new subcontext is created and bounded to {@code name}.
 *
 * @param startContext a Context, which is supposed to have a certain subContext
 * @param name the name of a subcontext of {@code startContext}
 * @return a chosen subcontext of {@code startContext}
 * @throws NamingException if a naming exception occurs, while executing {@code createSubcontext()} or {@code lookup()}
 *//*from   w w  w . j  av a 2 s  . c  o m*/
@NotNull
public static Context findSharedContext(@NotNull Context startContext, @NotNull String name)
        throws NamingException {
    Context resultContext;

    try {
        resultContext = startContext.createSubcontext(name);
    } catch (NameAlreadyBoundException e) {
        resultContext = (Context) startContext.lookup(name);
    }
    return resultContext;
}

From source file:com.silverpeas.components.model.AbstractSpringJndiDaoTest.java

/**
 * Workaround to be able to use Sun's JNDI file system provider on Unix
 *
 * @param ic : the JNDI initial context/*  ww  w  .ja  v a 2  s . c o  m*/
 * @param jndiName : the binding name
 * @param ref : the reference to be bound
 * @throws NamingException
 */
protected static 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:Util.java

/**
 * Lookup an object in the given context
 * /*  w  w  w .  java 2  s  . com*/
 * @param context
 *          the context
 * @param name
 *          the name to lookup
 * @param clazz
 *          the expected type
 * @return the object
 * @throws Exception
 *           for any error
 */
public static Object lookup(Context context, Name name, Class clazz) throws Exception {
    Object result = context.lookup(name);
    checkObject(context, name.toString(), result, clazz);
    return result;
}

From source file:Util.java

/**
 * Lookup an object in the given context
 * //from w w w .ja  v a 2s.  c  o m
 * @param context
 *          the context
 * @param name
 *          the name to lookup
 * @param clazz
 *          the expected type
 * @return the object
 * @throws Exception
 *           for any error
 */
public static Object lookup(Context context, String name, Class clazz) throws Exception {
    Object result = context.lookup(name);
    checkObject(context, name, result, clazz);
    return result;
}

From source file:eu.planets_project.tb.impl.persistency.ExperimentPersistencyImpl.java

/**
 * A Factory method to build a reference to this interface.
 * @return//from  w  w  w  .  ja v a  2  s  .  c  o m
 */
public static ExperimentPersistencyRemote getInstance() {
    try {
        Context jndiContext = getInitialContext();
        ExperimentPersistencyRemote dao_r = (ExperimentPersistencyRemote) PortableRemoteObject.narrow(
                jndiContext.lookup("testbed/ExperimentPersistencyImpl/remote"),
                ExperimentPersistencyRemote.class);
        return dao_r;
    } catch (NamingException e) {
        //TODO integrate message into logging mechanism
        System.out.println("Failure in getting PortableRemoteObject: " + e.toString());
        return null;
    }
}