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:com.wso2telco.proxy.util.DBUtils.java

private static void initializeDatasource() throws NamingException {
    if (dataSource != null) {
        return;/*  w  w w  . j a  va2 s.c  om*/
    }

    String dataSourceName = null;
    try {
        Context ctx = new InitialContext();
        dataSourceName = configurationService.getDataHolder().getMobileConnectConfig().getAuthProxy()
                .getDataSourceName();
        if (dataSourceName != null) {
            dataSource = (DataSource) ctx.lookup(dataSourceName);
        } else {
            throw new ConfigurationException("DataSource could not be found in mobile-connect.xml");
        }
    } catch (ConfigurationException e) {
        throw new ConfigurationException("DataSource could not be found in mobile-connect.xml");
    } catch (NamingException e) {
        throw new NamingException("Exception occurred while initiating data source : " + dataSourceName);
    }
}

From source file:org.brucalipto.sqlutil.SQLManager.java

protected static DataSource setupDataSource(final String dsJNDIName) {
    Context env = null;
    final String contextURI = dsJNDIName.startsWith(REF_PREFIX) ? dsJNDIName : REF_PREFIX + dsJNDIName;
    log.debug("Looking for '" + contextURI + "' in Context");
    try {// w w  w.j  av  a  2 s.co  m
        env = new InitialContext();
        return (DataSource) env.lookup(contextURI);
    } catch (NamingException e) {
        log.error("Error getting datasource '' from Context", e);
        return null;
    } finally {
        try {
            if (env != null)
                env.close();
        } catch (NamingException e) {
            log.error("Error closing context", e);
        }
    }
}

From source file:com.cws.esolutions.core.utils.MQUtils.java

/**
 * Gets an MQ message off a specified queue and returns it as an
 * <code>Object</code> to the requestor for further processing.
 *
 * @param connName - The connection name to utilize
 * @param authData - The authentication data to utilize, if required
 * @param responseQueue - The request queue name to put the message on
 * @param timeout - How long to wait for a connection or response
 * @param messageId - The JMS correlation ID of the message the response is associated with
 * @return <code>Object</code> - The serializable data returned by the MQ request
 * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing
 *///from w  w w. jav  a2 s . c o  m
public static final synchronized Object getMqMessage(final String connName, final List<String> authData,
        final String responseQueue, final long timeout, final String messageId) throws UtilityException {
    final String methodName = MQUtils.CNAME
            + "getMqMessage(final String connName, final List<String> authData, final String responseQueue, final long timeout, final String messageId) throws UtilityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", connName);
        DEBUGGER.debug("Value: {}", responseQueue);
        DEBUGGER.debug("Value: {}", timeout);
        DEBUGGER.debug("Value: {}", messageId);
    }

    Connection conn = null;
    Session session = null;
    Object response = null;
    Context envContext = null;
    MessageConsumer consumer = null;
    ConnectionFactory connFactory = null;

    try {
        try {
            InitialContext 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);
        }

        if (envContext != null) {
            try {
                consumer = session.createConsumer((Destination) envContext.lookup(responseQueue),
                        "JMSCorrelationID='" + messageId + "'");
            } catch (NamingException nx) {
                throw new UtilityException(nx.getMessage(), nx);
            }
        } else {
            Destination destination = session.createQueue(responseQueue);

            if (DEBUG) {
                DEBUGGER.debug("Destination: {}", destination);
            }

            consumer = session.createConsumer(destination, "JMSCorrelationID='" + messageId + "'");
        }

        if (DEBUG) {
            DEBUGGER.debug("MessageConsumer: {}", consumer);
        }

        ObjectMessage message = (ObjectMessage) consumer.receive(timeout);

        if (DEBUG) {
            DEBUGGER.debug("ObjectMessage: {}", message);
        }

        if (message == null) {
            throw new UtilityException("Failed to retrieve message within the timeout specified.");
        }

        response = message.getObject();
        message.acknowledge();

        if (DEBUG) {
            DEBUGGER.debug("Object: {}", response);
        }
    } 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 response;
}

From source file:be.fedict.eid.dss.sp.StartupServletContextListener.java

public static void bindComponent(String jndiName, Object component) throws NamingException {

    LOG.debug("bind component: " + jndiName);
    InitialContext initialContext = new InitialContext();
    String[] names = jndiName.split("/");
    Context context = initialContext;
    for (int idx = 0; idx < names.length - 1; idx++) {
        String name = names[idx];
        LOG.debug("name: " + name);
        NamingEnumeration<NameClassPair> listContent = context.list("");
        boolean subContextPresent = false;
        while (listContent.hasMore()) {
            NameClassPair nameClassPair = listContent.next();
            if (!name.equals(nameClassPair.getName())) {
                continue;
            }//from   w w  w  . ja v a2  s  . c  o m
            subContextPresent = true;
        }
        if (!subContextPresent) {
            context = context.createSubcontext(name);
        } else {
            context = (Context) context.lookup(name);
        }
    }
    String name = names[names.length - 1];
    context.rebind(name, component);
}

From source file:org.apache.axis2.transport.jms.JMSUtils.java

public static <T> T lookup(Context context, Class<T> clazz, String name) throws NamingException {

    Object object = context.lookup(name);
    try {/*from  w w  w.j  av a 2  s .  c  o m*/
        return clazz.cast(object);
    } catch (ClassCastException ex) {
        // Instead of a ClassCastException, throw an exception with some
        // more information.
        if (object instanceof Reference) {
            Reference ref = (Reference) object;
            handleException("JNDI failed to de-reference Reference with name " + name + "; is the factory "
                    + ref.getFactoryClassName() + " in your classpath?");
            return null;
        } else {
            handleException("JNDI lookup of name " + name + " returned a " + object.getClass().getName()
                    + " while a " + clazz + " was expected");
            return null;
        }
    }
}

From source file:com.wso2telco.dbUtil.DataBaseConnectUtils.java

private static void initializeConnectDatasource() throws NamingException {
    if (mConnectDatasource != null) {
        return;//from  w w w .  j av a  2  s . co  m
    }

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

From source file:com.alfaariss.oa.util.database.jdbc.DataSourceFactory.java

private static DataSource createByContext(IConfigurationManager configurationManager, Element eConfig)
        throws DatabaseException {
    DataSource dataSource = null;
    try {//from  w w  w .ja  va2 s . co  m
        String sContext = configurationManager.getParam(eConfig, "environment_context");
        if (sContext == null) {
            _logger.info("Could not find the optional 'environment_context' item in config");
        } else {
            String sResourceRef = configurationManager.getParam(eConfig, "resource-ref");
            if (sResourceRef == null) {
                _logger.warn("Could not find the 'resource-ref' item in config");
                throw new DatabaseException(SystemErrors.ERROR_CONFIG_READ);
            }

            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);
            }

            try {
                dataSource = (DataSource) envCtx.lookup(sResourceRef);
            } catch (NamingException e) {
                _logger.warn("Could not find resource ref: " + sResourceRef, e);
                throw new DatabaseException(SystemErrors.ERROR_INIT);
            }
        }
    } catch (DatabaseException e) {
        throw e;
    } catch (Exception e) {
        _logger.warn("Could not create datasource", e);
        throw new DatabaseException(SystemErrors.ERROR_INTERNAL);
    }
    return dataSource;
}

From source file:org.apache.openjpa.lib.conf.Configurations.java

/**
 * Looks up the given name in JNDI. If the name is null, null is returned.
 *//*from   ww w  .  j a  v  a  2s .c  o m*/
public static Object lookup(String name, String userKey, Log log) {
    if (StringUtils.isEmpty(name))
        return null;

    Context ctx = null;
    try {
        ctx = new InitialContext();
        Object result = ctx.lookup(name);
        if (result == null && log != null && log.isWarnEnabled())
            log.warn(_loc.get("jndi-lookup-failed", userKey, name));
        return result;
    } catch (NamingException ne) {
        throw new NestableRuntimeException(_loc.get("naming-err", name).getMessage(), ne);
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException ne) {
                // ignore
            }
        }
    }
}

From source file:com.wso2telco.dep.verificationhandler.verifier.DatabaseUtils.java

/**
 * Initialize am data source.//  w  ww. j a  v  a2s.  c om
 *
 * @throws NamingException the naming exception
 */
public static void initializeAMDataSource() throws NamingException {
    if (amDatasource != null) {
        return;
    }

    String amDataSourceName = "jdbc/WSO2AM_DB";

    if (amDataSourceName != null) {
        try {
            Context ctx = new InitialContext();
            amDatasource = (DataSource) ctx.lookup(amDataSourceName);
        } catch (NamingException e) {
            log.error(e);
            throw e;
        }

    }
}

From source file:com.wso2telco.dep.verificationhandler.verifier.DatabaseUtils.java

/**
 * Initialize data source./*from w  ww  . j  av a  2  s  .  c om*/
 *
 * @throws NamingException the naming exception
 */
public static void initializeDataSource() throws NamingException {
    if (statDatasource != null) {
        return;
    }

    String statdataSourceName = "jdbc/WSO2AM_STATS_DB";

    if (statdataSourceName != null) {
        try {
            Context ctx = new InitialContext();
            statDatasource = (DataSource) ctx.lookup(statdataSourceName);
        } catch (NamingException e) {
            log.error(e);
            throw e;
        }

    }
}