Example usage for javax.naming InitialContext InitialContext

List of usage examples for javax.naming InitialContext InitialContext

Introduction

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

Prototype

public InitialContext() throws NamingException 

Source Link

Document

Constructs an initial context.

Usage

From source file:com.web.server.XMLDeploymentScanner.java

public XMLDeploymentScanner(String scanDirectory, String userLibDir) {
    super(scanDirectory);
    this.userLibDir = userLibDir;
    File userLibJars = new File(userLibDir);
    CopyOnWriteArrayList<String> jarList = new CopyOnWriteArrayList();
    getUsersJars(userLibJars, jarList);/*from ww w .  j  ava2s  .co  m*/
    URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    userLibJarLoader = new WebClassLoader(loader.getURLs());
    for (String jarFilePath : jarList) {
        try {
            userLibJarLoader.addURL(new URL("file:/" + jarFilePath.replace("\\", "/")));
        } catch (MalformedURLException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }
    }

    DigesterLoader xmlDigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() {

        protected void loadRules() {
            // TODO Auto-generated method stub
            try {
                loadXMLRules(new InputSource(new FileInputStream("./config/datasource-rules.xml")));
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    });
    xmlDigester = xmlDigesterLoader.newDigester();
    try {
        ic = new InitialContext();
        ic.createSubcontext("java:");
    } catch (NamingException e1) {
        // TODO Auto-generated catch block
    }

    File[] xmlFiles = new File(scanDirectory).listFiles();

    if (xmlFiles != null && xmlFiles.length > 0) {
        for (File xmlFile : xmlFiles) {
            if (xmlFile.getName().toLowerCase().endsWith("datasource.xml")) {
                installDataSource(xmlFile);
            }
        }
    }

    // TODO Auto-generated constructor stub
}

From source file:com.funambol.server.db.DataSourceFactoryTest.java

/**
 * Test of getObjectInstance method, of class DataSourceFactory.
 *///from w  w  w. j  a v a2s . co m
public void testGetObjectInstance_WrongClass() throws Exception {
    DataSourceFactory dataSourceFactory = new DataSourceFactory();
    InitialContext context = new InitialContext();
    Hashtable environment = new Hashtable();

    Name name = new CompositeName("fnblds");

    //
    // not javax.sql.DataSource --> exception
    //
    Reference ref = new Reference("javax.sql.DataSourceeeee");
    Object result = null;
    boolean exception = false;

    try {
        result = dataSourceFactory.getObjectInstance(ref, name, context, environment);
    } catch (NamingException e) {
        exception = true;
    }
    assertTrue(exception);
}

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

public static boolean checkConnection(String systemName) {
    if (systemName == null) {
        throw new RuntimeException("systemName is required.");
    }/*  w  ww . j  a  v a  2s .c  o m*/
    logger.debug("systemName:" + systemName);
    Connection connection = null;
    try {
        Properties props = DBConfiguration.getDataSourcePropertiesByName(systemName);
        logger.debug("props:" + props);
        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);
        }
        if (connection != null) {
            return true;
        }

    } catch (Exception ex) {
        logger.error(ex);
        ex.printStackTrace();
    } finally {
        JdbcUtils.close(connection);
    }
    return false;
}

From source file:net.kamhon.ieagle.dao.DynamicDataSource.java

public void afterPropertiesSet() throws Exception {
    if (StringUtils.isNotBlank(jndiName)) {

        Context initContext = null;
        try {/*www . j  a va 2s. com*/
            initContext = new InitialContext();
            dataSource = (DataSource) initContext.lookup(jndiName);
            log.info("Using DataSource " + jndiName);
        } catch (Exception e1) {
            try {
                dataSource = (DataSource) initContext.lookup("java:/comp/env/" + jndiName);
                log.info("Using DataSource " + "java:/comp/env/" + jndiName);
            } catch (Exception e2) {
                try {
                    if (jndiName.startsWith("comp/env/")) {
                        jndiName = jndiName.substring("comp/env/".length());
                        System.out.println("\n\n" + jndiName + "\n\n");
                        dataSource = (DataSource) initContext.lookup(jndiName);

                        log.info("Using DataSource " + jndiName);
                    }
                } catch (Exception e3) {
                    initBasicDataSource();
                }
            }
        }
    }

    if (dataSource == null) {
        initBasicDataSource();
    }
}

From source file:com.mdmserver.managers.ControllerFacade.java

public void lockPhone(int accountId) throws IOException {
    Account account = databaseManager.getAccountByAccountId(accountId);
    Context ctx;/*from  w w w .j av  a 2  s  .c  om*/
    try {
        ctx = new InitialContext();
        ConnectionFactory connectionFactory = (ConnectionFactory) ctx.lookup("jms/mdmConnectionFactory");
        Queue queue = (Queue) ctx.lookup("jms/mdmQueue");
        MessageProducer messageProducer;
        System.out.println("Naming success");
        try {

            javax.jms.Connection connection = connectionFactory.createConnection();
            javax.jms.Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            messageProducer = session.createProducer(queue);
            TextMessage message = session.createTextMessage();
            message.setStringProperty(Account.FIELD_NAME_CLOUD_ID, account.getCloudId());
            ControlClient cClient = new ControlClient();
            cClient.setCommandType(ControlClient.LOCK_PHONE_CONTROL);
            Gson gson = new Gson();
            message.setStringProperty(ControlClient.CONTROL_CLIENT_KEY, gson.toJson(cClient));
            System.out.println("It come from Servlet:" + message.getText());
            messageProducer.send(message);
            System.out.println("JMS success");
        } catch (JMSException ex) {
            //                  Logger.getLogger(Control.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("JMS exception");
        }

    } catch (NamingException ex) {
        //                Logger.getLogger(Control.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("Naming exception");
    }
}

From source file:de.sqlcoach.db.jdbc.DBConnection.java

/**
 * Gets the pool connection./*from   w w w. j  a v  a2  s .c  om*/
 * 
 * @return the pool connection
 * 
 * @throws NamingException
 *           the naming exception
 * @throws SQLException
 *           the SQL exception
 */
protected static DBConnection getPoolConnection(String dataSourceName) throws NamingException, SQLException {
    final Context initCtx = new InitialContext();
    final Context envCtx = (Context) initCtx.lookup("java:comp/env");

    final String name = "jdbc/" + dataSourceName;

    DBConnection dbconn = null;

    Integer connectionCnt = DBConnection.connectionCounter.get(dataSourceName);
    if (connectionCnt == null)
        connectionCnt = 0;

    if (log.isInfoEnabled()) {
        log.info("getPoolConnection ENTER [dataSource=" + dataSourceName + " connectionCnt=" + connectionCnt
                + "]");
    }

    // final DataSource ds = (DataSource)envCtx.lookup(name);
    // if (ds == null) {
    // log.error ("getPoolConnection : No DataSource for "+ name+ " !");
    // return null;
    // } else {
    // if (log.isDebugEnabled())
    // log.debug("getPoolConnection : DataSource: "+ds.toString());
    // }

    // final Connection cn = ds.getConnection();
    final Connection cn = getSimpleConnection(dataSourceName);
    if (cn == null) { // Failed !
        log.error("getPoolConnection : No Connection for " + name + " ! (connectionCnt:" + connectionCnt + ")");
        return null;
    } else { // Success
        DBConnection.connectionCounter.put(dataSourceName, connectionCnt++);
        dbconn = new DBConnection(cn, connectionCnt, dataSourceName);
        if (log.isDebugEnabled())
            log.debug("getPoolConnection : Connection: " + cn.toString());
    }

    cn.setAutoCommit(false);

    // Set Oracle date format to YYYY-MM-DD
    // final java.sql.DatabaseMetaData dm = cn.getMetaData();
    // final String prodname = dm.getDatabaseProductName();
    // if (prodname.equalsIgnoreCase("Oracle")) { // Only for Oracle !!
    // try (Statement s = cn.createStatement()) {
    // s.execute("ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD'");
    // if (log.isDebugEnabled())
    // log.debug("getPoolConnection : ProductName=" + prodname + "\nALTER
    // SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD'");
    // } catch (SQLException e) {
    // log.warn("getPoolConnection : ProductName="+prodname+"\nALTER SESSION SET
    // NLS_DATE_FORMAT = 'YYYY-MM-DD': ", e);
    // }
    // } else {
    // if (log.isDebugEnabled())
    // log.debug("getPoolConnection : Kein Oracle cn= "+cn+ "
    // ProductName="+prodname);
    // }

    if (log.isInfoEnabled())
        log.info("getPoolConnection LEAVE dbconn=" + dbconn);

    return dbconn;
}

From source file:edu.ucsd.library.dams.api.FileStoreServlet.java

/**
 * Initialize the servlet.//w w  w . jav  a 2  s  .c o m
 * @see HttpServlet#init().
 */
public void init() throws ServletException {
    /* begin ucsd changes */
    try {
        InitialContext ctx = new InitialContext();
        String damsHome = null;
        try {
            damsHome = (String) ctx.lookup("java:comp/env/dams/home");
        } catch (Exception ex) {
            damsHome = "dams";
        }
        props = DAMSAPIServlet.loadConfig();
        fsDefault = props.getProperty("fs.default");
        df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
        // RFC 822, Wed, 23 May 2012 11:54:18 GMT
    } catch (Exception ex) {
        log.warn("Unable to lookup default filestore", ex);
        throw new ServletException("Unable to lookup default filestore");
    }
    /* end ucsd changes */
}

From source file:com.jobhunt.rest.Login.java

private UserSessionRemote lookupUserSessionRemote() {
    try {// w w w.  j  a  v a  2  s.c  om
        Context c = new InitialContext();
        return (UserSessionRemote) c.lookup("java:global/JobhuntEJB/UserSessionBean");
    } catch (NamingException ne) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
        throw new RuntimeException(ne);
    }
}

From source file:io.apiman.manager.test.server.ManagerApiTestServer.java

/**
 * Stop the server.//  w  ww .  j  a  v  a  2 s.co m
 * @throws Exception
 */
public void stop() throws Exception {
    server.stop();
    ds.close();
    InitialContext ctx = new InitialContext();
    ctx.unbind("java:comp/env/jdbc/ApiManagerDS"); //$NON-NLS-1$
}

From source file:com.silverpeas.jcrutil.model.impl.AbstractJcrTestCase.java

@Before
public void init() throws Exception {
    InitialContext ic = new InitialContext();
    Properties properties = new Properties();
    properties.load(PathTestUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"));
    DataSource ds = BasicDataSourceFactory.createDataSource(properties);
    rebind(ic, JNDINames.DATABASE_DATASOURCE, ds);
    ic.rebind(JNDINames.DATABASE_DATASOURCE, ds);
    rebind(ic, JNDINames.ADMIN_DATASOURCE, ds);
    ic.rebind(JNDINames.ADMIN_DATASOURCE, ds);
    setUpDatabase();/*  w w w  .j  av  a 2s.c  o m*/
}