Project

General

Profile

« Previous | Next » 

Revision 794be65e

Added by Andreas Müller almost 2 years ago

cleanup

View differences:

cdmlib-commons/src/main/java/eu/etaxonomy/cdm/common/AbstractStringComparator.java
1
/**
2
 * Copyright (C) 2009 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
package eu.etaxonomy.cdm.common;
10

  
11
import java.util.Comparator;
12
import java.util.HashMap;
13
import java.util.Map;
14
import java.util.regex.Pattern;
15

  
16
/**
17
 * Abstract Comparator for Strings which allows define substitution rules which
18
 * are applied to the String to be compared before the actual comparison takes
19
 * place. By this it is e.g. possible to influence the position of objects in sorted lists etc.
20
 * <p>
21
 * <b>Intended usage</b>: To allow maximum flexibility the property
22
 * {@link #setSubstitutionRules(Map)} should be set in the spring application
23
 * context.
24
 *
25
 * @author a.kohlbecker
26
 * @since 24.06.2009
27
 */
28
public abstract class AbstractStringComparator<T extends Object> implements Comparator<T> {
29

  
30
	protected Map<Pattern, String> substitutionRules = null;
31

  
32
	/**
33
	 * Set the private field substitutionRules. The substitutionRules consist of
34
	 * a regular expression as key and a string to be prepended as value.
35
	 */
36
	public void setSubstitutionRules(Map<String, String> substitutionRules) {
37
		this.substitutionRules = new HashMap<Pattern, String>(substitutionRules.size());
38
		for (String regex : substitutionRules.keySet()) {
39
			this.substitutionRules.put(Pattern.compile(regex), substitutionRules.get(regex));
40
		}
41
	}
42

  
43
	/**
44
	 * Applies the first matching <code>substitutionRules</code> set by
45
	 * {@link #setSubstitutionRules()} to the given String. A rules is applied
46
	 * in the following way: If the regular expression matches the given string
47
	 * <code>s</code> the String mapped by the regular expression is prepended
48
	 * to <code>s</code>.
49
	 *
50
	 * @param s
51
	 * @return
52
	 */
53
	protected String applySubstitutionRules(String s) {
54
		if (substitutionRules == null) {
55
			return s;
56
		}
57
		StringBuffer sb = new StringBuffer();
58
		for (Pattern pattern : substitutionRules.keySet()) {
59
			if (pattern.matcher(s).matches()) {
60
				sb.append(substitutionRules.get(pattern)).append(s);
61
				return sb.toString();
62
			}
63

  
64
		}
65
		return s;
66
	}
67

  
68
}
1
/**
2
 * Copyright (C) 2009 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
package eu.etaxonomy.cdm.common;
10

  
11
import java.util.Comparator;
12
import java.util.HashMap;
13
import java.util.Map;
14
import java.util.regex.Pattern;
15

  
16
/**
17
 * Abstract Comparator for Strings which allows define substitution rules which
18
 * are applied to the String to be compared before the actual comparison takes
19
 * place. By this it is e.g. possible to influence the position of objects in sorted lists etc.
20
 * <p>
21
 * <b>Intended usage</b>: To allow maximum flexibility the property
22
 * {@link #setSubstitutionRules(Map)} should be set in the spring application
23
 * context.
24
 *
25
 * @author a.kohlbecker
26
 * @since 24.06.2009
27
 */
28
public abstract class AbstractStringComparator<T extends Object> implements Comparator<T> {
29

  
30
	protected Map<Pattern, String> substitutionRules = null;
31

  
32
	/**
33
	 * Set the private field substitutionRules. The substitutionRules consist of
34
	 * a regular expression as key and a string to be prepended as value.
35
	 */
36
	public void setSubstitutionRules(Map<String, String> substitutionRules) {
37
		this.substitutionRules = new HashMap<>(substitutionRules.size());
38
		for (String regex : substitutionRules.keySet()) {
39
			this.substitutionRules.put(Pattern.compile(regex), substitutionRules.get(regex));
40
		}
41
	}
42

  
43
	/**
44
	 * Applies the first matching <code>substitutionRules</code> set by
45
	 * {@link #setSubstitutionRules()} to the given String. A rules is applied
46
	 * in the following way: If the regular expression matches the given string
47
	 * <code>s</code> the String mapped by the regular expression is prepended
48
	 * to <code>s</code>.
49
	 *
50
	 * @param s
51
	 * @return
52
	 */
53
	protected String applySubstitutionRules(String s) {
54
		if (substitutionRules == null) {
55
			return s;
56
		}
57
		StringBuffer sb = new StringBuffer();
58
		for (Pattern pattern : substitutionRules.keySet()) {
59
			if (pattern.matcher(s).matches()) {
60
				sb.append(substitutionRules.get(pattern)).append(s);
61
				return sb.toString();
62
			}
63

  
64
		}
65
		return s;
66
	}
67

  
68
}
cdmlib-commons/src/main/java/eu/etaxonomy/cdm/common/CdmUtils.java
35 35
 */
36 36
public class CdmUtils {
37 37

  
38
    private static final Logger logger = LogManager.getLogger(CdmUtils.class);
38
    private static final Logger logger = LogManager.getLogger();
39 39

  
40 40
    static private boolean urlIsJarOrBundle(URL url){
41 41
        return url.getProtocol().startsWith("jar") || url.getProtocol().startsWith("bundleresource");
cdmlib-commons/src/main/java/eu/etaxonomy/cdm/common/DoubleResult.java
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
package eu.etaxonomy.cdm.common;

10

  
11
import org.apache.logging.log4j.LogManager;

12
import org.apache.logging.log4j.Logger;

13

  
14
/**

15
 * An instance of this class represents an method result that contains 2 variables. The variables may be typified.

16
 *

17
 * @author a.mueller

18
 * @since 30.10.2008

19
 */

20
public class DoubleResult<S extends Object, T extends Object> {

21

  
22
	private static final Logger logger = LogManager.getLogger(DoubleResult.class);

23

  
24
	private S firstResult = null;

25
	private T secondResult = null;

26

  
27
	public DoubleResult() {

28
		if (logger.isDebugEnabled()){logger.debug("Constructor");}

29
	}

30

  
31
	public DoubleResult(S firstResult, T secondResult) {

32
		this.firstResult = firstResult;

33
		this.secondResult = secondResult;

34
	}

35

  
36
	public S getFirstResult() {

37
		return firstResult;

38
	}

39
	public void setFirstResult(S firstResult) {

40
		this.firstResult = firstResult;

41
	}

42

  
43
	public T getSecondResult() {

44
		return secondResult;

45
	}

46
	public void setSecondResult(T secondResult) {

47
		this.secondResult = secondResult;

48
	}

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
package eu.etaxonomy.cdm.common;
10

  
11
import org.apache.logging.log4j.LogManager;
12
import org.apache.logging.log4j.Logger;
13

  
14
/**
15
 * An instance of this class represents an method result that contains 2 variables. The variables may be typified.
16
 *
17
 * @author a.mueller
18
 * @since 30.10.2008
19
 */
20
public class DoubleResult<S extends Object, T extends Object> {
21

  
22
	private static final Logger logger = LogManager.getLogger();
23

  
24
	private S firstResult = null;
25
	private T secondResult = null;
26

  
27
	public DoubleResult() {
28
		if (logger.isDebugEnabled()){logger.debug("Constructor");}
29
	}
30

  
31
	public DoubleResult(S firstResult, T secondResult) {
32
		this.firstResult = firstResult;
33
		this.secondResult = secondResult;
34
	}
35

  
36
	public S getFirstResult() {
37
		return firstResult;
38
	}
39
	public void setFirstResult(S firstResult) {
40
		this.firstResult = firstResult;
41
	}
42

  
43
	public T getSecondResult() {
44
		return secondResult;
45
	}
46
	public void setSecondResult(T secondResult) {
47
		this.secondResult = secondResult;
48
	}
49 49
}
cdmlib-commons/src/main/java/eu/etaxonomy/cdm/common/DynamicBatch.java
23 23
 */
24 24
public class DynamicBatch {
25 25

  
26
    public static final Logger logger = LogManager.getLogger(DynamicBatch.class);
26
    public static final Logger logger = LogManager.getLogger();
27 27

  
28 28
    int batchSize;
29 29
    int batchItemCount = -1;
cdmlib-commons/src/main/java/eu/etaxonomy/cdm/common/ExcelUtils.java
35 35
 */
36 36
public class ExcelUtils {
37 37

  
38
	private static final Logger logger = LogManager.getLogger(ExcelUtils.class);
38
	private static final Logger logger = LogManager.getLogger();
39 39

  
40 40
    /** Reads all rows of an Excel worksheet */
41 41
    public static List<Map<String, String>> parseXLS(URI uri) throws FileNotFoundException {
cdmlib-commons/src/main/java/eu/etaxonomy/cdm/common/FileCopy.java
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
package eu.etaxonomy.cdm.common;

10

  
11
import java.io.File;

12
import java.io.FileInputStream;

13
import java.io.FileOutputStream;

14
import java.io.IOException;

15
import java.io.InputStream;

16
import java.io.OutputStream;

17

  
18
import org.apache.logging.log4j.LogManager;

19
import org.apache.logging.log4j.Logger;

20

  
21
/**

22
 * @author a.mueller

23
 * @since 20.11.2008

24
 */

25
public class FileCopy {

26

  
27
	private static final Logger logger = LogManager.getLogger(FileCopy.class);

28

  
29
	// overwrite constants

30
	public static final int DO_OVERWRITE = 1;

31
	public static final int NO_OVERWRITE = 2;

32

  
33
	// default values

34
	private static int bufferSize = 4 * 1024;

35
	private static int overwrite = DO_OVERWRITE;

36

  
37
	/**

38
	 * Copies a File to another directory

39
	 * @param sourceFile

40
	 * @param destinationDirectory

41
	 * @param destFileName

42
	 * @return

43
	 * @throws IOException

44
	 */

45
	public static boolean copy(File sourceFile, File destinationDirectory, String destFileName)

46
			throws IOException {

47
		if (sourceFile == null){

48
			logger.debug("No sourcefile defined");

49
			throw new IOException("No sourcefile defined");

50
		}

51
		if (!sourceFile.isFile() || !sourceFile.canRead()) {

52
			logger.debug("Not a readable file: " + sourceFile.getName());

53
			throw new IOException("Not a readable file: " + sourceFile.getName());

54
		}

55
		if (destFileName == null || destFileName.equals("")){

56
			destFileName = sourceFile.getName();

57
		}

58
		InputStream in = new FileInputStream(sourceFile);

59
		copy(in, destinationDirectory, destFileName);

60

  
61
		if (!destinationDirectory.isDirectory()) {

62
			logger.warn("Not a directory: " + destinationDirectory.getName());

63
			return false;

64
		}

65
		File destinationFile = new File(destinationDirectory, destFileName);

66

  
67
		OutputStream out = new FileOutputStream(destinationFile);

68

  
69
		return copy(in, out);

70
	}

71

  
72
	public static boolean copy(InputStream in, File destinationDirectory, String destFileName)

73
			throws IOException {

74

  
75
		if (!destinationDirectory.isDirectory()) {

76
			throw new IOException("Destination is not a directory");

77
		}

78
		if (destFileName == null || destFileName.equals("")){

79
			throw new IOException("No destination file name specified");

80
		}

81
		File destinationFile = new File(destinationDirectory, destFileName);

82
		OutputStream out = new FileOutputStream(destinationFile);

83

  
84
		return copy(in, out);

85
	}

86

  
87
	public static boolean copy(InputStream in, OutputStream out)

88
			throws IOException {

89
		byte[] buffer = new byte[bufferSize];

90
		int bytesRead;

91
		while ((bytesRead = in.read(buffer)) >= 0) {

92
			out.write(buffer, 0, bytesRead);

93
		}

94
		out.close();

95
		in.close();

96
		logger.debug("File copied");

97
		return true;

98
	}

99

  
100
	public static boolean copy(String source, String destDirectory, String destFileName)

101
			throws IOException {

102
		File sourceFile = new File(source);

103
		File destinationDir = new File(destDirectory);

104
		return copy(sourceFile, destinationDir, destFileName);

105
	}

106

  
107
	public static boolean copy(String source, String destDirectory)

108
			throws IOException {

109
		return copy(source, destDirectory, null);

110
	}

111

  
112
	/**

113
	 * True if file

114
	 * @param file File destination

115
	 * @return true if data can be copied, false otherwise

116
	 */

117
	public static boolean doCopy(File file) {

118
		boolean exists = file.exists();

119
		if (overwrite == DO_OVERWRITE || !exists) {

120
			return true;

121
		} else if (overwrite == NO_OVERWRITE) {

122
			return false;

123
		} else{

124
			return false;

125
		}

126
	}

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
package eu.etaxonomy.cdm.common;
10

  
11
import java.io.File;
12
import java.io.FileInputStream;
13
import java.io.FileOutputStream;
14
import java.io.IOException;
15
import java.io.InputStream;
16
import java.io.OutputStream;
17

  
18
import org.apache.logging.log4j.LogManager;
19
import org.apache.logging.log4j.Logger;
20

  
21
/**
22
 * @author a.mueller
23
 * @since 20.11.2008
24
 */
25
public class FileCopy {
26

  
27
	private static final Logger logger = LogManager.getLogger();
28

  
29
	// overwrite constants
30
	public static final int DO_OVERWRITE = 1;
31
	public static final int NO_OVERWRITE = 2;
32

  
33
	// default values
34
	private static int bufferSize = 4 * 1024;
35
	private static int overwrite = DO_OVERWRITE;
36

  
37
	/**
38
	 * Copies a File to another directory
39
	 * @param sourceFile
40
	 * @param destinationDirectory
41
	 * @param destFileName
42
	 * @return
43
	 * @throws IOException
44
	 */
45
	public static boolean copy(File sourceFile, File destinationDirectory, String destFileName)
46
			throws IOException {
47
		if (sourceFile == null){
48
			logger.debug("No sourcefile defined");
49
			throw new IOException("No sourcefile defined");
50
		}
51
		if (!sourceFile.isFile() || !sourceFile.canRead()) {
52
			logger.debug("Not a readable file: " + sourceFile.getName());
53
			throw new IOException("Not a readable file: " + sourceFile.getName());
54
		}
55
		if (destFileName == null || destFileName.equals("")){
56
			destFileName = sourceFile.getName();
57
		}
58
		InputStream in = new FileInputStream(sourceFile);
59
		copy(in, destinationDirectory, destFileName);
60

  
61
		if (!destinationDirectory.isDirectory()) {
62
			logger.warn("Not a directory: " + destinationDirectory.getName());
63
			return false;
64
		}
65
		File destinationFile = new File(destinationDirectory, destFileName);
66

  
67
		OutputStream out = new FileOutputStream(destinationFile);
68

  
69
		return copy(in, out);
70
	}
71

  
72
	public static boolean copy(InputStream in, File destinationDirectory, String destFileName)
73
			throws IOException {
74

  
75
		if (!destinationDirectory.isDirectory()) {
76
			throw new IOException("Destination is not a directory");
77
		}
78
		if (destFileName == null || destFileName.equals("")){
79
			throw new IOException("No destination file name specified");
80
		}
81
		File destinationFile = new File(destinationDirectory, destFileName);
82
		OutputStream out = new FileOutputStream(destinationFile);
83

  
84
		return copy(in, out);
85
	}
86

  
87
	public static boolean copy(InputStream in, OutputStream out)
88
			throws IOException {
89
		byte[] buffer = new byte[bufferSize];
90
		int bytesRead;
91
		while ((bytesRead = in.read(buffer)) >= 0) {
92
			out.write(buffer, 0, bytesRead);
93
		}
94
		out.close();
95
		in.close();
96
		logger.debug("File copied");
97
		return true;
98
	}
99

  
100
	public static boolean copy(String source, String destDirectory, String destFileName)
101
			throws IOException {
102
		File sourceFile = new File(source);
103
		File destinationDir = new File(destDirectory);
104
		return copy(sourceFile, destinationDir, destFileName);
105
	}
106

  
107
	public static boolean copy(String source, String destDirectory)
108
			throws IOException {
109
		return copy(source, destDirectory, null);
110
	}
111

  
112
	/**
113
	 * True if file
114
	 * @param file File destination
115
	 * @return true if data can be copied, false otherwise
116
	 */
117
	public static boolean doCopy(File file) {
118
		boolean exists = file.exists();
119
		if (overwrite == DO_OVERWRITE || !exists) {
120
			return true;
121
		} else if (overwrite == NO_OVERWRITE) {
122
			return false;
123
		} else{
124
			return false;
125
		}
126
	}
127 127
}
cdmlib-commons/src/main/java/eu/etaxonomy/cdm/common/JvmMonitor.java
23 23
 */
24 24
public class JvmMonitor {
25 25

  
26
    public static final Logger logger = LogManager.getLogger(JvmMonitor.class);
26
    public static final Logger logger = LogManager.getLogger();
27 27

  
28 28
    private long gcTimeLast = 0;
29 29

  
cdmlib-commons/src/main/java/eu/etaxonomy/cdm/common/ResultWrapper.java
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 org.apache.logging.log4j.LogManager;
13
import org.apache.logging.log4j.Logger;
14

  
15
/**
16
 * Wrapps a result object so it can be used as method parameter and changed within the method.
17
 * This is useful especially for simple data types like <code>Boolean</code> etc.<br>
18
 * Example (usage):<br><code>
19
 * 	public String myMethod(String oneParameter, ResultWrapper<Boolean> success){<br>
20
 * 	    __if (oneParameter.equals("foo")){<br>
21
 * 	    ____success = success.setValue(false);<br>
22
 * 	    ____return "Foo";<br>
23
 * 	__}else{<br>
24
 * 	____//don't change success<br>
25
 * 	____return "All the best";<br>
26
 * 	__}<br>
27
 * 	}
28
 * </code>
29
 * Here a String is returned but the boolean value may also be changed and it's value is useable
30
 * by the calling method
31
 *
32
 * @author a.mueller
33
 * @since 01.11.2008
34
 */
35
public class ResultWrapper<T> {
36

  
37
	private static final Logger logger = LogManager.getLogger(ResultWrapper.class);
38

  
39
	public static final ResultWrapper<Boolean> NewInstance(Boolean value){
40
		ResultWrapper<Boolean> result = new ResultWrapper<Boolean>();
41
		result.setValue(value);
42
		if (logger.isDebugEnabled()){logger.debug("New Instance");}
43
		return result;
44
	}
45

  
46
	private T object;
47

  
48
	public T getValue() {
49
		return object;
50
	}
51

  
52
	public void setValue(T value) {
53
		this.object = value;
54
	}
55
}
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 org.apache.logging.log4j.LogManager;
13
import org.apache.logging.log4j.Logger;
14

  
15
/**
16
 * Wrapps a result object so it can be used as method parameter and changed within the method.
17
 * This is useful especially for simple data types like <code>Boolean</code> etc.<br>
18
 * Example (usage):<br><code>
19
 * 	public String myMethod(String oneParameter, ResultWrapper<Boolean> success){<br>
20
 * 	    __if (oneParameter.equals("foo")){<br>
21
 * 	    ____success = success.setValue(false);<br>
22
 * 	    ____return "Foo";<br>
23
 * 	__}else{<br>
24
 * 	____//don't change success<br>
25
 * 	____return "All the best";<br>
26
 * 	__}<br>
27
 * 	}
28
 * </code>
29
 * Here a String is returned but the boolean value may also be changed and it's value is useable
30
 * by the calling method
31
 *
32
 * @author a.mueller
33
 * @since 01.11.2008
34
 */
35
public class ResultWrapper<T> {
36

  
37
	private static final Logger logger = LogManager.getLogger();
38

  
39
	public static final ResultWrapper<Boolean> NewInstance(Boolean value){
40
		ResultWrapper<Boolean> result = new ResultWrapper<Boolean>();
41
		result.setValue(value);
42
		if (logger.isDebugEnabled()){logger.debug("New Instance");}
43
		return result;
44
	}
45

  
46
	private T object;
47

  
48
	public T getValue() {
49
		return object;
50
	}
51

  
52
	public void setValue(T value) {
53
		this.object = value;
54
	}
55
}
cdmlib-commons/src/main/java/eu/etaxonomy/cdm/common/StreamUtils.java
1
/**
2
* Copyright (C) 2009 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
package eu.etaxonomy.cdm.common;
10

  
11
import java.io.File;
12
import java.io.FileOutputStream;
13
import java.io.IOException;
14
import java.io.InputStream;
15
import java.io.InputStreamReader;
16
import java.io.StringBufferInputStream;
17
import java.net.HttpURLConnection;
18
import java.net.URL;
19

  
20
import org.apache.logging.log4j.LogManager;
21
import org.apache.logging.log4j.Logger;
22

  
23
/**
24
 * @author a.kohlbecker
25
 * @since 16.12.2010
26
 *
27
 */
28
public class StreamUtils {
29

  
30
	public static final Logger logger = LogManager.getLogger(StreamUtils.class);
31
	private static final int BUFFER_SIZE = 4096;
32

  
33
	/**
34
	 * Replaces each substring of this stream that matches the literal search sequence with the specified literal replace sequence.
35
	 * The replacement proceeds from the beginning of the stream to the end, for example, replacing "aa" with "b" in the string "aaa" will result in "ba" rather than "ab".
36
	 *
37
	 * @param stream
38
	 * @param search The sequence of char values to be replaced
39
	 * @param replace The replacement sequence of char values
40
	 * @return
41
	 * @throws IOException
42
	 *
43
	 */
44
	public static InputStream streamReplace(InputStream stream, String search,	String replace) throws IOException {
45
		InputStreamReader reader = new InputStreamReader(stream);
46
		StringBuilder strBuilder = new StringBuilder();
47

  
48
		char[] cbuf = new char[1024];
49
		int charsRead = -1;
50
		while ((charsRead = reader.read(cbuf)) > -1){
51
			strBuilder.append(cbuf, 0, charsRead);
52
		}
53
		String replacedContent = strBuilder.toString().replace(search, replace);
54
		StringBufferInputStream replacedStream = new StringBufferInputStream(replacedContent); //TODO replace with StringReader
55
		logger.debug(replacedContent);
56
		return replacedStream;
57
	}
58

  
59
	public static InputStream streamReplaceAll(InputStream stream, String regex, String replace) throws IOException {
60
		InputStreamReader reader = new InputStreamReader(stream);
61
		StringBuilder strBuilder = new StringBuilder();
62

  
63
		char[] cbuf = new char[1024];
64
		int charsRead = -1;
65
		while ((charsRead = reader.read(cbuf)) > -1){
66
			strBuilder.append(cbuf, 0, charsRead);
67
		}
68
		String replacedContent = strBuilder.toString().replaceAll(regex, replace);
69
		StringBufferInputStream replacedStream = new StringBufferInputStream(replacedContent); //TODO replace with StringReader
70
		logger.debug(replacedContent);
71
		return replacedStream;
72
	}
73

  
74
	public static String readToString(InputStream stream) throws IOException {
75
		InputStreamReader reader = new InputStreamReader(stream);
76
		StringBuilder strBuilder = new StringBuilder();
77

  
78
		char[] cbuf = new char[1024];
79
		int charsRead = -1;
80
		while ((charsRead = reader.read(cbuf)) > -1){
81
			strBuilder.append(cbuf, 0, charsRead);
82
		}
83
		return strBuilder.toString();
84
	}
85

  
86
	public static void downloadFile(URL url, String saveDir)
87
            throws IOException {
88

  
89
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
90
        int responseCode = httpConn.getResponseCode();
91

  
92
        // always check HTTP response code first
93
        if (responseCode == HttpURLConnection.HTTP_OK) {
94
            String fileName = "";
95
            String disposition = httpConn.getHeaderField("Content-Disposition");
96

  
97
            if (disposition != null) {
98
                // extracts file name from header field
99
                int index = disposition.indexOf("filename=");
100
                if (index > 0) {
101
                    fileName = disposition.substring(index + 10,
102
                            disposition.length() - 1);
103
                }
104
            } else {
105
                // extracts file name from URL
106
                fileName = url.getFile().toString().substring(url.getFile().lastIndexOf("/") + 1,
107
                        url.getFile().length());
108
            }
109

  
110
            // opens input stream from the HTTP connection
111
            InputStream inputStream = httpConn.getInputStream();
112
            String saveFilePath = saveDir + File.separator + fileName;
113

  
114
            // opens an output stream to save into file
115
            FileOutputStream outputStream = new FileOutputStream(saveFilePath);
116

  
117
            int bytesRead = -1;
118
            byte[] buffer = new byte[BUFFER_SIZE];
119
            while ((bytesRead = inputStream.read(buffer)) != -1) {
120
                outputStream.write(buffer, 0, bytesRead);
121
            }
122

  
123
            outputStream.close();
124
            inputStream.close();
125

  
126

  
127
        } else {
128
           logger.error("No file to download. Server replied HTTP code: " + responseCode);
129
        }
130
        httpConn.disconnect();
131
    }
132

  
133

  
134
}
1
/**
2
* Copyright (C) 2009 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
package eu.etaxonomy.cdm.common;
10

  
11
import java.io.File;
12
import java.io.FileOutputStream;
13
import java.io.IOException;
14
import java.io.InputStream;
15
import java.io.InputStreamReader;
16
import java.io.StringBufferInputStream;
17
import java.net.HttpURLConnection;
18
import java.net.URL;
19

  
20
import org.apache.logging.log4j.LogManager;
21
import org.apache.logging.log4j.Logger;
22

  
23
/**
24
 * @author a.kohlbecker
25
 * @since 16.12.2010
26
 *
27
 */
28
public class StreamUtils {
29

  
30
	public static final Logger logger = LogManager.getLogger();
31
	private static final int BUFFER_SIZE = 4096;
32

  
33
	/**
34
	 * Replaces each substring of this stream that matches the literal search sequence with the specified literal replace sequence.
35
	 * The replacement proceeds from the beginning of the stream to the end, for example, replacing "aa" with "b" in the string "aaa" will result in "ba" rather than "ab".
36
	 *
37
	 * @param stream
38
	 * @param search The sequence of char values to be replaced
39
	 * @param replace The replacement sequence of char values
40
	 * @return
41
	 * @throws IOException
42
	 *
43
	 */
44
	public static InputStream streamReplace(InputStream stream, String search,	String replace) throws IOException {
45
		InputStreamReader reader = new InputStreamReader(stream);
46
		StringBuilder strBuilder = new StringBuilder();
47

  
48
		char[] cbuf = new char[1024];
49
		int charsRead = -1;
50
		while ((charsRead = reader.read(cbuf)) > -1){
51
			strBuilder.append(cbuf, 0, charsRead);
52
		}
53
		String replacedContent = strBuilder.toString().replace(search, replace);
54
		StringBufferInputStream replacedStream = new StringBufferInputStream(replacedContent); //TODO replace with StringReader
55
		logger.debug(replacedContent);
56
		return replacedStream;
57
	}
58

  
59
	public static InputStream streamReplaceAll(InputStream stream, String regex, String replace) throws IOException {
60
		InputStreamReader reader = new InputStreamReader(stream);
61
		StringBuilder strBuilder = new StringBuilder();
62

  
63
		char[] cbuf = new char[1024];
64
		int charsRead = -1;
65
		while ((charsRead = reader.read(cbuf)) > -1){
66
			strBuilder.append(cbuf, 0, charsRead);
67
		}
68
		String replacedContent = strBuilder.toString().replaceAll(regex, replace);
69
		StringBufferInputStream replacedStream = new StringBufferInputStream(replacedContent); //TODO replace with StringReader
70
		logger.debug(replacedContent);
71
		return replacedStream;
72
	}
73

  
74
	public static String readToString(InputStream stream) throws IOException {
75
		InputStreamReader reader = new InputStreamReader(stream);
76
		StringBuilder strBuilder = new StringBuilder();
77

  
78
		char[] cbuf = new char[1024];
79
		int charsRead = -1;
80
		while ((charsRead = reader.read(cbuf)) > -1){
81
			strBuilder.append(cbuf, 0, charsRead);
82
		}
83
		return strBuilder.toString();
84
	}
85

  
86
	public static void downloadFile(URL url, String saveDir)
87
            throws IOException {
88

  
89
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
90
        int responseCode = httpConn.getResponseCode();
91

  
92
        // always check HTTP response code first
93
        if (responseCode == HttpURLConnection.HTTP_OK) {
94
            String fileName = "";
95
            String disposition = httpConn.getHeaderField("Content-Disposition");
96

  
97
            if (disposition != null) {
98
                // extracts file name from header field
99
                int index = disposition.indexOf("filename=");
100
                if (index > 0) {
101
                    fileName = disposition.substring(index + 10,
102
                            disposition.length() - 1);
103
                }
104
            } else {
105
                // extracts file name from URL
106
                fileName = url.getFile().toString().substring(url.getFile().lastIndexOf("/") + 1,
107
                        url.getFile().length());
108
            }
109

  
110
            // opens input stream from the HTTP connection
111
            InputStream inputStream = httpConn.getInputStream();
112
            String saveFilePath = saveDir + File.separator + fileName;
113

  
114
            // opens an output stream to save into file
115
            FileOutputStream outputStream = new FileOutputStream(saveFilePath);
116

  
117
            int bytesRead = -1;
118
            byte[] buffer = new byte[BUFFER_SIZE];
119
            while ((bytesRead = inputStream.read(buffer)) != -1) {
120
                outputStream.write(buffer, 0, bytesRead);
121
            }
122

  
123
            outputStream.close();
124
            inputStream.close();
125

  
126

  
127
        } else {
128
           logger.error("No file to download. Server replied HTTP code: " + responseCode);
129
        }
130
        httpConn.disconnect();
131
    }
132

  
133

  
134
}
cdmlib-commons/src/main/java/eu/etaxonomy/cdm/common/UriUtils.java
60 60
 * @since Sep 23, 2010
61 61
 */
62 62
public class UriUtils {
63
    private static final Logger logger = LogManager.getLogger(UriUtils.class);
63

  
64
    private static final Logger logger = LogManager.getLogger();
64 65

  
65 66
    protected static final String URI_IS_NOT_ABSOLUTE = "URI is not absolute (protocol is missing)";
66 67

  
cdmlib-commons/src/main/java/eu/etaxonomy/cdm/common/XmlHelp.java
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.File;
13
import java.io.FileNotFoundException;
14
import java.io.FileOutputStream;
15
import java.io.IOException;
16
import java.io.InputStream;
17
import java.io.OutputStream;
18
import java.util.ArrayList;
19
import java.util.List;
20

  
21
import org.apache.logging.log4j.LogManager;
22
import org.apache.logging.log4j.Logger;
23
import org.jdom.Attribute;
24
import org.jdom.Document;
25
import org.jdom.Element;
26
import org.jdom.JDOMException;
27
import org.jdom.Namespace;
28
import org.jdom.input.SAXBuilder;
29
import org.jdom.output.Format;
30
import org.jdom.output.XMLOutputter;
31

  
32
public class XmlHelp {
33
	private static final Logger logger = LogManager.getLogger(XmlHelp.class);
34

  
35
	public final static Format prettyFormat = Format.getPrettyFormat();
36
	/**
37
	 * Writes the Document doc to the specified file
38
	 * @param doc
39
	 * @param path
40
	 * @param fileName
41
	 * @return true, if no error
42
	 *
43
	 * TODO throw the FileNotFoundException and handle in the calling method. That is more likely the place where you can do
44
	 * something about the problem
45
	 */
46
	static public boolean saveToXml(Document doc, String path, String fileName, Format format ){
47
		try {
48
			if (! fileName.endsWith(".xml")){
49
				fileName += ".xml";
50
			}
51
			FileOutputStream outFile = new FileOutputStream(path + File.separator + fileName);
52
			return saveToXml(doc, outFile, format);
53
		} catch (FileNotFoundException e) {
54
			logger.error("FileNotFoundException in saveToXml()");
55
			return false;
56
		}
57

  
58
	}
59

  
60
	/**
61
	 * Writes the Document doc to the specified file
62
	 * @param doc
63
	 * @param path
64
	 * @param fileName
65
	 * @return true, if no error
66
	 *
67
	 * TODO throw the IOException and handle in the calling method. That is more likely the place where you can do
68
	 * something about the problem
69
	 */
70
	static public boolean saveToXml(Document doc, OutputStream outStream, Format format ){
71
		try {
72
			XMLOutputter out = new XMLOutputter(format);
73
			out.output(doc, outStream);
74
			return true;
75
		} catch (IOException e) {
76
			logger.error("IOException in saveToXml()");
77
			return false;
78
		}
79
	}
80

  
81
	static public Element getFirstAttributedChild(Element parent, String elementName, String attributeName, String attributeValue){
82
		Namespace ns = parent.getNamespace();
83

  
84
		List<Element> elList = getChildren(parent, elementName, ns);
85
		for (Element el : elList){
86
			Attribute attr =  el.getAttribute(attributeName);
87
			if (attr != null && attr.getValue().equalsIgnoreCase(attributeValue)){
88
				return el;
89
			}
90
		}
91
		return null;
92
	}
93

  
94
	static public List<Element> getAttributedChildList(Element parent, String elementName, String attributeName){
95
		List<Element> resultList = new ArrayList<Element>();
96
		Namespace ns = parent.getNamespace();
97
		List<Element> elList = getChildren(parent, elementName, ns);
98
		for (Element el : elList){
99
			Attribute attr =  el.getAttribute(attributeName);
100
			if (attr != null){
101
				resultList.add(el);
102
			}
103
		}
104
		return resultList;
105
	}
106

  
107
	/**
108
	 * Returns a list of children with the given element name and with a given attribute name and
109
	 * a given value for this attribute.<BR>
110
	 * The value comparison is case insensitive.
111
	 * @param parent
112
	 * @param elementName
113
	 * @param attributeName
114
	 * @param value
115
	 * @return
116
	 */
117
	static public List<Element> getAttributedChildListWithValue(Element parent, String elementName, String attributeName, String value){
118
		List<Element> resultList = new ArrayList<Element>();
119
		Namespace ns = parent.getNamespace();
120
		List<Element> elList = getChildren(parent, elementName, ns);
121
		for (Element el : elList){
122
			Attribute attr =  el.getAttribute(attributeName);
123
			if (attr != null){
124
				if (attr.getValue().equalsIgnoreCase(value)){
125
					resultList.add(el);
126
				}
127
			}
128
		}
129
		return resultList;
130
	}
131

  
132
	@SuppressWarnings("unchecked")
133
	private static List<Element> getChildren(Element parent, String elementName,Namespace ns) {
134
		return parent.getChildren(elementName, ns);
135
	}
136

  
137
	public static String getChildAttributeValue(Element element, String childElementName, Namespace childElementNamespace, String childAttributeName, Namespace childAttributeNamespace){
138
		Element child = element.getChild(childElementName, childElementNamespace);
139
		if (child == null){
140
			return null;
141
		}
142
		Attribute childAttribute = child.getAttribute(childAttributeName, childAttributeNamespace);
143
		if (childAttribute == null){
144
			return null;
145
		}
146
		return childAttribute.getValue();
147
	}
148

  
149
	public static String getChildContent(Element element, String childElementName, Namespace childElementNamespace, String childAttributeName, Namespace childAttributeNamespace){
150
		Element child = element.getChild(childElementName, childElementNamespace);
151
		if (child == null){
152
			return null;
153
		}
154
		List childContent = child.getContent();
155
		if (childContent.isEmpty()){
156
			return null;
157
		}
158
		for (Object content:childContent){
159
			if (content instanceof Element){
160
				Element contentEl = (Element)content;
161
				if (contentEl.getName().equals(childAttributeName)){
162
					return contentEl.getText();
163
				}
164
			}
165
		}
166
		return null;
167
	}
168

  
169
	/**
170
	 * @param parent
171
	 * @param elementName
172
	 * @param attributeName
173
	 * @param attributeValue
174
	 * @return
175
	 */
176
	static public Element getOrAddChild(Element parent, String elementName, String attributeName, String attributeValue){
177
		Element result = null;
178
		if (parent != null){
179
			if (attributeName != null){
180
				result = getFirstAttributedChild(parent, elementName, attributeName, attributeValue);
181
			}else{
182
				result = parent.getChild(elementName, parent.getNamespace());
183
			}
184
			if (result == null){
185
				result  = new Element(elementName, parent.getNamespace());
186
				if (attributeName != null){
187
					Attribute attr = new Attribute(attributeName, attributeValue);
188
					result.setAttribute(attr);
189
				}
190
			}
191
			if (result.getParent()== null){
192
				parent.addContent(result);
193
			}
194
		}
195
		return result;
196
	}
197

  
198
	static public Element insertXmlRefProperty(Element parent, String strName, String strValue){
199
		Namespace ns = parent.getNamespace();
200
		Element property = new Element("property", ns);
201
		Attribute name = new Attribute("name", strName);
202
		property.setAttribute(name);
203
		Attribute value = new Attribute("value", strValue);
204
		property.setAttribute(value);
205
		parent.addContent(property);
206
		return  property;
207
	}
208

  
209
	static public Element insertXmlValueProperty(Element parent, String strName, String strValue){
210
		Namespace ns = parent.getNamespace();
211
		Element property = new Element("property", ns);
212
		Attribute name = new Attribute("name", strName);
213
		property.setAttribute(name);
214
		Attribute value = new Attribute("value", strValue);
215
		property.setAttribute(value);
216
		parent.addContent(property);
217
		return  property;
218
	}
219

  
220

  
221
	static public Element insertXmlBean(Element parent, String strId, String strClass){
222
		Namespace ns = parent.getNamespace();
223
		Element bean = new Element("bean", ns);
224
		Attribute id = new Attribute("id", strId);
225
		bean.setAttribute(id);
226
		Attribute clazz = new Attribute("class", strClass);
227
		bean.setAttribute(clazz);
228
		parent.addContent(bean);
229
		return  bean;
230
	}
231

  
232

  
233
	/**
234
	 * returns the root Element in the File xmlFile
235
	 * @param xmlInput
236
	 * @return
237
	 * @throws JDOMException
238
	 * @throws IOException
239
	 */
240
	static public  Element getRoot(InputStream xmlInput) throws JDOMException, IOException{
241
		SAXBuilder builder = new SAXBuilder();
242
		Document doc = builder.build(xmlInput);
243
		Element root = doc.getRootElement();
244
		return root;
245
	}
246

  
247
	/**
248
	 * returns the root Element in the File xmlFile
249
	 *
250
	 * @param xmlInput
251
	 * @param elementName
252
	 * @return
253
	 * TODO throw the JDOMException and the IOException and handle in the calling method. That is more likely the place where you can do
254
	 * something about the problem
255
	 */
256
	static public  Element getRoot(InputStream xmlInput, String elementName){
257
		try {
258
			SAXBuilder builder = new SAXBuilder();
259
			Document doc = builder.build(xmlInput);
260
			Element root = doc.getRootElement();
261
			if (root.getName() != elementName){
262
				return null;
263
			}else{
264
				return root;
265
			}
266
		} catch (JDOMException e) {
267
			e.printStackTrace();
268
			return null;
269
		} catch (IOException e) {
270
			e.printStackTrace();
271
			return null;
272
		}
273
	}
274

  
275
	/**
276
	 * returns the root Element in the File xmlFile
277
	 * @param xmlInput
278
	 * @return
279
	 *
280
	 * TODO throw the IOException and handle in the calling method. That is more likely the place where you can do
281
	 * something about the problem
282
	 */
283
	static public  Element getBeansRoot(InputStream xmlInput){
284
		try {
285
			SAXBuilder builder = new SAXBuilder();
286
			Document doc = builder.build(xmlInput);
287
			Element root = doc.getRootElement();
288
			if (root.getName() != "beans"){
289
				return null;
290
			}else{
291
				return root;
292
			}
293
		} catch (JDOMException e) {
294
			e.printStackTrace();
295
			return null;
296
		} catch (IOException e) {
297
			e.printStackTrace();
298
			return null;
299
		}
300
	}
301

  
302
	/**
303
	 * Gets the child element and tests if there is no other child element exists having the same name.
304
	 * The result is returned as a pair of thd child element and a boolean value that indicates if the
305
	 * elements cardinality was correct. <BR>
306
	 * If there is more then one child element with the child element name
307
	 * or if there is no such element and obligatory is <code>true</code> the second part of the result is <code>false</code>
308
	 * Otherwise it is <code>true</code>.
309
	 * @param parentElement the parent element
310
	 * @param childName name of the child element
311
	 * @param nsChild the namespace for the child element
312
	 * @param obligatory if <code>true</code>, return value is only <code>true</code> if exactly 1 child element with
313
	 * the given name exists
314
	 * @return
315
	 */
316
	static public DoubleResult<Element, Boolean> getSingleChildElement(Element parentElement, String childName, Namespace nsChild, boolean obligatory){
317
		DoubleResult<Element, Boolean> result = new DoubleResult<Element, Boolean>();
318
		result.setSecondResult(false);
319

  
320
		if (parentElement == null){
321
			logger.warn("Parent element is null");
322
			return result;
323
		}
324
		List<Element> elList = getChildren(parentElement, childName, nsChild);
325
		if (elList.size() > 1){
326
			logger.error("Multiple '" + childName + "' elements.");
327
			return result;
328
		}else if (elList.size() == 0){
329
			logger.info("There is no '" + childName + "' element");
330
			if (! obligatory){
331
				result.setSecondResult(true);
332
			}
333
			return result;
334
		}
335
		Element childElement = elList.get(0);
336
		result.setFirstResult(childElement);
337
		result.setSecondResult(true);
338
		return result;
339
	}
340

  
341
	static public Element getSingleChildElement(ResultWrapper<Boolean> success, Element parentElement, String childName, Namespace nsChild, boolean obligatory){
342

  
343
		if (parentElement == null){
344
			logger.warn("Parent element is null");
345
			success.setValue(false);
346
			return null;
347
		}
348
		List<Element> elList = getChildren(parentElement, childName, nsChild);
349
		if (elList.size() > 1){
350
			logger.error("Multiple '" + childName + "' elements.");
351
			success.setValue(false);
352
			return null;
353
		}else if (elList.size() == 0){
354
			elList = getChildren(parentElement, childName, null);
355
			logger.info("There is no '" + childName + "' element");
356
			if (obligatory){
357
				success.setValue(false);
358
			}
359
			return null;
360
		}
361

  
362
		Element childElement = elList.get(0);
363
		return childElement;
364
	}
365

  
366
	static public List<Element> getMultipleChildElement(Element parentElement, String childName, Namespace nsChild, boolean obligatory){
367

  
368
		if (parentElement == null){
369
			logger.warn("Parent element is null");
370
			return null;
371
		}
372

  
373
		List<Element> elList = getChildren(parentElement, childName.trim(), nsChild);
374

  
375
		if (elList.size() == 0){
376
			logger.info("There is no '" + childName + "' element");
377
			return null;
378
		}
379
		return elList;
380
	}
381

  
382
	public static String getChildContentAttributeValue(Element element,
383
			String childAttributeName, Namespace taxonNameNamespace, String childElementName,
384
			Namespace childElementNamespace) {
385
		Element child = element.getChild(childAttributeName, taxonNameNamespace);
386
		if (child == null){
387
			return null;
388
		}
389
		List childContent = child.getContent();
390
		if (childContent.isEmpty()){
391
			return null;
392
		}
393
		for (Object content:childContent){
394
			if (content instanceof Element){
395
				Element contentEl = (Element)content;
396
				if (contentEl == null){
397
					return null;
398
				}
399
				if (!(contentEl.getAttributeValue(childElementName) == null)){
400
					Attribute at = contentEl.getAttribute("ressource");
401
					if (at != null) {
402
                        return at.getValue();
403
                    }
404
				}
405
			}
406
		}
407
		return null;
408
	}
409

  
410
}
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.File;
13
import java.io.FileNotFoundException;
14
import java.io.FileOutputStream;
15
import java.io.IOException;
16
import java.io.InputStream;
17
import java.io.OutputStream;
18
import java.util.ArrayList;
19
import java.util.List;
20

  
21
import org.apache.logging.log4j.LogManager;
22
import org.apache.logging.log4j.Logger;
23
import org.jdom.Attribute;
24
import org.jdom.Document;
25
import org.jdom.Element;
26
import org.jdom.JDOMException;
27
import org.jdom.Namespace;
28
import org.jdom.input.SAXBuilder;
29
import org.jdom.output.Format;
30
import org.jdom.output.XMLOutputter;
31

  
32
public class XmlHelp {
33

  
34
	private static final Logger logger = LogManager.getLogger();
35

  
36
	public final static Format prettyFormat = Format.getPrettyFormat();
37
	/**
38
	 * Writes the Document doc to the specified file
39
	 * @param doc
40
	 * @param path
41
	 * @param fileName
42
	 * @return true, if no error
43
	 *
44
	 * TODO throw the FileNotFoundException and handle in the calling method. That is more likely the place where you can do
45
	 * something about the problem
46
	 */
47
	static public boolean saveToXml(Document doc, String path, String fileName, Format format ){
48
		try {
49
			if (! fileName.endsWith(".xml")){
50
				fileName += ".xml";
51
			}
52
			FileOutputStream outFile = new FileOutputStream(path + File.separator + fileName);
53
			return saveToXml(doc, outFile, format);
54
		} catch (FileNotFoundException e) {
55
			logger.error("FileNotFoundException in saveToXml()");
56
			return false;
57
		}
58
	}
59

  
60
	/**
61
	 * Writes the Document doc to the specified file
62
	 * @param doc
63
	 * @param path
64
	 * @param fileName
65
	 * @return true, if no error
66
	 *
67
	 * TODO throw the IOException and handle in the calling method. That is more likely the place where you can do
68
	 * something about the problem
69
	 */
70
	static public boolean saveToXml(Document doc, OutputStream outStream, Format format ){
71
		try {
72
			XMLOutputter out = new XMLOutputter(format);
73
			out.output(doc, outStream);
74
			return true;
75
		} catch (IOException e) {
76
			logger.error("IOException in saveToXml()");
77
			return false;
78
		}
79
	}
80

  
81
	static public Element getFirstAttributedChild(Element parent, String elementName, String attributeName, String attributeValue){
82
		Namespace ns = parent.getNamespace();
83

  
84
		List<Element> elList = getChildren(parent, elementName, ns);
85
		for (Element el : elList){
86
			Attribute attr =  el.getAttribute(attributeName);
87
			if (attr != null && attr.getValue().equalsIgnoreCase(attributeValue)){
88
				return el;
89
			}
90
		}
91
		return null;
92
	}
93

  
94
	static public List<Element> getAttributedChildList(Element parent, String elementName, String attributeName){
95
		List<Element> resultList = new ArrayList<Element>();
96
		Namespace ns = parent.getNamespace();
97
		List<Element> elList = getChildren(parent, elementName, ns);
98
		for (Element el : elList){
99
			Attribute attr =  el.getAttribute(attributeName);
100
			if (attr != null){
101
				resultList.add(el);
102
			}
103
		}
104
		return resultList;
105
	}
106

  
107
	/**
108
	 * Returns a list of children with the given element name and with a given attribute name and
109
	 * a given value for this attribute.<BR>
110
	 * The value comparison is case insensitive.
111
	 * @param parent
112
	 * @param elementName
113
	 * @param attributeName
114
	 * @param value
115
	 * @return
116
	 */
117
	static public List<Element> getAttributedChildListWithValue(Element parent, String elementName, String attributeName, String value){
118
		List<Element> resultList = new ArrayList<Element>();
119
		Namespace ns = parent.getNamespace();
120
		List<Element> elList = getChildren(parent, elementName, ns);
121
		for (Element el : elList){
122
			Attribute attr =  el.getAttribute(attributeName);
123
			if (attr != null){
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff