Project

General

Profile

Download (16.5 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
	public static File getCdmSubDir(String dirName) {
80

    
81
		File folder = new File(System.getProperty("user.home") + File.separator
82
				+ cdmFolderName + File.separator + dirName + File.separator);
83

    
84
		// if the directory does not exist, create it
85
		if (!folder.exists()) {
86
			if (!folder.mkdir()) {
87
				// TODO throw some Exception
88
				return null;
89
			}
90
		}
91
		return folder;
92
	}
93

    
94

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

    
107
    /**
108
     * Returns the an InputStream for a read-only source
109
     * @param resourceFileName the resources path within the classpath(!)
110
     * @return
111
     * @throws IOException
112
     */
113
    public static InputStreamReader getUtf8ResourceReader(String resourceFileName)
114
            throws IOException{
115
        InputStream urlStream = CdmUtils.class.getResourceAsStream("/"+ resourceFileName);
116
        InputStreamReader inputStreamReader = new InputStreamReader(urlStream, "UTF8");
117
        return inputStreamReader;
118
    }
119

    
120

    
121
    /**
122
     * @return
123
     */
124
    static public String getFolderSeperator(){
125
        if (folderSeperator == null){
126
            URL url = CdmUtils.class.getResource("/"+ MUST_EXIST_FILE);
127
            if ( url != null && ! urlIsJarOrBundle(url) ){
128
                folderSeperator =  File.separator;
129
            }else{
130
                folderSeperator = "/";
131
            }
132
        }
133
        return folderSeperator;
134
    }
135

    
136

    
137
    /**
138
     * @param url
139
     * @return
140
     */
141
    static private boolean urlIsJarOrBundle(URL url){
142
        return url.getProtocol().startsWith("jar") || url.getProtocol().startsWith("bundleresource");
143
    }
144

    
145
    /**
146
     * Returns the file name for the file in which 'clazz' is to be found (helps finding according libraries)
147
     * @param clazz
148
     * @return
149
     */
150
    static public String findLibrary(Class<?> clazz){
151
        String result = null;
152
        if (clazz != null){
153
            String fullPackageName = clazz.getCanonicalName();
154
            fullPackageName = fullPackageName.replace(".", "/");
155
            URL url = CdmUtils.class.getResource("/" + fullPackageName + ".class" );
156
            if (url != null){
157
                result = url.getFile();
158
            }else{
159
                result = "";
160
            }
161
            logger.debug("LibraryURL for " + clazz.getCanonicalName() + " : " + result);
162
        }
163
        return result;
164
    }
165

    
166
    static public String testMe(){
167
        String message = "This is a test";
168
        System.out.println(message);
169
        return message;
170
    }
171

    
172
    static public String readInputLine(String inputQuestion){
173
        try {
174

    
175
            System.out.print(inputQuestion);
176
            BufferedReader in = new BufferedReader( new java.io.InputStreamReader( System.in ));
177
            String input;
178
            input = in.readLine();
179
            return input;
180
        } catch (IOException e) {
181
            logger.warn("IOExeption");
182
            return null;
183
        }
184
    }
185

    
186

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

    
197

    
198
    /**
199
     * Returns value if value is not <code>null</code>. Returns empty string if value is <code>null</code>.
200
     * @param value
201
     * @return
202
     */
203
    static public String Nz(String value){
204
        return (value == null ? "" : value);
205
    }
206

    
207
    /**
208
     * Returns value if value is not <code>null</code>. Returns defaultValue if value is <code>null</code>.
209
     * @param value
210
     * @return
211
     */
212
    static public String Nz(String value, String defaultValue){
213
        return (value == null ? defaultValue : value);
214
    }
215

    
216
    /**
217
     * Returns value if value is not <code>null</code>. Returns 0 if value is <code>null</code>.
218
     * @param value
219
     * @return
220
     */
221
    static public Integer Nz(Integer value){
222
        return (value == null ? 0 : value);
223
    }
224

    
225
    /**
226
     * Returns value if value is not <code>null</code>. Returns 0 if value is <code>null</code>.
227
     * @param value
228
     * @return
229
     */
230
    static public Long Nz(Long value){
231
        return (value == null ? 0 : value);
232
    }
233

    
234
    /**
235
     * Returns str if str is not the empty String (''). Returns null if str is empty.
236
     * @param str
237
     * @return
238
     */
239
    static public String Ne(String str){
240
        return ("".equals(str)? null : str);
241
    }
242

    
243
    /**
244
     * Returns str if str.trim() is not empty. Returns null otherwise.
245
     * @param str
246
     * @return
247
     */
248
    static public String Nb(String str){
249
        return (str == null || str.trim().equals("")? null : str);
250
    }
251

    
252

    
253
    /**
254
     * Concatenates an array of strings using the defined seperator.<BR>
255
     * <code>Null</code> values are interpreted as empty strings.<BR>
256
     * If all strings are <code>null</code> then <code>null</code> is returned.
257
     * @param strings
258
     * @param seperator
259
     * @return String
260
     */
261
    static public String concat(CharSequence separator, String[] strings){
262
        String result = "";
263
        boolean allNull = true;
264
        for (String string : strings){
265
            if (string != null){
266
                if (result.length() > 0 && string.length() > 0){
267
                    result += separator;
268
                }
269
                result += string;
270
                allNull = false;
271
            }
272
        }
273
        //if all strings are null result should be null, not ""
274
        if (allNull){
275
            return null;
276
        }else {
277
            return result;
278
        }
279
    }
280

    
281
    /**
282
     * Concatenates two strings, using the defined seperator.<BR>
283
     * <code>Null</code> values are interpreted as empty Strings.<BR>
284
     * If both strings are <code>null</code> then <code>null</code> is returned.
285
     * @see #concat(CharSequence, String[])
286
     * @param seperator
287
     * @param string1
288
     * @param string2
289
     * @return String
290
     */
291
    static public String concat(CharSequence separator, String string1, String string2){
292
        String[] strings = {string1, string2};
293
        return concat(separator, strings);
294
    }
295

    
296

    
297
	/**
298
	 * Returns <code>preferred</code> if not blank, else returns <code>alternative</code>.
299
	 * If reverse is <code>true</code> computation is
300
	 * the other way round (<code>alternative</code> if not blank, otherwise <code>preferred</code>).
301
	 * @param preferred first string
302
	 * @param alternative second string
303
	 * @param reverse reverse flag
304
	 * @param nzTrim if <code>true</code> the result is trimmed and <code>null</code> values are replaced by empty string.
305
	 * @return the preferred string
306
	 */
307
	static public String getPreferredNonEmptyString(String preferred, String alternative, boolean reverse, boolean nzTrim){
308
		String result;
309
		if (! reverse){
310
			result = StringUtils.isBlank(preferred) ? alternative : preferred;
311
		}else{
312
			result = StringUtils.isBlank(alternative) ? preferred : alternative;
313
		}
314
		if (nzTrim){
315
			result = Nz(result).trim();
316
		}
317
		return result;
318
	}
319

    
320

    
321
    /** Returns a version of the input where all contiguous
322
     * whitespace characters are replaced with a single
323
     * space. Line terminators are treated like whitespace.
324
     *
325
     * @param inputStr
326
     * @return
327
     */
328
    public static CharSequence removeDuplicateWhitespace(CharSequence inputStr) {
329

    
330
        String patternStr = "\\s+";
331
        String replaceStr = " ";
332
        Pattern pattern = Pattern.compile(patternStr);
333
        Matcher matcher = pattern.matcher(inputStr);
334
        return matcher.replaceAll(replaceStr);
335
    }
336

    
337

    
338
    /** Builds a list of strings by splitting an input string
339
     * with delimiters whitespace, comma, or semicolon
340
     * @param value
341
     * @return
342
     */
343
    public static ArrayList<String> buildList(String value) {
344

    
345
        ArrayList<String> resultList = new ArrayList<String>();
346
        for (String tag : value.split("[\\s,;]+")) {
347
            resultList.add(tag);
348
        }
349
        return resultList;
350
    }
351

    
352

    
353
    static public boolean urlExists(String strUrl, boolean withWarning){
354
        try {
355
             HttpURLConnection.setFollowRedirects(false);
356
              // note : you may also need
357
              //        HttpURLConnection.setInstanceFollowRedirects(false)
358
              HttpURLConnection con =
359
                 (HttpURLConnection) new URL(strUrl).openConnection();
360
              con.setRequestMethod("HEAD");
361
              return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
362
        } catch (MalformedURLException e) {
363
            if (withWarning) {
364
                logger.warn(e);
365
            }
366
        } catch (IOException e) {
367
            //
368
        };
369
        return false;
370
    }
371

    
372
    static public URI string2Uri(String string) {
373
        URI uri = null;
374
        try {
375
            uri = new URI(string);
376
            logger.debug("uri: " + uri.toString());
377
        } catch (URISyntaxException ex) {
378
            logger.error("Problem converting string " + string + " to URI " + uri);
379
            return null;
380
        }
381
        return uri;
382
    }
383

    
384
    static public boolean isNumeric(String string){
385
        if (string == null){
386
            return false;
387
        }
388
        try {
389
            Double.valueOf(string);
390
            return true;
391
        } catch (NumberFormatException e) {
392
            return false;
393
        }
394

    
395
    }
396

    
397
    /**
398
     * Returns <code>true</code> if the passed string starts with an upper case letter.
399
     * <code>false</code> otherwise. The later includes <code>null</code> and empty strings.
400
     * @param string
401
     * @return
402
     */
403
    static public boolean isCapital(String string){
404
        if (isBlank(string)){
405
            return false;
406
        }else{
407
            Character firstChar = string.charAt(0);
408
            if (firstChar.equals(Character.toUpperCase(firstChar))){
409
                return true;
410
            }else{
411
                return false;
412
            }
413
        }
414

    
415
    }
416

    
417
    /**
418
     * Returns true if string is null, "" or string.trim() is ""
419
     * @see isNotEmpty(String string)
420
     * @param string
421
     * @return
422
     */
423
    static public boolean isBlank(String string){
424
        if (string == null){
425
            return true;
426
        }
427
        if ("".equals(string.trim())){
428
            return true;
429
        }
430
        return false;
431
    }
432

    
433
    /**
434
     * Returns <code>false</code> if string is null, "" or string.trim() is ""
435
     * @see isNotEmpty(String string)
436
     * @param string
437
     * @return
438
     */
439
    static public boolean isNotBlank(String string){
440
        return ! isBlank(string);
441
    }
442

    
443
    /**
444
     * @see #isBlank(String)
445
     * @deprecated use {@link #isBlank(String)} instead
446
     * @param string
447
     * @return
448
     */
449
    @Deprecated
450
    static public boolean isEmpty(String string){
451
        return isBlank(string);
452
    }
453

    
454
    static public boolean areBlank(String ... strings){
455
        for (String string : strings){
456
            if (! isBlank(string)){
457
                return false;
458
            }
459
        }
460
        return true;
461
    }
462

    
463
    /**
464
     * Tests if two objects are equal or both null. Otherwise returns false
465
     * @param obj1
466
     * @param obj2
467
     * @return
468
     */
469
    public static boolean nullSafeEqual(Object obj1, Object obj2) {
470
        if (obj1 == null && obj2 == null){
471
            return true;
472
        }
473
        if (obj1 == null && obj2 != null){
474
            return false;
475
        }
476
        return (obj1.equals(obj2));
477
    }
478

    
479
    /**
480
     * Returns false if string is null, "" or string.trim() is ""
481
     * Else true.
482
     * @see isBlank(String string)
483
     * @see #isNotBlank(String)
484
     * @deprecated use {@link #isNotBlank(String)} instead
485
     * @param string
486
     * @return
487
     */
488
    @Deprecated
489
    static public boolean isNotEmpty(String string){
490
        return isNotBlank(string);
491
    }
492

    
493

    
494
    /**
495
     * Computes all fields recursively
496
     * @param clazz
497
     * @return
498
     */
499
    public static Map<String, Field> getAllFields(Class clazz, Class highestClass, boolean includeStatic, boolean includeTransient, boolean makeAccessible, boolean includeHighestClass) {
500
        Map<String, Field> result = new HashMap<String, Field>();
501
        if ( highestClass.isAssignableFrom(clazz) && (clazz != highestClass || includeHighestClass)){
502
            //exclude static
503
            for (Field field: clazz.getDeclaredFields()){
504
                if (includeStatic || ! Modifier.isStatic(field.getModifiers())){
505
                    if (includeTransient || ! isTransient(field)){
506
                        field.setAccessible(makeAccessible);
507
                        result.put(field.getName(), field);
508
                    }
509
                }
510
            }
511

    
512
            //include superclass fields
513
            Class superclass = clazz.getSuperclass();
514
            if (superclass != null){
515
                result.putAll(getAllFields(superclass, highestClass, includeStatic, includeTransient, makeAccessible, includeHighestClass));
516
            }
517
        }
518
        return result;
519
    }
520

    
521

    
522
    /**
523
     * Returns true, if field has an annotation of type javax.persistence.Annotation
524
     * @param field
525
     * @return
526
     */
527
    protected static boolean isTransient(Field field) {
528
        for (Annotation annotation : field.getAnnotations()){
529
            //if (Transient.class.isAssignableFrom(annotation.annotationType())){
530
            if (annotation.annotationType().getSimpleName().equals("Transient")){
531
                return true;
532
            }
533
        }
534
        return false;
535
    }
536

    
537
    /**
538
     * Trims the string and if the string ends with a dot removes it.
539
     * @param string
540
     * @return
541
     */
542
    public static String removeTrailingDot(String string){
543
        if (string == null){
544
            return null;
545
        }
546
        if (string.trim().endsWith(".")){
547
            return string.substring(0, string.length() -1);
548
        }
549
        return string;
550
    }
551

    
552
    /**
553
     * Returns surrounding brackets "(",")". Trim the string if necessary.
554
     * @param text
555
     * @return
556
     */
557
    public static String removeBrackets(String text) {
558
        if (text == null){
559
            return null;
560
        }
561
        text = text.trim();
562
        if (text.matches("^\\(.*\\)$")){
563
            text = text.substring(1, text.length() -1);
564
        }
565
        return text;
566
    }
567
}
(3-3/20)