1 /*
2 * Copyright 2010 Fraunhofer Gesellschaft, Munich, Germany,
3 * for its Fraunhofer Institute for Computer Architecture and Software
4 * Technology (FIRST), Berlin, Germany. All rights reserved.
5 * http://www.first.fraunhofer.de/
6 */
7
8 package net.kwfgrid.gwes.util;
9
10 import java.util.regex.Pattern;
11 import java.util.regex.Matcher;
12 import java.util.List;
13 import java.io.*;
14
15 /**
16 * @author Andreas Hoheisel
17 * (<a href="http://www.andreas-hoheisel.de">www.andreas-hoheisel.de</a>)
18 * @version $Id: StringUtils.java 1478 2011-02-10 14:49:57Z hoheisel $
19 */
20 public class StringUtils {
21
22 public static final Pattern PATTERN_PROBABILITY = Pattern.compile("\\{?[0-9.]+\\p{Space}?\\%\\}?");
23 public static final Pattern PATTERN_SPACES_AND_MORE = Pattern.compile("[,; \\t\\n\\x0B\\f\\r]+");
24 public static final Pattern PATTERN_SLASH_AND_COMMA = Pattern.compile("[,/]");
25
26 public static String stripNamespacePrefix(String str) {
27 if (str == null) return null;
28 String[] strA = str.split(":");
29 if (strA.length <= 1) {
30 return str;
31 } else {
32 return strA[1];
33 }
34 }
35
36 /**
37 * Replaces "$" by "/gwdl:data/" and leading "*" by "/gwdl:data/*" in edgeExpressions.
38 * This method also trims the edge expression.
39 * @param edgeExpression
40 * @return
41 */
42 public static String expandContextVariables(String edgeExpression) {
43 if (edgeExpression == null) return null;
44 // remove leading and trailing spaces
45 String ret = edgeExpression.trim();
46 // replace leading * by /gwdl:data/*
47 ret = ret.replaceFirst("^\\*","/gwdl:data/*");
48 // replace $ by /gwdl:data/
49 ret = ret.replaceAll("\\$","/gwdl:data/");
50 return ret;
51 }
52
53 /**
54 * Replace URL edge expression ("http://host/dir/file#foo") with value after # ("foo").
55 *
56 * @param str
57 * @return the edge expression without owl part
58 */
59 public static String stripOwl(String str) {
60 if (str == null) return null;
61 String[] strA = str.split("#");
62 if (strA.length <= 1) {
63 return str;
64 } else {
65 return strA[1];
66 }
67 }
68
69 public static double getProbability(String str) {
70 Matcher match = PATTERN_PROBABILITY.matcher(str);
71 if (match.find()) {
72 String substring = str.substring(match.start(),match.end()).replaceAll("[{}%]","");
73 double ret = Double.parseDouble(substring); // value is in percent
74 return ret/100d;
75 } else {
76 return -1d;
77 }
78 }
79
80 /**
81 * Strip the probability substring from string. E.g.: "x{50.3%}" -> "x"
82 * @param str
83 * @return String without the probability substring.
84 */
85 public static String stripProbability(String str) {
86 String[] strarr = PATTERN_PROBABILITY.split(str,2);
87 return strarr[0];
88 }
89
90 /**
91 * Extract the text contents of an XML element, e.g., <name>Hugo</name> = Hugo
92 * @param xml The XML
93 * @param elementname The element name.
94 * @return
95 */
96 public static String extractStringFromXML (String xml, String elementname) {
97 int begin = xml.indexOf("<" + elementname + ">");
98 // ToDo: add length of attributes to begin.
99 //if (begin < 0) begin = xml.indexOf("<" + elementname + " ");
100 if (begin < 0) return null;
101 int end = xml.indexOf("</" + elementname + ">");
102 if (end < 0) return null;
103 String res = xml.substring(begin + elementname.length() + 2, end).trim();
104 // logger.info(elementname+"="+res);
105 return res;
106 }
107
108 /**
109 * Splits a string using as delimiter one ore more space-type characters (space, tab, etc.) or the
110 * characters "," and ";".
111 * @param str The string to split.
112 * @return array of string without the delimiters
113 */
114 public static String[] splitSpacesAndMore(String str) {
115 if (str == null) return null;
116 return PATTERN_SPACES_AND_MORE.split(str);
117 }
118
119 /**
120 * Trim string and replace all string characters that are not within 0-9, a-z, A-Z by "-".
121 *
122 * @param message The message string to be filtered
123 * @return The clean string only containing 0-9, a-z, A-Z.
124 */
125 public static String filter(String message) {
126 if (message == null) return (null);
127 String m = message.trim();
128
129 char content[] = new char[m.length()];
130 m.getChars(0, m.length(), content, 0);
131 StringBuffer result = new StringBuffer(content.length);
132 for (char c : content) {
133 if ( (c >= 'a') && (c<='z') ) result.append(c);
134 else if ( (c >= 'A') && (c<='Z') ) result.append(c);
135 else if ( (c >= '0') && (c<='9') ) result.append(c);
136 else result.append('-');
137 }
138 return (result.toString());
139 }
140
141 /**
142 * Extracts CN from DN and replaces chars that are not alphanumeric.
143 * Supports the following DN formats:
144 * "CN=..., OU=..., OU=..., O=..., C=.."
145 * "/C=../O=.../OU=.../OU=.../CN=..."
146 * @param userID The user ID, e.g., a DN extracted from a certificate.
147 * @return The CN or the useID if no "CN=" is available.
148 */
149 public static String extractFilteredCNFromDN(String userID) {
150 if (userID==null) return null;
151
152 // check for CN
153 String[] parts = PATTERN_SLASH_AND_COMMA.split(userID);
154 for (String part : parts) {
155 if (part.startsWith("CN=")) {
156 // CN found
157 return filter(part.substring(3));
158 }
159 }
160
161 // CN not found
162 return filter(userID);
163 }
164
165 /**
166 * Appends XML element to string buffer. If contents is null or an empty String, this method does NOT
167 * append an empty element!
168 * "<elementName>contents</elementName>"
169 * @param buffer The String Buffer to append.
170 * @param elementName Name of the Element.
171 * @param contents The contents.
172 */
173 public static void addXmlToStringBuffer(StringBuffer buffer, String elementName, String contents) {
174 if (contents != null && contents.length() > 0) {
175 buffer.append('<').append(elementName).append('>').append(contents).append("</").append(elementName).append('>');
176 }
177 }
178
179 /**
180 * Appends XML element to string buffer. If contents is less than zero, this method does NOT
181 * append an element!
182 * "<elementName>contents</elementName>"
183 * @param buffer The String Buffer to append.
184 * @param elementName Name of the Element.
185 * @param contents The contents.
186 */
187 public static void addXmlToStringBuffer(StringBuffer buffer, String elementName, long contents) {
188 if (contents >= 0L) {
189 buffer.append('<').append(elementName).append('>').append(contents).append("</").append(elementName).append('>');
190 }
191 }
192
193 /**
194 * Appends XML element to string buffer. If contents is less than zero, this method does NOT
195 * append an element!
196 * "<elementName>contents</elementName>"
197 * @param buffer The String Buffer to append.
198 * @param elementName Name of the Element.
199 * @param contents The contents.
200 */
201 public static void addXmlToStringBuffer(StringBuffer buffer, String elementName, int contents) {
202 if (contents >= 0L) {
203 buffer.append('<').append(elementName).append('>').append(contents).append("</").append(elementName).append('>');
204 }
205 }
206
207 public static String convertStreamToString(InputStream is) throws IOException {
208 if (is != null) {
209 Writer writer = new StringWriter();
210
211 char[] buffer = new char[1024];
212 try {
213 Reader reader = new BufferedReader(
214 new InputStreamReader(is, "UTF-8"));
215 int n;
216 while ((n = reader.read(buffer)) != -1) {
217 writer.write(buffer, 0, n);
218 }
219 } finally {
220 is.close();
221 }
222 return writer.toString();
223 } else {
224 return null;
225 }
226 }
227
228 /**
229 * Convert a List<List<String>> into String[][]
230 * @param listlist The input list of list of Strings
231 * @return the corresponding String[][] object.
232 */
233 public static String[][] convertListListToStringArrayArray(List<List<String>> listlist) {
234 String[][] ret = new String[listlist.size()][];
235 for (int i=0; i<listlist.size(); i++) {
236 List<String> l = listlist.get(i);
237 String[] strarr = new String[l.size()];
238 for (int j=0; j<l.size(); j++) {
239 String str = l.get(j);
240 strarr[j] = str;
241 }
242 ret[i] = strarr;
243 }
244 return ret;
245 }
246
247 }