Example usage for java.util Properties stringPropertyNames

List of usage examples for java.util Properties stringPropertyNames

Introduction

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

Prototype

public Set<String> stringPropertyNames() 

Source Link

Document

Returns an unmodifiable set of keys from this property list where the key and its corresponding value are strings, including distinct keys in the default property list if a key of the same name has not already been found from the main properties list.

Usage

From source file:org.nuxeo.runtime.deployment.preprocessor.DeploymentPreprocessor.java

protected void initContextProperties(CommandContext ctx) {
    ConfigurationGenerator confGen = new ConfigurationGenerator();
    confGen.init();// w w w  .j av a2s.c  o  m
    Properties props = confGen.getUserConfig();
    for (String key : props.stringPropertyNames()) {
        ctx.put(key, props.getProperty(key));
    }
}

From source file:com.cloudera.cdk.maven.plugins.WorkflowXmlWriter.java

private void appendJavaAction(XMLWriter writer, Workflow workflow) throws MojoExecutionException {
    Properties hadoopConfiguration = workflow.getHadoopConfiguration();

    writer.startElement("action");
    writer.addAttribute("name", "java-node");

    writer.startElement("java");
    doWriteElement(writer, "job-tracker", "${" + AbstractAppMojo.JOBTRACKER_PROPERTY + "}");
    doWriteElement(writer, "name-node", "${" + AbstractAppMojo.NAMENODE_PROPERTY + "}");
    doWriteElement(writer, "main-class", workflow.getToolClass());
    for (String key : hadoopConfiguration.stringPropertyNames()) {
        String value = hadoopConfiguration.getProperty(key);
        doWriteElement(writer, "arg", "-D");
        doWriteElement(writer, "arg", key + "=" + value);
    }/*from   ww w  . j  a v  a 2s  .  c om*/
    if (!workflow.getLibJars().isEmpty()) {
        doWriteElement(writer, "arg", "-libjars");
        doWriteElement(writer, "arg", Joiner.on(',').join(workflow.getLibJars()));
    }
    String[] args = workflow.getArgs();
    if (args != null) {
        for (String arg : args) {
            doWriteElement(writer, "arg", arg);
        }
    }
    writer.endElement();

    doWriteElement(writer, "ok", "to", "end");
    doWriteElement(writer, "error", "to", "fail");

    writer.endElement();
}

From source file:net.lunikon.rethul.service.FileService.java

/**
 * Loads a language file and writes its content to the corresponding file in
 * rethul. Only keys are imported that are also defined by the master. All
 * imported strings are marked as "pending".
 * //from   ww w.  jav  a2 s. com
 * @param file
 *            The file.
 * @param locale
 *            The locale.
 */
public void reload(File file, Locale locale) {
    // first, load master keys
    Set<String> masterKeys = stringsDAO.loadMasterKeySet(file);

    // load properties from file
    Properties props = new Properties();
    try {
        String path = FileStatus.getLanguageFilePath(file, locale);
        FileInputStream is = new FileInputStream(path);
        props.load(is);
        is.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    // add all values that exist in master
    for (String key : props.stringPropertyNames()) {
        if (!masterKeys.contains(key))
            continue;

        String value = props.getProperty(key);

        LocalizedString ls = new LocalizedString(file, key, value);
        ls.setLocale(locale);
        ls.setPending(true);
        stringsDAO.save(ls);
    }
}

From source file:io.druid.guice.JsonConfigurator.java

public <T> T configurate(Properties props, String propertyPrefix, Class<T> clazz) throws ProvisionException {
    verifyClazzIsConfigurable(clazz);/*from   w  w w.j a  v  a 2  s.c  om*/

    // Make it end with a period so we only include properties with sub-object thingies.
    final String propertyBase = propertyPrefix.endsWith(".") ? propertyPrefix : propertyPrefix + ".";

    Map<String, Object> jsonMap = Maps.newHashMap();
    for (String prop : props.stringPropertyNames()) {
        if (prop.startsWith(propertyBase)) {
            final String propValue = props.getProperty(prop);
            Object value;
            try {
                // If it's a String Jackson wants it to be quoted, so check if it's not an object or array and quote.
                String modifiedPropValue = propValue;
                if (!(modifiedPropValue.startsWith("[") || modifiedPropValue.startsWith("{"))) {
                    modifiedPropValue = String.format("\"%s\"", modifiedPropValue);
                }
                value = jsonMapper.readValue(modifiedPropValue, Object.class);
            } catch (IOException e) {
                log.info(e, "Unable to parse [%s]=[%s] as a json object, using as is.", prop, propValue);
                value = propValue;
            }

            jsonMap.put(prop.substring(propertyBase.length()), value);
        }
    }

    final T config;
    try {
        config = jsonMapper.convertValue(jsonMap, clazz);
    } catch (IllegalArgumentException e) {
        throw new ProvisionException(
                String.format("Problem parsing object at prefix[%s]: %s.", propertyPrefix, e.getMessage()), e);
    }

    final Set<ConstraintViolation<T>> violations = validator.validate(config);
    if (!violations.isEmpty()) {
        List<String> messages = Lists.newArrayList();

        for (ConstraintViolation<T> violation : violations) {
            String path = "";
            try {
                Class<?> beanClazz = violation.getRootBeanClass();
                final Iterator<Path.Node> iter = violation.getPropertyPath().iterator();
                while (iter.hasNext()) {
                    Path.Node next = iter.next();
                    if (next.getKind() == ElementKind.PROPERTY) {
                        final String fieldName = next.getName();
                        final Field theField = beanClazz.getDeclaredField(fieldName);

                        if (theField.getAnnotation(JacksonInject.class) != null) {
                            path = String.format(" -- Injected field[%s] not bound!?", fieldName);
                            break;
                        }

                        JsonProperty annotation = theField.getAnnotation(JsonProperty.class);
                        final boolean noAnnotationValue = annotation == null
                                || Strings.isNullOrEmpty(annotation.value());
                        final String pathPart = noAnnotationValue ? fieldName : annotation.value();
                        if (path.isEmpty()) {
                            path += pathPart;
                        } else {
                            path += "." + pathPart;
                        }
                    }
                }
            } catch (NoSuchFieldException e) {
                throw Throwables.propagate(e);
            }

            messages.add(String.format("%s - %s", path, violation.getMessage()));
        }

        throw new ProvisionException(Iterables.transform(messages, new Function<String, Message>() {
            @Nullable
            @Override
            public Message apply(@Nullable String input) {
                return new Message(String.format("%s%s", propertyBase, input));
            }
        }));
    }

    log.info("Loaded class[%s] from props[%s] as [%s]", clazz, propertyBase, config);

    return config;
}

From source file:de.codesourcery.eve.skills.ui.config.AppConfig.java

public void load() throws IOException {

    log.debug("load(): Loading app config from " + file);

    if (file.exists()) {
        final Properties props = new Properties();
        final Reader instream = new FileReader(file);
        try {//  w w  w  .  j a  va2s.  c o m
            props.load(instream);
            clear();
            setDefaults();
            for (String key : props.stringPropertyNames()) {
                put(key, (String) props.get(key));
            }
        } finally {
            instream.close();
        }
    }
}

From source file:com.izforge.izpack.util.LogUtils.java

public static void loadConfiguration(final Properties configuration) throws IOException {
    if (OVERRIDE) {
        LogManager manager = LogManager.getLogManager();

        // Merge global logging properties
        InputStream baseResourceStream = null;
        try {//from  www . j av a2 s.c  o  m
            baseResourceStream = LogUtils.class.getResourceAsStream(LOGGING_BASE_CONFIGURATION);
            final Properties baseProps = new Properties();
            baseProps.load(baseResourceStream);
            mergeLoggingConfiguration(configuration, baseProps);
        } finally {
            IOUtils.closeQuietly(baseResourceStream);
        }

        boolean mkdirs = false;
        String pattern = null;
        if (configuration.getProperty("handlers") != null
                && configuration.getProperty("handlers").contains(FILEHANDLER_CLASSNAME)
                && manager.getProperty("handlers").contains(FILEHANDLER_CLASSNAME)) {
            // IzPack maintains just one log file, don't override the existing handler type of it.
            // Special use case: Command line argument -logfile "wins" over the <log-file> tag.
            // Assumption at the moment for optimization: Just FileHandler is used for configurations from install.xml.
            return;
        }
        for (String key : configuration.stringPropertyNames()) {
            if (key.equals(FILEHANDLER_CLASSNAME + ".pattern")) {
                // Workaround for not normalized file paths, for example ${INSTALL_PATH}/../install_log/name.log
                // to get them working before creating ${INSTALL_PATH} in the
                // com.izforge.izpack.installer.unpacker.UnpackerBase.preUnpack phase
                // otherwise the FileHandler will fail when opening files already in constructor and not recover from that.
                pattern = FilenameUtils.normalize(configuration.getProperty(key));
                configuration.setProperty(key, pattern);
            } else if (key.equals(FILEHANDLER_CLASSNAME + ".mkdirs")) {
                // This key goes beyond the capabilities of java.util.logging.FileHandler
                mkdirs = Boolean.parseBoolean(configuration.getProperty(key));
                configuration.remove(key);
            }
        }
        if (mkdirs && pattern != null) {
            FileUtils.forceMkdirParent(new File(pattern));
        }

        // Merge user settings compiled in
        final Properties userProps = new Properties();
        InputStream userPropsStream = LogUtils.class
                .getResourceAsStream(ResourceManager.getInstallLoggingConfigurationResourceName());
        try {
            if (userPropsStream != null) {
                userProps.load(userPropsStream);
                for (String userPropName : userProps.stringPropertyNames()) {
                    if (userPropName.endsWith(".level") && !userPropName.startsWith(FILEHANDLER_CLASSNAME)) {
                        String level = userProps.getProperty(userPropName);
                        if (level != null) {
                            configuration.setProperty(userPropName, level);
                        }
                    }
                }
            }
        } finally {
            IOUtils.closeQuietly(userPropsStream);
        }

        InputStream defaultResourceStream = null;
        try {
            defaultResourceStream = LogUtils.class.getResourceAsStream(LOGGING_CONFIGURATION);
            final Properties defaultProps = new Properties();
            defaultProps.load(defaultResourceStream);
            mergeLoggingConfiguration(configuration, defaultProps);
        } finally {
            IOUtils.closeQuietly(defaultResourceStream);
        }

        if (Debug.isDEBUG()) {
            configuration.setProperty(FILEHANDLER_CLASSNAME + ".level", Level.FINE.toString());
            configuration.setProperty(ConsoleHandler.class.getName() + ".level", Level.FINE.toString());
        }

        // Set general log level which acts as filter in front of all handlers
        String fileLevelName = configuration.getProperty(FILEHANDLER_CLASSNAME + ".level",
                Level.ALL.toString());
        Level fileLevel = Level.ALL;
        if (fileLevelName != null) {
            fileLevel = Level.parse(fileLevelName);
        }

        String consoleLevelName = configuration.getProperty(CONSOLEHANDLER_CLASSNAME + ".level",
                Level.INFO.toString());
        Level consoleLevel = Level.INFO;
        if (consoleLevelName != null) {
            consoleLevel = Level.parse(consoleLevelName);
        }

        configuration.setProperty(".level",
                (fileLevel.intValue() < consoleLevel.intValue()) ? fileLevelName : consoleLevelName);

        final PipedOutputStream out = new PipedOutputStream();
        final PipedInputStream in = new PipedInputStream(out);
        try {
            new Thread(new Runnable() {
                public void run() {
                    try {
                        configuration.store(out, null);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        IOUtils.closeQuietly(out);
                    }
                }
            }).start();

            manager.readConfiguration(in);
        } finally {
            IOUtils.closeQuietly(in);
        }
    }
}

From source file:org.xenei.jdbc4sparql.J4SConnection.java

/**
 * Adds any new properties form the argument into our internal properties.
 *
 * @param properties/*w  ww . j a  va2s.  c  o m*/
 */
private void mergeProperties(final Properties properties) {
    for (final String s : properties.stringPropertyNames()) {
        if (!this.properties.containsKey(s)) {
            this.properties.put(s, properties.getProperty(s));
        }
    }
}

From source file:com.ibm.jaggr.core.impl.options.OptionsImpl.java

/**
 * Sets the properties object for the current options and updates
 * the shadow map that is returned to callers of {@link #getOptionsMap()}.
 *
 * @param props The new properties.//  ww  w  . ja  v a 2s. co  m
 */
protected void setProps(Properties props) {
    this.props = props;
    // Update the shadow map
    Map<String, String> map = new HashMap<String, String>();
    for (String name : props.stringPropertyNames()) {
        map.put(name, (String) props.getProperty(name));
    }
    shadowMap = Collections.unmodifiableMap(map);
}

From source file:org.duracloud.common.queue.aws.SQSTaskQueue.java

protected Task marshallTask(Message msg) {
    Properties props = new Properties();
    Task task = null;/*from  ww w .  j  a  v  a 2 s . c  o m*/
    try {
        props.load(new StringReader(msg.getBody()));

        if (props.containsKey(Task.KEY_TYPE)) {
            task = new Task();
            for (final String key : props.stringPropertyNames()) {
                if (key.equals(Task.KEY_TYPE)) {
                    task.setType(Task.Type.valueOf(props.getProperty(key)));
                } else {
                    task.addProperty(key, props.getProperty(key));
                }
            }
            task.addProperty(MsgProp.MSG_ID.name(), msg.getMessageId());
            task.addProperty(MsgProp.RECEIPT_HANDLE.name(), msg.getReceiptHandle());
        } else {
            log.error("SQS message from queue: " + queueName + ", queueUrl: " + queueUrl
                    + " does not contain a 'task type'");
        }
    } catch (IOException ioe) {
        log.error("Error creating Task", ioe);
    }
    return task;
}

From source file:de.unihannover.se.processSimulation.interactive.ServerMain.java

private BulkParameterFactory loadParameters(int requestId) throws IOException {
    final File requestDir = this.getRequestDir(requestId);
    final File paramsFile = new File(requestDir, PARAMS_PROPERTIES);
    try (FileInputStream in = new FileInputStream(paramsFile)) {
        final Properties properties = new Properties();
        properties.load(in);/*from   w ww.  ja  v  a2  s  .  c  om*/

        BulkParameterFactory ret = BulkParameterFactory.forCommercial();
        for (final String name : properties.stringPropertyNames()) {
            final ParameterType type = ParameterType.valueOf(name);
            ret = ret.copyWithChangedParam(type, type.parse(properties.getProperty(name)));
        }
        return ret;
    }
}