Project

General

Profile

Download (16.1 KB) Statistics
| Branch: | Tag: | Revision:
1
// $Id$
2
/**
3
* Copyright (C) 2007 EDIT
4
* European Distributed Institute of Taxonomy
5
* http://www.e-taxonomy.eu
6
*
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.
9
*/
10

    
11
package eu.etaxonomy.cdm.common;
12

    
13
import java.io.BufferedReader;
14
import java.io.File;
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;
23
import java.net.URI;
24
import java.net.URISyntaxException;
25
import java.net.URL;
26
import java.util.ArrayList;
27
import java.util.HashMap;
28
import java.util.Map;
29
import java.util.regex.Matcher;
30
import java.util.regex.Pattern;
31

    
32
import org.apache.commons.lang.StringUtils;
33
import org.apache.log4j.Logger;
34

    
35
/**
36
 * @author a.mueller
37
 * @author a.kohlbecker
38
 */
39
public class CdmUtils {
40

    
41
    private static final Logger logger = Logger.getLogger(CdmUtils.class);
42

    
43
    /**
44
     * The per user cdm folder name: ".cdmLibrary"
45
     */
46
    private static final String cdmFolderName = ".cdmLibrary";
47

    
48
    final static String userHome = System.getProperty("user.home");
49

    
50
    /**
51
     * The per user cdm folder "~/.cdmLibrary"
52
     */
53
    public final static File perUserCdmFolder = new File(userHome + File.separator + ".cdmLibrary" );
54

    
55

    
56

    
57

    
58
    static final String MUST_EXIST_FILE = "MUST-EXIST.txt";
59

    
60
    //folder seperator
61
    static String folderSeperator;
62

    
63
    //TODO refactor to: public static File getUserHomeDir()
64
    public static String getHomeDir() throws IOException{
65
        //TODO why do we need System.getenv("USERPROFILE")? System.getProperty("user.home") is fully sufficient!!
66
        String homeDirString = System.getenv("USERPROFILE") != null ? System.getenv("USERPROFILE") : System.getProperty("user.home");
67

    
68
        if( ! new File(homeDirString).canWrite()){
69
            throw new IOException("Can not write to home directory. Assumed path is: " + homeDirString);
70
        }
71

    
72
        return homeDirString;
73
    }
74

    
75
    public static File getCdmHomeDir() {
76
        return new File(System.getProperty("user.home")+File.separator+cdmFolderName+File.separator);
77
    }
78

    
79

    
80

    
81

    
82
    /**
83
     * Returns the an InputStream for a read-only source
84
     * @param resourceFileName the resources path within the classpath(!)
85
     * @return
86
     * @throws IOException
87
     */
88
    public static InputStream getReadableResourceStream(String resourceFileName)
89
            throws IOException{
90
        InputStream urlStream = CdmUtils.class.getResourceAsStream("/"+ resourceFileName);
91
        return urlStream;
92
    }
93

    
94
    /**
95
     * Returns the an InputStream for a read-only source
96
     * @param resourceFileName the resources path within the classpath(!)
97
     * @return
98
     * @throws IOException
99
     */
100
    public static InputStreamReader getUtf8ResourceReader(String resourceFileName)
101
            throws IOException{
102
        InputStream urlStream = CdmUtils.class.getResourceAsStream("/"+ resourceFileName);
103
        InputStreamReader inputStreamReader = new InputStreamReader(urlStream, "UTF8");
104
        return inputStreamReader;
105
    }
106

    
107

    
108
    /**
109
     * @return
110
     */
111
    static public String getFolderSeperator(){
112
        if (folderSeperator == null){
113
            URL url = CdmUtils.class.getResource("/"+ MUST_EXIST_FILE);
114
            if ( url != null && ! urlIsJarOrBundle(url) ){
115
                folderSeperator =  File.separator;
116
            }else{
117
                folderSeperator = "/";
118
            }
119
        }
120
        return folderSeperator;
121
    }
122

    
123

    
124
    /**
125
     * @param url
126
     * @return
127
     */
128
    static private boolean urlIsJarOrBundle(URL url){
129
        return url.getProtocol().startsWith("jar") || url.getProtocol().startsWith("bundleresource");
130
    }
131

    
132
    /**
133
     * Returns the file name for the file in which 'clazz' is to be found (helps finding according libraries)
134
     * @param clazz
135
     * @return
136
     */
137
    static public String findLibrary(Class<?> clazz){
138
        String result = null;
139
        if (clazz != null){
140
            String fullPackageName = clazz.getCanonicalName();
141
            fullPackageName = fullPackageName.replace(".", "/");
142
            URL url = CdmUtils.class.getResource("/" + fullPackageName + ".class" );
143
            if (url != null){
144
                result = url.getFile();
145
            }else{
146
                result = "";
147
            }
148
            logger.debug("LibraryURL for " + clazz.getCanonicalName() + " : " + result);
149
        }
150
        return result;
151
    }
152

    
153
    static public String testMe(){
154
        String message = "This is a test";
155
        System.out.println(message);
156
        return message;
157
    }
158

    
159
    static public String readInputLine(String inputQuestion){
160
        try {
161

    
162
            System.out.print(inputQuestion);
163
            BufferedReader in = new BufferedReader( new java.io.InputStreamReader( System.in ));
164
            String input;
165
            input = in.readLine();
166
            return input;
167
        } catch (IOException e) {
168
            logger.warn("IOExeption");
169
            return null;
170
        }
171
    }
172

    
173

    
174
    /**
175
     * Returns the trimmed value string if value is not <code>null</code>.
176
     * Returns the empty string if value is <code>null</code>.
177
     * @param value
178
     * @return
179
     */
180
    static public String NzTrim(String value){
181
        return (value == null ? "" : value);
182
    }
183

    
184

    
185
    /**
186
     * Returns value if value is not <code>null</code>. Returns empty string if value is <code>null</code>.
187
     * @param value
188
     * @return
189
     */
190
    static public String Nz(String value){
191
        return (value == null ? "" : value);
192
    }
193

    
194
    /**
195
     * Returns value if value is not <code>null</code>. Returns defaultValue if value is <code>null</code>.
196
     * @param value
197
     * @return
198
     */
199
    static public String Nz(String value, String defaultValue){
200
        return (value == null ? defaultValue : value);
201
    }
202

    
203
    /**
204
     * Returns value if value is not <code>null</code>. Returns 0 if value is <code>null</code>.
205
     * @param value
206
     * @return
207
     */
208
    static public Integer Nz(Integer value){
209
        return (value == null ? 0 : value);
210
    }
211

    
212
    /**
213
     * Returns value if value is not <code>null</code>. Returns 0 if value is <code>null</code>.
214
     * @param value
215
     * @return
216
     */
217
    static public Long Nz(Long value){
218
        return (value == null ? 0 : value);
219
    }
220

    
221
    /**
222
     * Concatenates an array of strings using the defined seperator.<BR>
223
     * <code>Null</code> values are interpreted as empty strings.<BR>
224
     * If all strings are <code>null</code> then <code>null</code> is returned.
225
     * @param strings
226
     * @param seperator
227
     * @return String
228
     */
229
    static public String concat(CharSequence separator, String[] strings){
230
        String result = "";
231
        boolean allNull = true;
232
        for (String string : strings){
233
            if (string != null){
234
                if (result.length() > 0 && string.length() > 0){
235
                    result += separator;
236
                }
237
                result += string;
238
                allNull = false;
239
            }
240
        }
241
        //if all strings are null result should be null, not ""
242
        if (allNull){
243
            return null;
244
        }else {
245
            return result;
246
        }
247
    }
248

    
249
    /**
250
     * Concatenates two strings, using the defined seperator.<BR>
251
     * <code>Null</code> values are interpreted as empty Strings.<BR>
252
     * If both strings are <code>null</code> then <code>null</code> is returned.
253
     * @see #concat(CharSequence, String[])
254
     * @param seperator
255
     * @param string1
256
     * @param string2
257
     * @return String
258
     */
259
    static public String concat(CharSequence separator, String string1, String string2){
260
        String[] strings = {string1, string2};
261
        return concat(separator, strings);
262
    }
263
    
264
	
265
	/**
266
	 * Returns <code>preferred</code> if not blank, else returns <code>alternative</code>.
267
	 * If reverse is <code>true</code> computation is 
268
	 * the other way round (<code>alternative</code> if not blank, otherwise <code>preferred</code>).
269
	 * @param preferred first string
270
	 * @param alternative second string
271
	 * @param reverse reverse flag
272
	 * @param nzTrim if <code>true</code> the result is trimmed and <code>null</code> values are replaced by empty string.
273
	 * @return the preferred string
274
	 */
275
	static public String getPreferredNonEmptyString(String preferred, String alternative, boolean reverse, boolean nzTrim){
276
		String result;
277
		if (! reverse){
278
			result = StringUtils.isBlank(preferred) ? alternative : preferred;
279
		}else{
280
			result = StringUtils.isBlank(alternative) ? preferred : alternative;
281
		}
282
		if (nzTrim){
283
			result = Nz(result).trim();
284
		}
285
		return result;
286
	}
287

    
288

    
289
    /** Returns a version of the input where all contiguous
290
     * whitespace characters are replaced with a single
291
     * space. Line terminators are treated like whitespace.
292
     *
293
     * @param inputStr
294
     * @return
295
     */
296
    public static CharSequence removeDuplicateWhitespace(CharSequence inputStr) {
297

    
298
        String patternStr = "\\s+";
299
        String replaceStr = " ";
300
        Pattern pattern = Pattern.compile(patternStr);
301
        Matcher matcher = pattern.matcher(inputStr);
302
        return matcher.replaceAll(replaceStr);
303
    }
304

    
305

    
306
    /** Builds a list of strings by splitting an input string
307
     * with delimiters whitespace, comma, or semicolon
308
     * @param value
309
     * @return
310
     */
311
    public static ArrayList<String> buildList(String value) {
312

    
313
        ArrayList<String> resultList = new ArrayList<String>();
314
        for (String tag : value.split("[\\s,;]+")) {
315
            resultList.add(tag);
316
        }
317
        return resultList;
318
    }
319

    
320

    
321
    static public boolean urlExists(String strUrl, boolean withWarning){
322
        try {
323
             HttpURLConnection.setFollowRedirects(false);
324
              // note : you may also need
325
              //        HttpURLConnection.setInstanceFollowRedirects(false)
326
              HttpURLConnection con =
327
                 (HttpURLConnection) new URL(strUrl).openConnection();
328
              con.setRequestMethod("HEAD");
329
              return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
330
        } catch (MalformedURLException e) {
331
            if (withWarning) {
332
                logger.warn(e);
333
            }
334
        } catch (IOException e) {
335
            //
336
        };
337
        return false;
338
    }
339

    
340
    static public URI string2Uri(String string) {
341
        URI uri = null;
342
        try {
343
            uri = new URI(string);
344
            logger.debug("uri: " + uri.toString());
345
        } catch (URISyntaxException ex) {
346
            logger.error("Problem converting string " + string + " to URI " + uri);
347
            return null;
348
        }
349
        return uri;
350
    }
351

    
352
    static public boolean isNumeric(String string){
353
        if (string == null){
354
            return false;
355
        }
356
        try {
357
            Double.valueOf(string);
358
            return true;
359
        } catch (NumberFormatException e) {
360
            return false;
361
        }
362

    
363
    }
364

    
365
    /**
366
     * Returns true if the passed string starts with an upper case letter.
367
     * @param string
368
     * @return
369
     */
370
    static public boolean isCapital(String string){
371
        if (isBlank(string)){
372
            return false;
373
        }else{
374
            Character firstChar = string.charAt(0);
375
            if (firstChar.equals(Character.toUpperCase(firstChar))){
376
                return true;
377
            }else{
378
                return false;
379
            }
380
        }
381

    
382
    }
383

    
384
    /**
385
     * Returns true if string is null, "" or string.trim() is ""
386
     * @see isNotEmpty(String string)
387
     * @param string
388
     * @return
389
     */
390
    static public boolean isBlank(String string){
391
        if (string == null){
392
            return true;
393
        }
394
        if ("".equals(string.trim())){
395
            return true;
396
        }
397
        return false;
398
    }
399

    
400
    /**
401
     * Returns <code>false</code> if string is null, "" or string.trim() is ""
402
     * @see isNotEmpty(String string)
403
     * @param string
404
     * @return
405
     */
406
    static public boolean isNotBlank(String string){
407
        return ! isBlank(string);
408
    }
409

    
410
    /**
411
     * @see #isBlank(String)
412
     * @deprecated use {@link #isBlank(String)} instead
413
     * @param string
414
     * @return
415
     */
416
    @Deprecated
417
    static public boolean isEmpty(String string){
418
        return isBlank(string);
419
    }
420

    
421
    static public boolean areBlank(String ... strings){
422
        for (String string : strings){
423
            if (! isBlank(string)){
424
                return false;
425
            }
426
        }
427
        return true;
428
    }
429

    
430
    /**
431
     * Tests if two objects are equal or both null. Otherwise returns false
432
     * @param obj1
433
     * @param obj2
434
     * @return
435
     */
436
    public static boolean nullSafeEqual(Object obj1, Object obj2) {
437
        if (obj1 == null && obj2 == null){
438
            return true;
439
        }
440
        if (obj1 == null && obj2 != null){
441
            return false;
442
        }
443
        return (obj1.equals(obj2));
444
    }
445

    
446
    /**
447
     * Returns false if string is null, "" or string.trim() is ""
448
     * Else true.
449
     * @see isBlank(String string)
450
     * @see #isNotBlank(String)
451
     * @deprecated use {@link #isNotBlank(String)} instead
452
     * @param string
453
     * @return
454
     */
455
    @Deprecated
456
    static public boolean isNotEmpty(String string){
457
        return isNotBlank(string);
458
    }
459

    
460

    
461
    /**
462
     * Computes all fields recursively
463
     * @param clazz
464
     * @return
465
     */
466
    public static Map<String, Field> getAllFields(Class clazz, Class highestClass, boolean includeStatic, boolean includeTransient, boolean makeAccessible, boolean includeHighestClass) {
467
        Map<String, Field> result = new HashMap<String, Field>();
468
        if ( highestClass.isAssignableFrom(clazz) && (clazz != highestClass || includeHighestClass)){
469
            //exclude static
470
            for (Field field: clazz.getDeclaredFields()){
471
                if (includeStatic || ! Modifier.isStatic(field.getModifiers())){
472
                    if (includeTransient || ! isTransient(field)){
473
                        field.setAccessible(makeAccessible);
474
                        result.put(field.getName(), field);
475
                    }
476
                }
477
            }
478

    
479
            //include superclass fields
480
            Class superclass = clazz.getSuperclass();
481
            if (superclass != null){
482
                result.putAll(getAllFields(superclass, highestClass, includeStatic, includeTransient, makeAccessible, includeHighestClass));
483
            }
484
        }
485
        return result;
486
    }
487

    
488

    
489
    /**
490
     * Returns true, if field has an annotation of type javax.persistence.Annotation
491
     * @param field
492
     * @return
493
     */
494
    protected static boolean isTransient(Field field) {
495
        for (Annotation annotation : field.getAnnotations()){
496
            //if (Transient.class.isAssignableFrom(annotation.annotationType())){
497
            if (annotation.annotationType().getSimpleName().equals("Transient")){
498
                return true;
499
            }
500
        }
501
        return false;
502
    }
503

    
504
    /**
505
     * Trims the string and if the string ends with a dot removes it.
506
     * @param string
507
     * @return
508
     */
509
    public static String removeTrailingDot(String string){
510
        if (string == null){
511
            return null;
512
        }
513
        if (string.trim().endsWith(".")){
514
            return string.substring(0, string.length() -1);
515
        }
516
        return string;
517
    }
518

    
519
    /**
520
     * Returns surrounding brackets "(",")". Trim the string if necessary.
521
     * @param text
522
     * @return
523
     */
524
    public static String removeBrackets(String text) {
525
        if (text == null){
526
            return null;
527
        }
528
        text = text.trim();
529
        if (text.matches("^\\(.*\\)$")){
530
            text = text.substring(1, text.length() -1);
531
        }
532
        return text;
533
    }
534
}
(2-2/13)