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:ar.com.zauber.commons.spring.configurers.JndiInitialContextHelper.java

/** dado paths jndi retorna archivos de propiedades */
public static Resource[] getJndiLocations(final String[] filePathJndiNames) {

    final ResourceLoader resourceLoader = new DefaultResourceLoader();

    try {/*from  w w  w . j  a v  a2 s.  c o m*/
        final InitialContext initCtx = new InitialContext();
        final Resource[] locations = new Resource[filePathJndiNames.length];
        boolean found = false;

        try {
            final Context envCtx = (Context) initCtx.lookup("java:comp/env");
            for (int i = 0; i < filePathJndiNames.length; i++) {
                locations[i] = resourceLoader.getResource((String) envCtx.lookup(filePathJndiNames[i]));
            }
            found = true;
        } catch (final NamingException e) {
            LOGGER.warn("Error JNDI looking up 'java:comp/env':" + e.getExplanation());
            // void
        }

        if (!found) {
            // Para Jetty 7 Server
            try {
                for (int i = 0; i < filePathJndiNames.length; i++) {
                    locations[i] = resourceLoader.getResource((String) initCtx.lookup(filePathJndiNames[i]));
                }
            } catch (final NamingException e) {
                LOGGER.warn("Hubo un error en el lookup de JNDI. Se usaran " + "properties del classpath: "
                        + e.getExplanation());
                return null;
            }
        }

        return locations;
    } catch (final NamingException e) {
        LOGGER.warn("Hubo un error en el lookup de JNDI. Se usaran " + "properties del classpath: "
                + e.getExplanation());
        return null;
    }
}

From source file:org.pepstock.jem.annotations.SetFields.java

private static void setFieldByAnnotation(InitialContext ic, Object object, String name, Field field)
        throws NamingException, IllegalAccessException {
    // gets object via JNDI
    Object objectJNDI = (Object) ic.lookup(name);
    // if is static or it's a java main class (object = null) sets statically
    if (Modifier.isStatic(field.getModifiers()) || object == null) {
        FieldUtils.writeStaticField(field, objectJNDI, true);
    } else {/*from  www  .  ja va 2  s  .  c  om*/
        // sets field
        FieldUtils.writeField(field, object, objectJNDI, true);
    }
}

From source file:org.wso2.carbon.custom.connector.EJBUtil.java

/**
 * @param messageContext messageContext/*from   www.  j  a v  a  2 s . c  o m*/
 * @param jndiName       jndi name
 * @return ejb remote object
 */
public static Object getEJBObject(MessageContext messageContext, String jndiName) {
    Object ejbObject = null;
    try {
        InitialContext context = new InitialContext(
                (Properties) messageContext.getProperty(EJBConstants.JNDI_PROPERTIES));
        Object obj = context.lookup(getParameter(messageContext, jndiName).toString());
        EJBHome ejbHome = (EJBHome) PortableRemoteObject.narrow(obj, EJBHome.class);
        Method method = ejbHome.getClass().getDeclaredMethod(EJBConstants.CREATE);
        if (method != null) {
            ejbObject = method.invoke(ejbHome);
        } else
            handleException("ejb home is missing ");
    } catch (IllegalAccessException e) {
        handleException("Failed to get ejb Object because of IllegalAccessException ", e);
    } catch (InvocationTargetException e) {
        handleException("Failed to get ejb Object because of InvocationTargetException ", e);
    } catch (NoSuchMethodException e) {
        handleException("Failed lookup because of create method not exist " + e.getMessage());
    } catch (NamingException e) {
        handleException("Failed lookup because of NamingException ", e);
    }
    return ejbObject;
}

From source file:org.jbpm.db.JbpmSessionFactory.java

/**
 * a singleton is kept in JbpmSessionFactory as a convenient central location.
 *//* w w w  .  j  a v  a2  s . co m*/
public static JbpmSessionFactory getInstance() {
    if (instance == null) {

        // if there is a JNDI name configured
        if (jndiName != null) {
            try {
                // fetch the JbpmSessionFactory from JNDI
                log.debug("fetching JbpmSessionFactory from '" + jndiName + "'");
                InitialContext initialContext = new InitialContext();
                Object o = initialContext.lookup(jndiName);
                instance = (JbpmSessionFactory) PortableRemoteObject.narrow(o, JbpmSessionFactory.class);
            } catch (Exception e) {
                throw new JbpmException("couldn't fetch JbpmSessionFactory from jndi '" + jndiName + "'");
            }

        } else { // else there is no JNDI name configured
            // create a new default instance.
            log.debug("building singleton JbpmSessionFactory");
            instance = buildJbpmSessionFactory();
        }
    }
    return instance;
}

From source file:com.glaf.core.jdbc.DBConnectionFactory.java

public static boolean checkConnection(java.util.Properties props) {
    Connection connection = null;
    try {//w  w  w  . jav a  2s.  co  m
        if (StringUtils.isNotEmpty(props.getProperty(DBConfiguration.JDBC_DATASOURCE))) {
            InitialContext ctx = new InitialContext();
            DataSource ds = (DataSource) ctx.lookup(props.getProperty(DBConfiguration.JDBC_DATASOURCE));
            connection = ds.getConnection();
        } else {
            ConnectionProvider provider = ConnectionProviderFactory.createProvider(props);
            if (provider != null) {
                connection = provider.getConnection();
            }
        }
        if (connection != null) {
            return true;
        }
    } catch (Exception ex) {
        logger.error(ex);
        ex.printStackTrace();
    } finally {
        JdbcUtils.close(connection);
    }
    return false;
}

From source file:org.apache.stratos.status.monitor.agent.clients.service.MessageBrokerServiceClient.java

private static void executeService() throws SQLException {
    int serviceID = MySQLConnectionInitializer.getServiceID(StatusMonitorConstants.MESSAGING);
    AuthConfigBean authConfigBean = StatusMonitorConfigurationBuilder.getAuthConfigBean();

    String userName = authConfigBean.getUserName();
    tcpUserName = userName.replace('@', '!');

    //check whether login success
    if (ServiceLoginClient.loginChecker(StatusMonitorConstants.MESSAGING_HOST, serviceID)) {

        Properties properties = new Properties();
        properties.put(Context.INITIAL_CONTEXT_FACTORY, StatusMonitorAgentConstants.QPID_ICF);
        properties.put(StatusMonitorAgentConstants.CF_NAME_PREFIX + StatusMonitorAgentConstants.CF_NAME,
                getTCPConnectionURL(tcpUserName, authConfigBean.getPassword()));

        if (log.isDebugEnabled()) {
            log.debug("getTCPConnectionURL(username,password) = "
                    + getTCPConnectionURL(tcpUserName, authConfigBean.getPassword()));
        }/*from w  w w.j  a v a  2  s.c  om*/
        try {
            InitialContext ctx = new InitialContext(properties);
            // Lookup connection factory
            QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx
                    .lookup(StatusMonitorAgentConstants.CF_NAME);
            QueueConnection queueConnection = connFactory.createQueueConnection();
            queueConnection.start();
            QueueSession queueSession = queueConnection.createQueueSession(false,
                    QueueSession.AUTO_ACKNOWLEDGE);

            // Send message
            Queue queue = queueSession.createQueue(
                    StatusMonitorAgentConstants.QUEUE_NAME_MB + ";{create:always, node:{durable: True}}");

            // create the message to send
            TextMessage textMessage = queueSession.createTextMessage("Test Message Hello");
            javax.jms.QueueSender queueSender = queueSession.createSender(queue);
            queueSender.setTimeToLive(100000000);

            QueueReceiver queueReceiver = queueSession.createReceiver(queue);
            queueSender.send(textMessage);

            TextMessage message = (TextMessage) queueReceiver.receiveNoWait();

            if (message.getText().equals("Test Message Hello")) {
                MySQLConnector.insertStats(serviceID, true);
                MySQLConnector.insertState(serviceID, true, "");
            } else {
                MySQLConnector.insertStats(serviceID, false);
                MySQLConnector.insertState(serviceID, false, "Send and retrieve messages failed");
            }
            queueSender.close();
            queueSession.close();
            queueConnection.close();

        } catch (JMSException e) {
            MySQLConnector.insertStats(serviceID, false);
            MySQLConnector.insertState(serviceID, false, e.getMessage());
            String msg = "Exception in executing the client - "
                    + "Status Monitor Agent for MessageBrokerServiceClient";
            log.warn(msg, e);

        } catch (NamingException e) {
            MySQLConnector.insertStats(serviceID, false);
            MySQLConnector.insertState(serviceID, false, e.getMessage());
            String msg = "Naming exception in executing the client - "
                    + "Status Monitor agent for MessageBrokerServiceClient";
            log.warn(msg, e);
        }
    }
}

From source file:org.pepstock.jem.jppf.JPPFUtil.java

/**
 * Try to load JPPF configuration from data description
 * @param ic JNDI initial context to get input stream
 * @return JPPF properties/*from  www  .  j  av  a 2s.c  o m*/
 */
public static TypedProperties loadTypedPropertiesFromDataDescription(InitialContext ic) {
    // try to load configuration from data description
    // if data description is allocated
    TypedProperties propsFromDataDescritpion = new TypedProperties();
    // gets input stream
    try {
        Object ddconfig = (Object) ic.lookup(Keys.JPPF_CONFIG_DATADESCRIPTION);
        InputStream configInputStream = (InputStream) ddconfig;
        // loads properties
        propsFromDataDescritpion.load(configInputStream);

    } catch (NamingException e) {
        // ignore
        LogAppl.getInstance().ignore(e.getMessage(), e);
    } catch (IOException e) {
        // ignore
        LogAppl.getInstance().ignore(e.getMessage(), e);
    }
    return propsFromDataDescritpion;
}

From source file:com.glweb.infrastructure.persistence.hibernate.HibernateUtil.java

/**
 * Returns the <code>SessionFactory</code> retrieved via JNDI.
 *///  w  w w.j a va 2  s . c  o  m
public static SessionFactory retrieveJndiSessionFactory() throws GLWebPersistenceException {

    if (null == getJndiSessionFactory()) {
        try {
            new Configuration().configure();
            InitialContext _ctx = NamingUtilities.getInitialContext();
            setJndiSessionFactory((SessionFactory) _ctx.lookup(JNDI_SESSION_FACTORY));
        } catch (HibernateException he) {
            throw new GLWebPersistenceException(he);
        } catch (NamingException ne) {
            throw new GLWebPersistenceException(ne);
        }
    }

    return getJndiSessionFactory();
}

From source file:com.glaf.core.jdbc.DBConnectionFactory.java

public static Connection getConnection(java.util.Properties props) {
    Connection connection = null;
    try {// w  ww .  j  ava  2s. c  om
        if (props != null) {
            if (StringUtils.isNotEmpty(props.getProperty(DBConfiguration.JDBC_DATASOURCE))) {
                InitialContext ctx = new InitialContext();
                DataSource ds = (DataSource) ctx.lookup(props.getProperty(DBConfiguration.JDBC_DATASOURCE));
                connection = ds.getConnection();
            } else {
                String systemName = props.getProperty(DBConfiguration.JDBC_NAME);
                if (StringUtils.isNotEmpty(systemName)) {
                    ConnectionProvider provider = ConnectionProviderFactory.createProvider(systemName);
                    if (provider != null) {
                        connection = provider.getConnection();
                    }
                } else {
                    ConnectionProvider provider = ConnectionProviderFactory.createProvider(props);
                    if (provider != null) {
                        connection = provider.getConnection();
                    }
                }
            }
        }
        if (connection != null) {
            ConnectionThreadHolder.addConnection(connection);
        }
        return connection;
    } catch (Exception ex) {
        logger.error(ex);
        ex.printStackTrace();
        throw new RuntimeException(ex);
    }
}

From source file:com.glaf.core.jdbc.DBConnectionFactory.java

public static Connection getConnection(String systemName) {
    if (systemName == null) {
        throw new RuntimeException("systemName is required.");
    }//from   ww  w . j  av  a 2s . c  om
    logger.debug("systemName:" + systemName);
    Connection connection = null;
    try {
        Properties props = DBConfiguration.getDataSourcePropertiesByName(systemName);
        if (props != null) {
            if (StringUtils.isNotEmpty(props.getProperty(DBConfiguration.JDBC_DATASOURCE))) {
                InitialContext ctx = new InitialContext();
                DataSource ds = (DataSource) ctx.lookup(props.getProperty(DBConfiguration.JDBC_DATASOURCE));
                connection = ds.getConnection();
            } else {
                ConnectionProvider provider = ConnectionProviderFactory.createProvider(systemName);
                if (provider != null) {
                    connection = provider.getConnection();
                }
            }
        } else {
            // DataSource ds = ContextFactory.getBean("dataSource");
            // connection = ds.getConnection();
        }
        if (connection != null) {
            ConnectionThreadHolder.addConnection(connection);
        }
        return connection;
    } catch (Exception ex) {
        logger.error(ex);
        ex.printStackTrace();
        throw new RuntimeException(ex);
    }
}