View Javadoc

1   /*
2    * Copyright 2005 University Corporation for Advanced Internet Development, Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.opensaml.xml.util;
18  
19  import java.io.BufferedReader;
20  import java.io.File;
21  import java.io.FileInputStream;
22  import java.io.IOException;
23  import java.io.InputStream;
24  import java.io.InputStreamReader;
25  import java.nio.charset.Charset;
26  import java.nio.charset.CharsetDecoder;
27  import java.util.ArrayList;
28  import java.util.Iterator;
29  import java.util.List;
30  import java.util.StringTokenizer;
31  
32  /** Helper class for working with various datatypes. */
33  public final class DatatypeHelper {
34  
35      /** Constructor. */
36      private DatatypeHelper() {
37  
38      }
39  
40      /**
41       * A "safe" null/empty check for strings.
42       * 
43       * @param s The string to check
44       * 
45       * @return true if the string is null or the trimmed string is length zero
46       */
47      public static boolean isEmpty(String s) {
48          if (s != null) {
49              String sTrimmed = s.trim();
50              if (sTrimmed.length() > 0) {
51                  return false;
52              }
53          }
54  
55          return true;
56      }
57  
58      /**
59       * Compares two strings for equality, allowing for nulls.
60       * 
61       * @param <T> type of object to compare
62       * @param s1 The first operand
63       * @param s2 The second operand
64       * 
65       * @return true if both are null or both are non-null and the same strng value
66       */
67      public static <T> boolean safeEquals(T s1, T s2) {
68          if (s1 == null || s2 == null) {
69              return s1 == s2;
70          }
71  
72          return s1.equals(s2);
73      }
74  
75      /**
76       * A safe string trim that handles nulls.
77       * 
78       * @param s the string to trim
79       * 
80       * @return the trimmed string or null if the given string was null
81       */
82      public static String safeTrim(String s) {
83          if (s != null) {
84              return s.trim();
85          }
86  
87          return null;
88      }
89  
90      /**
91       * Removes preceeding or proceeding whitespace from a string or return null if the string is null or of zero length
92       * after trimming (i.e. if the string only contained whitespace).
93       * 
94       * @param s the string to trim
95       * 
96       * @return the trimmed string or null
97       */
98      public static String safeTrimOrNullString(String s) {
99          if (s != null) {
100             String sTrimmed = s.trim();
101             if (sTrimmed.length() > 0) {
102                 return sTrimmed;
103             }
104         }
105 
106         return null;
107     }
108 
109     /**
110      * Converts an integer into an unsigned 4-byte array.
111      * 
112      * @param integer integer to convert
113      * 
114      * @return 4-byte array representing integer
115      */
116     public static byte[] intToByteArray(int integer) {
117         byte[] intBytes = new byte[4];
118         intBytes[0] = (byte) ((integer & 0xff000000) >>> 24);
119         intBytes[1] = (byte) ((integer & 0x00ff0000) >>> 16);
120         intBytes[2] = (byte) ((integer & 0x0000ff00) >>> 8);
121         intBytes[3] = (byte) ((integer & 0x000000ff));
122 
123         return intBytes;
124     }
125 
126     /**
127      * Reads the contents of a file in to a byte array.
128      * 
129      * @param file file to read
130      * @return the byte contents of the file
131      * 
132      * @throws IOException throw if there is a problem reading the file in to the byte array
133      */
134     public static byte[] fileToByteArray(File file) throws IOException {
135         long numOfBytes = file.length();
136 
137         if (numOfBytes > Integer.MAX_VALUE) {
138             throw new IOException("File is to large to be read in to a byte array");
139         }
140 
141         byte[] bytes = new byte[(int) numOfBytes];
142         FileInputStream ins = new FileInputStream(file);
143         int offset = 0;
144         int numRead = 0;
145         do {
146             numRead = ins.read(bytes, offset, bytes.length - offset);
147             offset += numRead;
148         } while (offset < bytes.length && numRead >= 0);
149 
150         if (offset < bytes.length) {
151             throw new IOException("Could not completely read file " + file.getName());
152         }
153 
154         ins.close();
155         return bytes;
156     }
157 
158     /**
159      * Reads an input stream into a string. The provide stream is <strong>not</strong> closed.
160      * 
161      * @param input the input stream to read
162      * @param decoder character decoder to use, if null, system default character set is used
163      * 
164      * @return the string read from the stream
165      * 
166      * @throws IOException thrown if there is a problem reading from the stream and decoding it
167      */
168     public static String inputstreamToString(InputStream input, CharsetDecoder decoder) throws IOException {
169         CharsetDecoder charsetDecoder = decoder;
170         if (decoder == null) {
171             charsetDecoder = Charset.defaultCharset().newDecoder();
172         }
173 
174         BufferedReader reader = new BufferedReader(new InputStreamReader(input, charsetDecoder));
175 
176         StringBuilder stringBuffer = new StringBuilder();
177         String line = reader.readLine();
178         while(line != null){
179             stringBuffer.append(line).append("\n");
180             line = reader.readLine();
181         }
182 
183         reader.close();
184 
185         return stringBuffer.toString();
186     }
187 
188     /**
189      * Converts a delimited string into a list.
190      * 
191      * @param string the string to be split into a list
192      * @param delimiter the delimiter between values. This string may contain
193      *                  multiple delimiter characters, as allowed by
194      *                  {@link StringTokenizer}
195      * 
196      * @return the list of values or an empty list if the given string is null or empty
197      */
198     public static List<String> stringToList(String string, String delimiter) {
199         if (delimiter == null) {
200             throw new IllegalArgumentException("String delimiter may not be null");
201         }
202 
203         ArrayList<String> values = new ArrayList<String>();
204 
205         String trimmedString = safeTrimOrNullString(string);
206         if (trimmedString != null) {
207             StringTokenizer tokens = new StringTokenizer(trimmedString, delimiter);
208             while (tokens.hasMoreTokens()) {
209                 values.add(tokens.nextToken());
210             }
211         }
212 
213         return values;
214     }
215 
216     /**
217      * Converts a List of strings into a single string, with values separated by a
218      * specified delimiter.
219      * 
220      * @param values list of strings
221      * @param delimiter the delimiter used between values
222      * 
223      * @return delimited string of values
224      */
225     public static String listToStringValue(List<String> values, String delimiter) {
226         if (delimiter == null) {
227             throw new IllegalArgumentException("String delimiter may not be null");
228         }
229         
230         StringBuilder stringValue = new StringBuilder();
231         Iterator<String> valueItr = values.iterator();
232         while(valueItr.hasNext()){
233             stringValue.append(valueItr.next());
234             if(valueItr.hasNext()){
235                 stringValue.append(delimiter);
236             }
237         }
238         
239         return stringValue.toString();
240     }
241 }