Source Code Cross Referenced for IOUtil.java in  » Development » rapla » org » rapla » components » util » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Development » rapla » org.rapla.components.util 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*--------------------------------------------------------------------------*
002:         | Copyright (C) 2006 Christopher Kohlhaas                                  |
003:         |                                                                          |
004:         | This program is free software; you can redistribute it and/or modify     |
005:         | it under the terms of the GNU General Public License as published by the |
006:         | Free Software Foundation. A copy of the license has been included with   |
007:         | these distribution in the COPYING file, if not go to www.fsf.org         |
008:         |                                                                          |
009:         | As a special exception, you are granted the permissions to link this     |
010:         | program with every library, which license fulfills the Open Source       |
011:         | Definition as published by the Open Source Initiative (OSI).             |
012:         *--------------------------------------------------------------------------*/
013:        package org.rapla.components.util;
014:
015:        import java.io.BufferedInputStream;
016:        import java.io.ByteArrayOutputStream;
017:        import java.io.File;
018:        import java.io.FileInputStream;
019:        import java.io.FileOutputStream;
020:        import java.io.IOException;
021:        import java.io.InputStream;
022:        import java.io.OutputStream;
023:        import java.io.PrintWriter;
024:        import java.io.UnsupportedEncodingException;
025:        import java.lang.reflect.InvocationTargetException;
026:        import java.lang.reflect.Method;
027:        import java.net.MalformedURLException;
028:        import java.net.URL;
029:        import java.net.URLDecoder;
030:        import java.net.URLEncoder;
031:        import java.util.ArrayList;
032:        import java.util.StringTokenizer;
033:
034:        import org.apache.avalon.framework.CascadingException;
035:
036:        /** Some IOHelper methods. */
037:        abstract public class IOUtil {
038:
039:            /** returns the path of the url without the last path component */
040:            public static URL getBase(URL url) {
041:                try {
042:                    String file = url.getPath();
043:                    String separator = "/";
044:                    if (url.getProtocol().equals("file")
045:                            && file.indexOf(File.separator) > 0) {
046:                        separator = File.separator;
047:                    }
048:                    int index = file.lastIndexOf(separator);
049:                    String dir = (index < 0) ? file : file.substring(0,
050:                            index + 1);
051:                    return new URL(url.getProtocol(), url.getHost(), url
052:                            .getPort(), dir);
053:                } catch (MalformedURLException e) {
054:                    // This should not happen
055:                    e.printStackTrace();
056:                    throw new RuntimeException(
057:                            "Unknown error while getting the base of the url!");
058:                } // end of try-catch
059:            }
060:
061:            /** reads the content form an url into a ByteArray*/
062:            public static byte[] readBytes(URL url) throws IOException {
063:                InputStream in = null;
064:                ByteArrayOutputStream out = new ByteArrayOutputStream();
065:                try {
066:                    in = url.openStream();
067:                    byte[] buffer = new byte[1024];
068:                    int count = 0;
069:                    do {
070:                        out.write(buffer, 0, count);
071:                        count = in.read(buffer, 0, buffer.length);
072:                    } while (count != -1);
073:                    return out.toByteArray();
074:                } finally {
075:                    if (in != null) {
076:                        in.close();
077:                    } // end of if ()
078:                }
079:            }
080:
081:            /** same as {@link URLDecoder#decode}.
082:             *   But calls the deprecated method under 1.3.
083:             */
084:            public static String decode(String s, String enc)
085:                    throws UnsupportedEncodingException {
086:                return callEncodeDecode(URLDecoder.class, "decode", s, enc);
087:            }
088:
089:            /** same as {@link URLEncoder#encode}.
090:             * But calls the deprecated method under 1.3.
091:             */
092:            public static String encode(String s, String enc)
093:                    throws UnsupportedEncodingException {
094:                return callEncodeDecode(URLEncoder.class, "encode", s, enc);
095:            }
096:
097:            private static String callEncodeDecode(Class clazz,
098:                    String methodName, String s, String enc)
099:                    throws UnsupportedEncodingException {
100:                Assert.notNull(s);
101:                Assert.notNull(enc);
102:                try {
103:                    Method method = clazz.getMethod(methodName, new Class[] {
104:                            String.class, String.class });
105:                    return (String) method
106:                            .invoke(null, new Object[] { s, enc });
107:                } catch (NoSuchMethodException ex) {
108:                    try {
109:                        Method method = URLDecoder.class.getMethod(methodName,
110:                                new Class[] { String.class });
111:                        return (String) method.invoke(null, new Object[] { s });
112:                    } catch (Exception ex2) {
113:                        ex2.printStackTrace();
114:                        throw new IllegalStateException("Should not happen"
115:                                + ex2.getMessage());
116:                    }
117:                } catch (InvocationTargetException ex) {
118:                    throw (UnsupportedEncodingException) ex
119:                            .getTargetException();
120:                } catch (IllegalAccessException ex) {
121:                    ex.printStackTrace();
122:                    throw new IllegalStateException("Should not happen"
123:                            + ex.getMessage());
124:                }
125:            }
126:
127:            /**  returns a BufferedInputStream from the url.
128:                 If the url-protocol is "file" no url connection will
129:                 be opened.
130:             */
131:            public static InputStream getInputStream(URL url)
132:                    throws IOException {
133:                if (url.getProtocol().equals("file")) {
134:                    String path = decode(url.getPath(), "UTF-8");
135:                    return new BufferedInputStream(new FileInputStream(path));
136:                } else {
137:                    return new BufferedInputStream(url.openStream());
138:                } // end of else
139:            }
140:
141:            public static File getFileFrom(URL url) throws IOException {
142:                String path = decode(url.getPath(), "UTF-8");
143:                return new File(path);
144:            }
145:
146:            /** copies a file.
147:             * @param srcPath the source-path. Thats the path of the file that should be copied.
148:             * @param destPath the destination-path
149:             */
150:
151:            public static void copy(String srcPath, String destPath)
152:                    throws IOException {
153:                copy(srcPath, destPath, false);
154:            }
155:
156:            /** copies a file.
157:             * @param srcPath the source-path. Thats the path of the file that should be copied.
158:             * @param destPath the destination-path
159:             */
160:            public static void copy(String srcPath, String destPath,
161:                    boolean onlyOverwriteIfNewer) throws IOException {
162:                copy(new File(srcPath), new File(destPath),
163:                        onlyOverwriteIfNewer);
164:            }
165:
166:            /** copies a file.
167:             */
168:            public static void copy(File srcFile, File destFile,
169:                    boolean onlyOverwriteIfNewer) throws IOException {
170:                if (!srcFile.exists()) {
171:                    throw new IOException(srcFile.getPath()
172:                            + " doesn't exist!!");
173:                }
174:                if (destFile.exists()
175:                        && destFile.lastModified() >= srcFile.lastModified()
176:                        && onlyOverwriteIfNewer) {
177:                    return;
178:                }
179:                FileInputStream in = null;
180:                FileOutputStream out = null;
181:                try {
182:                    in = new FileInputStream(srcFile);
183:                    out = new FileOutputStream(destFile);
184:                    copyStreams(in, out);
185:                } finally {
186:                    if (in != null)
187:                        in.close();
188:
189:                    if (out != null)
190:                        out.close();
191:                }
192:            }
193:
194:            /** copies the contents of the input stream to the output stream.
195:             * @param in
196:             * @param out
197:             * @throws IOException
198:             */
199:            public static void copyStreams(InputStream in, OutputStream out)
200:                    throws IOException {
201:                byte[] buf = new byte[32000];
202:                int n = 0;
203:                while (n != -1) {
204:                    out.write(buf, 0, n);
205:                    n = in.read(buf, 0, buf.length);
206:                }
207:            }
208:
209:            /** returns the relative path of file to base.
210:             * @throws IOException if position of file is not relative  to base
211:             */
212:            public static String getRelativePath(File base, File file)
213:                    throws IOException {
214:                String filePath = file.getAbsoluteFile().getCanonicalPath();
215:                String basePath = base.getAbsoluteFile().getCanonicalPath();
216:                int start = filePath.indexOf(basePath);
217:                if (start != 0)
218:                    throw new IOException(basePath + " not ancestor of "
219:                            + filePath);
220:                return filePath.substring(basePath.length());
221:            }
222:
223:            /** returns the relative path of file to base.
224:             * same as {@link #getRelativePath(File, File)} but replaces windows-plattform-specific
225:             * file separator <code>\</code> with <code>/</code>
226:             * @throws IOException if position of file is not relative  to base
227:             */
228:            public static String getRelativeURL(File base, File file)
229:                    throws IOException {
230:                StringBuffer result = new StringBuffer(getRelativePath(base,
231:                        file));
232:                for (int i = 0; i < result.length(); i++) {
233:                    if (result.charAt(i) == '\\')
234:                        result.setCharAt(i, '/');
235:                }
236:                return result.toString();
237:            }
238:
239:            public static File[] getJarFiles(String baseDir, String dirList)
240:                    throws IOException {
241:                ArrayList completeList = new ArrayList();
242:                StringTokenizer tokenizer = new StringTokenizer(dirList, ",");
243:                while (tokenizer.hasMoreTokens()) {
244:                    File jarDir = new File(baseDir, tokenizer.nextToken());
245:                    if (jarDir.exists() && jarDir.isDirectory()) {
246:                        File[] jarFiles = jarDir.listFiles();
247:                        for (int i = 0; i < jarFiles.length; i++) {
248:                            if (jarFiles[i].getAbsolutePath().endsWith(".jar")) {
249:                                completeList
250:                                        .add(jarFiles[i].getCanonicalFile());
251:                            }
252:                        }
253:                    }
254:                }
255:                return (File[]) completeList.toArray(new File[] {});
256:            }
257:
258:            public static String getStackTraceAsString(Throwable ex) {
259:                ByteArrayOutputStream bytes = new ByteArrayOutputStream();
260:                PrintWriter writer = new PrintWriter(bytes, true);
261:                writer.println("<h2>" + ex.getMessage() + "</h2><br/>");
262:                ex.printStackTrace(writer);
263:                while (ex instanceof  CascadingException) {
264:                    ex = ((CascadingException) ex).getCause();
265:                    if (ex != null) {
266:                        writer.println("<br/><h2>Caused by: " + ex.getMessage()
267:                                + "</h2><br/>");
268:                        ex.printStackTrace(writer);
269:                    } else {
270:                        break;
271:                    }
272:                }
273:                return bytes.toString();
274:            }
275:
276:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.