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:dk.statsbiblioteket.util.XPropertiesTest.java

public void testEnvironment() throws Exception {
    new Properties(null);

    Properties sysProps = new Properties();
    sysProps.setProperty("XProperty:foo", "bar");
    sysProps.setProperty("XProperty:int", "87");
    sysProps.setProperty("XProperty:negative", "-43");
    sysProps.setProperty("XProperty:double", "12.13");
    sysProps.setProperty("XProperty:negdouble", "-14.0");
    sysProps.setProperty("XProperty:true", "true");
    sysProps.setProperty("XProperty:false", "false");
    sysProps.setProperty("XProperty:sub/int", "88");
    sysProps.setProperty("XProperty:uboat/deep/s", "flam");

    System.getProperties().putAll(sysProps);

    XProperties properties = new XProperties();

    assertEquals("Should contain imported sysprops", sysProps.size(), properties.size());

    assertEquals("Environment-specified Strings should work", "bar", properties.getString("foo"));
    assertEquals("Environment-specified ints should work", 87, properties.getInteger("int"));
    assertEquals("Environment-specified negative ints should work", -43, properties.getInteger("negative"));
    assertEquals("Environment-specified doubles should work", 12.13, properties.getDouble("double"));
    assertEquals("Environment-specified negative doubles should work", -14.0,
            properties.getDouble("negdouble"));
    assertEquals("Environment-specified true should work", true, properties.getBoolean("true"));
    assertEquals("Environment-specified false should work", false, properties.getBoolean("false"));
    assertEquals("Environment-specified subproperty should work", 88,
            properties.getSubProperty("sub").getInteger("int"));
    assertEquals("Environment-specified subsubproperty should work", "flam",
            properties.getSubProperty("uboat").getSubProperty("deep").getString("s"));

    // Clean up// w ww.  j av a 2  s . c  o m
    for (Object prop : sysProps.keySet()) {
        System.clearProperty((String) prop);
    }
    assertEquals("System XProperties was not cleaned up", 0, new XProperties().size());
}

From source file:de.huxhorn.lilith.swing.ApplicationPreferences.java

private Map<String, String> loadProperties(File file) {
    InputStream is = null;/*w w w  .j av  a 2  s.co  m*/
    try {
        is = new BufferedInputStream(new FileInputStream(file));
        Properties props = new Properties();
        props.load(is);
        Map<String, String> result = new HashMap<>();
        for (Object keyObj : props.keySet()) {
            String key = (String) keyObj;
            String value = (String) props.get(key);
            if (value != null) {
                result.put(key, value);
            }
        }
        return result;
    } catch (IOException e) {
        if (logger.isWarnEnabled())
            logger.warn("Couldn't load properties from '" + file.getAbsolutePath() + "'!", e);
    } finally {
        IOUtilities.closeQuietly(is);
    }
    return null;
}

From source file:dk.statsbiblioteket.util.XPropertiesTest.java

public void testException() throws Exception {
    Properties sysProps = new Properties();
    sysProps.setProperty("XProperty:foo", "bar");
    sysProps.setProperty("XProperty:int", "87");
    sysProps.setProperty("XProperty:negative", "-43");
    sysProps.setProperty("XProperty:true", "true");
    sysProps.setProperty("XProperty:false", "false");
    sysProps.setProperty("XProperty:sub/int", "88");
    sysProps.setProperty("XProperty:uboat/deep/s", "flam");

    System.getProperties().putAll(sysProps);

    XProperties properties = new XProperties();
    try {//from w  ww . jav  a2  s  .com
        properties.getBoolean("gnaf");
        Assert.fail("Getting non-existing  should throw an exception");
    } catch (NullPointerException e) {
        // Expected
    }
    try {
        properties.getChar("gnaf");
        Assert.fail("Getting non-existing char should throw an exception");
    } catch (NullPointerException e) {
        // Expected
    }
    try {
        properties.getDouble("gnaf");
        Assert.fail("Getting non-existing double should throw an exception");
    } catch (NullPointerException e) {
        // Expected
    }
    try {
        properties.getInteger("gnaf");
        Assert.fail("Getting non-existing int should throw an exception");
    } catch (NullPointerException e) {
        // Expected
    }
    try {
        properties.getString("gnaf");
        Assert.fail("Getting non-existing String should throw an exception");
    } catch (NullPointerException e) {
        // Expected
    }
    try {
        properties.getSubProperty("gnaf");
        Assert.fail("Getting non-existing sub-property should throw an exception");
    } catch (NullPointerException e) {
        // Expected
    }

    // Clean up
    for (Object prop : sysProps.keySet()) {
        System.clearProperty((String) prop);
    }
    assertEquals("System XProperties was not cleaned up", 0, new XProperties().size());
}

From source file:de.huxhorn.lilith.swing.ApplicationPreferences.java

/**
 * @param file the properties xml file/*w  ww .  j a  va  2s  .c o  m*/
 * @return the resulting map
 * @noinspection MismatchedQueryAndUpdateOfCollection
 */
private Map<String, String> loadPropertiesXml(File file) {
    InputStream is = null;
    try {
        is = new BufferedInputStream(new FileInputStream(file));
        Properties props = new Properties();
        props.loadFromXML(is);
        Map<String, String> result = new HashMap<>();
        for (Object keyObj : props.keySet()) {
            String key = (String) keyObj;
            String value = (String) props.get(key);
            if (value != null) {
                result.put(key, value);
            }
        }
        return result;
    } catch (IOException e) {
        if (logger.isWarnEnabled())
            logger.warn("Couldn't load properties from '" + file.getAbsolutePath() + "'!", e);
    } finally {
        IOUtilities.closeQuietly(is);
    }
    return null;
}

From source file:com.photon.phresco.framework.rest.api.ConfigurationService.java

private FeatureConfigure getPropTemplateFromConfigFile(String appDirName, String customerId,
        ServiceManager serviceManager, String featureName, String envName, String rootModulePath,
        String subModuleName) throws PhrescoException {
    List<PropertyTemplate> propertyTemplates = new ArrayList<PropertyTemplate>();
    try {//w w  w .  j a  va2s. c o m
        FeatureConfigure featureConfigure = new FeatureConfigure();
        FrameworkServiceUtil frameworkServiceUtil = new FrameworkServiceUtil();
        ProjectInfo projectInfo = Utility.getProjectInfo(rootModulePath, subModuleName);
        List<Configuration> featureConfigurations = frameworkServiceUtil
                .getApplicationProcessor(appDirName, customerId, serviceManager, rootModulePath, subModuleName)
                .preConfiguration(projectInfo.getAppInfos().get(0), featureName, envName);
        Properties properties = null;
        if (CollectionUtils.isNotEmpty(featureConfigurations)) {
            for (Configuration featureConfiguration : featureConfigurations) {
                properties = featureConfiguration.getProperties();
                Set<Object> keySet = properties.keySet();
                for (Object objectKey : keySet) {
                    String keyStr = (String) objectKey;
                    String dispName = keyStr.replace(".", " ");
                    PropertyTemplate propertyTemplate = new PropertyTemplate();
                    propertyTemplate.setKey(keyStr);
                    propertyTemplate.setName(dispName);
                    propertyTemplates.add(propertyTemplate);
                }
            }
        }
        featureConfigure.setHasCustomProperty(true);
        featureConfigure.setProperties(properties);
        featureConfigure.setPropertyTemplates(propertyTemplates);
        return featureConfigure;
    } catch (PhrescoException e) {
        throw new PhrescoException(e);
    }
}

From source file:JNLPAppletLauncher.java

private void updateDeploymentPropertiesImpl() {
    String userHome = System.getProperty("user.home");
    File dontAskFile = new File(userHome + File.separator + ".jnlp-applet" + File.separator + DONT_ASK);
    if (dontAskFile.exists())
        return; // User asked us not to prompt again

    int option = 0;

    if (!getBooleanParameter("noddraw.check.silent")) {
        option = JOptionPane.showOptionDialog(null,
                "For best robustness of OpenGL applets on Windows,\n"
                        + "we recommend disabling Java2D's use of DirectDraw.\n"
                        + "This setting will affect all applets, but is unlikely\n"
                        + "to slow other applets down significantly. May we update\n"
                        + "your deployment.properties to turn off DirectDraw for\n"
                        + "applets? You can change this back later if necessary\n"
                        + "using the Java Control Panel, Java tab, under Java\n" + "Applet Runtime Settings.",
                "Update deployment.properties?", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,
                null, new Object[] { "Yes", "No", "No, Don't Ask Again" }, "Yes");
    }/* www.j a  v a2 s .  c  o m*/

    if (option < 0 || option == 1)
        return; // No

    if (option == 2) {
        try {
            dontAskFile.createNewFile();
        } catch (IOException e) {
        }
        return; // No, Don't Ask Again
    }

    try {
        // Must update deployment.properties
        File propsDir = new File(getDeploymentPropsDir());
        if (!propsDir.exists()) {
            // Don't know what's going on or how to set this permanently
            return;
        }

        File propsFile = new File(propsDir, "deployment.properties");
        if (!propsFile.exists()) {
            // Don't know what's going on or how to set this permanently
            return;
        }

        Properties props = new Properties();
        InputStream input = new BufferedInputStream(new FileInputStream(propsFile));
        props.load(input);
        input.close();
        // Search through the keys looking for JRE versions
        Set/*<String>*/ jreVersions = new HashSet/*<String>*/();
        for (Iterator /*<String>*/ iter = props.keySet().iterator(); iter.hasNext();) {
            String key = (String) iter.next();
            if (key.startsWith(JRE_PREFIX)) {
                int idx = key.lastIndexOf(".");
                if (idx >= 0 && idx > JRE_PREFIX.length()) {
                    String jreVersion = key.substring(JRE_PREFIX.length(), idx);
                    jreVersions.add(jreVersion);
                }
            }
        }

        // Make sure the currently-running JRE shows up in this set to
        // avoid repeated displays of the dialog. It might not in some
        // upgrade scenarios where there was a pre-existing
        // deployment.properties and the new Java Control Panel hasn't
        // been run yet.
        jreVersions.add(System.getProperty("java.version"));

        // OK, now that we know all JRE versions covered by the
        // deployment.properties, check out the args for each and update
        // them
        for (Iterator /*<String>*/ iter = jreVersions.iterator(); iter.hasNext();) {
            String version = (String) iter.next();
            String argKey = JRE_PREFIX + version + ".args";
            String argVal = props.getProperty(argKey);
            if (argVal == null) {
                argVal = NODDRAW_PROP;
            } else if (argVal.indexOf(NODDRAW_PROP) < 0) {
                argVal = argVal + " " + NODDRAW_PROP;
            }
            props.setProperty(argKey, argVal);
        }

        OutputStream output = new BufferedOutputStream(new FileOutputStream(propsFile));
        props.store(output, null);
        output.close();

        if (!getBooleanParameter("noddraw.check.silent")) {
            // Tell user we're done
            JOptionPane.showMessageDialog(null, "For best robustness, we recommend you now exit and\n"
                    + "restart your web browser. (Note: clicking \"OK\" will\n" + "not exit your browser.)",
                    "Browser Restart Recommended", JOptionPane.INFORMATION_MESSAGE);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.adito.security.actions.SetPasswordAction.java

/**
 * @param mapping//from w w  w .ja v  a 2s.c  o  m
 * @param form
 * @param request
 * @param response
 * @return ActionForward
 * @throws Exception
 */
public ActionForward commit(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    SetPasswordForm setPasswordForm = (SetPasswordForm) form;
    User user = setPasswordForm.getUser();
    UserDatabase udb = UserDatabaseManager.getInstance()
            .getUserDatabase(getSessionInfo(request).getUser().getRealm());

    if (user == null) {
        user = (User) this.getSessionInfo(request).getHttpSession().getAttribute("newUser");
    }

    if (!udb.supportsPasswordChange()) {
        throw new Exception("Underlying database does not support changing of passwords.");
    }
    SessionInfo info = this.getSessionInfo(request);

    // Read in all of the confidential user attribute values

    /* BPS - Can only do this if the users key is currently loaded */

    Properties confidentialAttributes = new Properties();
    UserAttributes userAttributes = (UserAttributes) PropertyClassManager.getInstance()
            .getPropertyClass(UserAttributes.NAME);
    if ("automatic".equals(Property.getProperty(new SystemConfigKey("security.privateKeyMode")))
            && PublicKeyStore.getInstance().hasLoadedKey(user.getPrincipalName())) {
        for (PropertyDefinition def : userAttributes.getDefinitions()) {
            AttributeDefinition attrDef = (AttributeDefinition) def;
            if (attrDef.getVisibility() == AttributeDefinition.USER_CONFIDENTIAL_ATTRIBUTE) {
                String val = attrDef.getPropertyClass()
                        .retrieveProperty(new UserAttributeKey(user, def.getName()));
                if (val == null) {
                    val = def.getDefaultValue();
                }
                confidentialAttributes.setProperty(def.getName(), val);
            }
        }
    }

    try {

        char[] creds = LogonControllerFactory.getInstance().getPasswordFromCredentials(
                (AuthenticationScheme) request.getSession().getAttribute(Constants.AUTH_SESSION));

        if (creds == null) {
            HttpSession httpSession = getSessionInfo(request).getHttpSession();
            httpSession.setAttribute("newUser", user);
            // as the form will be reset, we need to store the current values to be used later
            httpSession.setAttribute(SetPasswordForm.SAVED_PASSWORD, setPasswordForm.getConfirmPassword());
            httpSession.setAttribute(SetPasswordForm.SAVED_FORCE_PASSWORD_CHANGE,
                    setPasswordForm.getForceChangePasswordAtLogon());
            String forwardTo = Util
                    .urlEncode(CoreUtil.addParameterToPath(request.getServletPath(), "action", "commit"));
            return new ActionForward("/promptForSessionPassword.do?forwardTo=" + forwardTo, false);
        }

        udb.setPassword(user.getPrincipalName(), setPasswordForm.getNewPassword(),
                setPasswordForm.getForceChangePasswordAtLogon(),
                LogonControllerFactory.getInstance().getUser(request), new String(creds));

        /* Only attempt to re-encrypt user attributes if users key is loaded */
        if ("automatic".equals(Property.getProperty(new SystemConfigKey("security.privateKeyMode")))) {
            if (PublicKeyStore.getInstance().hasLoadedKey(user.getPrincipalName())) {
                PublicKeyStore.getInstance().removeKeys(user.getPrincipalName());
                PublicKeyStore.getInstance().verifyPrivateKey(user.getPrincipalName(),
                        setPasswordForm.getNewPassword().toCharArray());
                for (Iterator i = confidentialAttributes.keySet().iterator(); i.hasNext();) {
                    String n = (String) i.next();
                    AttributeDefinition attrDef = (AttributeDefinition) userAttributes.getDefinition(n);
                    if (attrDef.getVisibility() == AttributeDefinition.USER_CONFIDENTIAL_ATTRIBUTE) {
                        Property.setProperty(new UserAttributeKey(user, n),
                                confidentialAttributes.getProperty(n), info);
                    }
                }
            }
        } else {
            PublicKeyStore.getInstance().removeCachedKeys(user.getPrincipalName());
        }

        CoreServlet.getServlet().fireCoreEvent(
                new CoreEvent(this, CoreEventConstants.CHANGE_PASSWORD, null, info, CoreEvent.STATE_SUCCESSFUL)
                        .addAttribute(CoreAttributeConstants.EVENT_ATTR_PRINCIPAL_ID, user.getPrincipalName()));
        return mapping.findForward("success");
    } catch (PasswordPolicyViolationException e) {
        saveError(request, "setPassword.error.doesNotMatchPolicy");
        return mapping.findForward("display");
    } catch (Exception e) {
        CoreServlet.getServlet()
                .fireCoreEvent(new CoreEvent(this, CoreEventConstants.CHANGE_PASSWORD, null, info,
                        CoreEvent.STATE_UNSUCCESSFUL).addAttribute(
                                CoreAttributeConstants.EVENT_ATTR_PRINCIPAL_ID, user.getPrincipalName()));
        throw e;
    } finally {
    }
}

From source file:edu.ku.brc.specify.Specify.java

/**
 * /*from www. j av  a  2s . c  o  m*/
 */
protected void importPrefs() {
    JFileChooser chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    String title = getResourceString("Specify.SELECT_FILE_OR_DIR");//$NON-NLS-1$
    if (chooser.showDialog(null, title) != JFileChooser.CANCEL_OPTION) {
        File destFile = chooser.getSelectedFile();

        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream(destFile));
            AppPreferences remotePrefs = AppPreferences.getRemote();

            for (Object key : properties.keySet()) {
                String keyStr = (String) key;
                remotePrefs.getProperties().put(keyStr, properties.get(key));
            }

        } catch (Exception ex) {
            log.error(ex); // XXX Error Dialog
        }

    } else {
        throw new NoSuchElementException("The External File Repository needs a valid directory."); //$NON-NLS-1$
    }
}

From source file:org.alfresco.bm.test.TestRun.java

/**
 * Called to ensure that the application context is started.
 * <p/>/* w  w w .  j a  v  a2 s .  c  o  m*/
 * Note that we only pull out the test and test run names at this point so that we don't end up
 * using stale data.
 */
private synchronized void start() {
    DBObject runObj = getRunObj(true);
    if (runObj == null) {
        // Nothing much we can do here
        return;
    }

    // Check the application context
    if (testRunCtx != null) {
        // There is nothing to do, the context is already available
        return;
    }

    // INFO logging as this is a critical part of the whole application
    if (logger.isInfoEnabled()) {
        logger.info("Starting test run application context: " + runObj);
    }

    ObjectId testObjId = (ObjectId) runObj.get(FIELD_TEST);
    ObjectId runObjId = (ObjectId) runObj.get(FIELD_ID);
    String run = (String) runObj.get(FIELD_NAME);
    // We need to build the test run FQN out of the test run details
    DBObject testObj = testDAO.getTest(testObjId, false);
    if (testObj == null) {
        logger.warn("The test associated with the test run has been removed: " + runObj);
        logger.warn("The test run will be stopped and deleted: " + id);
        stop();
        testDAO.deleteTestRun(id);
        return;
    }
    String test = (String) testObj.get(FIELD_NAME);
    String release = (String) testObj.get(FIELD_RELEASE);
    Integer schema = (Integer) testObj.get(FIELD_SCHEMA);
    String testRunFqn = test + "." + run;

    // Extract the current properties for the run
    Set<String> propsToMask = new HashSet<String>(7);
    Properties testRunProps = new Properties();
    {
        testRunProps.put(PROP_DRIVER_ID, driverId);
        testRunProps.put(PROP_TEST, test);
        testRunProps.put(PROP_TEST_RUN, run);
        testRunProps.put(PROP_TEST_RUN_ID, id.toString());
        testRunProps.put(PROP_TEST_RUN_FQN, testRunFqn);

        BasicDBList propObjs = (BasicDBList) runObj.get(FIELD_PROPERTIES);
        for (Object obj : propObjs) {
            DBObject propObj = (DBObject) obj;
            String propName = (String) propObj.get(FIELD_NAME);
            String propDef = (String) propObj.get(FIELD_DEFAULT);
            String propValue = (String) propObj.get(FIELD_VALUE);
            if (propValue == null) {
                propValue = propDef;
            }
            testRunProps.put(propName, propValue);
            // Check on the masking for later reporting
            boolean mask = Boolean.parseBoolean((String) propObj.get(FIELD_MASK));
            if (mask) {
                propsToMask.add(propName);
            }
        }
    }

    // Create the child application context WITHOUT AUTOSTART
    // TODO: This is hard coded to "config/spring/test-context.xml".  It should be one of the
    //       test definition properties and have the same as default.
    ClassPathXmlApplicationContext testRunCtx = new ClassPathXmlApplicationContext(
            new String[] { PATH_TEST_CONTEXT }, false);
    // When running stand-alone, there might not be a parent context
    if (parentCtx != null) {
        testRunCtx.setParent(parentCtx);
    }
    // Push cluster properties into the context (must be done AFTER setting parent context)
    ConfigurableEnvironment ctxEnv = testRunCtx.getEnvironment();
    ctxEnv.getPropertySources().addFirst(new PropertiesPropertySource("run-props", testRunProps));
    ctxEnv.getPropertySources().addFirst(new PropertiesPropertySource("system-props", System.getProperties()));

    // Complete logging of what is going to be used for the test
    if (logger.isInfoEnabled()) {
        String nl = "\n";
        StringBuilder sb = new StringBuilder(1024);
        sb.append("Test run application context starting: ").append(nl).append("   Run ID:       ").append(id)
                .append(nl).append("   Test Name:    ").append(test).append(nl).append("   Run Name:     ")
                .append(run).append(nl).append("   Driver ID:    ").append(driverId).append(nl)
                .append("   Release:      ").append(release).append(nl).append("   Schema:       ")
                .append(schema).append(nl).append("   Test Run Properties:   ").append(nl);
        for (Object propNameObj : testRunProps.keySet()) {
            String propName = (String) propNameObj;
            String propValue = testRunProps.getProperty(propName);
            if (propsToMask.contains(propName) || propName.toLowerCase().contains("username")
                    || propName.toLowerCase().contains("password")) {
                propValue = MASK;
            }
            sb.append("      ").append(propName).append("=").append(propValue).append(nl);
        }
        sb.append("   System Properties:   ").append(nl);
        for (Object propNameObj : System.getProperties().keySet()) {
            String propName = (String) propNameObj;
            String propValue = System.getProperty(propName);
            if (propsToMask.contains(propName) || propName.toLowerCase().contains("username")
                    || propName.toLowerCase().contains("password")) {
                propValue = MASK;
            }
            sb.append("      ").append(propName).append("=").append(propValue).append(nl);
        }
        logger.info(sb);
    }

    // Now refresh (to load beans) and start
    try {
        this.testRunCtx = testRunCtx;
        // 2015-08-04 fkbecker: store definitions first - for refresh() or start() may fail, too. 
        this.test = test;
        this.run = run;
        this.release = release;
        this.schema = schema;

        testRunCtx.refresh();
        testRunCtx.start();

        // Make sure that the required components are present and of the correct type
        // There may be multiple beans of the type, so we have to use the specific bean name.
        @SuppressWarnings("unused")
        CompletionEstimator estimator = (CompletionEstimator) testRunCtx.getBean("completionEstimator");
        @SuppressWarnings("unused")
        EventProcessor startEventProcessor = (EventProcessor) testRunCtx.getBean("event.start");

        // Register the driver with the test run
        testDAO.addTestRunDriver(runObjId, driverId);

        // Log the successful startup
        logService.log(driverId, test, run, LogLevel.INFO,
                "Successful startup of test run '" + testRunFqn + "'.");
    } catch (Exception e) {
        /*
        Throwable root = ExceptionUtils.getRootCause(e);
        if (root != null && (root instanceof MongoException || root instanceof IOException))
        {
        // 2015-08-04 fkbecker IOException also thrown by FTP file service if host not reachable ...
        // FIXME 
                
        String msg1 = "Failed to start test run application '" + testRunFqn + "': " + e.getCause().getMessage();
        //String msg2 = "Set the test run property '" + PROP_MONGO_TEST_HOST + "' (<server>:<port>) as required.";
        // We deal with this specifically as it's a simple case of not finding the MongoDB
        logger.error(msg1);
        //logger.error(msg2);
        logService.log(driverId, test, run, LogLevel.ERROR, msg1);
        //logService.log(driverId, test, run, LogLevel.ERROR, msg2);
        }
        else
        {*/
        String stack = ExceptionUtils.getStackTrace(e);
        logger.error("Failed to start test run application '" + testRunFqn + "': ", e);
        String error = "Failed to start test run application '" + testRunFqn + ". \r\n" + stack;
        logService.log(driverId, test, run, LogLevel.ERROR, error);
        //}
        stop();
    }
}

From source file:org.apache.geode.distributed.internal.DistributionConfigImpl.java

/**
 * For every key in p mark it as being from the given source.
 *///from  www .ja v  a 2s .  c o m
private void setSource(Properties p, ConfigSource source) {
    if (source == null) {
        throw new IllegalArgumentException("Valid ConfigSource must be specified instead of null.");
    }
    for (Object k : p.keySet()) {
        this.sourceMap.put((String) k, source);
    }
}