<commit_before>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.commons.crypto.utils;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;

import org.apache.commons.crypto.cipher.CipherTransformation;
import org.apache.commons.crypto.cipher.CryptoCipher;
import org.apache.commons.crypto.cipher.CryptoCipherFactory;
import org.apache.commons.crypto.conf.ConfigurationKeys;
import static org.apache.commons.crypto.conf.ConfigurationKeys.COMMONS_CRYPTO_CIPHER_CLASSES_DEFAULT;
import static org.apache.commons.crypto.conf.ConfigurationKeys.COMMONS_CRYPTO_CIPHER_CLASSES_KEY;
import static org.apache.commons.crypto.conf.ConfigurationKeys.COMMONS_CRYPTO_CIPHER_JCE_PROVIDER_KEY;
import static org.apache.commons.crypto.conf.ConfigurationKeys.COMMONS_CRYPTO_LIB_NAME_KEY;
import static org.apache.commons.crypto.conf.ConfigurationKeys.COMMONS_CRYPTO_LIB_PATH_KEY;
import static org.apache.commons.crypto.conf.ConfigurationKeys.COMMONS_CRYPTO_LIB_TEMPDIR_KEY;
import static org.apache.commons.crypto.conf.ConfigurationKeys.COMMONS_CRYPTO_SECURE_RANDOM_DEVICE_FILE_PATH_DEFAULT;
import static org.apache.commons.crypto.conf.ConfigurationKeys.COMMONS_CRYPTO_SECURE_RANDOM_DEVICE_FILE_PATH_KEY;
import static org.apache.commons.crypto.conf.ConfigurationKeys.COMMONS_CRYPTO_STREAM_BUFFER_SIZE_DEFAULT;
import static org.apache.commons.crypto.conf.ConfigurationKeys.COMMONS_CRYPTO_STREAM_BUFFER_SIZE_KEY;
import static org.apache.commons.crypto.conf.ConfigurationKeys.COMMONS_CRYPTO_SYSTEM_PROPERTIES_FILE;

/**
 * General utility methods.
 */
public final class Utils {

    private static final int MIN_BUFFER_SIZE = 512;

    /**
     * For AES, the algorithm block is fixed size of 128 bits.
     *
     * @see <a href="http://en.wikipedia.org/wiki/Advanced_Encryption_Standard">
     *      http://en.wikipedia.org/wiki/Advanced_Encryption_Standard</a>
     */
    private static final int AES_BLOCK_SIZE = CipherTransformation.AES_CTR_NOPADDING
            .getAlgorithmBlockSize();

    /**
     * The private constructor of {@Link Utils}.
     */
    private Utils() {
    }

    static {
        loadSystemProperties();
    }

    /**
     * loads system properties when configuration file of the name
     * {@link ConfigurationKeys#COMMONS_CRYPTO_SYSTEM_PROPERTIES_FILE} is found.
     */
    private static void loadSystemProperties() {
        try {
            InputStream is = Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream(COMMONS_CRYPTO_SYSTEM_PROPERTIES_FILE);

            if (is == null) {
                return; // no configuration file is found
            }
            // Load property file
            Properties props = new Properties();
            props.load(is);
            is.close();
            Enumeration<?> names = props.propertyNames();
            while (names.hasMoreElements()) {
                String name = (String) names.nextElement();
                if (name.startsWith(ConfigurationKeys.CONF_PREFIX)) {
                    if (System.getProperty(name) == null) {
                        System.setProperty(name, props.getProperty(name));
                    }
                }
            }
        } catch (Throwable ex) {
            System.err.println("Could not load '"
                    + COMMONS_CRYPTO_SYSTEM_PROPERTIES_FILE
                    + "' from classpath: " + ex.toString());
        }
    }

    /**
     * Forcibly free the direct buffer.
     *
     * @param buffer the bytebuffer to be freed.
     */
    public static void freeDirectBuffer(ByteBuffer buffer) {
        try {
            /* Using reflection to implement sun.nio.ch.DirectBuffer.cleaner()
            .clean(); */
            Class<?> sunClass = Class.forName("sun.nio.ch.DirectBuffer");
            Class<?> cleanerClass = Class.forName("sun.misc.Cleaner");

            Class<?>[] interfaces = buffer.getClass().getInterfaces();

            for (Class<?> clazz : interfaces) {
                if (clazz.getName().equals(sunClass.getName())) {
                    final Object[] NO_PARAM = new Object[0];
                    /* DirectBuffer#cleaner() */
                    Method getCleaner = sunClass.getMethod("cleaner");
                    Object cleaner = getCleaner.invoke(buffer, NO_PARAM);
                    /* Cleaner#clean() */
                    Method cleanMethod = cleanerClass.getMethod("clean");
                    cleanMethod.invoke(cleaner, NO_PARAM);
                    return;
                }<commit_msg>Don't try to instantiate class unless it is necessary<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.commons.crypto.utils;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;

import org.apache.commons.crypto.cipher.CipherTransformation;
import org.apache.commons.crypto.cipher.CryptoCipher;
import org.apache.commons.crypto.cipher.CryptoCipherFactory;
import org.apache.commons.crypto.conf.ConfigurationKeys;
import static org.apache.commons.crypto.conf.ConfigurationKeys.COMMONS_CRYPTO_CIPHER_CLASSES_DEFAULT;
import static org.apache.commons.crypto.conf.ConfigurationKeys.COMMONS_CRYPTO_CIPHER_CLASSES_KEY;
import static org.apache.commons.crypto.conf.ConfigurationKeys.COMMONS_CRYPTO_CIPHER_JCE_PROVIDER_KEY;
import static org.apache.commons.crypto.conf.ConfigurationKeys.COMMONS_CRYPTO_LIB_NAME_KEY;
import static org.apache.commons.crypto.conf.ConfigurationKeys.COMMONS_CRYPTO_LIB_PATH_KEY;
import static org.apache.commons.crypto.conf.ConfigurationKeys.COMMONS_CRYPTO_LIB_TEMPDIR_KEY;
import static org.apache.commons.crypto.conf.ConfigurationKeys.COMMONS_CRYPTO_SECURE_RANDOM_DEVICE_FILE_PATH_DEFAULT;
import static org.apache.commons.crypto.conf.ConfigurationKeys.COMMONS_CRYPTO_SECURE_RANDOM_DEVICE_FILE_PATH_KEY;
import static org.apache.commons.crypto.conf.ConfigurationKeys.COMMONS_CRYPTO_STREAM_BUFFER_SIZE_DEFAULT;
import static org.apache.commons.crypto.conf.ConfigurationKeys.COMMONS_CRYPTO_STREAM_BUFFER_SIZE_KEY;
import static org.apache.commons.crypto.conf.ConfigurationKeys.COMMONS_CRYPTO_SYSTEM_PROPERTIES_FILE;

/**
 * General utility methods.
 */
public final class Utils {

    private static final int MIN_BUFFER_SIZE = 512;

    /**
     * For AES, the algorithm block is fixed size of 128 bits.
     *
     * @see <a href="http://en.wikipedia.org/wiki/Advanced_Encryption_Standard">
     *      http://en.wikipedia.org/wiki/Advanced_Encryption_Standard</a>
     */
    private static final int AES_BLOCK_SIZE = CipherTransformation.AES_CTR_NOPADDING
            .getAlgorithmBlockSize();

    /**
     * The private constructor of {@Link Utils}.
     */
    private Utils() {
    }

    static {
        loadSystemProperties();
    }

    /**
     * loads system properties when configuration file of the name
     * {@link ConfigurationKeys#COMMONS_CRYPTO_SYSTEM_PROPERTIES_FILE} is found.
     */
    private static void loadSystemProperties() {
        try {
            InputStream is = Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream(COMMONS_CRYPTO_SYSTEM_PROPERTIES_FILE);

            if (is == null) {
                return; // no configuration file is found
            }
            // Load property file
            Properties props = new Properties();
            props.load(is);
            is.close();
            Enumeration<?> names = props.propertyNames();
            while (names.hasMoreElements()) {
                String name = (String) names.nextElement();
                if (name.startsWith(ConfigurationKeys.CONF_PREFIX)) {
                    if (System.getProperty(name) == null) {
                        System.setProperty(name, props.getProperty(name));
                    }
                }
            }
        } catch (Throwable ex) {
            System.err.println("Could not load '"
                    + COMMONS_CRYPTO_SYSTEM_PROPERTIES_FILE
                    + "' from classpath: " + ex.toString());
        }
    }

    /**
     * Forcibly free the direct buffer.
     *
     * @param buffer the bytebuffer to be freed.
     */
    public static void freeDirectBuffer(ByteBuffer buffer) {
        try {
            /* Using reflection to implement sun.nio.ch.DirectBuffer.cleaner()
            .clean(); */
            final String SUN_CLASS = "sun.nio.ch.DirectBuffer";
            Class<?>[] interfaces = buffer.getClass().getInterfaces();

            for (Class<?> clazz : interfaces) {
                if (clazz.getName().equals(SUN_CLASS)) {
                    final Object[] NO_PARAM = new Object[0];
                    /* DirectBuffer#cleaner() */
                    Method getCleaner = Class.forName(SUN_CLASS).getMethod("cleaner");
                    Object cleaner = getCleaner.invoke(buffer, NO_PARAM);
                    /* Cleaner#clean() */
                    Method cleanMethod = Class.forName("sun.misc.Cleaner").getMethod("clean");
                    cleanMethod.invoke(cleaner, NO_PARAM);
                    return;
                }
{'fraction_non_alphanumeric': 0.09153776160145587, 'fraction_numerical': 0.002001819836214741, 'mean_word_length': 2.8349616189811586, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, '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': '1560623', 'n_tokens_mistral': 3027, 'n_tokens_neox': 2907, 'n_words': 694}