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:gov.nih.nci.cdmsconnector.c3d.service.globus.resource.C3DGridServiceResourceBase.java

public C3DGridServiceResourceConfiguration getConfiguration() {
    if (this.configuration != null) {
        return this.configuration;
    }/*from  w w w.j a  v  a 2  s  .  c om*/
    MessageContext ctx = MessageContext.getCurrentContext();

    String servicePath = ctx.getTargetService();
    servicePath = servicePath.substring(0, servicePath.lastIndexOf("/"));
    servicePath += "/C3DGridService";

    String jndiName = Constants.JNDI_SERVICES_BASE_NAME + servicePath + "/configuration";
    logger.debug("Will read configuration from jndi name: " + jndiName);
    try {
        Context initialContext = new InitialContext();
        this.configuration = (C3DGridServiceResourceConfiguration) initialContext.lookup(jndiName);
    } catch (Exception e) {
        logger.error("when performing JNDI lookup for " + jndiName + ": " + e, e);
    }

    return this.configuration;
}

From source file:gov.nih.nci.security.util.ConfigurationHelper.java

private DataSource getDataSourceFromConfiguration(Properties configPropetries) {
    DataSource ds = null;/* ww w  . j a  v  a2  s  .  com*/
    if (configPropetries != null) {
        String datasource = configPropetries.getProperty("hibernate.connection.datasource");
        if (!StringUtils.isEmpty(datasource)) {
            log.info("Datasource::" + datasource);
            try {
                InitialContext initialContext = new InitialContext();
                ds = (DataSource) initialContext.lookup(datasource);
            } catch (NamingException ex) {
                log.info("Exception occured while looking up datasource::" + datasource);
            }
        } else {
            String urlProperty = configPropetries.getProperty("hibernate.connection.url");
            String usernameProperty = configPropetries.getProperty("hibernate.connection.username");
            String passwordProperty = configPropetries.getProperty("hibernate.connection.password");
            String driverProperty = configPropetries.getProperty("hibernate.connection.driver_class");

            log.info("Connection:user:" + configPropetries.getProperty("hibernate.connection.username"));
            log.info("Connection:url:" + configPropetries.getProperty("hibernate.connection.url"));

            DriverManagerDataSource dataSource = new DriverManagerDataSource();
            dataSource.setDriverClassName(driverProperty);
            dataSource.setUrl(urlProperty);
            dataSource.setUsername(usernameProperty);
            dataSource.setPassword(passwordProperty);
            ds = dataSource;
        }
    }
    return ds;
}

From source file:gov.nih.nci.clinicalconnector.service.globus.resource.ClinicalConnectorResourceBase.java

public ClinicalConnectorResourceConfiguration getConfiguration() {
    if (this.configuration != null) {
        return this.configuration;
    }// ww w . jav a2 s .  co m
    MessageContext ctx = MessageContext.getCurrentContext();

    String servicePath = ctx.getTargetService();
    servicePath = servicePath.substring(0, servicePath.lastIndexOf("/"));
    servicePath += "/ClinicalConnector";

    String jndiName = Constants.JNDI_SERVICES_BASE_NAME + servicePath + "/configuration";
    logger.debug("Will read configuration from jndi name: " + jndiName);
    try {
        Context initialContext = new InitialContext();
        this.configuration = (ClinicalConnectorResourceConfiguration) initialContext.lookup(jndiName);
    } catch (Exception e) {
        logger.error("when performing JNDI lookup for " + jndiName + ": " + e, e);
    }

    return this.configuration;
}

From source file:it.eng.spagobi.engines.exporters.KpiExporter.java

public File getKpiReportPDF(List<KpiResourceBlock> kpiBlocks, BIObject obj, String userId) throws Exception {
    logger.debug("IN");

    //Build report template
    String docName = (obj != null) ? obj.getName() : "";
    BasicTemplateBuilder basic = new BasicTemplateBuilder(docName);
    String template2 = "";
    List templates = basic.buildTemplate(kpiBlocks);
    boolean first = true;

    //String template2=basic.buildTemplate(kpiBlocks);

    //System.out.println(template2);

    String outputType = "PDF";
    HashedMap parameters = new HashedMap();
    parameters.put("PARAM_OUTPUT_FORMAT", outputType);

    //parameters.put("SBI_HTTP_SESSION", session);   ???

    JREmptyDataSource conn = new JREmptyDataSource(1);

    // identity string for object execution
    UUIDGenerator uuidGen = UUIDGenerator.getInstance();
    UUID uuid_local = uuidGen.generateTimeBasedUUID();
    String executionId = uuid_local.toString();
    executionId = executionId.replaceAll("-", "");

    //Creta etemp file
    String dirS = System.getProperty("java.io.tmpdir");
    File dir = new File(dirS);
    dir.mkdirs();/*  ww  w.j a va2  s . com*/

    List filesToDelete = new ArrayList();
    logger.debug("Create Temp File");
    String fileName = "report" + executionId;
    File tmpFile = File.createTempFile(fileName, "." + outputType, dir);
    OutputStream out = new FileOutputStream(tmpFile);
    try {
        if (templates != null && !templates.isEmpty()) {
            int subreports = 0;
            Iterator it = templates.iterator();
            while (it.hasNext()) {
                String template = (String) it.next();
                if (first)
                    template2 = template;
                else {

                    File f = new File(dirS + File.separatorChar + "Detail" + subreports + ".jasper");
                    logger.debug("Compiling subtemplate file: " + f);
                    filesToDelete.add(f);

                    File file = new File(dirS + File.separatorChar + "Detail" + subreports + ".jrxml");
                    if (file.exists()) {
                        boolean deleted = file.delete();
                        file = new File(dirS + File.separatorChar + "Detail" + subreports + ".jrxml");
                    }
                    FileOutputStream stream = new FileOutputStream(file);
                    stream.write(template.getBytes());
                    stream.flush();
                    stream.close();
                    filesToDelete.add(file);

                    JasperCompileManager.compileReportToFile(
                            dirS + File.separatorChar + "Detail" + subreports + ".jrxml",
                            dirS + File.separatorChar + "Detail" + subreports + ".jasper");
                    subreports++;
                }
                first = false;
            }
        }

        File f = new File(dirS + File.separatorChar + "Master.jasper");
        logger.debug("Compiling subtemplate file: " + f);
        filesToDelete.add(f);

        File file = new File(dirS + File.separatorChar + "Master.jrxml");
        if (file.exists()) {
            boolean deleted = file.delete();
            file = new File(dirS + File.separatorChar + "Master.jrxml");
        }
        FileOutputStream stream = new FileOutputStream(file);
        stream.write(template2.getBytes());
        stream.flush();
        stream.close();
        filesToDelete.add(file);

        StringBufferInputStream sbis = new StringBufferInputStream(template2);
        JasperCompileManager.compileReportToFile(dirS + File.separatorChar + "Master.jrxml",
                dirS + File.separatorChar + "Master.jasper");

        logger.debug("Filling report ...");
        Context ctx = new InitialContext();
        Session aSession = HibernateUtil.currentSession();
        JasperPrint jasperPrint = null;
        try {
            Transaction tx = aSession.beginTransaction();
            //Connection jdbcConnection = aSession.connection();
            Connection jdbcConnection = HibernateUtil.getConnection(aSession);
            jasperPrint = JasperFillManager.fillReport(dirS + File.separatorChar + "Master.jasper", parameters,
                    jdbcConnection);
            logger.debug("Report filled succesfully");
        } finally {
            if (aSession != null) {
                if (aSession.isOpen())
                    aSession.close();
            }
        }
        logger.debug("Exporting report: Output format is [" + outputType + "]");
        JRExporter exporter = null;
        //JRExporter exporter = ExporterFactory.getExporter(outputType);   
        // Set the PDF exporter
        exporter = (JRExporter) Class.forName("net.sf.jasperreports.engine.export.JRPdfExporter").newInstance();

        if (exporter == null)
            exporter = new JRPdfExporter();

        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
        exporter.exportReport();
        logger.debug("Report exported succesfully");
        //in = new BufferedInputStream(new FileInputStream(tmpFile));
        logger.debug("OUT");
        return tmpFile;

    } catch (Throwable e) {
        logger.error("An exception has occured", e);
        throw new Exception(e);
    } finally {
        out.flush();
        out.close();
        if (filesToDelete != null && !filesToDelete.isEmpty()) {
            Iterator it = filesToDelete.iterator();
            while (it.hasNext()) {
                File temp = (File) it.next();
                temp.delete();
            }
        }
        //tmpFile.delete();

    }

}

From source file:com.ocpsoft.pretty.faces.el.resolver.CDIBeanNameResolver.java

/**
 * Tries to get the BeanManager from JNDI
 * //from   www.j a  va 2s.  c  om
 * @param jndiName
 *           The JNDI name used for lookup
 * @return BeanManager instance or <code>null</code>
 */
private Object getBeanManagerFromJNDI(String jndiName) {

    try {
        // perform lookup
        InitialContext initialContext = new InitialContext();
        Object obj = initialContext.lookup(jndiName);

        if (log.isTraceEnabled()) {
            log.trace("Found BeanManager in: " + jndiName);
        }

        return obj;

    } catch (NamingException e) {
        if (log.isDebugEnabled()) {
            log.debug("Unable to get BeanManager from '" + jndiName + "': " + e.getMessage());
        }
    }

    return null;
}

From source file:com.app.server.EJBDeployer.java

public void init(Vector serviceList, ServerConfig serverConfig, MBeanServer mbeanServer) {
    this.serviceList = serviceList;
    this.serverConfig = serverConfig;
    this.mbeanServer = mbeanServer;
    this.serviceRegistryPort = Integer.parseInt(serverConfig.getServicesregistryport());
    //System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory");
    //System.setProperty(Context.PROVIDER_URL, "rmi://localhost:"+serverConfig.getServicesregistryport());;
    try {/*from ww  w .  j a  v  a  2s  .  c  o  m*/
        fsManager = new StandardFileSystemManager();
        System.setProperty("java.io.tmpdir", serverConfig.getCachedir());
        /*DefaultFileReplicator replicator = new DefaultFileReplicator(new File(cacheDir));
        //fsManager.setReplicator(new PrivilegedFileReplicator(replicator));
        fsManager.setTemporaryFileStore(replicator);*/
        fsManager.init();
        registry = LocateRegistry.createRegistry(Integer.parseInt(serverConfig.getServicesregistryport()));
        try {
            ic = new InitialContext();
            Context subctx = null;
            try {
                subctx = (Context) ic.lookup("java:");
            } catch (Exception ex) {
                log.error("Error in getting the java context", ex);
                //ex.printStackTrace();
            }
            if (subctx == null) {
                ic.createSubcontext("java:");
            }
            remoteBindingInterface = new RemoteBindingObject(ic);
            Object jndilookupobj = UnicastRemoteObject.exportObject((Remote) remoteBindingInterface,
                    this.serviceRegistryPort);
            //registry.rebind("RemoteBindingObject", (Remote) jndilookupobj);
        } catch (Exception ex) {
            log.error("error in registring to the remote binding object", ex);
            //e1.printStackTrace();
        }
        this.jms = new EmbeddedJMS();
        this.jms.start();

    } catch (Exception e) {
        log.error("error in initialization", e);
        // TODO Auto-generated catch block
        //e.printStackTrace();
    }
    connectionFactory = (ConnectionFactory) jms.lookup("java:/ConnectionFactory");
    log.info("initialized");
}

From source file:Util.java

/**
 * Lookup an object in the default initial context
 * /*from   w w  w  .ja  v a  2s. c  om*/
 * @param name
 *          the name to lookup
 * @param clazz
 *          the expected type
 * @return the object
 * @throws Exception
 *           for any error
 */
public static Object lookup(String name, Class<?> clazz) throws Exception {
    InitialContext ctx = new InitialContext();
    try {
        return lookup(ctx, name, clazz);
    } finally {
        ctx.close();
    }
}

From source file:de.zib.gndms.GORFX.offer.service.globus.resource.OfferResourceBase.java

public OfferResourceConfiguration getConfiguration() {
    if (this.configuration != null) {
        return this.configuration;
    }/*from w  w w .  j a va  2 s . com*/
    MessageContext ctx = MessageContext.getCurrentContext();

    String servicePath = ctx.getTargetService();
    servicePath = servicePath.substring(0, servicePath.lastIndexOf("/"));
    servicePath += "/Offer";

    String jndiName = Constants.JNDI_SERVICES_BASE_NAME + servicePath + "/configuration";
    logger.debug("Will read configuration from jndi name: " + jndiName);
    try {
        Context initialContext = new InitialContext();
        this.configuration = (OfferResourceConfiguration) initialContext.lookup(jndiName);
    } catch (Exception e) {
        logger.error("when performing JNDI lookup for " + jndiName + ": " + e, e);
    }

    return this.configuration;
}

From source file:fr.cnes.sitools.datasource.jdbc.business.SitoolsSQLDataSourceFactory.java

/**
 * Retrieval of a DataSource as a JNDI resource
 * /*from w  ww . j  a v a  2  s . c o  m*/
 * Lookup the DataSource, which will be backed by a pool that the application server provides. DataSource instances
 * are also a good candidate for caching as an instance variable, as JNDI lookups can be expensive as well.
 * 
 * @param dsName
 *          JNDI resource name
 * @return DataSource
 */
public static DataSource getJNDIDataSource(String dsName) {
    SitoolsSQLDataSource foundDataSource = dataSources.get(dsName);
    if (foundDataSource != null) {
        return foundDataSource;
    }

    DataSource ds = null;
    try {
        InitialContext ctx = new InitialContext();

        ds = (DataSource) ctx.lookup(dsName);
        JDBCDataSource jdbcDS = new JDBCDataSource();
        jdbcDS.setName(dsName);
        dataSources.put(dsName, new SitoolsSQLDataSource(jdbcDS, ds, null));

    } catch (NamingException e) {
        Context.getCurrentLogger().log(Level.INFO, null, e);

    }
    return ds;
}

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  ava  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);
    }
}