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:gov.nih.nci.security.util.ConfigurationHelper.java

private DataSource getDataSourceFromDocument(Document hibernateConfigDoc) throws CSConfigurationException {
    Element hbnConfigElement = hibernateConfigDoc.getRootElement();
    DataSource ds = null;/*from   ww w.j  a va 2s  . c  o  m*/
    org.jdom.Element urlProperty = null, usernameProperty = null, passwordProperty = null,
            driverProperty = null;
    try {
        org.jdom.Element dataSourceProperty = (org.jdom.Element) XPath.selectSingleNode(hibernateConfigDoc,
                "/hibernate-configuration//session-factory//property[@name='connection.datasource']");
        if (dataSourceProperty != null && dataSourceProperty.getTextTrim() != null) {
            try {
                InitialContext initialContext = new InitialContext();
                ds = (DataSource) initialContext.lookup(dataSourceProperty.getTextTrim());
            } catch (NamingException ex) {
                ex.printStackTrace();
                throw new CSConfigurationException();
            }
        } else {
            urlProperty = (org.jdom.Element) XPath.selectSingleNode(hibernateConfigDoc,
                    "/hibernate-configuration//session-factory//property[@name='connection.url']");
            usernameProperty = (org.jdom.Element) XPath.selectSingleNode(hibernateConfigDoc,
                    "/hibernate-configuration//session-factory//property[@name='connection.username']");
            passwordProperty = (org.jdom.Element) XPath.selectSingleNode(hibernateConfigDoc,
                    "/hibernate-configuration//session-factory//property[@name='connection.password']");
            driverProperty = (org.jdom.Element) XPath.selectSingleNode(hibernateConfigDoc,
                    "/hibernate-configuration//session-factory//property[@name='connection.driver_class']");

            DriverManagerDataSource dataSource = new DriverManagerDataSource();
            dataSource.setDriverClassName(driverProperty.getTextTrim());
            dataSource.setUrl(urlProperty.getTextTrim());
            dataSource.setUsername(usernameProperty.getTextTrim());
            dataSource.setPassword(passwordProperty.getTextTrim());

            ds = dataSource;
        }
    } catch (JDOMException e) {
        e.printStackTrace();
        throw new CSConfigurationException();
    }
    return ds;
}

From source file:org.wildfly.camel.test.jms.TransactedJMSIntegrationTest.java

private void sendMessage(Connection connection, String jndiName, String message) throws Exception {
    InitialContext initialctx = new InitialContext();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination destination = (Destination) initialctx.lookup(jndiName);
    MessageProducer producer = session.createProducer(destination);
    TextMessage msg = session.createTextMessage(message);
    producer.send(msg);//  w ww.  ja v  a  2s  .  c  o m
    connection.start();
}

From source file:org.mc4j.ems.impl.jmx.connection.support.providers.JBossConnectionProvider.java

protected void doConnect() throws Exception {
    ClassLoader currentLoader = Thread.currentThread().getContextClassLoader();

    try {// www .  j  a  v a 2 s.  c  om
        System.setProperty("jmx.serial.form", "1.1");

        // TODO: Used to need this, but it appears to work without now (verify)
        // Change the context classloader as the JBoss version of the
        // MBeanServerFactory uses it to find their class

        ClassLoader childLoader = this.getClass().getClassLoader();
        Thread.currentThread().setContextClassLoader(childLoader);

        InitialContext context = getInitialContext();

        if (getConnectionSettings().getPrincipal() != null) {
            initJaasLoginContext();
        }

        Object rmiAdaptor = context.lookup(this.connectionSettings.getJndiName());

        // GH: Works around a real strange "LinkageError: Duplicate class found"
        // by loading these classes in the main connection classloader
        //Class foo = RMINotificationListener.class;
        //foo = RMINotificationListenerMBean.class;

        // TODO GH!: I think this fixes notifications, but breaks compatibility with at least 3.0.8
        //RMIConnectorImpl connector = new RMIConnectorImpl(rmiAdaptor);

        if (this.proxy != null) {
            // This is a reconnect
            log.debug("Reconnecting to remote JBoss MBeanServer...");
            this.proxy.setRemoteServer(rmiAdaptor);
        } else {
            this.proxy = new GenericMBeanServerProxy(rmiAdaptor);
            this.proxy.setProvider(this);
            setStatsProxy(proxy);
            this.mbeanServer = proxy.buildServerProxy();
        }
        //this.mgmt = retrieveMEJB();
    } finally {
        // Set the context classloader back to what it was.
        Thread.currentThread().setContextClassLoader(currentLoader);
    }
}

From source file:org.quartz.impl.jdbcjobstore.JTANonClusteredSemaphore.java

/**
 * Helper method to get the current <code>{@link javax.transaction.Transaction}</code>
 * from the <code>{@link javax.transaction.TransactionManager}</code> in JNDI.
 * //from  w  w  w. j a  va2s .  com
 * @return The current <code>{@link javax.transaction.Transaction}</code>, null if
 * not currently in a transaction.
 */
protected Transaction getTransaction() throws LockException {
    InitialContext ic = null;
    try {
        ic = new InitialContext();
        TransactionManager tm = (TransactionManager) ic.lookup(transactionManagerJNDIName);

        return tm.getTransaction();
    } catch (SystemException e) {
        throw new LockException("Failed to get Transaction from TransactionManager", e);
    } catch (NamingException e) {
        throw new LockException(
                "Failed to find TransactionManager in JNDI under name: " + transactionManagerJNDIName, e);
    } finally {
        if (ic != null) {
            try {
                ic.close();
            } catch (NamingException ignored) {
            }
        }
    }
}

From source file:org.wso2.mb.integration.common.clients.operations.queue.QueueMessageSender.java

public QueueMessageSender(String connectionString, String hostName, String port, String userName,
        String password, String queueName, AtomicInteger messageCounter, int numOfMessagesToSend,
        int delayBetweenMessages, String filePath, int printNumberOfMessagesPer, boolean isToPrintEachMessage,
        Long jmsExpiration) {/*from  w ww. j a va2  s.c  o  m*/

    this.hostName = hostName;
    this.port = port;
    this.connectionString = connectionString;
    this.messageCounter = messageCounter;
    this.queueName = queueName;
    this.numOfMessagesToSend = numOfMessagesToSend;
    this.delay = delayBetweenMessages;
    this.filePath = filePath;
    if (filePath != null && !filePath.equals("")) {
        readFromFile = true;
    }
    this.printNumberOfMessagesPer = printNumberOfMessagesPer;
    this.isToPrintEachMessage = isToPrintEachMessage;
    this.jmsExpiration = jmsExpiration;

    Properties properties = new Properties();
    properties.put(Context.INITIAL_CONTEXT_FACTORY, QPID_ICF);
    properties.put(CF_NAME_PREFIX + CF_NAME, getTCPConnectionURL(userName, password));
    properties.put("queue." + queueName, queueName);

    log.info("getTCPConnectionURL(userName,password) = " + getTCPConnectionURL(userName, password));

    try {
        InitialContext ctx = new InitialContext(properties);
        // Lookup connection factory
        QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.lookup(CF_NAME);
        queueConnection = connFactory.createQueueConnection();
        queueConnection.start();
        queueSession = queueConnection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);

        // Send message
        Queue queue = (Queue) ctx.lookup(queueName);
        queueSender = queueSession.createSender(queue);

    } catch (NamingException e) {
        log.error("Error while looking up for queue", e);
    } catch (JMSException e) {
        log.error("Error while initializing queue connection", e);
    }

}

From source file:org.efaps.db.Context.java

/**
 * Resets the context to current defined values in the Javax naming
 * environment.//from   ww w  .ja v a 2  s .  c om
 *
 * @throws StartupException if context could not be reseted to new values
 * @see #DBTYPE
 * @see #DATASOURCE
 * @see #TRANSMANAG
 * @see #TRANSMANAGTIMEOUT
 */
public static void reset() throws StartupException {
    try {
        final InitialContext initCtx = new InitialContext();
        final javax.naming.Context envCtx = (javax.naming.Context) initCtx.lookup("java:comp/env");
        Context.DBTYPE = (AbstractDatabase<?>) envCtx.lookup(INamingBinds.RESOURCE_DBTYPE);
        Context.DATASOURCE = (DataSource) envCtx.lookup(INamingBinds.RESOURCE_DATASOURCE);
        Context.TRANSMANAG = (TransactionManager) envCtx.lookup(INamingBinds.RESOURCE_TRANSMANAG);
        try {
            Context.TRANSMANAGTIMEOUT = 0;
            final Map<?, ?> props = (Map<?, ?>) envCtx.lookup(INamingBinds.RESOURCE_CONFIGPROPERTIES);
            if (props != null) {
                final String transactionTimeoutString = (String) props.get(IeFapsProperties.TRANSACTIONTIMEOUT);
                if (transactionTimeoutString != null) {
                    Context.TRANSMANAGTIMEOUT = Integer.parseInt(transactionTimeoutString);
                }
            }
        } catch (final NamingException e) {
            // this is actual no error, so nothing is presented
            Context.TRANSMANAGTIMEOUT = 0;
        }
    } catch (final NamingException e) {
        throw new StartupException("eFaps context could not be initialized", e);
    }
}

From source file:org.sofun.core.security.oauth.OAuthSofunProvider.java

/**
 * Returns the OAuth token storage service.
 * // w  w  w.  j  av a 2s  .c om
 * @return a {@link OAuthJPAStorageImpl} instance.
 * @throws OAuthException
 */
private OAuthJPAStorage getStorage() throws OAuthException {
    if (storage == null) {
        InitialContext ctx;
        try {
            ctx = new InitialContext();
            return (OAuthJPAStorage) ctx.lookup("sofun/OAUthJPAStorageImpl/local");
        } catch (NamingException e) {
            throw new OAuthException(500, e.getMessage());
        }
    }
    return storage;
}

From source file:com.boylesoftware.web.impl.auth.SessionlessAuthenticationService.java

/**
 * Create new authenticator./*from w ww. j  a  va 2 s.  c  om*/
 *
 * @param userRecordHandler User record handler.
 * @param userRecordsCache Authenticated user records cache.
 *
 * @throws UnavailableException If an error happens creating the service.
 */
public SessionlessAuthenticationService(final UserRecordHandler<T> userRecordHandler,
        final UserRecordsCache<T> userRecordsCache) throws UnavailableException {

    // store the references
    this.userRecordHandler = userRecordHandler;
    this.userRecordsCache = userRecordsCache;

    // get configured secret key from the JNDI
    String secretKeyStr;
    try {
        final InitialContext jndi = new InitialContext();
        try {
            secretKeyStr = (String) jndi.lookup("java:comp/env/secretKey");
        } finally {
            jndi.close();
        }
    } catch (final NamingException e) {
        throw new UnavailableException("Error looking up secret key in the JNDI: " + e);
    }
    if (!secretKeyStr.matches("[0-9A-Fa-f]{32}"))
        throw new UnavailableException("Configured secret key is" + " invalid. The key must be a 16 bytes value"
                + " encoded as a hexadecimal string.");
    final Key secretKey = new SecretKeySpec(Hex.decode(secretKeyStr), CipherToolbox.ALGORITHM);

    // create the cipher pool
    this.cipherPool = new FastPool<>(new PoolableObjectFactory<CipherToolbox>() {

        @Override
        public CipherToolbox makeNew(final FastPool<CipherToolbox> pool, final int pooledObjectId) {

            return new CipherToolbox(pool, pooledObjectId, secretKey);
        }
    }, "AuthenticatorCiphersPool");
}

From source file:org.wso2.mb.integration.common.clients.operations.topic.TopicMessageReceiver.java

public TopicMessageReceiver(String connectionString, String hostName, String port, String userName,
        String password, String topicName, boolean isDurable, String subscriptionID, int ackMode,
        boolean useMessageListener, AtomicInteger messageCounter, int delayBetweenMessages,
        int printNumberOfMessagesPer, boolean isToPrintEachMessage, String fileToWriteReceivedMessages,
        int stopAfter, int unsubscrbeAfter, int ackAfterEach, int commitAfterEach, int rollbackAfterEach) {

    this.hostName = hostName;
    this.port = port;
    this.connectionString = connectionString;
    this.useMessageListener = useMessageListener;
    this.delayBetweenMessages = delayBetweenMessages;
    this.messageCounter = messageCounter;
    this.topicName = topicName;
    this.printNumberOfMessagesPer = printNumberOfMessagesPer;
    this.isToPrintEachMessage = isToPrintEachMessage;
    this.fileToWriteReceivedMessages = fileToWriteReceivedMessages;
    this.stopAfter = stopAfter;
    this.unSubscribeAfter = unsubscrbeAfter;
    this.ackAfterEach = ackAfterEach;
    this.commitAfterEach = commitAfterEach;
    this.rollbackAfterEach = rollbackAfterEach;

    this.subscriptionId = subscriptionID;

    Properties properties = new Properties();
    properties.put(Context.INITIAL_CONTEXT_FACTORY, QPID_ICF);
    properties.put(CF_NAME_PREFIX + CF_NAME, getTCPConnectionURL(userName, password));
    properties.put("topic." + topicName, topicName);

    log.info("getTCPConnectionURL(userName,password) = " + getTCPConnectionURL(userName, password));

    try {//from  w w w.j a va  2 s.c om
        InitialContext ctx = new InitialContext(properties);
        // Lookup connection factory
        TopicConnectionFactory connFactory = (TopicConnectionFactory) ctx.lookup(CF_NAME);
        topicConnection = connFactory.createTopicConnection();
        topicConnection.setClientID(subscriptionId);
        topicConnection.start();
        if (ackMode == TopicSession.SESSION_TRANSACTED) {
            topicSession = topicConnection.createTopicSession(true, QueueSession.SESSION_TRANSACTED);
        } else {
            topicSession = topicConnection.createTopicSession(false, QueueSession.AUTO_ACKNOWLEDGE);
        }

        // Send message
        Topic topic = (Topic) ctx.lookup(topicName);
        log.info("Starting listening on topic: " + topic);

        if (isDurable) {
            topicSubscriber = topicSession.createDurableSubscriber(topic, subscriptionId);
        } else {
            topicSubscriber = topicSession.createSubscriber(topic);
        }

    } catch (NamingException e) {
        log.error("Error while looking up for topic", e);
    } catch (JMSException e) {
        log.error("Error while initializing topic connection", e);
    }

}

From source file:io.apiman.gateway.engine.policies.BasicAuthLDAPTest.java

private DirContext createContext() throws NamingException {
    // Create a environment container
    Hashtable<Object, Object> env = new Hashtable<>();

    String url = "ldap://" + LDAP_SERVER + ":" + ldapServer.getPort();

    // Create a new context pointing to the partition
    env.put(Context.PROVIDER_URL, url);
    env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
    env.put(Context.SECURITY_CREDENTIALS, "secret");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    // Let's open a connection on this partition
    InitialContext initialContext = new InitialContext(env);

    // We should be able to read it
    DirContext appRoot = (DirContext) initialContext.lookup("");
    Assert.assertNotNull(appRoot);//  w  ww  .  j a va 2s  .co m

    return appRoot;
}