3 * Copyright (C) 2007 EDIT
4 * European Distributed Institute of Taxonomy
5 * http://www.e-taxonomy.eu
7 * The contents of this file are subject to the Mozilla Public License Version 1.1
8 * See LICENSE.TXT at the top of this package for the full license terms.
11 package eu
.etaxonomy
.cdm
.common
;
13 import java
.io
.BufferedReader
;
15 import java
.io
.IOException
;
16 import java
.io
.InputStream
;
17 import java
.io
.InputStreamReader
;
18 import java
.lang
.annotation
.Annotation
;
19 import java
.lang
.reflect
.Field
;
20 import java
.lang
.reflect
.Modifier
;
21 import java
.net
.HttpURLConnection
;
22 import java
.net
.MalformedURLException
;
24 import java
.net
.URISyntaxException
;
26 import java
.util
.ArrayList
;
27 import java
.util
.HashMap
;
29 import java
.util
.regex
.Matcher
;
30 import java
.util
.regex
.Pattern
;
31 import org
.apache
.log4j
.Logger
;
37 public class CdmUtils
{
38 private static final Logger logger
= Logger
.getLogger(CdmUtils
.class);
41 static final String MUST_EXIST_FILE
= "MUST-EXIST.txt";
44 static String folderSeperator
;
47 public static String
getHomeDir() throws IOException
{
48 String homeDirString
= System
.getenv("USERPROFILE") != null ? System
.getenv("USERPROFILE") : System
.getProperty("user.home");
50 if( ! new File(homeDirString
).canWrite()){
51 throw new IOException("Can not write to home directory. Assumed path is: " + homeDirString
);
58 * Returns the an InputStream for a read-only source
59 * @param resourceFileName the resources path within the classpath(!)
63 public static InputStream
getReadableResourceStream(String resourceFileName
)
65 InputStream urlStream
= CdmUtils
.class.getResourceAsStream("/"+ resourceFileName
);
70 * Returns the an InputStream for a read-only source
71 * @param resourceFileName the resources path within the classpath(!)
75 public static InputStreamReader
getUtf8ResourceReader(String resourceFileName
)
77 InputStream urlStream
= CdmUtils
.class.getResourceAsStream("/"+ resourceFileName
);
78 InputStreamReader inputStreamReader
= new InputStreamReader(urlStream
, "UTF8");
79 return inputStreamReader
;
86 static public String
getFolderSeperator(){
87 if (folderSeperator
== null){
88 URL url
= CdmUtils
.class.getResource("/"+ MUST_EXIST_FILE
);
89 if ( url
!= null && ! urlIsJarOrBundle(url
) ){
90 folderSeperator
= File
.separator
;
92 folderSeperator
= "/";
95 return folderSeperator
;
103 static private boolean urlIsJarOrBundle(URL url
){
104 return url
.getProtocol().startsWith("jar") || url
.getProtocol().startsWith("bundleresource");
108 * Returns the file name for the file in which 'clazz' is to be found (helps finding according libraries)
112 static public String
findLibrary(Class
<?
> clazz
){
113 String result
= null;
115 String fullPackageName
= clazz
.getCanonicalName();
116 fullPackageName
= fullPackageName
.replace(".", "/");
117 URL url
= CdmUtils
.class.getResource("/" + fullPackageName
+ ".class" );
119 result
= url
.getFile();
123 logger
.debug("LibraryURL for " + clazz
.getCanonicalName() + " : " + result
);
128 static public String
testMe(){
129 String message
= "This is a test";
130 System
.out
.println(message
);
134 static public String
readInputLine(String inputQuestion
){
137 System
.out
.print(inputQuestion
);
138 BufferedReader in
= new BufferedReader( new java
.io
.InputStreamReader( System
.in
));
140 input
= in
.readLine();
142 } catch (IOException e
) {
143 logger
.warn("IOExeption");
150 * Returns the trimmed value string if value is not <code>null</code>.
151 * Returns the empty string if value is <code>null</code>.
155 static public String
NzTrim(String value
){
156 return (value
== null ?
"" : value
);
161 * Returns value if value is not <code>null</code>. Returns empty string if value is <code>null</code>.
165 static public String
Nz(String value
){
166 return (value
== null ?
"" : value
);
171 * Returns value if value is not <code>null</code>. Returns 0 if value is <code>null</code>.
175 static public Integer
Nz(Integer value
){
176 return (value
== null ?
0 : value
);
180 * Returns value if value is not <code>null</code>. Returns 0 if value is <code>null</code>.
184 static public Long
Nz(Long value
){
185 return (value
== null ?
0 : value
);
189 * Concatenates an array of strings using the defined seperator.<BR>
190 * <code>Null</code> values are interpreted as empty strings.<BR>
191 * If all strings are <code>null</code> then <code>null</code> is returned.
196 static public String
concat(CharSequence seperator
, String
[] strings
){
198 boolean allNull
= true;
199 for (String string
: strings
){
201 if (result
.length() > 0 && string
.length() > 0){
208 //if all strings are null result should be null, not ""
217 * Concatenates two strings, using the defined seperator.<BR>
218 * <code>Null</code> values are interpreted as empty Strings.<BR>
219 * If both strings are <code>null</code> then <code>null</code> is returned.
220 * @see #concat(CharSequence, String[])
226 static public String
concat(CharSequence seperator
, String string1
, String string2
){
227 String
[] strings
= {string1
, string2
};
228 return concat(seperator
, strings
);
232 /** Returns a version of the input where all contiguous
233 * whitespace characters are replaced with a single
234 * space. Line terminators are treated like whitespace.
239 public static CharSequence
removeDuplicateWhitespace(CharSequence inputStr
) {
241 String patternStr
= "\\s+";
242 String replaceStr
= " ";
243 Pattern pattern
= Pattern
.compile(patternStr
);
244 Matcher matcher
= pattern
.matcher(inputStr
);
245 return matcher
.replaceAll(replaceStr
);
249 /** Builds a list of strings by splitting an input string
250 * with delimiters whitespace, comma, or semicolon
254 public static ArrayList
<String
> buildList(String value
) {
256 ArrayList
<String
> resultList
= new ArrayList
<String
>();
257 for (String tag
: value
.split("[\\s,;]+")) {
264 static public boolean urlExists(String strUrl
, boolean withWarning
){
266 HttpURLConnection
.setFollowRedirects(false);
267 // note : you may also need
268 // HttpURLConnection.setInstanceFollowRedirects(false)
269 HttpURLConnection con
=
270 (HttpURLConnection
) new URL(strUrl
).openConnection();
271 con
.setRequestMethod("HEAD");
272 return (con
.getResponseCode() == HttpURLConnection
.HTTP_OK
);
273 } catch (MalformedURLException e
) {
277 } catch (IOException e
) {
283 static public URI
string2Uri(String string
) {
286 uri
= new URI(string
);
287 logger
.debug("uri: " + uri
.toString());
288 } catch (URISyntaxException ex
) {
289 logger
.error("Problem converting string " + string
+ " to URI " + uri
);
295 static public boolean isNumeric(String string
){
300 Double
.valueOf(string
);
302 } catch (NumberFormatException e
) {
309 * Returns true if string is null, "" or string.trim() is ""
310 * @see isNotEmpty(String string)
314 static public boolean isEmpty(String string
){
318 if ("".equals(string
.trim())){
325 * Tests if two objects are equal or both null. Otherwise returns false
330 public static boolean nullSafeEqual(Object obj1
, Object obj2
) {
331 if (obj1
== null && obj2
== null){
334 if (obj1
== null && obj2
!= null){
337 return (obj1
.equals(obj2
));
341 * Returns false if string is null, "" or string.trim() is ""
343 * @see isEmpty(String string)
347 static public boolean isNotEmpty(String string
){
348 return !isEmpty(string
);
353 * Computes all fields recursively
357 public static Map
<String
, Field
> getAllFields(Class clazz
, Class highestClass
, boolean includeStatic
, boolean includeTransient
, boolean makeAccessible
, boolean includeHighestClass
) {
358 Map
<String
, Field
> result
= new HashMap
<String
, Field
>();
359 if ( highestClass
.isAssignableFrom(clazz
) && (clazz
!= highestClass
|| includeHighestClass
)){
361 for (Field field
: clazz
.getDeclaredFields()){
362 if (includeStatic
|| ! Modifier
.isStatic(field
.getModifiers())){
363 if (includeTransient
|| ! isTransient(field
)){
364 field
.setAccessible(makeAccessible
);
365 result
.put(field
.getName(), field
);
370 //include superclass fields
371 Class superclass
= clazz
.getSuperclass();
372 if (superclass
!= null){
373 result
.putAll(getAllFields(superclass
, highestClass
, includeStatic
, includeTransient
, makeAccessible
, includeHighestClass
));
381 * Returns true, if field has an annotation of type javax.persistence.Annotation
385 protected static boolean isTransient(Field field
) {
386 for (Annotation annotation
: field
.getAnnotations()){
387 //if (Transient.class.isAssignableFrom(annotation.annotationType())){
388 if (annotation
.annotationType().getSimpleName().equals("Transient")){