Example usage for javax.naming InitialContext lookup

List of usage examples for javax.naming InitialContext lookup

Introduction

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

Prototype

public Object lookup(Name name) throws NamingException 

Source Link

Usage

From source file:org.enhydra.jdbc.pool.StandardPoolDataSource.java

public Object getObjectInstance(Object refObj, Name name, Context nameCtx, Hashtable env) throws Exception {

    super.getObjectInstance(refObj, name, nameCtx, env);
    Reference ref = (Reference) refObj;
    this.setLifeTime(Long.parseLong((String) ref.get("lifeTime").getContent()));
    this.setJdbcTestStmt((String) ref.get("jdbcTestStmt").getContent());
    this.setMaxSize(Integer.parseInt((String) ref.get("maxSize").getContent()));
    this.setMinSize(Integer.parseInt((String) ref.get("minSize").getContent()));
    this.setDataSourceName((String) ref.get("dataSourceName").getContent());
    InitialContext ictx = new InitialContext(env);
    cpds = (ConnectionPoolDataSource) ictx.lookup(this.dataSourceName);
    return this;
}

From source file:com.att.ajsc.csilogging.common.QueueConnector.java

@PostConstruct
public void init() {

    if (csiEnable && StringUtils.isNotEmpty(initialContextFactoryName)
            && StringUtils.isNotEmpty(connectionFactoryName) && StringUtils.isNotEmpty(providerURL)) {

        if (StringUtils.isNotEmpty(System.getenv(("com_att_aft_config_file")))) {
            System.setProperty("com.att.aft.config.file", System.getenv("com_att_aft_config_file"));
        }/*from w w w .j av a  2  s .co  m*/

        if (StringUtils.isEmpty(System.getProperty("com.att.aft.config.file"))) {
            logger.error("Environment or System properties dont have the property com.att.aft.config.file");
            return;
        }

        QueueConnectionFactory queueConnectionFactory;
        InitialContext jndi = null;
        ConnectionFactory connectionFactory = null;
        try {

            Properties env = new Properties();
            env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactoryName);
            env.put(Context.PROVIDER_URL, providerURL);
            jndi = new InitialContext(env);
            connectionFactory = (ConnectionFactory) jndi.lookup(connectionFactoryName);
            queueConnectionFactory = (QueueConnectionFactory) connectionFactory;
            if (StringUtils.isNotEmpty(auditDestinationName)) {
                auditQueueConnection = queueConnectionFactory.createQueueConnection();
                auditQueueSession = auditQueueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
                Queue auditQueue = (Queue) auditQueueSession.createQueue(auditDestinationName);
                auditQueueSender = auditQueueSession.createSender(auditQueue);
                auditQueueConnection.start();
                logger.info("*************CONNECTED :" + auditDestinationName + "*************");

            }

            if (StringUtils.isNotEmpty(perfDestinationName)) {
                pefQueueConnection = queueConnectionFactory.createQueueConnection();
                pefQueueSession = pefQueueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
                Queue perfQueue = (Queue) pefQueueSession.createQueue(perfDestinationName);
                pefQueueSender = pefQueueSession.createSender(perfQueue);
                pefQueueConnection.start();
                logger.info("*************CONNECTED :" + perfDestinationName + "*************");
            }

        } catch (Exception e) {
            logger.error("Error while connecting to the Queue" + e);
        }
    }

}

From source file:com.silverpeas.jcrutil.BetterRepositoryFactoryBean.java

protected Repository createJndiRepository(String jndiName) {
    try {//from   w  w w.j  a  v  a  2  s .com
        InitialContext ic = new InitialContext();
        prepareContext(ic, jndiName);
        RegistryHelper.registerRepository(new InitialContext(), jndiName,
                getConfiguration().getFile().getAbsolutePath(), getHomeDir().getFile().getAbsolutePath(), true);
        return (Repository) ic.lookup(jndiName);
    } catch (RepositoryException ex) {
        Logger.getLogger(BetterRepositoryFactoryBean.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(BetterRepositoryFactoryBean.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NamingException ex) {
        Logger.getLogger(BetterRepositoryFactoryBean.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:org.firstopen.singularity.admin.view.ECSpecBean.java

public ECSpecBean(String name) {

    try {//from ww  w  .  j av  a 2  s.co m
        if (System.getSecurityManager() == null) {

            System.setSecurityManager(new SecurityManager());
        }

        InitialContext jndiContext = JNDIUtil.getInitialContext();
        Object objref = jndiContext.lookup("jnp://localhost:1099/ejb/ale/AleSLSB");
        AleSLSBHome aleSLSBHome = (AleSLSBHome) PortableRemoteObject.narrow(objref, AleSLSBHome.class);

        aSLSB = aleSLSBHome.create();

        createLogicalDeviceSelectList();

        createECSpecSelectList();

    } catch (Exception e) {
        log.error("can't create ECSpecBean");
        /*
         * can't recover wrap in RuntimeException
         */
        throw new InfrastructureException(e);
    }
}

From source file:org.apache.servicemix.jms.AbstractJmsProcessor.java

protected ConnectionFactory getConnectionFactory(InitialContext ctx) throws NamingException {
    // First check configured connectionFactory on the endpoint
    ConnectionFactory connectionFactory = endpoint.getConnectionFactory();
    // Then, check for jndi connection factory name on the endpoint
    if (connectionFactory == null && endpoint.getJndiConnectionFactoryName() != null) {
        connectionFactory = (ConnectionFactory) ctx.lookup(endpoint.getJndiConnectionFactoryName());
    }/*from ww w.  j a v  a2s.c o m*/
    // Check for a configured connectionFactory on the configuration
    if (connectionFactory == null && endpoint.getConfiguration().getConnectionFactory() != null) {
        connectionFactory = endpoint.getConfiguration().getConnectionFactory();
    }
    // Check for jndi connection factory name on the configuration
    if (connectionFactory == null && endpoint.getConfiguration().getJndiConnectionFactoryName() != null) {
        connectionFactory = (ConnectionFactory) ctx
                .lookup(endpoint.getConfiguration().getJndiConnectionFactoryName());
    }
    return connectionFactory;
}

From source file:org.betaconceptframework.astroboa.client.service.AbstractClientServiceWrapper.java

<R> Object connectToRemoteService(Class<R> serviceClass, String jndiName) {
    //Call this method to actually get the referenced object
    try {//  w  w w  . ja  va  2s  .  co  m

        /*
         * According to the documentation 
         * https://docs.jboss.org/author/display/AS71/EJB+invocations+from+a+remote+client+using+JNDI
         * 
         * and to this thread https://community.jboss.org/message/647202#647202
         * 
         * JBoss AS7 has changed the procedure for a remote client invocation.
         * We have to use these JBoss Specific API in order to be able to dynamically provide information
         * about the server host name or ip and the port.
         * 
         * Bear in mind that in these properties no username and password is provided.
         * This means that the JBoss AS7 which hosts the Astroboa must have its 
         * security-realm for the subsystem remoting disabled.
         * 
         * This code must be reviewed as not only it contains JBoss Specific API but also
         * remoting subsystem must be active without security
         */
        Properties ejbClientConfigurationProperties = new Properties();
        ejbClientConfigurationProperties
                .put("remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED", "false");
        ejbClientConfigurationProperties.put("remote.connections", "default");
        ejbClientConfigurationProperties.put("remote.connection.default.host", serverHostNameOrIp);
        ejbClientConfigurationProperties.put("remote.connection.default.port", port);
        ejbClientConfigurationProperties.put(
                "remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS", "false");

        final EJBClientConfiguration ejbClientConfiguration = new PropertiesBasedEJBClientConfiguration(
                ejbClientConfigurationProperties);

        // EJB client context selection is based on selectors. So let's create a ConfigBasedEJBClientContextSelector which uses our EJBClientConfiguration created in previous step
        final ContextSelector<EJBClientContext> ejbClientContextSelector = new ConfigBasedEJBClientContextSelector(
                ejbClientConfiguration);
        // Now let's setup the EJBClientContext to use this selector
        final ContextSelector<EJBClientContext> previousSelector = EJBClientContext
                .setSelector(ejbClientContextSelector);
        ////////////////

        //Context environmental properties specific to JBoss Naming Context
        Properties jndiEnvironmentProperties = new Properties();
        //jndiEnvironmentProperties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
        jndiEnvironmentProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
        //jndiEnvironmentProperties.put(Context.PROVIDER_URL, "jnp://"+serverHostNameOrIpAndPortDelimitedWithSemiColon);

        InitialContext context = new InitialContext(jndiEnvironmentProperties);

        if (StringUtils.isBlank(jndiName)) {
            jndiName = createJNDIBindingNameForService(serviceClass, false);
        }

        try {
            return context.lookup(jndiName);
        } catch (Exception e) {
            logger.warn("Could not connect to local service " + serviceClass.getSimpleName(), e);
            //try with '#' instead of '!'
            if (jndiName.contains("!")) {
                return context.lookup(jndiName.replace("!", "#"));
            }
            return null;
        }

    } catch (Exception e) {
        logger.error("", e);
        return null;
    }
}

From source file:org.apache.servicemix.jms.AbstractJmsProcessor.java

protected void commonDoStartTasks(InitialContext ctx) throws Exception {
    channel = endpoint.getServiceUnit().getComponent().getComponentContext().getDeliveryChannel();
    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    destination = endpoint.getDestination();
    if (destination == null) {
        if (endpoint.getJndiDestinationName() != null) {
            destination = (Destination) ctx.lookup(endpoint.getJndiDestinationName());
        } else if (endpoint.getJmsProviderDestinationName() != null) {
            if (STYLE_QUEUE.equals(endpoint.getDestinationStyle())) {
                destination = session.createQueue(endpoint.getJmsProviderDestinationName());
            } else {
                destination = session.createTopic(endpoint.getJmsProviderDestinationName());
            }/* ww  w . ja va 2s .  c  om*/
        } else {
            throw new IllegalStateException("No destination provided");
        }
    }
    if (endpoint.getJndiReplyToName() != null) {
        replyToDestination = (Destination) ctx.lookup(endpoint.getJndiReplyToName());
    } else if (endpoint.getJmsProviderReplyToName() != null) {
        if (destination instanceof Queue) {
            replyToDestination = session.createQueue(endpoint.getJmsProviderReplyToName());
        } else {
            replyToDestination = session.createTopic(endpoint.getJmsProviderReplyToName());
        }
    }
}

From source file:it.openutils.mgnlaws.magnolia.init.ClasspathProviderImpl.java

/**
 * @see info.magnolia.repository.Provider#init(info.magnolia.repository.RepositoryMapping)
 *//*  www .jav  a2 s  . c o m*/
public void init(RepositoryMapping repositoryMapping) throws RepositoryNotInitializedException {
    checkXmlSettings();

    this.repositoryMapping = repositoryMapping;
    /* connect to repository */
    Map params = this.repositoryMapping.getParameters();
    String configFile = (String) params.get(CONFIG_FILENAME_KEY);
    if (!StringUtils.startsWith(configFile, ClasspathPropertiesInitializer.CLASSPATH_PREFIX)) {
        configFile = Path.getAbsoluteFileSystemPath(configFile);
    }
    String repositoryHome = (String) params.get(REPOSITORY_HOME_KEY);
    repositoryHome = getRepositoryHome(repositoryHome);

    // cleanup the path, to remove eventual ../.. and make it absolute
    try {
        File repoHomeFile = new File(repositoryHome);
        repositoryHome = repoHomeFile.getCanonicalPath();
    } catch (IOException e1) {
        // should never happen and it's not a problem at this point, just pass it to jackrabbit and see
    }

    String clusterid = SystemProperty.getProperty(MAGNOLIA_CLUSTERID_PROPERTY);
    if (StringUtils.isNotBlank(clusterid)) {
        System.setProperty(JACKRABBIT_CLUSTER_ID_PROPERTY, clusterid);
    }

    // get it back from system properties, if it has been set elsewhere
    clusterid = System.getProperty(JACKRABBIT_CLUSTER_ID_PROPERTY);

    log.info("Loading repository at {} (config file: {}) - cluster id: \"{}\"",
            new Object[] { repositoryHome, configFile, StringUtils.defaultString(clusterid, "<unset>") });

    bindName = (String) params.get(BIND_NAME_KEY);
    jndiEnv = new Hashtable<String, Object>();
    jndiEnv.put(Context.INITIAL_CONTEXT_FACTORY, params.get(CONTEXT_FACTORY_CLASS_KEY));
    jndiEnv.put(Context.PROVIDER_URL, params.get(PROVIDER_URL_KEY));

    try {
        InitialContext ctx = new InitialContext(jndiEnv);
        // first try to find the existing object if any
        try {
            this.repository = (Repository) ctx.lookup(bindName);
        } catch (NameNotFoundException ne) {
            log.debug("No JNDI bound Repository found with name {}, trying to initialize a new Repository",
                    bindName);
            ClasspathRegistryHelper.registerRepository(ctx, bindName, configFile, repositoryHome, true);
            this.repository = (Repository) ctx.lookup(bindName);
        }
        this.validateWorkspaces();
    } catch (NamingException e) {
        log.error("Unable to initialize repository: " + e.getMessage(), e);
        throw new RepositoryNotInitializedException(e);
    } catch (RepositoryException e) {
        log.error("Unable to initialize repository: " + e.getMessage(), e);
        throw new RepositoryNotInitializedException(e);
    } catch (TransformerFactoryConfigurationError e) {
        log.error("Unable to initialize repository: " + e.getMessage(), e);
        throw new RepositoryNotInitializedException(e);
    }
}

From source file:org.openbmp.db_rest.resources.Orr.java

/**
 * Initialize the class Sets the data source
 * //from  w  w  w.  j a va 2  s  .  c  o  m
 * @throws
 */
@PostConstruct
public void init() {
    InitialContext initctx = null;
    try {

        initctx = new InitialContext();
        mysql_ds = (DataSource) initctx.lookup("java:/comp/env/jdbc/MySQLDB");

    } catch (NamingException e) {
        System.err.println("ERROR: Cannot find resource configuration, check context.xml config");
        e.printStackTrace();
    }
}

From source file:org.tolven.analysis.bean.SnapshotBean.java

private CohortSnapshotLocal getCohortBean(String cohortType) {
    try {//  w  w  w . j a va2  s .c  o m
        String bean = cohortTypes.getProperty(cohortType);
        if (bean == null) {
            throw new RuntimeException("Could not locate bean for cohort code '" + cohortType);
        } else {
            InitialContext ctx = new InitialContext();
            return (CohortSnapshotLocal) ctx.lookup(bean);
        }
    } catch (NamingException ex) {
        throw new RuntimeException("Could not locate bean for cohort code '" + cohortType + "'", ex);
    }
}