Utils.java

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

  19. import java.io.File;
  20. import java.io.IOException;
  21. import java.io.InputStream;
  22. import java.net.URL;
  23. import java.security.GeneralSecurityException;
  24. import java.util.ArrayList;
  25. import java.util.Enumeration;
  26. import java.util.List;
  27. import java.util.Objects;
  28. import java.util.Properties;

  29. import org.apache.commons.crypto.Crypto;
  30. import org.apache.commons.crypto.cipher.CryptoCipher;
  31. import org.apache.commons.crypto.cipher.CryptoCipherFactory;

  32. /**
  33.  * General utility methods.
  34.  */
  35. public final class Utils {

  36.     private static class DefaultPropertiesHolder {
  37.         static final Properties DEFAULT_PROPERTIES = createDefaultProperties();

  38.         /**
  39.          * Loads system properties when configuration file of the name
  40.          * {@link #SYSTEM_PROPERTIES_FILE} is found.
  41.          *
  42.          * @return the default properties
  43.          */
  44.         private static Properties createDefaultProperties() {
  45.           // default to system
  46.           final Properties defaultedProps = new Properties(System.getProperties());
  47.           final URL url = Thread.currentThread().getContextClassLoader().getResource(SYSTEM_PROPERTIES_FILE);
  48.           if (url == null) {
  49.               // Fail early when the resource is not found which makes SpotBugs happy on Java 17.
  50.               return defaultedProps;
  51.           }
  52.           try {
  53.               final Properties fileProps = new Properties();
  54.               try (InputStream is = url.openStream()) {
  55.                   fileProps.load(is);
  56.               }
  57.               final Enumeration<?> names = fileProps.propertyNames();
  58.               while (names.hasMoreElements()) {
  59.                   final String name = (String) names.nextElement();
  60.                   // ensure System properties override ones in the file so one can override the file on the command line
  61.                   if (System.getProperty(name) == null) {
  62.                       defaultedProps.setProperty(name, fileProps.getProperty(name));
  63.                   }
  64.               }
  65.           } catch (final Exception ex) {
  66.               System.err.println("Could not load '" + SYSTEM_PROPERTIES_FILE + "' from classpath: " + ex.toString());
  67.           }
  68.           return defaultedProps;
  69.       }
  70.    }

  71.     /**
  72.      * The file name of configuration file.
  73.      */
  74.     private static final String SYSTEM_PROPERTIES_FILE = Crypto.CONF_PREFIX + "properties";

  75.     /**
  76.      * Ensures the truth of an expression involving one or more parameters to
  77.      * the calling method.
  78.      *
  79.      * @param expression a boolean expression.
  80.      * @throws IllegalArgumentException if expression is false.
  81.      */
  82.     public static void checkArgument(final boolean expression) {
  83.         if (!expression) {
  84.             throw new IllegalArgumentException();
  85.         }
  86.     }

  87.     /**
  88.      * Checks the truth of an expression.
  89.      *
  90.      * @param expression a boolean expression.
  91.      * @param errorMessage the exception message to use if the check fails; will
  92.      *        be converted to a string using <code>String
  93.      *                     .valueOf(Object)</code>.
  94.      * @throws IllegalArgumentException if expression is false.
  95.      */
  96.     public static void checkArgument(final boolean expression, final Object errorMessage) {
  97.         if (!expression) {
  98.             throw new IllegalArgumentException(String.valueOf(errorMessage));
  99.         }
  100.     }

  101.     /**
  102.      * Ensures that an object reference passed as a parameter to the calling
  103.      * method is not null.
  104.      *
  105.      * @param <T> the type of the object reference to be checked.
  106.      * @param reference an object reference.
  107.      * @return the non-null reference that was validated.
  108.      * @throws NullPointerException if reference is null.
  109.      * @deprecated Use {@link Objects#requireNonNull(Object)}.
  110.      */
  111.     @Deprecated
  112.     public static <T> T checkNotNull(final T reference) {
  113.         return Objects.requireNonNull(reference, "reference");
  114.     }

  115.     /**
  116.      * Ensures the truth of an expression involving the state of the calling
  117.      * instance, but not involving any parameters to the calling method.
  118.      *
  119.      * @param expression a boolean expression.
  120.      * @throws IllegalStateException if expression is false.
  121.      */
  122.     public static void checkState(final boolean expression) {
  123.         checkState(expression, null);
  124.     }

  125.     /**
  126.      * Ensures the truth of an expression involving the state of the calling
  127.      * instance, but not involving any parameters to the calling method.
  128.      *
  129.      * @param expression a boolean expression.
  130.      * @param message Error message for the exception when the expression is false.
  131.      * @throws IllegalStateException if expression is false.
  132.      */
  133.     public static void checkState(final boolean expression, final String message) {
  134.         if (!expression) {
  135.             throw new IllegalStateException(message);
  136.         }
  137.     }

  138.     /**
  139.      * Helper method to create a CryptoCipher instance and throws only
  140.      * IOException.
  141.      *
  142.      * @param properties The {@code Properties} class represents a set of
  143.      *        properties.
  144.      * @param transformation the name of the transformation, e.g.,
  145.      * <i>AES/CBC/PKCS5Padding</i>.
  146.      * See the Java Cryptography Architecture Standard Algorithm Name Documentation
  147.      * for information about standard transformation names.
  148.      * @return the CryptoCipher instance.
  149.      * @throws IOException if an I/O error occurs.
  150.      */
  151.     public static CryptoCipher getCipherInstance(final String transformation, final Properties properties) throws IOException {
  152.         try {
  153.             return CryptoCipherFactory.getCryptoCipher(transformation, properties);
  154.         } catch (final GeneralSecurityException e) {
  155.             throw new IOException(e);
  156.         }
  157.     }

  158.     /**
  159.      * Gets a properties instance that defaults to the System Properties
  160.      * plus any other properties found in the file
  161.      * {@link #SYSTEM_PROPERTIES_FILE}
  162.      * @return a Properties instance with defaults
  163.      */
  164.     public static Properties getDefaultProperties() {
  165.         return new Properties(DefaultPropertiesHolder.DEFAULT_PROPERTIES);
  166.     }

  167.     /**
  168.      * Gets the properties merged with default properties.
  169.      * @param newProp  User-defined properties
  170.      * @return User-defined properties with the default properties
  171.      */
  172.     public static Properties getProperties(final Properties newProp) {
  173.         final Properties properties = new Properties(DefaultPropertiesHolder.DEFAULT_PROPERTIES);
  174.         properties.putAll(newProp);
  175.         return properties;
  176.      }

  177.     /*
  178.      * Override the default DLL name if jni.library.path is a valid directory
  179.      * @param name - the default name, passed from native code
  180.      * @return the updated library path
  181.      * This method is designed for use from the DynamicLoader native code.
  182.      * Although it could all be implemented in native code, this hook method
  183.      * makes maintenance easier.
  184.      * The code is intended for use with macOS where SIP makes it hard to override
  185.      * the environment variables needed to override the DLL search path. It also
  186.      * works for Linux, but is not (currently) used or needed for Windows.
  187.      * Do not change the method name or its signature!
  188.      */
  189.     static String libraryPath(final String name) {
  190.         final String override = System.getProperty("jni.library.path");
  191.         if (override != null && new File(override).isDirectory()) {
  192.             return new File(override, name).getPath();
  193.         }
  194.         return name;
  195.     }

  196.     /**
  197.      * Splits class names sequence into substrings, Trim each substring into an
  198.      * entry,and returns an list of the entries.
  199.      *
  200.      * @param clazzNames a string consist of a list of the entries joined by a
  201.      *        delimiter, may be null or empty in which case an empty list is returned.
  202.      * @param separator a delimiter for the input string.
  203.      * @return a list of class entries.
  204.      */
  205.     public static List<String> splitClassNames(final String clazzNames, final String separator) {
  206.         final List<String> res = new ArrayList<>();
  207.         if (clazzNames == null || clazzNames.isEmpty()) {
  208.             return res;
  209.         }

  210.         for (String clazzName : clazzNames.split(separator)) {
  211.             clazzName = clazzName.trim();
  212.             if (!clazzName.isEmpty()) {
  213.                 res.add(clazzName);
  214.             }
  215.         }
  216.         return res;
  217.     }

  218.     /**
  219.      * The private constructor of {@link Utils}.
  220.      */
  221.     private Utils() {
  222.     }

  223. }