View Javadoc
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  
20  import java.io.IOException;
21  import java.io.InputStream;
22  import java.security.GeneralSecurityException;
23  import java.util.ArrayList;
24  import java.util.Enumeration;
25  import java.util.List;
26  import java.util.Properties;
27  
28  import org.apache.commons.crypto.Crypto;
29  import org.apache.commons.crypto.cipher.CryptoCipher;
30  import org.apache.commons.crypto.cipher.CryptoCipherFactory;
31  
32  /**
33   * General utility methods.
34   */
35  public final class Utils {
36  
37      private static class DefaultPropertiesHolder {
38          static final Properties DEFAULT_PROPERTIES = createDefaultProperties();
39       }
40  
41      /**
42       * The filename of configuration file.
43       * TODO is there any need for it to have the CONF_PREFIX?
44       */
45      private static final String SYSTEM_PROPERTIES_FILE = Crypto.CONF_PREFIX
46              + "properties";
47  
48      /**
49       * The private constructor of {@link Utils}.
50       */
51      private Utils() {
52      }
53  
54      /**
55       * Loads system properties when configuration file of the name
56       * {@link #SYSTEM_PROPERTIES_FILE} is found.
57       *
58       * @return the default properties
59       */
60      private static Properties createDefaultProperties() {
61          // default to system
62          Properties defaultedProps = new Properties(System.getProperties());
63          try {
64              InputStream is = Thread.currentThread().getContextClassLoader()
65                      .getResourceAsStream(SYSTEM_PROPERTIES_FILE);
66  
67              if (is == null) {
68                  return defaultedProps; // no configuration file is found
69              }
70              // Load property file
71              Properties fileProps = new Properties();
72              fileProps.load(is);
73              is.close();
74              Enumeration<?> names = fileProps.propertyNames();
75              while (names.hasMoreElements()) {
76                  String name = (String) names.nextElement();
77                  // ensure System properties override ones in the file so one can override the file on the command line
78                  if (System.getProperty(name) == null) {
79                      defaultedProps.setProperty(name, fileProps.getProperty(name));
80                  }
81              }
82          } catch (Exception ex) {
83              System.err.println("Could not load '"
84                      + SYSTEM_PROPERTIES_FILE
85                      + "' from classpath: " + ex.toString());
86          }
87          return defaultedProps;
88      }
89  
90      /**
91       * Gets a properties instance that defaults to the System Properties
92       * plus any other properties found in the file 
93       * {@link #SYSTEM_PROPERTIES_FILE}
94       * @return a Properties instance with defaults
95       */
96      public static Properties getDefaultProperties() {
97          return new Properties(DefaultPropertiesHolder.DEFAULT_PROPERTIES);
98       }
99  
100     /**
101      * Gets the properties merged with default properties.
102      * @param newProp  User-defined properties
103      * @return User-defined properties with the default properties
104      */
105     public static Properties getProperties(Properties newProp) {
106         Properties properties = new Properties(DefaultPropertiesHolder.DEFAULT_PROPERTIES);
107         properties.putAll(newProp);
108         return properties;
109      }
110 
111     /**
112      * Helper method to create a CryptoCipher instance and throws only
113      * IOException.
114      *
115      * @param props The <code>Properties</code> class represents a set of
116      *        properties.
117      * @param transformation the name of the transformation, e.g.,
118      * <i>AES/CBC/PKCS5Padding</i>.
119      * See the Java Cryptography Architecture Standard Algorithm Name Documentation
120      * for information about standard transformation names.
121      * @return the CryptoCipher instance.
122      * @throws IOException if an I/O error occurs.
123      */
124     public static CryptoCipher getCipherInstance(
125             String transformation, Properties props)
126             throws IOException {
127         try {
128             return CryptoCipherFactory.getCryptoCipher(transformation, props);
129         } catch (GeneralSecurityException e) {
130             throw new IOException(e);
131         }
132     }
133 
134     /**
135      * Ensures the truth of an expression involving one or more parameters to
136      * the calling method.
137      *
138      * @param expression a boolean expression.
139      * @throws IllegalArgumentException if expression is false.
140      */
141     public static void checkArgument(boolean expression) {
142         if (!expression) {
143             throw new IllegalArgumentException();
144         }
145     }
146 
147     /**
148      * Checks the truth of an expression.
149      *
150      * @param expression a boolean expression.
151      * @param errorMessage the exception message to use if the check fails; will
152      *        be converted to a string using <code>String
153      *                     .valueOf(Object)</code>.
154      * @throws IllegalArgumentException if expression is false.
155      */
156     public static void checkArgument(boolean expression, Object errorMessage) {
157         if (!expression) {
158             throw new IllegalArgumentException(String.valueOf(errorMessage));
159         }
160     }
161 
162     /**
163      * Ensures that an object reference passed as a parameter to the calling
164      * method is not null.
165      *
166      * @param <T> the type of the object reference to be checked.
167      * @param reference an object reference.
168      * @return the non-null reference that was validated.
169      * @throws NullPointerException if reference is null.
170      */
171     public static <T> T checkNotNull(T reference) {
172         if (reference == null) {
173             throw new NullPointerException();
174         }
175         return reference;
176     }
177 
178     /**
179      * Ensures the truth of an expression involving the state of the calling
180      * instance, but not involving any parameters to the calling method.
181      *
182      * @param expression a boolean expression.
183      * @throws IllegalStateException if expression is false.
184      */
185     public static void checkState(boolean expression) {
186         if (!expression) {
187             throw new IllegalStateException();
188         }
189     }
190 
191     /**
192      * Splits class names sequence into substrings, Trim each substring into an
193      * entry,and returns an list of the entries.
194      *
195      * @param clazzNames a string consist of a list of the entries joined by a
196      *        delimiter, may be null or empty in which case an empty list is returned.
197      * @param separator a delimiter for the input string.
198      * @return a list of class entries.
199      */
200     public static List<String> splitClassNames(String clazzNames, String separator) {
201         List<String> res = new ArrayList<>();
202         if (clazzNames == null || clazzNames.isEmpty()) {
203             return res;
204         }
205 
206         for (String clazzName : clazzNames.split(separator)) {
207             clazzName = clazzName.trim();
208             if (!clazzName.isEmpty()) {
209                 res.add(clazzName);
210             }
211         }
212         return res;
213     }
214 
215 }