<commit_before>package org.jivesoftware.util;

import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.JID;

/**
 * Represents a system property - also accessible via {@link JiveGlobals}. The only way to create a SystemProperty object
 * is to use a {@link Builder}.
 *
 * @param <T> The type of system property.
 */
public final class SystemProperty<T> {

    private static final Logger LOGGER = LoggerFactory.getLogger(SystemProperty.class);
    private static final Map<String, SystemProperty> PROPERTIES = new ConcurrentHashMap<>();
    private static final Map<ChronoUnit, Function<Duration, Long>> DURATION_TO_LONG = new HashMap<>();
    private static final Map<ChronoUnit, Function<Long, Duration>> LONG_TO_DURATION = new HashMap<>();
    private static final Map<Class, BiFunction<String, SystemProperty, Object>> FROM_STRING = new HashMap<>();
    private static final Map<Class, BiFunction<Object, SystemProperty, String>> TO_STRING = new HashMap<>();
    private static final Map<Class, BiFunction<Object, SystemProperty, String>> TO_DISPLAY_STRING = new HashMap<>();
    private static final Set<Class> NULLABLE_TYPES = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(String.class, Class.class, Duration.class, Instant.class, JID.class)));

    static {
        // Populate the map that turns a Duration to a Long based on the ChronoUnit a property should be saved in
        DURATION_TO_LONG.put(ChronoUnit.MILLIS, Duration::toMillis);
        DURATION_TO_LONG.put(ChronoUnit.SECONDS, Duration::getSeconds);
        DURATION_TO_LONG.put(ChronoUnit.MINUTES, Duration::toMinutes);
        DURATION_TO_LONG.put(ChronoUnit.HOURS, Duration::toHours);
        DURATION_TO_LONG.put(ChronoUnit.DAYS, Duration::toDays);
    }

    static {
        // Populate the map that turns a Long to a Duration based on the ChronoUnit a property should be saved in
        LONG_TO_DURATION.put(ChronoUnit.MILLIS, Duration::ofMillis);
        LONG_TO_DURATION.put(ChronoUnit.SECONDS, Duration::ofSeconds);
        LONG_TO_DURATION.put(ChronoUnit.MINUTES, Duration::ofMinutes);
        LONG_TO_DURATION.put(ChronoUnit.HOURS, Duration::ofHours);
        LONG_TO_DURATION.put(ChronoUnit.DAYS, Duration::ofDays);
    }

    static {
        // Given a String value and a system property, converts the String to the object of appropriate type or null
        FROM_STRING.put(String.class, (value, systemProperty) -> value);
        FROM_STRING.put(Integer.class, (value, systemProperty) -> org.jivesoftware.util.StringUtils.parseInteger(value).orElse(null));
        FROM_STRING.put(Long.class, (value, systemProperty) -> org.jivesoftware.util.StringUtils.parseLong(value).orElse(null));
        FROM_STRING.put(Double.class, (value, systemProperty) -> org.jivesoftware.util.StringUtils.parseDouble(value).orElse(null));
        FROM_STRING.put(Boolean.class, (value, systemProperty) -> value == null ? null : Boolean.valueOf(value));
        FROM_STRING.put(Duration.class, (value, systemProperty) -> org.jivesoftware.util.StringUtils.parseLong(value).map(longValue -> LONG_TO_DURATION.get(systemProperty.chronoUnit).apply(longValue)).orElse(null));
        FROM_STRING.put(Instant.class, (value, systemProperty) -> org.jivesoftware.util.StringUtils.parseLong(value).map(Instant::ofEpochMilli).orElse(null));
        FROM_STRING.put(JID.class, (value, systemProperty) -> {
            if(value == null) {
                return null;
            }
            try {
                return new JID(value);
            } catch(final Exception e) {
                LOGGER.warn("Configured property {} is not a valid JID", value);
                return null;
            }
        });
        FROM_STRING.put(Enum.class, (value, systemProperty) -> {
            if (StringUtils.isBlank(value)) {
                return null;
            }
            for (final Object constant : systemProperty.defaultValue.getClass().getEnumConstants()) {
                if (((Enum) constant).name().equals(value)) {
                    return constant;
                }
            }
            return null;
        });
        FROM_STRING.put(Class.class, (value, systemProperty) -> {
            if(StringUtils.isBlank(value)) {
                return null;
            }
            try {
                final Class clazz = Class.forName(value);
                //noinspection unchecked
                if (systemProperty.baseClass.isAssignableFrom(clazz)) {
                    return clazz;
                } else {
                    LOGGER.warn("Configured property {} is not an instance of {}", value, systemProperty.baseClass.getName());<commit_msg>OF-1964: SystemProperty should load classes with Thread.getContextClassloader as fallback (#1578)<commit_after>package org.jivesoftware.util;

import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.JID;

/**
 * Represents a system property - also accessible via {@link JiveGlobals}. The only way to create a SystemProperty object
 * is to use a {@link Builder}.
 *
 * @param <T> The type of system property.
 */
public final class SystemProperty<T> {

    private static final Logger LOGGER = LoggerFactory.getLogger(SystemProperty.class);
    private static final Map<String, SystemProperty> PROPERTIES = new ConcurrentHashMap<>();
    private static final Map<ChronoUnit, Function<Duration, Long>> DURATION_TO_LONG = new HashMap<>();
    private static final Map<ChronoUnit, Function<Long, Duration>> LONG_TO_DURATION = new HashMap<>();
    private static final Map<Class, BiFunction<String, SystemProperty, Object>> FROM_STRING = new HashMap<>();
    private static final Map<Class, BiFunction<Object, SystemProperty, String>> TO_STRING = new HashMap<>();
    private static final Map<Class, BiFunction<Object, SystemProperty, String>> TO_DISPLAY_STRING = new HashMap<>();
    private static final Set<Class> NULLABLE_TYPES = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(String.class, Class.class, Duration.class, Instant.class, JID.class)));

    static {
        // Populate the map that turns a Duration to a Long based on the ChronoUnit a property should be saved in
        DURATION_TO_LONG.put(ChronoUnit.MILLIS, Duration::toMillis);
        DURATION_TO_LONG.put(ChronoUnit.SECONDS, Duration::getSeconds);
        DURATION_TO_LONG.put(ChronoUnit.MINUTES, Duration::toMinutes);
        DURATION_TO_LONG.put(ChronoUnit.HOURS, Duration::toHours);
        DURATION_TO_LONG.put(ChronoUnit.DAYS, Duration::toDays);
    }

    static {
        // Populate the map that turns a Long to a Duration based on the ChronoUnit a property should be saved in
        LONG_TO_DURATION.put(ChronoUnit.MILLIS, Duration::ofMillis);
        LONG_TO_DURATION.put(ChronoUnit.SECONDS, Duration::ofSeconds);
        LONG_TO_DURATION.put(ChronoUnit.MINUTES, Duration::ofMinutes);
        LONG_TO_DURATION.put(ChronoUnit.HOURS, Duration::ofHours);
        LONG_TO_DURATION.put(ChronoUnit.DAYS, Duration::ofDays);
    }

    static {
        // Given a String value and a system property, converts the String to the object of appropriate type or null
        FROM_STRING.put(String.class, (value, systemProperty) -> value);
        FROM_STRING.put(Integer.class, (value, systemProperty) -> org.jivesoftware.util.StringUtils.parseInteger(value).orElse(null));
        FROM_STRING.put(Long.class, (value, systemProperty) -> org.jivesoftware.util.StringUtils.parseLong(value).orElse(null));
        FROM_STRING.put(Double.class, (value, systemProperty) -> org.jivesoftware.util.StringUtils.parseDouble(value).orElse(null));
        FROM_STRING.put(Boolean.class, (value, systemProperty) -> value == null ? null : Boolean.valueOf(value));
        FROM_STRING.put(Duration.class, (value, systemProperty) -> org.jivesoftware.util.StringUtils.parseLong(value).map(longValue -> LONG_TO_DURATION.get(systemProperty.chronoUnit).apply(longValue)).orElse(null));
        FROM_STRING.put(Instant.class, (value, systemProperty) -> org.jivesoftware.util.StringUtils.parseLong(value).map(Instant::ofEpochMilli).orElse(null));
        FROM_STRING.put(JID.class, (value, systemProperty) -> {
            if(value == null) {
                return null;
            }
            try {
                return new JID(value);
            } catch(final Exception e) {
                LOGGER.warn("Configured property {} is not a valid JID", value);
                return null;
            }
        });
        FROM_STRING.put(Enum.class, (value, systemProperty) -> {
            if (StringUtils.isBlank(value)) {
                return null;
            }
            for (final Object constant : systemProperty.defaultValue.getClass().getEnumConstants()) {
                if (((Enum) constant).name().equals(value)) {
                    return constant;
                }
            }
            return null;
        });
        FROM_STRING.put(Class.class, (value, systemProperty) -> {
            if(StringUtils.isBlank(value)) {
                return null;
            }
            try {
                final Class clazz = ClassUtils.forName(value);
                //noinspection unchecked
                if (systemProperty.baseClass.isAssignableFrom(clazz)) {
                    return clazz;
                } else {
                    LOGGER.warn("Configured property {} is not an instance of {}", value, systemProperty.baseClass.getName());
{'fraction_non_alphanumeric': 0.11103890075201932, 'fraction_numerical': 0.0012997864636524, 'mean_word_length': 3.2476340694006307, 'pattern_counts': {'":': 0, '<': 45, '<?xml version=': 0, '>': 67, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3750916', 'n_tokens_mistral': 3187, 'n_tokens_neox': 3102, 'n_words': 694}