Example usage for java.util Properties keySet

List of usage examples for java.util Properties keySet

Introduction

In this page you can find the example usage for java.util Properties keySet.

Prototype

@Override
    public Set<Object> keySet() 

Source Link

Usage

From source file:com.ms.commons.test.classloader.util.SimpleAntxLoader.java

protected List<String> getSvnUrlList(Properties p) {
    List<String> svnUrlList = new ArrayList<String>();
    String mark = p.getProperty(ANTX_PROPERTIES);
    if (StringUtils.trimToNull(mark) == null) {
        mark = ANTX_PROPERTIES_DEFAULT;/*from   w  ww. j ava2 s . c  o  m*/
    }
    if (StringUtils.isNotBlank(mark)) {
        String plusMark = ANTX_PROPERTIES + "." + StringUtils.trim(mark);

        for (Object key : p.keySet()) {
            String k = (key == null) ? "" : key.toString();
            if (k.startsWith(plusMark)) {
                String svnUrl = StringUtils.trimToNull(p.getProperty(k));
                svnUrlList.add(svnUrl);
            }
        }
    }
    if (!svnUrlList.isEmpty()) {
        System.err.println("Load svn urls: " + svnUrlList);
    }
    return svnUrlList;
}

From source file:ca.uhn.fhir.tinder.ant.TinderGeneratorTask.java

@Override
public void execute() throws BuildException {
    validateAttributes();//ww  w  .j  a v a 2s . c o m

    try {

        if (baseResourceNames == null || baseResourceNames.isEmpty()) {
            baseResourceNames = new ArrayList<String>();

            log("No resource names supplied, going to use all resources from version: "
                    + fhirContext.getVersion().getVersion());

            Properties p = new Properties();
            try {
                p.load(fhirContext.getVersion().getFhirVersionPropertiesFile());
            } catch (IOException e) {
                throw new BuildException("Failed to load version property file", e);
            }

            if (verbose) {
                log("Property file contains: " + p);
            }

            for (Object next : p.keySet()) {
                if (((String) next).startsWith("resource.")) {
                    baseResourceNames.add(((String) next).substring("resource.".length()).toLowerCase());
                }
            }
        } else {
            for (int i = 0; i < baseResourceNames.size(); i++) {
                baseResourceNames.set(i, baseResourceNames.get(i).toLowerCase());
            }
        }

        if (excludeResourceNames != null) {
            for (int i = 0; i < excludeResourceNames.size(); i++) {
                baseResourceNames.remove(excludeResourceNames.get(i).toLowerCase());
            }
        }

        log("Including the following resources: " + baseResourceNames);

        ResourceGeneratorUsingSpreadsheet gen = new ResourceGeneratorUsingSpreadsheet(version, projectHome);
        gen.setBaseResourceNames(baseResourceNames);

        try {
            gen.parse();

            //            gen.setFilenameSuffix("ResourceProvider");
            //            gen.setTemplate("/vm/jpa_daos.vm");
            //            gen.writeAll(packageDirectoryBase, null,packageBase);

            // gen.setFilenameSuffix("ResourceTable");
            // gen.setTemplate("/vm/jpa_resource_table.vm");
            // gen.writeAll(directoryBase, packageBase);

        } catch (Exception e) {
            throw new BuildException("Failed to parse FHIR metadata", e);
        }

        try {
            VelocityContext ctx = new VelocityContext();
            ctx.put("resources", gen.getResources());
            ctx.put("packageBase", packageBase);
            ctx.put("targetPackage", targetPackage);
            ctx.put("version", version);
            ctx.put("esc", new EscapeTool());

            String capitalize = WordUtils.capitalize(version);
            if ("Dstu".equals(capitalize)) {
                capitalize = "Dstu1";
            }
            ctx.put("versionCapitalized", capitalize);

            VelocityEngine v = new VelocityEngine();
            v.setProperty("resource.loader", "cp");
            v.setProperty("cp.resource.loader.class",
                    "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
            v.setProperty("runtime.references.strict", Boolean.TRUE);

            targetDirectoryFile.mkdirs();

            if (targetFile != null) {
                InputStream templateIs = null;
                if (templateFileFile != null) {
                    templateIs = new FileInputStream(templateFileFile);
                } else {
                    templateIs = ResourceGeneratorUsingSpreadsheet.class.getResourceAsStream(template);
                }
                InputStreamReader templateReader = new InputStreamReader(templateIs);

                File target = null;
                if (targetPackage != null) {
                    target = new File(targetDir, targetPackage.replace('.', File.separatorChar));
                } else {
                    target = new File(targetDir);
                }
                target.mkdirs();
                File f = new File(target, targetFile);
                OutputStreamWriter w = new OutputStreamWriter(new FileOutputStream(f, false), "UTF-8");

                v.evaluate(ctx, w, "", templateReader);
                w.close();

            } else {
                File packageDirectoryBase = new File(targetDir,
                        packageBase.replace(".", File.separatorChar + ""));
                packageDirectoryBase.mkdirs();

                gen.setFilenameSuffix(targetClassSuffix);
                gen.setTemplate(template);
                gen.setTemplateFile(templateFileFile);
                gen.writeAll(packageDirectoryBase, null, packageBase);

            }

        } catch (Exception e) {
            log("Caught exception: " + e.getClass().getName() + " [" + e.getMessage() + "]", 1);
            e.printStackTrace();
            throw new BuildException("Failed to generate file(s)", e);
        }

        cleanup();

    } catch (Exception e) {
        if (e instanceof BuildException) {
            throw (BuildException) e;
        }
        log("Caught exception: " + e.getClass().getName() + " [" + e.getMessage() + "]", 1);
        e.printStackTrace();
        throw new BuildException("Error processing " + getTaskName() + " task.", e);
    }
}

From source file:org.apache.wiki.providers.VersioningFileProvider.java

/**
 *  Goes through the repository and decides which version is
 *  the newest one in that directory.//  ww  w .  j a v  a 2  s .  c  o  m
 *
 *  @return Latest version number in the repository, or -1, if
 *          there is no page in the repository.
 */

// FIXME: This is relatively slow.
/*
private int findLatestVersion( String page )
{
File pageDir = findOldPageDir( page );
        
String[] pages = pageDir.list( new WikiFileFilter() );
        
if( pages == null )
{
    return -1; // No such thing found.
}
        
int version = -1;
        
for( int i = 0; i < pages.length; i++ )
{
    int cutpoint = pages[i].indexOf( '.' );
    if( cutpoint > 0 )
    {
        String pageNum = pages[i].substring( 0, cutpoint );
        
        try
        {
            int res = Integer.parseInt( pageNum );
        
            if( res > version )
            {
                version = res;
            }
        }
        catch( NumberFormatException e ) {} // It's okay to skip these.
    }
}
        
return version;
}
*/
private int findLatestVersion(String page) {
    int version = -1;

    try {
        Properties props = getPageProperties(page);

        for (Iterator i = props.keySet().iterator(); i.hasNext();) {
            String key = (String) i.next();

            if (key.endsWith(".author")) {
                int cutpoint = key.indexOf('.');
                if (cutpoint > 0) {
                    String pageNum = key.substring(0, cutpoint);

                    try {
                        int res = Integer.parseInt(pageNum);

                        if (res > version) {
                            version = res;
                        }
                    } catch (NumberFormatException e) {
                    } // It's okay to skip these. 
                }
            }
        }
    } catch (IOException e) {
        log.error("Unable to figure out latest version - dying...", e);
    }

    return version;
}

From source file:InstallJars.java

/**
 * Install based on a properties file<br>
 * /* www.j a  v  a  2  s  .c o m*/
 * @return recommended classpath
 * @exception IOException
 *              Thrown if a JAR file access error occurs
 */
public String install() throws IOException {
    StringBuffer classpath = new StringBuffer();
    Properties prop = new Properties();
    prop.load(new BufferedInputStream(new FileInputStream(propFilename)));
    for (Iterator i = prop.keySet().iterator(); i.hasNext();) {
        String key = (String) i.next();
        String value = prop.getProperty(key);
        String xurl = null;
        String xdir = null;
        String xcp = null;
        boolean xexpand = expand, xrun = run;
        if (value != null) {
            value = value.trim();
            if (value.length() > 0) {
                String delim = value.substring(0, 1);
                StringTokenizer st = new StringTokenizer(value.substring(1), delim);
                xurl = st.nextToken();
                xdir = (st.hasMoreTokens() ? st.nextToken() : ".").trim();
                if (xdir.length() == 0) {
                    xdir = ".";
                }
                xcp = (st.hasMoreTokens() ? st.nextToken() : xdir).trim();
                if (xcp.length() == 0) {
                    xcp = xdir;
                }
                classpath.append(xcp);
                classpath.append(";");
                while (st.hasMoreTokens()) {
                    String xoption = st.nextToken().trim();
                    if (xoption.equalsIgnoreCase("expand")) {
                        xexpand = true;
                    } else if (xoption.equalsIgnoreCase("noexpand")) {
                        xexpand = false;
                    } else if (xoption.equalsIgnoreCase("run")) {
                        xrun = true;
                    } else if (xoption.equalsIgnoreCase("norun")) {
                        xrun = false;
                    } else {
                        throw new IllegalArgumentException("invalid install property - " + key + "=" + value);
                    }
                }
            }
        }
        if (xurl == null || xurl.length() == 0) {
            throw new IllegalArgumentException("missing install property - " + key + "=" + value);
        }
        System.out.print("\nInstalling " + key);
        if (verbose) {
            System.out.print(" using URL=" + xurl + "; target=" + xdir + "; classpath=" + xcp + "; "
                    + (xexpand ? "expand" : "noexpand") + "; " + (xrun ? "run" : "norun"));
        }
        System.out.println("...");
        installFile(xurl, xdir, xexpand, xrun);
    }
    return classpath.toString();
}

From source file:freemind.controller.Controller.java

/**
 * @param listener The new listener. All currently available properties are sent to
 * the listener after registration. Here, the oldValue parameter is set to null.
 *///from   w  w w  .  j  a  v  a  2  s.  c  o m
public static void addPropertyChangeListenerAndPropagate(FreemindPropertyListener listener) {
    Controller.addPropertyChangeListener(listener);
    Properties properties = Resources.getInstance().getProperties();
    for (Iterator it = properties.keySet().iterator(); it.hasNext();) {
        String key = (String) it.next();
        listener.propertyChanged(key, properties.getProperty(key), null);
    }
}

From source file:com.edgenius.wiki.installation.SilenceInstall.java

/**
 * @param silence/*  www .  j  av  a 2s.c  o m*/
 * @param server
 * @param global
 * @param install
 * @throws IllegalAccessException 
 * @throws IllegalArgumentException 
 * @throws NumberFormatException 
 * @throws InvocationTargetException 
 */
private void sync(Properties prop, Server server, GlobalSetting global, Installation install)
        throws NumberFormatException, IllegalArgumentException, IllegalAccessException,
        InvocationTargetException {
    //AUTO detect country and timezone if properties file not set.
    if (StringUtils.isBlank(prop.getProperty("defaultCountry"))) {
        prop.setProperty("defaultCountry", Locale.getDefault().getCountry());
    }
    if (StringUtils.isBlank(prop.getProperty("defaultTimeZone"))) {
        prop.setProperty("defaultTimeZone", TimeZone.getDefault().getID());
    }
    for (Iterator<Object> iter = prop.keySet().iterator(); iter.hasNext();) {
        String key = (String) iter.next();
        if (DEFAULT_KEYS.contains(key))
            continue;

        Object obj = null;
        if (serverFields.contains(key)) {
            obj = server;
        } else if (globalFields.contains(key)) {
            obj = global;
        } else if (installFields.contains(key)) {
            obj = install;
        }
        if (obj == null) {
            log.warn(
                    "Invalid field name {} cann't find in any configuration files - could only configuration option for silence installation",
                    key);
            continue;
        }
        BeanUtils.setProperty(obj, key, getProperty(prop, key));
    }

}

From source file:com.foilen.smalltools.spring.messagesource.UsageMonitoringMessageSource.java

private void init() {

    // Check the base folder
    File basenameFile = new File(basename);
    logger.info("Base name is {}", basename);
    File directory = basenameFile.getParentFile();
    logger.info("Base directory is {}", directory.getAbsoluteFile());
    if (!directory.exists()) {
        throw new SmallToolsException("Directory: " + directory.getAbsolutePath() + " does not exists");
    }//ww  w  .j av  a2  s.  co m

    tmpUsed = new File(directory.getAbsolutePath() + File.separatorChar + "_messages_usage.txt");

    // Check the files in it
    String startswith = basenameFile.getName() + "_";
    String endswith = ".properties";
    for (File file : directory.listFiles(
            (FilenameFilter) (dir, name) -> name.startsWith(startswith) && name.endsWith(endswith))) {
        // Create the locale
        logger.info("Found messages file {}", directory.getAbsoluteFile());
        String filename = file.getName();
        String localePart = filename.substring(startswith.length(), filename.length() - endswith.length());
        Locale locale = new Locale(localePart);
        logger.info("Locale is {} -> {}", localePart, locale);
        filePerLocale.put(locale, file);

        // Load the file
        Properties properties = new Properties();
        try (FileInputStream inputStream = new FileInputStream(file)) {
            properties.load(new InputStreamReader(inputStream, CharsetTools.UTF_8));
        } catch (IOException e) {
            logger.error("Problem reading the property file {}", file.getAbsoluteFile(), e);
            throw new SmallToolsException("Problem reading the file", e);
        }

        // Check codes and save values
        Map<String, String> messages = new HashMap<>();
        messagesPerLocale.put(locale, messages);
        for (Object key : properties.keySet()) {
            String name = (String) key;
            String value = properties.getProperty(name);
            allCodesInFiles.add(name);
            messages.put(name, value);
        }

    }

    // Add missing codes in all the maps (copy one that has it)
    for (Locale locale : filePerLocale.keySet()) {
        Set<String> missingCodes = new HashSet<>();
        Map<String, String> messagesForCurrentLocale = messagesPerLocale.get(locale);

        // Get the ones missing
        missingCodes.addAll(allCodesInFiles);
        missingCodes.removeAll(messagesForCurrentLocale.keySet());

        for (String missingCode : missingCodes) {
            logger.info("Locale {} was missing code {}", locale, missingCode);

            String codeValue = findAnyValue(missingCode);
            messagesForCurrentLocale.put(missingCode, codeValue);
        }
    }

    // Load the already known codes
    if (tmpUsed.exists()) {
        for (String line : FileTools.readFileLinesIteration(tmpUsed.getAbsolutePath())) {
            knownUsedCodes.add(line);
        }
    }

    smoothTrigger = new SmoothTrigger(() -> {

        synchronized (lock) {

            logger.info("Begin saving locale files");

            // Go through each locale
            for (Entry<Locale, File> entry : filePerLocale.entrySet()) {
                Map<String, String> messages = messagesPerLocale.get(entry.getKey());

                try (PrintWriter printWriter = new PrintWriter(entry.getValue(),
                        CharsetTools.UTF_8.toString())) {

                    // Save the known used (sorted) at the top
                    for (String code : knownUsedCodes.stream().sorted(String.CASE_INSENSITIVE_ORDER)
                            .collect(Collectors.toList())) {
                        printWriter.println(code + "=" + messages.get(code));
                    }
                    printWriter.println();

                    // Save the others (sorted) at the bottom
                    Set<String> unknownCodes = new HashSet<>();
                    unknownCodes.addAll(messages.keySet());
                    unknownCodes.removeAll(knownUsedCodes);
                    if (!unknownCodes.isEmpty()) {
                        printWriter.println("# Unknown");
                        printWriter.println();

                        for (String code : unknownCodes.stream().sorted(String.CASE_INSENSITIVE_ORDER)
                                .collect(Collectors.toList())) {
                            printWriter.println(code + "=" + messages.get(code));
                        }
                        printWriter.println();
                    }
                } catch (Exception e) {
                    logger.error("Could not write the file", e);
                }
            }

            // Save the known
            FileTools.writeFile(Joiner.on('\n').join(
                    knownUsedCodes.stream().sorted(String.CASE_INSENSITIVE_ORDER).collect(Collectors.toList())),
                    tmpUsed);

            logger.info("Done saving locale files");
        }

    }) //
            .setDelayAfterLastTriggerMs(5000) //
            .setMaxDelayAfterFirstRequestMs(10000) //
            .setFirstPassThrough(true) //
            .start();

    smoothTrigger.request();
}

From source file:org.kaaproject.kaa.sandbox.web.services.SandboxServiceImpl.java

@Override
public void afterPropertiesSet() throws Exception {
    try {/*from   w  w w  .j  av  a2 s  .co  m*/

        LOG.info("Initializing Sandbox Service...");
        LOG.info("sandboxHome [{}]", Environment.getServerHomeDir());
        LOG.info("guiChangeHostEnabled [{}]", guiChangeHostEnabled);
        LOG.info("kaaNodeWebPort [{}]", kaaNodeWebPort);
        LOG.info("enableAnalytics [{}]", enableAnalytics);

        prepareAnalytics();

        JAXBContext jc = JAXBContext.newInstance("org.kaaproject.kaa.examples.common.projects");
        Unmarshaller unmarshaller = jc.createUnmarshaller();

        String demoProjectsXmlFile = Environment.getServerHomeDir() + "/" + DEMO_PROJECTS_FOLDER + "/"
                + DEMO_PROJECTS_XML_FILE;

        ProjectsConfig projectsConfig = (ProjectsConfig) unmarshaller.unmarshal(new File(demoProjectsXmlFile));
        for (Project project : projectsConfig.getProjects()) {
            projectsMap.put(project.getId(), project);
            LOG.info("Demo project: id [{}] name [{}]", project.getId(), project.getName());
        }
        for (Bundle bundle : projectsConfig.getBundles()) {
            bundlesMap.put(bundle.getId(), bundle);
            LOG.info("Demo projects bundle: id [{}] name [{}]", bundle.getId(), bundle.getName());
        }

        if (sandboxEnv == null) {
            Properties sandboxEnvProperties = org.kaaproject.kaa.server.common.utils.FileUtils
                    .readResourceProperties(SANDBOX_ENV_FILE);

            sandboxEnv = new String[sandboxEnvProperties.size()];
            int i = 0;
            for (Object key : sandboxEnvProperties.keySet()) {
                String keyValue = key + "=" + sandboxEnvProperties.getProperty(key.toString());
                sandboxEnv[i++] = keyValue;
                LOG.info("Sandbox env: [{}]", keyValue);
            }
        }
        LOG.info("Initialized Sandbox Service.");
    } catch (JAXBException e) {
        LOG.error("Unable to initialize Sandbox Service", e);
        throw e;
    }
}

From source file:podd.util.WebappInitializationUtil.java

private User createRepoAdminUser(Resource resource) {
    try {//from  w  ww.java2 s  .  c om
        File propertyFile = resource.getFile();
        final FileReader fileReader = new FileReader(propertyFile);
        Properties properties = new Properties();
        properties.load(fileReader);

        // try to load the user and if it doesn't exist create a new one
        String username = properties.get(USERNAME_KEY).toString();
        User admin = userDao.loadByUserName(username);
        if (null == admin) {
            admin = entityFactory.createUser(null);
        }
        // add properties to the user
        for (Object key : properties.keySet()) {
            final String value = properties.get(key).toString();
            String methodName = getSetterMethodName((String) key);
            final Method method = User.class.getDeclaredMethod(methodName, String.class);
            method.invoke(admin, value);
        }
        admin.setStatus(ACTIVE);
        admin.setRepositoryRole(rrDao.getRepositoryRole(REPOSITORY_ADMINISTRATOR.getName()));
        LOGGER.info("Creating repository administrator user: " + admin.getUserName());
        userDao.saveOrUpdate(admin);
        return admin;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:podd.util.WebappInitialisationUtil.java

private User createRepoAdminUser(Resource resource) {
    try {/*from w  ww  . j  av a 2s.  com*/
        File propertyFile = resource.getFile();
        final FileReader fileReader = new FileReader(propertyFile);
        Properties properties = new Properties();
        properties.load(fileReader);

        // try to load the user and if it doesn't exist create a new one
        String username = properties.get(USERNAME_KEY).toString();
        User admin = userDao.loadByUserName(username);
        if (null == admin) {
            admin = entityFactory.createUser(null);
        }
        // add properties to the user
        for (Object key : properties.keySet()) {
            final String value = properties.get(key).toString();
            String methodName = getSetterMethodName((String) key);
            final Method method = User.class.getDeclaredMethod(methodName, String.class);
            method.invoke(admin, value);
        }
        admin.setStatus(ACTIVE);
        admin.setRepositoryRole(rrDao.getRepositoryRole(RepositoryRole.REPOSITORY_ADMINISTRATOR.getName()));
        logger.info("Creating repository administrator user: " + admin.getUserName());
        userDao.saveOrUpdate(admin);
        return admin;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}