Example usage for java.util Properties containsKey

List of usage examples for java.util Properties containsKey

Introduction

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

Prototype

@Override
    public boolean containsKey(Object key) 

Source Link

Usage

From source file:com.taobao.diamond.common.Constants.java

/** ?-D > env > diamond.properties  */
public static void init() {
    File diamondFile = new File(System.getProperty("user.home"), "diamond/ServerAddress");
    if (!diamondFile.exists()) {
        diamondFile.getParentFile().mkdirs();
        try (OutputStream out = new FileOutputStream(diamondFile)) {
            out.write("localhost".getBytes());
        } catch (IOException e) {
            throw new IllegalStateException(diamondFile.toString(), e);
        }//w  w  w .  ja  v a  2s  . co m
    }
    List<Field> fields = new ArrayList<>();
    for (Field field : Constants.class.getDeclaredFields()) {
        if (Modifier.isPublic(field.getModifiers()) && !Modifier.isFinal(field.getModifiers())) {
            fields.add(field);
        }
    }

    Properties props = new Properties();
    {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        if (cl == null)
            cl = Constants.class.getClassLoader();
        try (InputStream in = cl.getResourceAsStream("diamond.properties")) {
            if (in != null)
                props.load(in);
        } catch (IOException e) {
            log.warn("load diamond.properties", e);
        }
    }
    props.putAll(System.getenv());
    props.putAll(System.getProperties());

    Map<String, Object> old = new HashMap<>();
    try {
        for (Field field : fields) {
            if (!props.containsKey(field.getName()))
                continue;
            old.put(field.getName(), field.get(Constants.class));

            String value = props.getProperty(field.getName());
            Class<?> clazz = field.getType();
            if (String.class.equals(clazz)) {
                field.set(Constraints.class, value);
            } else if (int.class.equals(clazz)) {
                if (value != null) {
                    field.set(Constraints.class, Integer.parseInt(value));
                }
            } else {
                throw new IllegalArgumentException(field + "  " + value + " ?");
            }
        }
    } catch (IllegalAccessException e) {
        throw new IllegalStateException(e);
    }

    setValue(old, "CONFIG_HTTP_URI_FILE", "HTTP_URI_FILE");
    setValue(old, "HTTP_URI_LOGIN", "HTTP_URI_FILE");
    setValue(old, "DAILY_DOMAINNAME", "DEFAULT_DOMAINNAME");
}

From source file:org.springmodules.cache.util.SemicolonSeparatedPropertiesParser.java

/**
 * Creates a <code>java.util.Properties</code> from the specified String.
 *
 * @param text// www .ja v  a  2  s. com
 *          the String to parse.
 * @throws IllegalArgumentException
 *           if the specified property does not match the regular expression
 *           pattern defined in <code>KEY_VALUE_REGEX</code>.
 * @throws IllegalArgumentException
 *           if the set of properties already contains the property specified
 *           by the given String.
 * @return a new instance of <code>java.util.Properties</code> created from
 *         the given text.
 */
public static Properties parseProperties(String text) throws IllegalArgumentException {
    String newText = text;

    if (!StringUtils.hasText(newText)) {
        return null;
    }

    if (newText.endsWith(PROPERTY_DELIMITER)) {
        // remove ';' at the end of the text (if applicable)
        newText = newText.substring(0, newText.length() - PROPERTY_DELIMITER.length());

        if (!StringUtils.hasText(newText)) {
            return null;
        }
    }

    Properties properties = new Properties();
    String[] propertiesAsText = StringUtils.delimitedListToStringArray(newText, PROPERTY_DELIMITER);

    int propertyCount = propertiesAsText.length;
    for (int i = 0; i < propertyCount; i++) {
        String property = propertiesAsText[i];
        Match match = KEY_VALUE_REGEX.match(property);

        if (!match.isSuccessful()) {
            String message = "The String " + StringUtils.quote(property)
                    + " should match the regular expression pattern "
                    + StringUtils.quote(KEY_VALUE_REGEX.getPattern());
            throw new IllegalArgumentException(message);
        }

        String[] groups = match.getGroups();
        String key = groups[1].trim();
        String value = groups[2].trim();

        if (properties.containsKey(key)) {
            throw new IllegalArgumentException(
                    "The property " + StringUtils.quote(key) + " is specified more than once");
        }
        properties.setProperty(key, value);
    }
    return properties;
}

From source file:gobblin.source.extractor.extract.kafka.ConfigStoreUtils.java

/**
 * Get topics from config store./*from w  w w.j  av  a2s.c  o  m*/
 * Topics will either be whitelisted or blacklisted using tag.
 * After filtering out topics via tag, their config property is checked.
 * For each shortlisted topic, config must contain either property topic.blacklist or topic.whitelist
 *
 * If tags are not provided, it will return all topics
 */
public static List<KafkaTopic> getTopicsFromConfigStore(Properties properties, String configStoreUri,
        GobblinKafkaConsumerClient kafkaConsumerClient) {
    ConfigClient configClient = ConfigClient.createConfigClient(VersionStabilityPolicy.WEAK_LOCAL_STABILITY);
    State state = new State();
    state.setProp(KafkaSource.TOPIC_WHITELIST, ".*");
    state.setProp(KafkaSource.TOPIC_BLACKLIST, StringUtils.EMPTY);
    List<KafkaTopic> allTopics = kafkaConsumerClient.getFilteredTopics(
            DatasetFilterUtils.getPatternList(state, KafkaSource.TOPIC_BLACKLIST),
            DatasetFilterUtils.getPatternList(state, KafkaSource.TOPIC_WHITELIST));
    Optional<Config> runtimeConfig = ConfigClientUtils.getOptionalRuntimeConfig(properties);

    if (properties.containsKey(GOBBLIN_CONFIG_TAGS_WHITELIST)) {
        Preconditions.checkArgument(properties.containsKey(GOBBLIN_CONFIG_FILTER),
                "Missing required property " + GOBBLIN_CONFIG_FILTER);
        String filterString = properties.getProperty(GOBBLIN_CONFIG_FILTER);
        Path whiteListTagUri = PathUtils.mergePaths(new Path(configStoreUri),
                new Path(properties.getProperty(GOBBLIN_CONFIG_TAGS_WHITELIST)));
        List<String> whitelistedTopics = new ArrayList<>();
        ConfigStoreUtils.getTopicsURIFromConfigStore(configClient, whiteListTagUri, filterString, runtimeConfig)
                .stream()
                .filter((URI u) -> ConfigUtils.getBoolean(
                        ConfigStoreUtils.getConfig(configClient, u, runtimeConfig), KafkaSource.TOPIC_WHITELIST,
                        false))
                .forEach(((URI u) -> whitelistedTopics.add(ConfigStoreUtils.getTopicNameFromURI(u))));

        return allTopics.stream().filter((KafkaTopic p) -> whitelistedTopics.contains(p.getName()))
                .collect(Collectors.toList());
    } else if (properties.containsKey(GOBBLIN_CONFIG_TAGS_BLACKLIST)) {
        Preconditions.checkArgument(properties.containsKey(GOBBLIN_CONFIG_FILTER),
                "Missing required property " + GOBBLIN_CONFIG_FILTER);
        String filterString = properties.getProperty(GOBBLIN_CONFIG_FILTER);
        Path blackListTagUri = PathUtils.mergePaths(new Path(configStoreUri),
                new Path(properties.getProperty(GOBBLIN_CONFIG_TAGS_BLACKLIST)));
        List<String> blacklistedTopics = new ArrayList<>();
        ConfigStoreUtils.getTopicsURIFromConfigStore(configClient, blackListTagUri, filterString, runtimeConfig)
                .stream()
                .filter((URI u) -> ConfigUtils.getBoolean(
                        ConfigStoreUtils.getConfig(configClient, u, runtimeConfig), KafkaSource.TOPIC_BLACKLIST,
                        false))
                .forEach(((URI u) -> blacklistedTopics.add(ConfigStoreUtils.getTopicNameFromURI(u))));
        return allTopics.stream().filter((KafkaTopic p) -> !blacklistedTopics.contains(p.getName()))
                .collect(Collectors.toList());
    } else {
        log.warn("None of the blacklist or whitelist tags are provided");
        return allTopics;
    }
}

From source file:com.hypersocket.i18n.I18N.java

public static boolean hasOveride(Locale locale, String resourceBundle, String key) {

    if (key == null) {
        throw new IllegalArgumentException("You must specify a key!");
    }//from   w  w w  .  j a v a 2  s  .c om
    if (resourceBundle == null) {
        throw new IllegalArgumentException("You must specify a resource bundle for key " + key);
    }

    File overideFile = getOverrideFile(locale, resourceBundle);

    if (overideFile.exists()) {

        if (!overideProperties.containsKey(overideFile)) {

            Properties properties = new Properties();
            try {
                InputStream in = new FileInputStream(overideFile);
                try {
                    properties.load(in);
                } catch (IOException ex) {
                } finally {
                    FileUtils.closeQuietly(in);
                }

                overideProperties.put(overideFile, properties);
            } catch (FileNotFoundException e) {

            }
        }

        if (overideProperties.containsKey(overideFile)) {
            Properties properties = overideProperties.get(overideFile);

            return properties.containsKey(key) && StringUtils.isNotEmpty(properties.getProperty(key));
        }
    }

    return false;
}

From source file:dk.hippogrif.prettyxml.PrettyPrint.java

/**
 * Checks known properties -//from ww w  .j  a v  a2 s . c o  m
 * present boolean properties are set to either "true" or "false",
 * indent=0 is removed,
 * string properties are trimmed and empty properties removed -
 * however, TEXT_MODE is checked when format is initialized
 * and ENCODING when used.
 *
 * @param prop holds the properties
 * @param extended to include in/out properties
 * @throws Exception if property error
 */
public static void checkProperties(Properties prop, boolean extended) throws Exception {
    for (Enumeration elements = prop.propertyNames(); elements.hasMoreElements();) {
        String s = (String) elements.nextElement();
        if (!keys.contains(s)) {
            prop.remove(s);
        }
    }
    checkBoolean(EXPAND_EMPTY_ELEMENTS, prop);
    checkBoolean(OMIT_DECLARATION, prop);
    checkBoolean(OMIT_ENCODING, prop);
    checkBoolean(INDENT_ATTRIBUTES, prop);
    checkBoolean(SORT_ATTRIBUTES, prop);
    if (prop.containsKey(INDENT)) {
        try {
            int i = Integer.parseInt(prop.getProperty(INDENT));
            if (i == 0) {
                prop.remove(INDENT);
            } else if (i < 1 || i > 99) {
                throw new Exception(INDENT + " must be an integer >= 0 and < 100");
            }
        } catch (NumberFormatException e) {
            throw new Exception(INDENT + " must be an integer >= 0 and < 100");
        }
    }
    if (prop.containsKey(LINE_SEPARATOR)) {
        String s = prop.getProperty(LINE_SEPARATOR);
        boolean err = true;
        for (int i = 0; i < LINE_SEPARATORS.length; i++) {
            if (LINE_SEPARATORS[i].equals(s)) {
                err = false;
                break;
            }
        }
        if (err) {
            throw new Exception(LINE_SEPARATOR + " must be \\r, \\n or \\r\\n");
        }
    }
    checkString(TRANSFORM, prop);
    if (extended) {
        checkString(INPUT, prop);
        checkString(URL, prop);
        checkString(OUTPUT, prop);
        if (prop.containsKey(INPUT) && prop.containsKey(URL)) {
            throw new Exception("do not use " + INPUT + " and " + URL + " at the same time");
        }
    } else {
        prop.remove(INPUT);
        prop.remove(URL);
        prop.remove(OUTPUT);
    }
}

From source file:com.hypersocket.i18n.I18N.java

public static String getResource(Locale locale, String resourceBundle, String key, Object... arguments) {

    if (key == null) {
        throw new IllegalArgumentException("You must specify a key!");
    }//from   w w w. ja v  a  2s  . c  o  m
    if (resourceBundle == null) {
        throw new IllegalArgumentException("You must specify a resource bundle for key " + key);
    }

    File overideFile = getOverrideFile(locale, resourceBundle);

    if (overideFile.exists()) {

        if (!overideProperties.containsKey(overideFile)) {

            Properties properties = new Properties();
            try {
                InputStream in = new FileInputStream(overideFile);
                try {
                    properties.load(in);
                } catch (IOException ex) {
                } finally {
                    FileUtils.closeQuietly(in);
                }

                overideProperties.put(overideFile, properties);
            } catch (FileNotFoundException e) {

            }
        }

        if (overideProperties.containsKey(overideFile)) {
            Properties properties = overideProperties.get(overideFile);

            if (properties.containsKey(key)) {
                String localizedString = properties.getProperty(key);
                if (arguments == null || arguments.length == 0) {
                    return localizedString;
                }

                MessageFormat messageFormat = new MessageFormat(localizedString);
                messageFormat.setLocale(locale);
                return messageFormat.format(formatParameters(arguments));
            }
        }
    }

    String bundlePath = resourceBundle;
    if (!bundlePath.startsWith("i18n/")) {
        bundlePath = "i18n/" + resourceBundle;
    }

    try {
        ResourceBundle resource = ResourceBundle.getBundle(bundlePath, locale, I18N.class.getClassLoader());
        String localizedString = resource.getString(key);
        if (arguments == null || arguments.length == 0) {
            return localizedString;
        }

        MessageFormat messageFormat = new MessageFormat(localizedString);
        messageFormat.setLocale(locale);
        return messageFormat.format(formatParameters(arguments));
    } catch (MissingResourceException mre) {
        return "Missing resource key [i18n/" + resourceBundle + "/" + key + "]";
    }
}

From source file:edu.umd.cs.eclipse.courseProjectManager.TurninProjectAction.java

public static void addPropertiesNotAlreadyDefined(Properties dst, Properties src) {
    for (Map.Entry<?, ?> entry : src.entrySet()) {
        if (!dst.containsKey(entry.getKey()))
            dst.setProperty((String) entry.getKey(), (String) entry.getValue());
    }// w  w  w  . jav  a  2  s.c o m
}

From source file:com.mozilla.fhr.consumer.FHRConsumer.java

/**
 * This method overrides KafkaConsumer but we can't annotate due to the way Java
 * determines types on static methods.//from   ww  w.j  a  va 2s .  co m
 */
public static KafkaConsumer fromOptions(CommandLine cmd) {
    Properties props = new Properties();
    String propsFilePath = cmd.getOptionValue("properties");
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(new FileInputStream(propsFilePath)));
        props.load(reader);
        props.setProperty("groupid", cmd.getOptionValue("groupid"));
    } catch (FileNotFoundException e) {
        LOG.error("Could not find properties file", e);
    } catch (IOException e) {
        LOG.error("Error reading properties file", e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                LOG.error("Error closing properties file", e);
            }
        }
    }

    int numThreads = props.containsKey("consumer.threads")
            ? Integer.parseInt(props.getProperty("consumer.threads"))
            : DEFAULT_NUM_THREADS;
    // if numthreads specified on command-line then override
    if (cmd.hasOption("numthreads")) {
        numThreads = Integer.parseInt(cmd.getOptionValue("numthreads"));
    }

    return new FHRConsumer(cmd.getOptionValue("topic"), props, numThreads);
}

From source file:org.apache.jackrabbit.core.OracleRepositoryTest.java

protected void setUp() throws Exception {
    final Properties sysProps = System.getProperties();
    if (!sysProps.containsKey("tests.oracle.url") || !sysProps.containsKey("tests.oracle.user")
            || !sysProps.containsKey("tests.oracle.password")
            || !sysProps.containsKey("tests.oracle.tablespace")
            || !sysProps.containsKey("tests.oracle.indexTablespace")) {
        throw new IllegalStateException("Missing system property for test");
    }/*from  w w  w .  j  a  v a  2  s  . c  om*/
    dir = File.createTempFile("jackrabbit_", null, new File("target"));
    dir.delete();
    dir.mkdir();
    final InputStream in = getClass().getResourceAsStream("/org/apache/jackrabbit/core/repository-oracle.xml");
    config = RepositoryConfig.create(in, dir.getPath());
}

From source file:org.apache.jackrabbit.core.OracleRetrocompatibleRepositoryTest.java

protected void setUp() throws Exception {
    final Properties sysProps = System.getProperties();
    if (!sysProps.containsKey("tests.oracle.url") || !sysProps.containsKey("tests.oracle.user")
            || !sysProps.containsKey("tests.oracle.password")
            || !sysProps.containsKey("tests.oracle.tablespace")) {
        throw new IllegalStateException("Missing system property for test");
    }//from   w  w w . j a va  2 s  .  c o  m
    dir = File.createTempFile("jackrabbit_", null, new File("target"));
    dir.delete();
    dir.mkdir();
    final InputStream in = getClass()
            .getResourceAsStream("/org/apache/jackrabbit/core/repository-oracle-compat.xml");
    config = RepositoryConfig.create(in, dir.getPath());
}