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:org.jboss.spring.deployers.AbstractSpringMetaDataDeployer.java

/**
 * Unind factory from non-serializable JNDI context.
 *
 * @param name the jndi name//from w  ww.  j  a  v a 2s .  c  om
 */
protected void unbind(String name) {
    InitialContext ctx = null;
    try {
        ctx = new InitialContext();
        ctx.unbind(name);
        NonSerializableFactory.unbind(name);
    } catch (NamingException e) {
        log.warn("Unable to unbind BeanFactory from JNDI", e);
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Throwable ignored) {
            }
        }
    }
}

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

private void getInitDBFileValues() {
    Statement stmt = null;//from w ww  .j  a v  a2  s.c o  m
    Statement stmt1 = null;
    Connection conn = null;
    try {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        DataSource ds = (DataSource)

        envCtx.lookup(this.repositoryMeta.getInternalAddress());
        conn = ds.getConnection();
        stmt1 = conn.createStatement();
        // TODO fix this
        stmt1.executeQuery("select uis_mid_onetimeinitweb('DATENADMIN','umsys','DE') as a from dual");

        stmt = conn.createStatement();
        // TODO: Fix that SQL
        ResultSet rs = stmt.executeQuery(
                "select t.dtyp_mimetype,d.*," + "f.fil_length,f.fil_id from  umsys.ibkuis_co_filetype t,"
                        + "uis_pp_documents_v d, ibkuis_pp_files f where d.D_ID =" + this.getDBDocID()
                        + "and f.fil_id = d.D_FIL_ID and t.dtyp_kz = upper(d.D_TYP)");
        if (rs.next()) {
            this.setName(rs.getString("D_FILE"));
            this.setExtension(rs.getString("D_TYP"));
            this.setContentLength(rs.getString("FIL_LENGTH"));
            this.setDBFileID(rs.getString("FIL_ID"));
            this.setMimeType(rs.getString("dtyp_mimetype"));
            System.out.println("BREAK");
        }
    } catch (NamingException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            if (stmt != null)
                stmt.close();
            if (stmt1 != null)
                stmt1.close();
            if (conn != null)
                conn.close();
        } catch (SQLException e) {
            /** Exception handling **/
        }
    }
}

From source file:net.sf.jabb.util.db.ConnectionUtility.java

/**
 * Create DataSource and bind it to JNDI
 * @param source   configuration//from   w  ww .j  av  a2s. c o m
 * @param jndiName   JNDI name that the DataSource needs to be bind to
 * @return   The DataSource created
 */
public static DataSource createDataSource(String source, String jndiName) {
    DataSource ds = createDataSource(source);
    if (ds != null && jndiName != null) {
        InitialContext ic;
        try {
            ic = new InitialContext();
            ic.bind(jndiName, ds);
        } catch (NamingException e) {
            log.error("Failed to bind data source '" + source + "' to JNDI name: " + jndiName, e);
        }
    }
    return ds;
}

From source file:com.joseflavio.iperoxo.IpeRoxo.java

/**
 * Inicia a {@link DataSource} e a {@link EntityManagerFactory}.
 *//* w  ww.  ja va  2 s .  co m*/
private static void executarFonteDeDados() throws IOException, NamingException {

    if (Boolean.parseBoolean(getPropriedade("DataSource.Enable"))) {
        log.info(getMensagem(null, "Log.Iniciando.DataSource"));
    } else {
        return;
    }

    System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
    System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");

    dataSource = new BasicDataSource();
    dataSource.setDriverClassName(getPropriedade("DataSource.Driver"));
    dataSource.setUrl(getPropriedade("DataSource.URL"));
    dataSource.setUsername(getPropriedade("DataSource.Username"));
    dataSource.setPassword(getPropriedade("DataSource.Password"));
    dataSource.setInitialSize(Integer.parseInt(getPropriedade("DataSource.InitialSize")));
    dataSource.setMaxTotal(Integer.parseInt(getPropriedade("DataSource.MaxTotal")));
    dataSource.setMinIdle(Integer.parseInt(getPropriedade("DataSource.MinIdle")));
    dataSource.setMaxIdle(Integer.parseInt(getPropriedade("DataSource.MaxIdle")));
    dataSource.setTestOnCreate(Boolean.parseBoolean(getPropriedade("DataSource.TestOnCreate")));
    dataSource.setTestWhileIdle(Boolean.parseBoolean(getPropriedade("DataSource.TestWhileIdle")));
    dataSource.setTestOnBorrow(Boolean.parseBoolean(getPropriedade("DataSource.TestOnBorrow")));
    dataSource.setTestOnReturn(Boolean.parseBoolean(getPropriedade("DataSource.TestOnReturn")));

    Context contexto = new InitialContext();
    try {
        contexto.bind("FONTE", dataSource);
    } finally {
        contexto.close();
    }

    while (true) {
        try (Connection con = getConnection()) {
            break;
        } catch (Exception e) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException f) {
            }
        }
    }

    if (Boolean.parseBoolean(getPropriedade("DataSource.JPA.Enable"))) {
        log.info(getMensagem(null, "Log.Iniciando.JPA"));
    } else {
        return;
    }

    emf = Persistence.createEntityManagerFactory("JPA");

    try {
        emf.createEntityManager().close();
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }

}

From source file:ca.nrc.cadc.db.DBUtil.java

/**
 * Create a JNDI DataSOurce resource with the specified name and environment context.
 * //w ww  .  jav  a2 s .c  om
 * @param dataSourceName
 * @param envContextName
 * @param config
 * @throws NamingException 
 */
public static void createJNDIDataSource(String dataSourceName, String envContextName, ConnectionConfig config)
        throws NamingException {
    log.debug("createDataSource: " + dataSourceName + " START");
    StandaloneContextFactory.initJNDI();

    Context initContext = new InitialContext();
    Context envContext = (Context) initContext.lookup(envContextName);
    if (envContext == null) {
        envContext = initContext.createSubcontext(envContextName);
    }
    log.debug("env: " + envContext);

    DataSource ds = getDataSource(config);
    envContext.bind(dataSourceName, ds);
    log.debug("createDataSource: " + dataSourceName + " DONE");
}

From source file:de.mpg.mpdl.inge.xmltransforming.TestBase.java

/**
 * Helper method to retrieve a EJB service instance. The name to be passed to the method is
 * normally 'ServiceXY.SERVICE_NAME'.//from   w w w  .  j ava  2  s . com
 * 
 * @param serviceName The name of the service, e.g.
 *        "ejb.de.mpg.mpdl.inge.xmltransforming.XmlTransforming"
 * 
 * @return instance of the EJB service
 * 
 * @throws NamingException Thrown if the service is not found.
 */
protected static Object getService(String serviceName) throws NamingException {
    InitialContext context = new InitialContext();
    Object serviceInstance = context.lookup(serviceName);
    assertNotNull(serviceInstance);
    return serviceInstance;
}

From source file:com.jaspersoft.jasperserver.api.metadata.olap.service.impl.OlapManagementServiceImpl.java

private MondrianConnectionSchemaParameters getConnectionParameters(MondrianConnection monConn,
        boolean transform) {
    MondrianConnectionSchemaParameters parameters = null;

    String monConnUri = transform ? transformUri(monConn.getURIString()) : monConn.getURIString();

    String dsUri = null;//from   w ww  .java2  s. co  m
    ReportDataSource dataSource = null;

    ResourceReference ref = monConn.getDataSource();
    if (ref.isLocal()) {
        dataSource = (ReportDataSource) ref.getLocalResource();
    } else {
        dsUri = transform ? transformUri(ref.getReferenceURI()) : ref.getReferenceURI();
        dataSource = (ReportDataSource) getRepositoryService().getResource(runtimeContext, dsUri);
    }

    if (dataSource == null) {
        throw new JSException("null data source on dereference of mondrian connection " + monConnUri + " for "
                + (monConn.getDataSource().isLocal() ? "local: " + ref.getLocalResource().getURIString()
                        : dsUri));
    }

    // Define values for schema cache key
    // This uri will be transformed as part of the CatalogLocator
    String catalogUrl = monConn.getSchema().getReferenceURI();

    if (transform) {
        catalogUrl = transformUri(catalogUrl);
    }

    catalogUrl = repositoryCatalogLocator.locate(catalogUrl);

    log.debug("catalogUrl: " + catalogUrl + ", original URI: " + monConn.getSchema().getReferenceURI()
            + ", transform: " + transform);

    if (dataSource instanceof JdbcReportDataSource) {
        JdbcReportDataSource jdbcDs = (JdbcReportDataSource) dataSource;
        String jdbcConnectString = jdbcDs.getConnectionUrl();
        String jdbcUser = jdbcDs.getUsername();
        parameters = new MondrianConnectionSchemaParameters(monConnUri, catalogUrl, jdbcConnectString,
                jdbcUser);
    } else {
        JndiJdbcReportDataSource jndiDs = (JndiJdbcReportDataSource) dataSource;

        String strDataSource = "";

        if ((jndiDs.getJndiName() != null && !jndiDs.getJndiName().startsWith("java:"))) {
            try {
                Context ctx = new InitialContext();
                ctx.lookup("java:comp/env/" + jndiDs.getJndiName());
                strDataSource = "java:comp/env/";
            } catch (NamingException e) {
                //Added as short time solution due of http://bugzilla.jaspersoft.com/show_bug.cgi?id=26570.
                //The main problem - this code executes in separate tread (non http).
                //Jboss 7 support team recommend that you use the non-component environment namespace for such situations.
                try {
                    Context ctx = new InitialContext();
                    ctx.lookup(jndiDs.getJndiName());
                    strDataSource = "";
                } catch (NamingException ex) {

                }
            }
        }

        strDataSource = strDataSource + jndiDs.getJndiName();
        parameters = new MondrianConnectionSchemaParameters(monConnUri, catalogUrl, strDataSource);
    }

    return parameters;
}

From source file:edu.harvard.hul.ois.pds.ws.PDSWebService.java

/**
 * Initialize the servlet.// w w  w  . j a v a2s  . co  m
 */

public void init(ServletConfig config) throws ServletException {
    super.init(config);

    try {
        Context initContext = new InitialContext();
        Context envContext = (Context) initContext.lookup("java:/comp/env");
        PdsConf pdsConf = (PdsConf) envContext.lookup("bean/PdsConf");
        conf = pdsConf.getConf();
        memcache = (CacheController) envContext.lookup("bean/CacheController");
        ds = (DataSource) envContext.lookup("jdbc/DrsDB");
    } catch (NamingException e) {
        e.printStackTrace();
    }

    cache = conf.getString("cache");
    idsUrl = conf.getString("ids");
    ftsUrl = conf.getString("fts");
    giffy = conf.getString("t2gif");
    cacheUrl = conf.getString("cacheUrl");
    pdsUrl = conf.getString("pds");
    nrsUrl = conf.getString("nrsUrl");
    String logFile = conf.getString("logFile");

    maxThumbnails = conf.getString("maxThumbnails");

    //Configure the logger
    logger = Logger.getLogger("edu.harvard.hul.ois.pds.ws");
    try {
        XmlLayout myLayout = new XmlLayout();
        //an appender for the access log
        Appender myAppender = new DailyRollingFileAppender(myLayout, logFile, conf.getString("logRollover"));
        logger.addAppender(myAppender);
    } catch (Exception e) {
        WebAppLogMessage message = new WebAppLogMessage();
        message.setContext("init logger");
        message.setMessage("Error initializing logger");
        logger.error(message, e);
        throw new ServletException(e.getMessage());
    }
    //reset the logger for this class
    logger = Logger.getLogger(PDSWebService.class);

    System.setProperty("org.xml.sax.driver", "org.apache.xerces.parsers.SAXParser");

    //init pdf conversions hash
    pdfConversions = new Hashtable<String, ArrayList<Integer>>();

    //Log successful servlet init
    WebAppLogMessage message = new WebAppLogMessage();
    message.setMessage("Servlet init()");
    logger.info(message);

    drs2Service = new ServiceWrapper(conf.getString("drs2ServiceURL"), conf.getString("drs2AppKey"), 1);

}

From source file:edu.harvard.i2b2.crc.loader.util.CRCLoaderUtil.java

public DataMartLoaderAsyncBeanLocal getDataMartLoaderBean() throws I2B2Exception {
    InitialContext ctx;/*from ww w  .j a v a2  s .c o m*/
    try {
        ctx = new InitialContext();
        return (DataMartLoaderAsyncBeanLocal) ctx.lookup("DataMartLoaderAsyncBean/local");
    } catch (NamingException e) {
        throw new I2B2Exception("Bean lookup error ", e);
    }

}

From source file:de.micromata.genome.gwiki.model.config.GWikiDAOContext.java

public Session getMailSession() {
    if (mailSession != null) {
        return mailSession;
    }//from  w w  w  .j a  v a2s  .  c  o m
    try {
        mailSession = (Session) new InitialContext().lookup("java:/comp/env/gwiki/mail/mailSession");
    } catch (NamingException e) {
        GWikiLog.warn("No Mail session found");
    }
    return mailSession;
}