Project

General

Profile

Download (17.4 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
* Copyright (C) 2007 EDIT
3
* European Distributed Institute of Taxonomy
4
* http://www.e-taxonomy.eu
5
*
6
* The contents of this file are subject to the Mozilla Public License Version 1.1
7
* See LICENSE.TXT at the top of this package for the full license terms.
8
*/
9

    
10
package eu.etaxonomy.cdm.common;
11

    
12
import java.io.BufferedReader;
13
import java.io.IOException;
14
import java.io.InputStream;
15
import java.io.InputStreamReader;
16
import java.lang.annotation.Annotation;
17
import java.lang.reflect.Field;
18
import java.lang.reflect.Modifier;
19
import java.net.HttpURLConnection;
20
import java.net.MalformedURLException;
21
import java.net.URI;
22
import java.net.URISyntaxException;
23
import java.net.URL;
24
import java.util.ArrayList;
25
import java.util.HashMap;
26
import java.util.List;
27
import java.util.Map;
28
import java.util.regex.Matcher;
29
import java.util.regex.Pattern;
30

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

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

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

    
42
    static private boolean urlIsJarOrBundle(URL url){
43
        return url.getProtocol().startsWith("jar") || url.getProtocol().startsWith("bundleresource");
44
    }
45

    
46
    /**
47
     * Returns the an InputStream for a read-only source
48
     * @param resourceFileName the resources path within the classpath(!)
49
     * @return
50
     * @throws IOException
51
     */
52
    public static InputStream getReadableResourceStream(String resourceFileName)
53
            throws IOException{
54
        InputStream urlStream = CdmUtils.class.getResourceAsStream("/"+ resourceFileName);
55
        return urlStream;
56
    }
57

    
58
    /**
59
     * Returns an InputStream for a read-only source
60
     * @param resourceFileName the resources path within the classpath(!)
61
     * @return
62
     * @throws IOException
63
     */
64
    public static InputStreamReader getUtf8ResourceReader(String resourceFileName)
65
            throws IOException{
66
        InputStream urlStream = CdmUtils.class.getResourceAsStream("/"+ resourceFileName);
67
        InputStreamReader inputStreamReader = new InputStreamReader(urlStream, "UTF8");
68
        return inputStreamReader;
69
    }
70

    
71
    /**
72
     * Returns the file name for the file in which 'clazz' is to be found (helps finding according libraries)
73
     * @param clazz
74
     * @return
75
     */
76
    static public String findLibrary(Class<?> clazz){
77
        String result = null;
78
        if (clazz != null){
79
            String fullPackageName = clazz.getCanonicalName();
80
            fullPackageName = fullPackageName.replace(".", "/");
81
            URL url = CdmUtils.class.getResource("/" + fullPackageName + ".class" );
82
            if (url != null){
83
                result = url.getFile();
84
            }else{
85
                result = "";
86
            }
87
            logger.debug("LibraryURL for " + clazz.getCanonicalName() + " : " + result);
88
        }
89
        return result;
90
    }
91

    
92
    static public String readInputLine(String inputQuestion){
93

    
94
        try {
95
            System.out.print(inputQuestion);
96
            BufferedReader in = new BufferedReader( new InputStreamReader( System.in ));
97
            String input;
98
            input = in.readLine();
99
            return input;
100
        } catch (IOException e) {
101
            logger.warn("IOExeption");
102
            return null;
103
        }
104
    }
105

    
106
    /**
107
     * Returns the trimmed value string if value is not <code>null</code>.
108
     * Returns the empty string if value is <code>null</code>.
109
     * @param value
110
     * @return
111
     */
112
    static public String NzTrim(String value){
113
        return (value == null ? "" : value);
114
    }
115

    
116
    /**
117
     * Returns value if value is not <code>null</code>. Returns empty string if value is <code>null</code>.
118
     * @param value
119
     * @return
120
     */
121
    static public String Nz(String value){
122
        return (value == null ? "" : value);
123
    }
124

    
125
    /**
126
     * Returns value if value is not <code>null</code>. Returns defaultValue if value is <code>null</code>.
127
     * @param value
128
     * @return
129
     */
130
    static public String Nz(String value, String defaultValue){
131
        return (value == null ? defaultValue : value);
132
    }
133

    
134
    /**
135
     * Returns value if value is not <code>null</code>. Returns 0 if value is <code>null</code>.
136
     * @param value
137
     * @return
138
     */
139
    static public Integer Nz(Integer value){
140
        return (value == null ? 0 : value);
141
    }
142

    
143
    /**
144
     * Returns value if value is not <code>null</code>. Returns 0 if value is <code>null</code>.
145
     * @param value
146
     * @return
147
     */
148
    static public Long Nz(Long value){
149
        return (value == null ? 0 : value);
150
    }
151

    
152
    /**
153
     * Returns str if str is not the empty String (''). Returns null if str is empty.
154
     * @param str
155
     * @return
156
     */
157
    static public String Ne(String str){
158
        return ("".equals(str)? null : str);
159
    }
160

    
161
    /**
162
     * Returns str if str.trim() is not empty. Returns null otherwise.
163
     * @param str
164
     * @return
165
     */
166
    static public String Nb(String str){
167
        return (str == null || str.trim().equals("")? null : str);
168
    }
169

    
170
    /**
171
     * Concatenates an array of strings using the defined separator.<BR>
172
     * <code>Null</code> values and empty strings are handled as if they
173
     * do not exist. So <BR><BR>
174
     *
175
     * concat(":", "a", "", null, "b") results in "a:b"<BR><BR>
176
     *
177
     * If all strings are <code>null</code> then <code>null</code> is returned.
178
     *
179
     * @see #concat(CharSequence, String, String)
180
     * @param strings the strings to concatenate
181
     * @param seperator the separator for concatenation
182
     * @return String the concatenation result
183
     */
184
    static public String concat(CharSequence separator, String... strings){
185
        StringBuffer result = new StringBuffer();
186
        boolean allNull = true;
187
        for (String string : strings){
188
            if (string != null){
189
                if (result.length() > 0 && string.length() > 0){
190
                    result.append(separator);
191
                }
192
                result.append(string);
193
                allNull = false;
194
            }
195
        }
196
        //if all strings are null result should be null, not ""
197
        if (allNull){
198
            return null;
199
        }else {
200
            return result.toString();
201
        }
202
    }
203

    
204

    
205
    /**
206
     * Concatenates two strings, using the defined separator.<BR>
207
     * <code>Null</code> values are interpreted as empty strings.<BR>
208
     * Empty strings are not included in concatenation so concat(":", "a", "")
209
     * results in "a", not "a:".<BR>
210
     *
211
     * If both strings are <code>null</code> then <code>null</code> is returned.
212
     *
213
     * @see #concat(CharSequence, String[])
214
     * @param sepearator the separator
215
     * @param string1 first string to concatenate
216
     * @param string2 second string to concatenate
217
     * @return String the concatenated string
218
     */
219
    static public String concat(CharSequence separator, String string1, String string2){
220
        String[] strings = {string1, string2};
221
        return concat(separator, strings);
222
    }
223

    
224
	/**
225
	 * Returns <code>preferred</code> if not blank, else returns <code>alternative</code>.
226
	 * If reverse is <code>true</code> computation is
227
	 * the other way round (<code>alternative</code> if not blank, otherwise <code>preferred</code>).
228
	 * @param preferred first string
229
	 * @param alternative second string
230
	 * @param reverse reverse flag
231
	 * @param nzTrim if <code>true</code> the result is trimmed and <code>null</code> values are replaced by empty string.
232
	 * @return the preferred string
233
	 */
234
	static public String getPreferredNonEmptyString(String preferred, String alternative, boolean reverse, boolean nzTrim){
235
		String result;
236
		if (! reverse){
237
			result = StringUtils.isBlank(preferred) ? alternative : preferred;
238
		}else{
239
			result = StringUtils.isBlank(alternative) ? preferred : alternative;
240
		}
241
		if (nzTrim){
242
			result = Nz(result).trim();
243
		}
244
		return result;
245
	}
246

    
247
    /** Returns a version of the input where all contiguous
248
     * whitespace characters are replaced with a single
249
     * space. Line terminators are treated like whitespace.
250
     *
251
     * @param inputStr
252
     * @return
253
     */
254
    public static CharSequence removeDuplicateWhitespace(CharSequence inputStr) {
255

    
256
        String patternStr = "\\s+";
257
        String replaceStr = " ";
258
        Pattern pattern = Pattern.compile(patternStr);
259
        Matcher matcher = pattern.matcher(inputStr);
260
        return matcher.replaceAll(replaceStr);
261
    }
262

    
263
    /**
264
     * Builds a list of strings by splitting an input string
265
     * with delimiters whitespace, comma, or semicolon
266
     * @param value
267
     * @return
268
     */
269
    public static List<String> buildList(String value) {
270

    
271
        List<String> resultList = new ArrayList<String>();
272
        for (String tag : value.split("[\\s,;]+")) {
273
            resultList.add(tag);
274
        }
275
        return resultList;
276
    }
277

    
278
    static public boolean urlExists(String strUrl, boolean withWarning){
279
        try {
280
             HttpURLConnection.setFollowRedirects(false);
281
              // note : you may also need
282
              //        HttpURLConnection.setInstanceFollowRedirects(false)
283
              HttpURLConnection con =
284
                 (HttpURLConnection) new URL(strUrl).openConnection();
285
              con.setRequestMethod("HEAD");
286
              return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
287
        } catch (MalformedURLException e) {
288
            if (withWarning) {
289
                logger.warn(e);
290
            }
291
        } catch (IOException e) {
292
            //
293
        }
294
        return false;
295
    }
296

    
297
    /**
298
     *
299
     * @param string
300
     * @return
301
     *
302
     * @deprecated unused and dangerous since it swallows the URISyntaxException --> need to be removed
303
     */
304
    @Deprecated
305
    static public URI string2Uri(String string) {
306
        URI uri = null;
307
        try {
308
            uri = new URI(string);
309
            logger.debug("uri: " + uri.toString());
310
        } catch (URISyntaxException ex) {
311
            logger.error("Problem converting string " + string + " to URI " + uri);
312
            return null;
313
        }
314
        return uri;
315
    }
316

    
317
    static public boolean isNumeric(String string){
318
        if (string == null){
319
            return false;
320
        }
321
        try {
322
            Double.valueOf(string);
323
            return true;
324
        } catch (NumberFormatException e) {
325
            return false;
326
        }
327
    }
328

    
329
    /**
330
     * Returns <code>true</code> if the passed string starts with an upper case letter.
331
     * <code>false</code> otherwise. The later includes <code>null</code> and empty strings.
332
     * @param string
333
     * @return
334
     */
335
    static public boolean isCapital(String string){
336
        if (isBlank(string)){
337
            return false;
338
        }else{
339
            Character firstChar = string.charAt(0);
340
            if (firstChar.equals(Character.toUpperCase(firstChar))){
341
                return true;
342
            }else{
343
                return false;
344
            }
345
        }
346
    }
347

    
348
    /**
349
     * Returns true if string is null, "" or string.trim() is ""
350
     * @see isNotEmpty(String string)
351
     * @param string
352
     * @return
353
     */
354
    static public boolean isBlank(String string){
355
        if (string == null){
356
            return true;
357
        }
358
        if ("".equals(string.trim())){
359
            return true;
360
        }
361
        return false;
362
    }
363

    
364
    /**
365
     * Returns <code>false</code> if string is null, "" or string.trim() is ""
366
     * @see isNotEmpty(String string)
367
     * @param string
368
     * @return
369
     */
370
    static public boolean isNotBlank(String string){
371
        return ! isBlank(string);
372
    }
373

    
374
    /**
375
     * @see #isBlank(String)
376
     * @deprecated use {@link #isBlank(String)} instead
377
     * @param string
378
     * @return
379
     */
380
    @Deprecated
381
    static public boolean isEmpty(String string){
382
        return isBlank(string);
383
    }
384

    
385
    static public boolean areBlank(String ... strings){
386
        for (String string : strings){
387
            if (! isBlank(string)){
388
                return false;
389
            }
390
        }
391
        return true;
392
    }
393

    
394
    /**
395
     * Tests if two objects are equal or both null. Otherwise returns false
396
     * @param obj1
397
     * @param obj2
398
     * @return
399
     */
400
    public static boolean nullSafeEqual(Object obj1, Object obj2) {
401
        if (obj1 == null){
402
            return obj2 == null;
403
        }
404
        return (obj1.equals(obj2));
405
    }
406

    
407
    /**
408
     * Compares 2 strings with defined values for <code>null</code>
409
     * @param str1
410
     * @param str2
411
     * @return
412
     */
413
    public static int nullSafeCompareTo(String str1, String str2) {
414
        if (str1 == null){
415
            return str2 == null ? 0 : -1;
416
        }else if (str2 == null){
417
            return 1;
418
        }else{
419
            return (str1.compareTo(str2));
420
        }
421
    }
422

    
423
    /**
424
     * Returns false if string is null, "" or string.trim() is ""
425
     * Else true.
426
     * @see isBlank(String string)
427
     * @see #isNotBlank(String)
428
     * @deprecated use {@link #isNotBlank(String)} instead
429
     * @param string
430
     * @return
431
     */
432
    @Deprecated
433
    static public boolean isNotEmpty(String string){
434
        return isNotBlank(string);
435
    }
436

    
437
    /**
438
     * Computes all fields recursively
439
     * @param clazz
440
     * @return
441
     */
442
    public static Map<String, Field> getAllFields(Class clazz, Class highestClass, boolean includeStatic, boolean includeTransient, boolean makeAccessible, boolean includeHighestClass) {
443
        Map<String, Field> result = new HashMap<>();
444
        if ( highestClass.isAssignableFrom(clazz) && (clazz != highestClass || includeHighestClass)){
445
            //exclude static
446
            for (Field field: clazz.getDeclaredFields()){
447
                if (includeStatic || ! Modifier.isStatic(field.getModifiers())){
448
                    if (includeTransient || ! isTransient(field)){
449
                        field.setAccessible(makeAccessible);
450
                        result.put(field.getName(), field);
451
                    }
452
                }
453
            }
454

    
455
            //include superclass fields
456
            Class<?> superclass = clazz.getSuperclass();
457
            if (superclass != null){
458
                result.putAll(getAllFields(superclass, highestClass, includeStatic, includeTransient, makeAccessible, includeHighestClass));
459
            }
460
        }
461
        return result;
462
    }
463

    
464
    /**
465
     * Returns true, if field has an annotation of type javax.persistence.Annotation
466
     * @param field
467
     * @return
468
     */
469
    protected static boolean isTransient(Field field) {
470
        for (Annotation annotation : field.getAnnotations()){
471
            //if (Transient.class.isAssignableFrom(annotation.annotationType())){
472
            if (annotation.annotationType().getSimpleName().equals("Transient")){
473
                return true;
474
            }
475
        }
476
        return false;
477
    }
478

    
479
    /**
480
     * Trims the string and if the string ends with a dot removes it.
481
     * @param string
482
     * @return
483
     */
484
    public static String removeTrailingDot(String string){
485
        if (string == null){
486
            return null;
487
        }
488
        if (string.trim().endsWith(".")){
489
            return string.substring(0, string.length() -1);
490
        }
491
        return string;
492
    }
493

    
494
    /**
495
     * Returns surrounding brackets "(",")". Trim the string if necessary.
496
     * @param text
497
     * @return
498
     */
499
    public static String removeBrackets(String text) {
500
        if (text == null){
501
            return null;
502
        }
503
        text = text.trim();
504
        if (text.matches("^\\(.*\\)$")){
505
            text = text.substring(1, text.length() -1);
506
        }
507
        return text;
508
    }
509

    
510
    /**
511
     * Compares 2 strings. If they are not empty and equal returns <code>true</code>
512
     * otherwise false.
513
     *
514
     * @param str1
515
     * @param str2
516
     * @return compare result as boolean
517
     */
518
    public static boolean nonEmptyEquals(String str1, String str2) {
519
        return (isNotBlank(str1) && str1.equals(str2));
520
    }
521

    
522
    /**
523
     * Compares if str1 and str2 is equal when ignoring whitespaces.
524
     * Returns <code>true</code> if both or <code>null</code> or
525
     * whitespace ignore equal.
526
     * @param str1
527
     * @param str2
528
     * @return
529
     */
530
    public static boolean equalsIgnoreWS(String str1, String str2) {
531
        if (str1 == null){
532
            return str2 == null;
533
        }else if (str2 == null){
534
            return false;
535
        }else{
536
            return str1.replaceAll("\\s", "").equals(str2.replaceAll("\\s", ""));
537
        }
538
    }
539

    
540
    /**
541
     * Checks if all strings given provide are {@link #isBlank(String) blank}.
542
     * Returns <code>true</code> if strs is null or empty
543
     * @param strs
544
     * @return
545
     */
546
    public static boolean isBlank(String ... strs) {
547
        if (strs == null){
548
            return true;
549
        }
550
        for (String str : strs) {
551
            if (isNotBlank(str)){
552
                return false;
553
            }
554
        }
555
        return true;
556
    }
557

    
558
    /**
559
     * Transforms a search string which allows wildcard "*" into a
560
     * java regular expression such that all other characters are handled as normal text.
561
     * @param regEx
562
     * @return
563
     */
564
    public static String quoteRegExWithWildcard(String regEx){
565
        return Pattern.quote(regEx).replace("*", "\\E.*\\Q").replace("\\Q\\E", "");
566
    }
567

    
568
    public static int diffIndex(String str1, String str2) {
569
        if (str1 == null || str2 == null){
570
            return 0;
571
        }
572
        for (int i = 0; i<str1.length() && i<str2.length() ;i++) {
573
            if (str1.charAt(i)!= str2.charAt(i)){
574
                return i;
575
            }
576
        }
577
        if(str1.length()!=str2.length()){
578
            return Math.max(str1.length(), str2.length());
579
        }
580
        return -1;
581
    }
582
}
(4-4/22)