1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
28
29 public final class DatatypeHelper {
30
31
32 private DatatypeHelper() {
33
34 }
35
36
37
38
39
40
41
42
43 public static boolean isEmpty(String s) {
44 if (s != null) {
45 String sTrimmed = s.trim();
46 if (sTrimmed.length() > 0) {
47 return false;
48 }
49 }
50
51 return true;
52 }
53
54
55
56
57
58
59
60
61
62
63 public static <T> boolean safeEquals(T s1, T s2) {
64 if (s1 == null || s2 == null) {
65 return s1 == s2;
66 }
67
68 return s1.equals(s2);
69 }
70
71
72
73
74
75
76
77
78 public static String safeTrim(String s) {
79 if (s != null) {
80 return s.trim();
81 }
82
83 return null;
84 }
85
86
87
88
89
90
91
92
93
94 public static String safeTrimOrNullString(String s) {
95 if (s != null) {
96 String sTrimmed = s.trim();
97 if (sTrimmed.length() > 0) {
98 return sTrimmed;
99 }
100 }
101
102 return null;
103 }
104
105
106
107
108
109
110
111
112 public static byte[] intToByteArray(int integer) {
113 byte[] intBytes = new byte[4];
114 intBytes[0] = (byte) ((integer & 0xff000000) >>> 24);
115 intBytes[1] = (byte) ((integer & 0x00ff0000) >>> 16);
116 intBytes[2] = (byte) ((integer & 0x0000ff00) >>> 8);
117 intBytes[3] = (byte) ((integer & 0x000000ff));
118
119 return intBytes;
120 }
121
122
123
124
125
126
127
128
129
130 public static byte[] fileToByteArray(File file) throws IOException {
131 long numOfBytes = file.length();
132
133 if (numOfBytes > Integer.MAX_VALUE) {
134 throw new IOException("File is to large to be read in to a byte array");
135 }
136
137 byte[] bytes = new byte[(int) numOfBytes];
138 FileInputStream ins = new FileInputStream(file);
139 int offset = 0;
140 int numRead = 0;
141 do{
142 numRead = ins.read(bytes, offset, bytes.length - offset);
143 offset += numRead;
144 }while(offset < bytes.length && numRead >= 0);
145
146 if (offset < bytes.length) {
147 throw new IOException("Could not completely read file " + file.getName());
148 }
149
150 ins.close();
151 return bytes;
152 }
153
154
155
156
157
158
159
160
161
162
163
164 public static String inputstreamToString(InputStream input, CharsetDecoder decoder) throws IOException {
165 CharsetDecoder charsetDecoder = decoder;
166 if (decoder == null) {
167 charsetDecoder = Charset.defaultCharset().newDecoder();
168 }
169
170 StringBuffer stringBuffer = new StringBuffer(2048);
171 BufferedReader reader = new BufferedReader(new InputStreamReader(input, charsetDecoder));
172
173 char[] chars = new char[1024];
174 while (reader.read(chars) > -1) {
175 stringBuffer.append(String.valueOf(chars));
176 chars = new char[1024];
177 }
178
179 reader.close();
180
181 return stringBuffer.toString();
182 }
183 }