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.nimbustools.ctxbroker.service.ContextBrokerHomeImpl.java

public static BootstrapFactory discoverBootstrapFactory() throws Exception {

    InitialContext ctx = null;
    try {//w  w  w  .j av a  2 s .co m
        ctx = new InitialContext();

        final BootstrapFactory factory = (BootstrapFactory) ctx.lookup(CONTEXTUALIZATION_BOOTSTRAP_FACTORY);

        if (factory == null) {
            throw new Exception("null from JNDI for BootstrapFactory (?)");
        }

        return factory;

    } finally {
        if (ctx != null) {
            ctx.close();
        }
    }
}

From source file:com.flexive.shared.EJBLookup.java

/**
 * Get a reference of the current EJB session context.
 *
 * @return the EJB session context/*from w  ww.j a  v a2 s .c om*/
 */
public static SessionContext getSessionContext() {
    try {
        final InitialContext ctx = new InitialContext();
        return (SessionContext) ctx.lookup("java:comp/EJBContext");
    } catch (NamingException e) {
        throw new FxLookupException("Failed to lookup session context: " + e.getMessage(), e)
                .asRuntimeException();
    }
}

From source file:com.flexive.shared.EJBLookup.java

/**
 * Get a reference of the transaction manager
 *
 * @return TransactionManager/*w w w.  j  a  v a 2s. c o m*/
 */
public static TransactionManager getTransactionManager() {
    for (String path : TM_JNDI_PATHS) {
        try {
            InitialContext ctx = new InitialContext();
            return (TransactionManager) ctx.lookup(path);
        } catch (NamingException e) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("No transaction manager found under JNDI path " + path);
            }
        }
    }
    throw new FxLookupException("Failed to lookup transaction manager").asRuntimeException();
}

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
 *///w  w  w  .j av a2 s. co  m
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:com.webbfontaine.valuewebb.model.util.Utils.java

public static EntityManagerFactory getEntityManagerFactory() {
    InitialContext context = getInitialContext();
    try {/*from   w w  w  . j  a v  a 2 s. c om*/
        return (EntityManagerFactory) context.lookup("java:/ValueWebbEntityManagerFactory");
    } catch (NamingException e) {
        throw Throwables.propagate(e);
    }
}

From source file:org.eclipse.ecr.core.storage.sql.reload.RepositoryReloader.java

public static List<Repository> getRepositories() throws NamingException {
    List<Repository> list = new LinkedList<Repository>();
    InitialContext context = new InitialContext();
    // we search both JBoss-like and Glassfish-like prefixes
    // @see NXCore#getRepository
    for (String prefix : new String[] { "java:NXRepository", "NXRepository" }) {
        NamingEnumeration<Binding> bindings;
        try {/*from ww w.  j  a  v  a  2  s  .  c  o  m*/
            bindings = context.listBindings(prefix);
        } catch (NamingException e) {
            continue;
        }
        for (NamingEnumeration<Binding> e = bindings; e.hasMore();) {
            Binding binding = e.nextElement();
            String name = binding.getName();
            if (binding.isRelative()) {
                name = prefix + '/' + name;
            }
            Object object = context.lookup(name);
            if (!(object instanceof Repository)) {
                continue;
            }
            list.add((Repository) object);
        }
    }
    return list;
}

From source file:com.webbfontaine.valuewebb.model.util.Utils.java

public static Connection getSQLConnection(String name) {
    InitialContext initContext;
    try {/*from   w  w w .  jav  a 2  s.co  m*/
        initContext = new InitialContext();
        DataSource dataSource = (DataSource) initContext.lookup(name);
        return dataSource.getConnection();
    } catch (NamingException e) {
        LOGGER.error("", e);
    } catch (SQLException e) {
        LOGGER.error("", e);
    }
    return null;
}

From source file:org.apache.stratos.adc.topology.mgt.subscriber.TopologySubscriber.java

public static void subscribe(String topicName) {
    Properties initialContextProperties = new Properties();
    TopicSubscriber topicSubscriber = null;
    TopicSession topicSession = null;/* ww  w  .  j av a  2 s. c  o  m*/
    TopicConnection topicConnection = null;
    InitialContext initialContext = null;

    initialContextProperties.put("java.naming.factory.initial",
            "org.wso2.andes.jndi.PropertiesFileInitialContextFactory");

    String mbServerIp = System.getProperty(TopologyConstants.MB_SERVER_IP) == null
            ? TopologyConstants.DEFAULT_MB_SERVER_IP
            : System.getProperty(TopologyConstants.MB_SERVER_IP);

    String connectionString = "amqp://admin:admin@clientID/carbon?brokerlist='tcp://" + mbServerIp
            + "'&reconnect='true'";
    initialContextProperties.put("connectionfactory.qpidConnectionfactory", connectionString);

    try {
        initialContext = new InitialContext(initialContextProperties);
        TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) initialContext
                .lookup("qpidConnectionfactory");
        topicConnection = topicConnectionFactory.createTopicConnection();
        topicConnection.start();
        topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

        Topic topic = topicSession.createTopic(topicName);
        topicSubscriber = topicSession.createSubscriber(topic);

        topicSubscriber.setMessageListener(new TopologyListener());

    } catch (Exception e) {
        log.error(e.getMessage(), e);

        try {
            if (topicSubscriber != null) {
                topicSubscriber.close();
            }

            if (topicSession != null) {
                topicSession.close();
            }

            if (topicConnection != null) {
                topicConnection.close();
            }
        } catch (JMSException e1) {
            // ignore
        }

    } finally {
        // start the health checker
        Thread healthChecker = new Thread(new TopicHealthChecker(topicName, topicSubscriber));
        healthChecker.start();
    }
}

From source file:org.nuxeo.ecm.core.storage.sql.reload.RepositoryReloader.java

public static List<Repository> getRepositories() throws NamingException {
    List<Repository> list = new LinkedList<Repository>();
    InitialContext context = new InitialContext();
    // we search both JBoss-like and Glassfish-like prefixes
    // @see NXCore#getRepository
    for (String prefix : new String[] { "java:NXRepository", "NXRepository" }) {
        NamingEnumeration<Binding> bindings;
        try {//from  w  w  w.jav  a 2  s .c o  m
            bindings = context.listBindings(prefix);
        } catch (NamingException e) {
            continue;
        }
        NamingEnumeration<Binding> e = null;
        try {
            for (e = bindings; e.hasMore();) {
                Binding binding = e.nextElement();
                String name = binding.getName();
                if (binding.isRelative()) {
                    name = prefix + '/' + name;
                }
                Object object = context.lookup(name);
                if (!(object instanceof Repository)) {
                    continue;
                }
                list.add((Repository) object);
            }
        } finally {
            if (e != null) {
                e.close();
            }
        }
    }
    return list;
}

From source file:org.apache.stratos.lb.endpoint.subscriber.TopologySubscriber.java

public static void subscribe(String topicName) {
    Properties initialContextProperties = new Properties();
    TopicSubscriber topicSubscriber = null;
    TopicSession topicSession = null;//  ww w.  jav  a 2s. c o m
    TopicConnection topicConnection = null;
    InitialContext initialContext = null;

    initialContextProperties.put("java.naming.factory.initial",
            "org.wso2.andes.jndi.PropertiesFileInitialContextFactory");

    String mbServerUrl = null;
    if (ConfigHolder.getInstance().getLbConfig() != null) {
        mbServerUrl = ConfigHolder.getInstance().getLbConfig().getLoadBalancerConfig().getMbServerUrl();
    }
    String connectionString = "amqp://admin:admin@clientID/carbon?brokerlist='tcp://"
            + (mbServerUrl == null ? TopologyConstants.DEFAULT_MB_SERVER_URL : mbServerUrl)
            + "'&reconnect='true'";
    initialContextProperties.put("connectionfactory.qpidConnectionfactory", connectionString);

    try {
        initialContext = new InitialContext(initialContextProperties);
        TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) initialContext
                .lookup("qpidConnectionfactory");
        topicConnection = topicConnectionFactory.createTopicConnection();
        topicConnection.start();
        topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

        Topic topic = topicSession.createTopic(topicName);
        topicSubscriber = topicSession.createSubscriber(topic);

        topicSubscriber.setMessageListener(new TopologyListener());

    } catch (Exception e) {
        log.error(e.getMessage(), e);

        try {
            if (topicSubscriber != null) {
                topicSubscriber.close();
            }

            if (topicSession != null) {
                topicSession.close();
            }

            if (topicConnection != null) {
                topicConnection.close();
            }
        } catch (JMSException e1) {
            // ignore
        }

    } finally {
        // start the health checker
        Thread healthChecker = new Thread(new TopicHealthChecker(topicName, topicSubscriber));
        healthChecker.start();
    }
}