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:org.efaps.db.store.VFSStoreResource.java

/**
 * Method called to initialize this StoreResource.
 * @param _instance     Instance of the object this StoreResource is wanted
 *                      for//from   ww  w. j a v a  2s.  c  om
 * @param _store        Store this resource belongs to
 * @throws EFapsException on error
 * @see Resource#initialize(Instance, Map, Compress)
 */
@Override
public void initialize(final Instance _instance, final Store _store) throws EFapsException {
    super.initialize(_instance, _store);

    final StringBuilder fileNameTmp = new StringBuilder();

    final String useTypeIdStr = getStore().getResourceProperties().get(VFSStoreResource.PROPERTY_USE_TYPE);
    if ("true".equalsIgnoreCase(useTypeIdStr)) {
        fileNameTmp.append(getInstance().getType().getId()).append("/");
    }

    final String numberSubDirsStr = getStore().getResourceProperties()
            .get(VFSStoreResource.PROPERTY_NUMBER_SUBDIRS);
    if (numberSubDirsStr != null) {
        final long numberSubDirs = Long.parseLong(numberSubDirsStr);
        final String pathFormat = "%0" + Math.round(Math.log10(numberSubDirs) + 0.5d) + "d";
        fileNameTmp.append(String.format(pathFormat, getInstance().getId() % numberSubDirs)).append("/");
    }
    fileNameTmp.append(getInstance().getType().getId()).append(".").append(getInstance().getId());
    this.storeFileName = fileNameTmp.toString();

    final String numberBackupStr = getStore().getResourceProperties()
            .get(VFSStoreResource.PROPERTY_NUMBER_BACKUP);
    if (numberBackupStr != null) {
        this.numberBackup = Integer.parseInt(numberBackupStr);
    }

    if (this.manager == null) {
        try {
            DefaultFileSystemManager tmpMan = null;
            if (getStore().getResourceProperties().containsKey(Store.PROPERTY_JNDINAME)) {
                final InitialContext initialContext = new InitialContext();
                final Context context = (Context) initialContext.lookup("java:comp/env");
                final NamingEnumeration<NameClassPair> nameEnum = context.list("");
                while (nameEnum.hasMoreElements()) {
                    final NameClassPair namePair = nameEnum.next();
                    if (namePair.getName()
                            .equals(getStore().getResourceProperties().get(Store.PROPERTY_JNDINAME))) {
                        tmpMan = (DefaultFileSystemManager) context
                                .lookup(getStore().getResourceProperties().get(Store.PROPERTY_JNDINAME));
                        break;
                    }
                }
            }
            if (tmpMan == null && this.manager == null) {
                this.manager = evaluateFileSystemManager();
            }
        } catch (final NamingException e) {
            throw new EFapsException(VFSStoreResource.class, "initialize.NamingException", e);
        }
    }
}

From source file:org.webdavaccess.LocalFileSystemStorage.java

public void begin(HttpServletRequest req, Hashtable parameters, String defaultStorageLocation)
        throws WebdavException {
    if (debug == -1) {
        String debugString = (String) parameters.get(DEBUG_PARAMETER);
        if (debugString == null) {
            debug = 0;/* w w  w.j a v  a 2s .c o  m*/
        } else {
            debug = Integer.parseInt(debugString);
        }
    }
    if (debug == 1)
        log.debug("LocalFileSystemStore.begin()");

    if (root == null) {

        String rootPath = (String) parameters.get(ROOTPATH_PARAMETER);
        if (rootPath != null) {
            try {
                InitialContext context = new InitialContext();
                Context environment = (Context) context.lookup("java:comp/env");
                rootPath = (String) environment.lookup(rootPath);
            } catch (Exception ex) {
                // Not an context env. use the original as root
            }
        }
        if (rootPath == null && defaultStorageLocation != null) {
            rootPath = defaultStorageLocation;
        }

        if (rootPath == null) {
            throw new WebdavException("missing parameter: " + ROOTPATH_PARAMETER);
        }

        root = new File(rootPath);
        if (!root.exists()) {
            if (!root.mkdirs()) {
                throw new WebdavException(
                        ROOTPATH_PARAMETER + ": " + root + " does not exist and could not be created");
            }
        }

        servletName = req.getServletPath();
    }

    mPropertiesCache = new MRUCache(MAX_PROPERTIES_CACHE_SIZE);

}

From source file:org.wyona.yanel.core.map.RealmManager.java

/**
 * Get realms configuration file (either based on yanel configuration or based on environment variable)
 * @param yanelConfigurationFilename Yanel configuration filename, either 'yanel.xml' or 'yanel.properties'
 * @return Realms configuration file, either something like /usr/local/tomcat/webapps/yanel/WEB-INF/classes/realms.xml or /home/foo/realms.xml
 *///from   w  w w  .j  a va 2s  . c o m
private File getRealmsConfigFile(String yanelConfigurationFilename) throws ConfigurationException {

    // 1.) Getting realms.xml from environment variable YANEL_REALMS_HOME
    java.util.Map<String, String> env = System.getenv();
    for (java.util.Map.Entry envEntry : env.entrySet()) {
        if (((String) envEntry.getKey()).equals("YANEL_REALMS_HOME")) {
            File yanelRealmsHome = new File((String) envEntry.getValue());
            if (yanelRealmsHome.isDirectory()) {
                File envRealmsConfigFile = new File(yanelRealmsHome, "realms.xml");
                if (envRealmsConfigFile.isFile()) {
                    log.warn("Use environment variable YANEL_REALMS_HOME '" + yanelRealmsHome
                            + "' in order to load realms configuration.");
                    return envRealmsConfigFile;
                } else {
                    log.warn("No realms configuration found: " + envRealmsConfigFile.getAbsolutePath());
                }
                break;
            }
        }
    }

    // 2.) Getting realms.xml from user home directory or rather hidden yanel directory inside user home directory
    log.debug("User home directory: " + System.getProperty("user.home"));

    File userHomeDotYanelRealmsConfigFile = new File(System.getProperty("user.home") + "/.yanel", "realms.xml");
    if (userHomeDotYanelRealmsConfigFile.isFile()) {
        log.warn("DEBUG: Use hidden folder inside user home directory: "
                + userHomeDotYanelRealmsConfigFile.getParentFile().getAbsolutePath());
        return userHomeDotYanelRealmsConfigFile;
    } else {
        log.warn("No realms configuration found inside hidden folder at user home directory: "
                + userHomeDotYanelRealmsConfigFile.getAbsolutePath());
    }

    File userHomeRealmsConfigFile = new File(System.getProperty("user.home"), "realms.xml");
    if (userHomeRealmsConfigFile.isFile()) {
        log.warn("DEPRECATED: Use user home directory: " + System.getProperty("user.home"));
        return userHomeRealmsConfigFile;
    } else {
        log.warn("No realms configuration found within user home directory: "
                + userHomeRealmsConfigFile.getAbsolutePath());
    }

    // 3.) Getting realms.xml from http://tomcat.apache.org/tomcat-5.5-doc/config/context.html#Environment_Entries
    String envEntryPath = "java:comp/env/yanel/realms-config-file";
    try {
        javax.naming.InitialContext ic = new javax.naming.InitialContext();
        if (ic.lookup(envEntryPath) != null) {
            log.warn("realms.xml set as environment entry: " + (String) ic.lookup(envEntryPath));
            return new File((String) ic.lookup(envEntryPath));
        } else {
            log.info("No enviroment entry '" + envEntryPath + "' set.");
        }
    } catch (Exception e) {
        log.info("No enviroment entry '" + envEntryPath + "' set.");
    }

    // 4.) Getting realms.xml from yanel.xml
    YANEL_CONFIGURATION_FILE = yanelConfigurationFilename;

    if (RealmManager.class.getClassLoader().getResource(YANEL_CONFIGURATION_FILE) == null) {
        log.warn("No such configuration file '" + YANEL_CONFIGURATION_FILE
                + "' in classpath, hence use default filename: " + Yanel.DEFAULT_CONFIGURATION_FILE);
        YANEL_CONFIGURATION_FILE = Yanel.DEFAULT_CONFIGURATION_FILE;
    }

    File realmsConfigFile = null;
    if (RealmManager.class.getClassLoader().getResource(YANEL_CONFIGURATION_FILE) != null) {
        if (YANEL_CONFIGURATION_FILE.endsWith(".xml")) {

            try {
                URI configFileUri = new URI(
                        RealmManager.class.getClassLoader().getResource(YANEL_CONFIGURATION_FILE).toString());
                yanelConfigFile = new File(configFileUri.getPath());
            } catch (Exception e) {
                String errorMsg = "Failure while reading configuration: " + e.getMessage();
                log.error(errorMsg, e);
                throw new ConfigurationException(errorMsg, e);
            }

            try {
                DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
                Configuration config;
                config = builder.buildFromFile(yanelConfigFile);

                realmsConfigFile = new File(config.getChild("realms-config").getAttribute("src"));
            } catch (Exception e) {
                String errorMsg = "Failure while reading configuration: " + e.getMessage();
                log.error(errorMsg, e);
                throw new ConfigurationException(errorMsg, e);
            }
            if (!realmsConfigFile.isAbsolute()) {
                realmsConfigFile = FileUtil.file(yanelConfigFile.getParentFile().getAbsolutePath(),
                        realmsConfigFile.toString());
            }
        } else if (YANEL_CONFIGURATION_FILE.endsWith("properties")) {
            propertiesURL = RealmManager.class.getClassLoader().getResource(YANEL_CONFIGURATION_FILE);
            if (propertiesURL == null) {
                String errMessage = "No such resource: " + YANEL_CONFIGURATION_FILE;
                log.error(errMessage);
                throw new ConfigurationException(errMessage);
            }
            Properties props = new Properties();
            try {
                props.load(propertiesURL.openStream());
                // use URLDecoder to avoid problems when the filename contains spaces, see
                // http://bugzilla.wyona.com/cgi-bin/bugzilla/show_bug.cgi?id=5165
                File propsFile = new File(URLDecoder.decode(propertiesURL.getFile()));

                realmsConfigFile = new File(props.getProperty("realms-config"));
                if (!realmsConfigFile.isAbsolute()) {
                    realmsConfigFile = FileUtil.file(propsFile.getParentFile().getAbsolutePath(),
                            realmsConfigFile.toString());
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
                throw new ConfigurationException("Could not load realms configuration file: " + propertiesURL);
            }
        } else {
            log.error(YANEL_CONFIGURATION_FILE + " has to be either '.xml' or '.properties'");
        }
    } else {
        log.error("No such configuration file in classpath: " + YANEL_CONFIGURATION_FILE);
    }

    if (realmsConfigFile == null) {
        throw new ConfigurationException("Realms configuration file could not be determined!");
    }

    return realmsConfigFile;
}

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

@Override
public void init(ServletConfig config) throws ServletException {
    sc = config.getServletContext();/*from  w  w w.  jav  a 2s .c om*/
    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();
    }
}

From source file:org.meveo.service.job.JobInstanceService.java

public Long execute(String jobInstanceCode, User currentUser, Map<String, String> params)
        throws BusinessException {
    log.info("execute timer={} ", jobInstanceCode);
    JobInstance entity = null;/*from  w w w  .  j  av a2s .c o m*/
    entity = findByCode(jobInstanceCode, currentUser.getProvider());
    if (entity == null) {
        throw new JobDoesNotExistsException(jobInstanceCode);
    }

    JobExecutionResultImpl result = new JobExecutionResultImpl();
    result.setJobInstance(entity);
    InitialContext ic;
    try {
        ic = new InitialContext();
        if (jobEntries.containsKey(entity.getJobCategoryEnum())) {
            HashMap<String, String> jobs = jobEntries.get(entity.getJobCategoryEnum());
            if (jobs.containsKey(entity.getJobTemplate())) {
                Job job = (Job) ic.lookup(jobs.get(entity.getJobTemplate()));
                jobExecutionService.create(result, currentUser);
                job.execute(entity, result, currentUser);
            }
        } else {
            throw new BusinessException("cannot find job category " + entity.getJobCategoryEnum());
        }
    } catch (NamingException e) {
        log.error("failed to execute ", e);
    }

    return result.getId();
}

From source file:org.meveo.service.job.JobInstanceService.java

public void execute(JobInstance entity) throws BusinessException {
    log.info("execute {}", entity.getJobTemplate());
    InitialContext ic;
    try {/*  w  w w.j a va  2  s  . com*/
        ic = new InitialContext();
        if (jobEntries.containsKey(entity.getJobCategoryEnum())) {
            HashMap<String, String> jobs = jobEntries.get(entity.getJobCategoryEnum());
            if (entity.isActive() && jobs.containsKey(entity.getJobTemplate())) {

                Job job = (Job) ic.lookup(jobs.get(entity.getJobTemplate()));

                User currentUser = userService
                        .attach(entity.getAuditable().getUpdater() != null ? entity.getAuditable().getUpdater()
                                : entity.getAuditable().getCreator());
                job.execute(entity, currentUser);
            }
        }
    } catch (NamingException e) {
        log.error("Failed to execute timerEntity job", e);
    }
}

From source file:org.jbpm.executor.impl.ExecutorImpl.java

/**
 * {@inheritDoc}//  w w  w  .  j av  a  2 s .  c om
 */
public void init() {
    if (!"true".equalsIgnoreCase(System.getProperty("org.kie.executor.disabled"))) {
        logger.info("Starting jBPM Executor Component ...\n" + " \t - Thread Pool Size: {}" + "\n"
                + " \t - Retries per Request: {}\n"
                + " \t - Load from storage interval: {} {} (if less or equal 0 only initial sync with storage) \n",
                threadPoolSize, retries, interval, timeunit.toString());

        scheduler = getScheduledExecutorService();

        if (useJMS) {
            try {
                InitialContext ctx = new InitialContext();
                if (this.connectionFactory == null) {
                    this.connectionFactory = (ConnectionFactory) ctx.lookup(connectionFactoryName);
                }
                if (this.queue == null) {
                    this.queue = (Queue) ctx.lookup(queueName);
                }
                logger.info("Executor JMS based support successfully activated on queue {}", queue);
            } catch (Exception e) {
                logger.warn(
                        "Disabling JMS support in executor because: unable to initialize JMS configuration for executor due to {}",
                        e.getMessage());
                logger.debug("JMS support executor failed due to {}", e.getMessage(), e);
                // since it cannot be initialized disable jms
                useJMS = false;
            }
        }

        LoadAndScheduleRequestsTask loadTask = new LoadAndScheduleRequestsTask(executorStoreService, scheduler,
                jobProcessor);
        if (interval <= 0) {
            scheduler.execute(loadTask);
        } else {
            logger.info("Interval ({}) is more than 0, scheduling periodic load of jobs from the storage",
                    interval);
            loadTaskFuture = scheduler.scheduleAtFixedRate(loadTask, 0, interval, timeunit);
        }
    } else {
        throw new ExecutorNotStartedException();
    }
}

From source file:com.ibm.soatf.component.jms.JmsComponent.java

private void resumeDestinationConsumption() {
    try {/*from   w  w w. j  a  va  2s.c  o m*/
        ProgressMonitor.init(2, "Connecting to queue...");
        queueName = jmsInterfaceConfig.getQueue().getJndiName();
        InitialContext ctx = getInitialContext(
                DEFAULT_PROTO + "://" + managedServer.getHostName() + ":" + managedServer.getPort(),
                adminServer.getSecurityPrincipal(), adminServer.getSecurityCredentials());
        //Queue queue = (Queue) ctx.lookup(queueName);
        Destination queue = (Destination) ctx.lookup(jmsInterfaceConfig.getQueue().getJndiName());
        weblogic.management.runtime.JMSDestinationRuntimeMBean destMBean = weblogic.jms.extensions.JMSRuntimeHelper
                .getJMSDestinationRuntimeMBean(ctx, queue);
        ProgressMonitor.increment("Resuming queue...");
        destMBean.resumeProduction();

        cor.markSuccessful();
        cor.addMsg(queueName + " queue active at " + managedServer.getHostName() + ":" + managedServer.getPort()
                + " production has been resumed.");
        /*
         cor.setOverallResultSuccess(false);
         cor.addMsg(queueName + " queue active at " + managedServer.getHostName() + ":" + managedServer.getPort() + " production pausing process finished ok, but the queue is not paused." 
         + "\nTry to restart the server.");
         */
    } catch (NamingException | JMSException ex) {
        cor.addMsg(queueName + " queue active at " + managedServer.getHostName() + ":" + managedServer.getPort()
                + " production pausing finished with exception:" + ex.getMessage());
        //throw new FrameworkExecutionException(ex);
    }
}

From source file:com.ibm.soatf.component.jms.JmsComponent.java

private void pauseDestinationProduction() {
    try {/*from   w  w  w.  j a v  a 2  s.c o  m*/
        ProgressMonitor.init(2, "Connecting to queue...");
        queueName = jmsInterfaceConfig.getQueue().getJndiName();
        InitialContext ctx = getInitialContext(
                DEFAULT_PROTO + "://" + managedServer.getHostName() + ":" + managedServer.getPort(),
                adminServer.getSecurityPrincipal(), adminServer.getSecurityCredentials());
        //Queue queue = (Queue) ctx.lookup(queueName);
        Destination queue = (Destination) ctx.lookup(jmsInterfaceConfig.getQueue().getJndiName());

        weblogic.management.runtime.JMSDestinationRuntimeMBean destMBean = weblogic.jms.extensions.JMSRuntimeHelper
                .getJMSDestinationRuntimeMBean(ctx, queue);
        ProgressMonitor.increment("Pausing queue...");
        destMBean.pauseProduction();
        if (destMBean.isProductionPaused()) {
            cor.markSuccessful();
            cor.addMsg(queueName + " queue active at " + managedServer.getHostName() + ":"
                    + managedServer.getPort() + " production has been paused.");
        } else {
            cor.addMsg(queueName + " queue active at " + managedServer.getHostName() + ":"
                    + managedServer.getPort()
                    + " production pausing process finished ok, but the queue is not paused."
                    + "\nTry to restart the server.");
        }
    } catch (NamingException | JMSException ex) {
        cor.addMsg(queueName + " queue active at " + managedServer.getHostName() + ":" + managedServer.getPort()
                + " production pausing finished with exception:" + ex.getMessage());

        //throw new FrameworkExecutionException(ex);
    }
}

From source file:ru.zinin.redis.session.RedisManager.java

@Override
protected void startInternal() throws LifecycleException {
    log.trace("EXEC startInternal();");

    sessionIdGenerator = new SessionIdGenerator();
    sessionIdGenerator.setJvmRoute(getJvmRoute());
    sessionIdGenerator.setSecureRandomAlgorithm(getSecureRandomAlgorithm());
    sessionIdGenerator.setSecureRandomClass(getSecureRandomClass());
    sessionIdGenerator.setSecureRandomProvider(getSecureRandomProvider());
    sessionIdGenerator.setSessionIdLength(getSessionIdLength());

    // Force initialization of the random number generator
    if (log.isDebugEnabled()) {
        log.debug("Force random number initialization starting");
    }/*from   ww  w  .j  av  a  2  s .com*/
    sessionIdGenerator.generateSessionId();
    if (log.isDebugEnabled()) {
        log.debug("Force random number initialization completed");
    }

    log.debug("Trying to get jedis pool from JNDI...");
    InitialContext initialContext = null;
    try {
        initialContext = new InitialContext();
        pool = (JedisPool) initialContext.lookup("java:/comp/env/" + jedisJndiName);
    } catch (NamingException e) {
        log.warn("JedisPool not found in JNDI");
    }

    log.debug("Pool from JNDI: " + pool);

    if (pool == null) {
        GenericObjectPool.Config config = new GenericObjectPool.Config();
        config.testOnBorrow = true;
        pool = new JedisPool(config, redisHostname, redisPort, redisTimeout, redisPassword);
    }

    if (!disableListeners) {
        Executors.newSingleThreadExecutor().execute(eventListenerThread);
    }

    setState(LifecycleState.STARTING);
}