1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.springframework.batch.support;
18
19 import java.io.IOException;
20 import java.io.StringReader;
21 import java.io.StringWriter;
22 import java.util.Arrays;
23 import java.util.List;
24 import java.util.Properties;
25
26 import org.springframework.util.DefaultPropertiesPersister;
27 import org.springframework.util.PropertiesPersister;
28 import org.springframework.util.StringUtils;
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44 public final class PropertiesConverter {
45
46 private static final PropertiesPersister propertiesPersister = new DefaultPropertiesPersister();
47
48 private static final String LINE_SEPARATOR = System.getProperty("line.separator");
49
50
51 private PropertiesConverter() {
52 };
53
54
55
56
57
58
59
60
61
62
63
64
65 public static Properties stringToProperties(String stringToParse) {
66
67 if (stringToParse == null) {
68 return new Properties();
69 }
70
71 if (!contains(stringToParse, "\n")) {
72 stringToParse = StringUtils.arrayToDelimitedString(
73 StringUtils.commaDelimitedListToStringArray(stringToParse), "\n");
74 }
75
76 StringReader stringReader = new StringReader(stringToParse);
77
78 Properties properties = new Properties();
79
80 try {
81 propertiesPersister.load(properties, stringReader);
82
83
84 }
85 catch (IOException ex) {
86 throw new IllegalStateException("Error while trying to parse String to java.util.Properties,"
87 + " given String: " + properties);
88 }
89
90 return properties;
91 }
92
93
94
95
96
97
98
99
100
101
102 public static String propertiesToString(Properties propertiesToParse) {
103
104
105 if (propertiesToParse == null || propertiesToParse.size() == 0) {
106 return "";
107 }
108
109 StringWriter stringWriter = new StringWriter();
110
111 try {
112 propertiesPersister.store(propertiesToParse, stringWriter, null);
113 }
114 catch (IOException ex) {
115
116 throw new IllegalStateException("Error while trying to convert properties to string");
117 }
118
119
120
121 String value = stringWriter.toString();
122 if (value.length() < 160) {
123 List<String> list = Arrays.asList(StringUtils.delimitedListToStringArray(value, LINE_SEPARATOR,
124 LINE_SEPARATOR));
125 String shortValue = StringUtils.collectionToCommaDelimitedString(list.subList(1, list.size()));
126 int count = StringUtils.countOccurrencesOf(shortValue, ",");
127 if (count == list.size() - 2) {
128 value = shortValue;
129 }
130 if (value.endsWith(",")) {
131 value = value.substring(0, value.length() - 1);
132 }
133 }
134 return value;
135 }
136
137 private static boolean contains(String str, String searchStr) {
138 return str.indexOf(searchStr) != -1;
139 }
140 }