Search in sources :

Example 1 with PropertyValidationException

use of org.candlepin.util.PropertyValidationException in project candlepin by candlepin.

the class ConsumerResource method sanitizeConsumerFacts.

/**
 * Sanitizes inbound consumer facts, truncating long facts and dropping invalid or untracked facts.
 *
 * @param facts the facts that are to be sanitized
 *
 * @return the sanitized facts
 */
private Map<String, String> sanitizeConsumerFacts(Map<String, String> facts) {
    Map<String, String> sanitized = new HashMap<>();
    Set<String> lowerCaseKeys = new HashSet<>();
    String factPattern = config.getString(ConfigProperties.CONSUMER_FACTS_MATCHER);
    Pattern pattern = Pattern.compile(factPattern);
    for (Map.Entry<String, String> fact : facts.entrySet()) {
        String key = fact.getKey();
        String value = fact.getValue();
        // Check for null fact keys (discard and continue)
        if (key == null) {
            log.warn("  Consumer contains a fact using a null key. Discarding fact...");
            continue;
        }
        // facts are case insensitive
        String lowerCaseKey = key.toLowerCase();
        if (lowerCaseKeys.contains(lowerCaseKey)) {
            log.warn("  Consumer contains duplicate fact. Discarding fact \"{}\"" + " with value \"{}\"", key, value);
            continue;
        }
        // Check for fact match (discard and continue)
        if (!pattern.matcher(key).matches()) {
            log.warn("  Consumer fact \"{}\" does not match pattern \"{}\"", key, factPattern);
            log.warn("  Discarding fact \"{}\"...", key);
            continue;
        }
        // Check for long keys or values, truncating as necessary
        if (key.length() > FactValidator.FACT_MAX_LENGTH) {
            key = key.substring(0, FactValidator.FACT_MAX_LENGTH - 3) + "...";
        }
        if (value != null && value.length() > FactValidator.FACT_MAX_LENGTH) {
            value = value.substring(0, FactValidator.FACT_MAX_LENGTH - 3) + "...";
        }
        // Validate fact (discarding malformed facts) (discard and continue)
        try {
            this.factValidator.validate(key, value);
        } catch (PropertyValidationException e) {
            log.warn("  {}", e.getMessage());
            log.warn("  Discarding fact \"{}\"...", key);
            continue;
        }
        sanitized.put(key, value);
        lowerCaseKeys.add(lowerCaseKey);
    }
    return sanitized;
}
Also used : Pattern(java.util.regex.Pattern) HashMap(java.util.HashMap) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) PropertyValidationException(org.candlepin.util.PropertyValidationException)

Aggregations

HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 LinkedHashSet (java.util.LinkedHashSet)1 Map (java.util.Map)1 Pattern (java.util.regex.Pattern)1 PropertyValidationException (org.candlepin.util.PropertyValidationException)1