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:binky.reportrunner.service.impl.DatasourceServiceImpl.java

private DataSource getDs(RunnerDataSource runnerDs)
        throws SecurityException, InstantiationException, IllegalAccessException, ClassNotFoundException,
        PropertyVetoException, NamingException, EncryptionException {

    final String jndiDataSource = runnerDs.getJndiName();

    if (StringUtils.isBlank(jndiDataSource)) {
        EncryptionUtil enc = new EncryptionUtil();
        logger.info("using dbcp pooled connection for: " + runnerDs.getDataSourceName());

        String jdbcUser = runnerDs.getUsername();
        if (StringUtils.isBlank(runnerDs.getPassword()))
            throw new SecurityException("password is empty");
        String jdbcPassword = enc.decrpyt(secureKey, runnerDs.getPassword());

        String jdbcUrl = runnerDs.getJdbcUrl();
        String databaseDriver = runnerDs.getJdbcClass();

        Class.forName(databaseDriver).newInstance();

        BasicDataSource ds1 = new BasicDataSource();
        ds1.setDriverClassName(databaseDriver);
        ds1.setUrl(jdbcUrl);/*  w  w  w  . j  a  v a  2s  .c  om*/
        ds1.setUsername(jdbcUser);
        ds1.setPassword(jdbcPassword);
        ds1.setInitialSize(runnerDs.getInitialPoolSize());
        ds1.setMaxActive(runnerDs.getMaxPoolSize());

        ds1.setRemoveAbandoned(true);
        ds1.setRemoveAbandonedTimeout(600);

        // do not want anything updating anything
        ds1.setDefaultReadOnly(true);

        ds1.setLogAbandoned(true);
        ds1.setTestOnBorrow(true);
        ds1.setTestOnReturn(true);
        ds1.setTestWhileIdle(true);

        // does this work across all RBMS? - no it doesn't
        //ds1.setValidationQuery("select 1");
        //ds1.setValidationQueryTimeout(300);

        return ds1;
    } else {
        logger.info(
                "getting datasource from JNDI url: " + jndiDataSource + " for " + runnerDs.getDataSourceName());
        Context initContext = new InitialContext();
        DataSource ds = (DataSource) initContext.lookup("java:/comp/env/" + jndiDataSource);
        return ds;
    }
}

From source file:com.duroty.service.Mailet.java

/**
 * Creates a new Mailet object./*  w w w  . ja va2s  . c  o m*/
 *
 * @param servible DOCUMENT ME!
 * @param messageName DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 * @param mime DOCUMENT ME!
 */
public Mailet(Servible servible, String messageName, String repositoryName, MimeMessage mime) {
    super();
    this.servible = servible;
    this.messageName = messageName;
    this.repositoryName = repositoryName;
    this.mime = mime;

    Map options = ApplicationConstants.options;

    try {
        ctx = new InitialContext();

        HashMap mail = (HashMap) ctx.lookup((String) options.get(Constants.MAIL_CONFIG));

        this.hibernateSessionFactory = (String) mail.get(Constants.HIBERNATE_SESSION_FACTORY);
        this.smtpSessionFactory = (String) mail.get(Constants.DUROTY_MAIL_FACTOTY);
        this.defaultLucenePath = (String) mail.get(Constants.MAIL_LUCENE_PATH);

        parseIndexLimit((String) mail.get(Constants.MAIL_ATTACHMENT_SIZE));

        String clazzAnalyzerName = (String) mail.get(Constants.MAIL_LUCENE_ANALYZER);

        if ((clazzAnalyzerName != null) && !clazzAnalyzerName.trim().equals("")) {
            Class clazz = null;
            clazz = Class.forName(clazzAnalyzerName.trim());
            this.analyzer = (Analyzer) clazz.newInstance();
        } else {
            this.analyzer = new StandardAnalyzer();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.silverpeas.components.model.AbstractTestDao.java

/**
 * Configure the data source from a JNDI context. This is called directly by JUnit 4 at test class
 * loading or by the setUp() method at each test invocation in JUnit 3.
 *
 * @throws IOException if an error occurs while communicating with the JNDI context.
 * @throws NamingException if the data source cannot be found in the JNDI context.
 * @throws Exception if the data source cannot be created.
 *//*from  w w  w . j  a  v a 2 s .  c  o  m*/
public void configureJNDIDatasource() throws Exception {
    InitialContext ic = new InitialContext();
    EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
    datasource = builder.setType(EmbeddedDatabaseType.H2).addScript(getTableCreationScript()).build();
    ic.rebind(jndiName, datasource);
}

From source file:biz.taoconsulting.dominodav.resource.DAVResourceJDBC.java

/**
 * /**/*from   www .  j a v  a 2s.c  om*/
 * 
 * @see biz.taoconsulting.dominodav.resource.DAVAbstractResource#getStream()
 */
public InputStream getStream() {

    Connection conn = null;
    Statement stmt = null;

    InputStream blobStream = null;

    try {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        DataSource ds = (DataSource)

        // THe internal address of a JDBC source is the data source
        envCtx.lookup(this.repositoryMeta.getInternalAddress());

        conn = ds.getConnection();
        stmt = conn.createStatement();
        // XXX: THat is plain wrong -- need to rework the JDBC data source
        // query
        ResultSet rs = stmt.executeQuery(
                "select f.fil_blocksize,f.fil_contents_blob from ibkuis_pp_files f where  f.fil_id="
                        + this.getDBFileID());
        if (rs.next()) {
            Blob blob = rs.getBlob(2);
            blobStream = blob.getBinaryStream();
        }
    } catch (NamingException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            if (stmt != null)
                stmt.close();

            if (conn != null)
                conn.close();
        } catch (SQLException e) {
            /** Exception handling **/
        }
    }
    return blobStream;
}

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

protected Repository createJndiRepository(String jndiName) {
    try {// www.ja  v  a 2 s.  c om
        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:com.jaspersoft.jasperserver.war.CSVServlet.java

private Context getJndiContext() throws NamingException {
    if (jndiContext == null) {
        jndiContext = new InitialContext();
    }//from  www  .j a  va 2  s  .  c om
    return jndiContext;
}

From source file:it.infn.ct.futuregateway.apiserver.APIContextListener.java

@Override
public final void contextDestroyed(final ServletContextEvent sce) {
    ExecutorService exServ;//from www . j  av a2s .  c  om
    try {
        Context ctx = new InitialContext();
        exServ = (ExecutorService) ctx.lookup("java:comp/env/threads/Submitter");
    } catch (NamingException ex) {
        exServ = (ExecutorService) sce.getServletContext().getAttribute("SubmissionThreadPool");
    }
    exServ.shutdown();
    try {
        if (!exServ.awaitTermination(Constants.MAXTHREADWAIT, TimeUnit.MINUTES)) {
            log.warn("Failed to shutdown the submission thread pool.");
        }
    } catch (InterruptedException ex) {
        log.error(ex);
    }
}

From source file:com.dattack.naming.StandaloneJndiTest.java

@Test
public void testLookupValidDataSource() {

    try {/*from   www.j  a  va2s  .  c  o m*/
        final InitialContext context = new InitialContext();
        final String name = getCompositeName(VALID_CONTEXT, VALID_OBJECT_NAME);
        final DataSource dataSource = (DataSource) context.lookup(name);
        assertNotNull(dataSource);
    } catch (final NamingException e) {
        fail(e.getMessage());
    }
}

From source file:com.portfolio.data.attachment.XSLService.java

@Override
public void init(ServletConfig config) throws ServletException {
    sc = config.getServletContext();//ww w .  ja v  a2 s . c o  m
    servletDir = sc.getRealPath("/");
    int last = servletDir.lastIndexOf(File.separator);
    last = servletDir.lastIndexOf(File.separator, last - 1);
    baseDir = servletDir.substring(0, last);
    server = config.getInitParameter("redirectedServer");

    //Setting up the JAXP TransformerFactory
    this.transFactory = TransformerFactory.newInstance();

    //Setting up the FOP factory
    this.fopFactory = FopFactory.newInstance();

    try {
        String dataProviderName = config.getInitParameter("dataProviderClass");
        dataProvider = (DataProvider) Class.forName(dataProviderName).newInstance();

        InitialContext cxt = new InitialContext();

        /// Init this here, might fail depending on server hosting
        ds = (DataSource) cxt.lookup("java:/comp/env/jdbc/portfolio-backend");
        if (ds == null) {
            throw new Exception("Data  jdbc/portfolio-backend source not found!");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}