KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > webharvest > utils > CommonUtil


1 /* Copyright (c) 2006-2007, Vladimir Nikic
2     All rights reserved.
3
4     Redistribution and use of this software in source and binary forms,
5     with or without modification, are permitted provided that the following
6     conditions are met:
7
8     * Redistributions of source code must retain the above
9       copyright notice, this list of conditions and the
10       following disclaimer.
11
12     * Redistributions in binary form must reproduce the above
13       copyright notice, this list of conditions and the
14       following disclaimer in the documentation and/or other
15       materials provided with the distribution.
16
17     * The name of Web-Harvest may not be used to endorse or promote
18       products derived from this software without specific prior
19       written permission.
20
21     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
22     AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23     IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24     ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
25     LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26     CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27     SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28     INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29     CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30     ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31     POSSIBILITY OF SUCH DAMAGE.
32
33     You can contact Vladimir Nikic by sending e-mail to
34     nikic_vladimir@yahoo.com. Please include the word "Web-Harvest" in the
35     subject line.
36 */

37 package org.webharvest.utils;
38
39 import java.io.*;
40 import java.net.URLDecoder JavaDoc;
41 import java.net.URLEncoder JavaDoc;
42 import java.util.*;
43
44 import javax.xml.transform.OutputKeys JavaDoc;
45 import javax.xml.transform.stream.StreamResult JavaDoc;
46
47 import net.sf.saxon.Configuration;
48 import net.sf.saxon.om.Item;
49 import net.sf.saxon.om.NodeInfo;
50 import net.sf.saxon.query.QueryResult;
51 import net.sf.saxon.trans.XPathException;
52 import net.sf.saxon.type.Type;
53
54 import org.webharvest.exception.VariableException;
55 import org.webharvest.runtime.variables.IVariable;
56 import org.webharvest.runtime.variables.EmptyVariable;
57 import org.webharvest.runtime.variables.ListVariable;
58 import org.webharvest.runtime.variables.NodeVariable;
59
60 /**
61  * Basic evaluation utilities
62  */

63 public class CommonUtil {
64
65     /**
66      * Contains pair of intger values
67      */

68     public static class IntPair {
69         public int x;
70         public int y;
71
72         public IntPair() {
73         }
74
75         public IntPair(int x, int y) {
76             this.x = x;
77             this.y = y;
78         }
79
80         public String JavaDoc toString() {
81             return "x = " + x + ", y = " + y;
82         }
83
84         public void defineFromString(String JavaDoc s, char separator, int maxValue) {
85             int columnIndex = s.indexOf(separator);
86             if (columnIndex == -1) {
87                 x = Integer.parseInt(s);
88                 y = x;
89             } else {
90                 if (columnIndex == 0) {
91                     x = 1;
92                     String JavaDoc s2 = s.substring(1);
93                     y = "".equals(s2) ? maxValue : Integer.parseInt(s2);
94                 } else if (columnIndex == s.length()-1) {
95                     x = Integer.parseInt( s.substring(0, s.length()-1) );
96                     y = maxValue;
97                 } else {
98                     String JavaDoc s1 = s.substring(0, columnIndex);
99                     String JavaDoc s2 = s.substring(columnIndex + 1);
100                     x = "".equals(s1) ? 1 : Integer.parseInt(s1);
101                     y = "".equals(s2) ? maxValue : Integer.parseInt(s2);
102                 }
103             }
104         }
105     }
106
107     public static String JavaDoc nvl(String JavaDoc value, String JavaDoc defaultValue) {
108         return value == null ? defaultValue : value;
109     }
110
111     public static String JavaDoc adaptFilename(String JavaDoc filePath) {
112         return filePath == null ? null : filePath.replace('\\', '/');
113     }
114
115     /**
116      * Checks if specified file path is absolute. Criteria for recogning absolute file paths is
117      * that i starts with /, \, or X: where X is some letter.
118      * @param path
119      * @return True, if specified filepath is absolute, false otherwise.
120      */

121     public static boolean isPathAbsolute(String JavaDoc path) {
122         if (path == null) {
123             return false;
124         }
125
126         path = adaptFilename(path);
127         int len = path.length();
128
129         return ( len >= 1 && path.startsWith("/") ) ||
130                ( len >= 2 && Character.isLetter(path.charAt(0)) && path.charAt(1) == ':' );
131     }
132
133     /**
134      * For the goven working path and file path returns absolute file path.
135      * @param workingPath
136      * @param filePath
137      * @return Absolute path of the second parameter according to absolute working path.
138      */

139     public static String JavaDoc getAbsoluteFilename(String JavaDoc workingPath, String JavaDoc filePath) {
140         filePath = adaptFilename(filePath);
141
142         // if file path is absolute, then return only filePath parameter
143
if (isPathAbsolute(filePath)) {
144             return filePath;
145         } else {
146             workingPath = adaptFilename(workingPath);
147             if (workingPath.endsWith("/")) {
148                 workingPath = workingPath.substring( 0, workingPath.length() - 1 );
149             }
150             return workingPath + "/" + filePath;
151         }
152     }
153     
154     /**
155      * Extracts a filename and directory from an absolute path.
156      */

157     public static String JavaDoc getDirectoryFromPath(String JavaDoc path) {
158         path = adaptFilename(path);
159         int index = path.lastIndexOf("/");
160
161         return path.substring(0, index);
162     }
163
164     /**
165      * Returns class name without packages for the specified object
166      */

167     public static String JavaDoc getClassName(Object JavaDoc o) {
168         if (o != null) {
169             String JavaDoc processorClassName = o.getClass().getName();
170             int dotIndex = processorClassName.lastIndexOf('.');
171             if (dotIndex >= 0) {
172                 processorClassName = processorClassName.substring(dotIndex+1);
173             }
174
175             return processorClassName;
176         } else {
177             return "null value";
178         }
179     }
180
181     public static String JavaDoc replicate(String JavaDoc s, int count) {
182         String JavaDoc result = "";
183         for (int i = 1; i <= count; i++) {
184             result += s;
185         }
186
187         return result;
188     }
189     
190     private static String JavaDoc encodeUrlParam(String JavaDoc value, String JavaDoc charset) throws UnsupportedEncodingException {
191         try {
192             String JavaDoc decoded = URLDecoder.decode(value, charset);
193             
194             String JavaDoc result = "";
195             for (int i = 0; i < decoded.length(); i++) {
196                 char ch = decoded.charAt(i);
197                 result += (ch == '#') ? "#" : URLEncoder.encode(String.valueOf(ch), charset);
198             }
199
200             return result;
201         } catch (IllegalArgumentException JavaDoc e) {
202             return value;
203         }
204     }
205
206     public static String JavaDoc encodeUrl(String JavaDoc url, String JavaDoc charset) {
207         int index = url.indexOf("?");
208         if (index >= 0) {
209             try {
210                 String JavaDoc result = url.substring(0, index+1);
211                 String JavaDoc paramsPart = url.substring(index+1);
212                 StringTokenizer tokenizer = new StringTokenizer(paramsPart, "&");
213                 while (tokenizer.hasMoreTokens()) {
214                     String JavaDoc definition = tokenizer.nextToken();
215                     int eqIndex = definition.indexOf("=");
216                     if (eqIndex >= 0) {
217                         String JavaDoc paramName = definition.substring(0, eqIndex);
218                         String JavaDoc paramValue = definition.substring(eqIndex + 1);
219                         result += paramName + "=" + encodeUrlParam(paramValue, charset) + "&";
220                     } else {
221                         result += encodeUrlParam(definition, charset) + "&";
222                     }
223                 }
224
225                 return result;
226             } catch (UnsupportedEncodingException e) {
227                 throw new VariableException("Charset " + charset + " is not supported!", e);
228             }
229         }
230
231         return url;
232     }
233     
234     /**
235      * Checks if specified string value represents boolean true value.
236      * @return If specified string equals (ignoring case) to 1, true or yes then
237      * true, otherwise false.
238      */

239     public static boolean isBooleanTrue(String JavaDoc value) {
240         if (value != null) {
241             return "1".equals(value) || "true".equalsIgnoreCase(value) || "yes".equalsIgnoreCase(value);
242         }
243         
244         return false;
245     }
246     
247     /**
248      * Escapes XML string - special characters: &'"<> are
249      * replaced with XML escape sequences: &amp; &apos; &quot; &lt; &gt;
250      */

251     public static String JavaDoc escapeXml(String JavaDoc s) {
252         if (s != null) {
253             StringBuffer JavaDoc result = new StringBuffer JavaDoc(s);
254             int index = 0;
255             for (int i = 0; i < s.length(); i++) {
256                 char ch = s.charAt(i);
257                 if (ch == '&') {
258                     String JavaDoc sub = s.substring(i);
259                     if ( !sub.startsWith("&amp;") &&
260                          !sub.startsWith("&apos;") &&
261                          !sub.startsWith("&gt;") &&
262                          !sub.startsWith("&lt;") &&
263                          !sub.startsWith("&quot;") ) {
264                         result.replace(index, index+1, "&amp;");
265                         index += 5;
266                     } else {
267                         index++;
268                     }
269                 } else if (ch == '\'') {
270                     result.replace(index, index+1, "&apos;");
271                     index += 6;
272                 } else if (ch == '>') {
273                     result.replace(index, index+1, "&gt;");
274                     index += 4;
275                 } else if (ch == '<') {
276                     result.replace(index, index+1, "&lt;");
277                     index += 4;
278                 } else if (ch == '\"') {
279                     result.replace(index, index+1, "&quot;");
280                     index += 6;
281                 } else {
282                     index++;
283                 }
284             }
285
286             return result.toString();
287         }
288
289         return null;
290     }
291
292     /**
293      * Serializes item after XPath or XQuery processor execution using Saxon.
294      */

295     public static String JavaDoc serializeItem(Item item, Configuration config) throws XPathException {
296         if (item instanceof NodeInfo) {
297             int type = ((NodeInfo)item).getNodeKind();
298             if (type == Type.DOCUMENT || type == Type.ELEMENT) {
299                 Properties props = new Properties();
300                 props.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
301                 props.setProperty(OutputKeys.INDENT, "yes");
302
303                 StringWriter stringWriter = new java.io.StringWriter JavaDoc();
304                 QueryResult.serialize((NodeInfo)item, new StreamResult JavaDoc(stringWriter), props, config);
305                 stringWriter.flush();
306                 return stringWriter.toString().replaceAll(" xmlns=\"http\\://www.w3.org/1999/xhtml\"", "");
307             }
308         }
309         
310         return item.getStringValue();
311     }
312     
313     public static String JavaDoc readStringFromFile(File file, String JavaDoc encoding) throws IOException {
314         if (!file.exists()) {
315             throw new IOException("File doesn't exist!");
316         }
317         
318         long fileLen = file.length();
319         if (fileLen <= 0L) {
320             if (file.exists()) {
321                 return ""; // empty file
322
}
323             return null; // all other file len problems
324
}
325         if (fileLen > Integer.MAX_VALUE) { // max String size
326
throw new IOException("File too big for loading into a String!");
327         }
328
329         FileInputStream fis = null;
330         InputStreamReader isr = null;
331         BufferedReader brin = null;
332
333         int length = (int) fileLen;
334         char[] buf = null;
335         int realSize = 0;
336         try {
337             fis = new FileInputStream(file);
338             isr = new InputStreamReader(fis, encoding);
339             brin = new BufferedReader(isr, 64 * 1024);
340             buf = new char[length];
341             int c;
342             while ((c = brin.read()) != -1) {
343                 buf[realSize] = (char) c;
344                 realSize++;
345             }
346         } finally {
347             if (brin != null) {
348                 brin.close();
349                 isr = null;
350                 fis = null;
351             }
352             if (isr != null) {
353                 isr.close();
354                 fis = null;
355             }
356             if (fis != null) {
357                 fis.close();
358             }
359         }
360         return new String JavaDoc(buf, 0, realSize);
361     }
362
363     public static byte[] readBytesFromFile(File file) throws IOException {
364         FileInputStream fileinputstream = new FileInputStream(file);
365         long l = file.length();
366
367         if (l > Integer.MAX_VALUE) {
368             throw new IOException("File too big for loading into a byte array!");
369         }
370         
371         byte byteArray[] = new byte[(int) l];
372
373         int i = 0;
374
375         for (int j = 0; (i < byteArray.length) && (j = fileinputstream.read(byteArray, i, byteArray.length - i)) >= 0; i += j);
376
377         if (i < byteArray.length) {
378             throw new IOException("Could not completely read the file " + file.getName());
379         }
380         fileinputstream.close();
381         return byteArray;
382     }
383
384     /**
385      * Checks if specified link is full URL.
386      * @param link
387      * @return True, if full URl, false otherwise.
388      */

389     public static boolean isFullUrl(String JavaDoc link) {
390         if (link == null) {
391             return false;
392         }
393         link = link.trim().toLowerCase();
394         return link.startsWith("http://") || link.startsWith("https://") || link.startsWith("file://");
395     }
396     
397     /**
398      * Calculates full URL for specified page URL and link
399      * which could be full, absolute or relative like there can
400      * be found in A or IMG tags.
401      */

402     public static String JavaDoc fullUrl(String JavaDoc pageUrl, String JavaDoc link) {
403         if ( isFullUrl(link) ) {
404             return link;
405         }
406         
407         boolean isLinkAbsolute = link.startsWith("/");
408         
409         if ( !isFullUrl(pageUrl) ) {
410             pageUrl = "http://" + pageUrl;
411         }
412         
413         int slashIndex = isLinkAbsolute ? pageUrl.indexOf("/", 8) : pageUrl.lastIndexOf("/");
414         if (slashIndex <= 8) {
415             pageUrl += "/";
416         } else {
417             pageUrl = pageUrl.substring(0, slashIndex+1);
418         }
419         
420         return isLinkAbsolute ? pageUrl + link.substring(1) : pageUrl + link;
421     }
422
423     /**
424      * Creates appropriate IVariable instance for the specified object.
425      * For colleactions and arrays ListVariable instance is returned,
426      * for null it is an EmptyVariable, and for others it is NodeVariable
427      * that wraps specified object.
428      * @param value
429      */

430     public static IVariable createVariable(Object JavaDoc value) {
431         if (value instanceof IVariable) {
432             return (IVariable) value;
433         } else if (value == null) {
434             return new EmptyVariable();
435         } else if (value instanceof Collection) {
436             Collection collection = (Collection) value;
437             return new ListVariable(new ArrayList(collection));
438         } else if (value instanceof Object JavaDoc[]) {
439             List list = Arrays.asList( (Object JavaDoc[]) value );
440             return new ListVariable(list);
441         } else {
442             return new NodeVariable(value);
443         }
444     }
445
446 }
Popular Tags