IOUtils.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. /* ========================================================================
  2. * JCommon : a free general purpose class library for the Java(tm) platform
  3. * ========================================================================
  4. *
  5. * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
  6. *
  7. * Project Info: http://www.jfree.org/jcommon/index.html
  8. *
  9. * This library is free software; you can redistribute it and/or modify it
  10. * under the terms of the GNU Lesser General Public License as published by
  11. * the Free Software Foundation; either version 2.1 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * This library is distributed in the hope that it will be useful, but
  15. * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  16. * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
  17. * License for more details.
  18. *
  19. * You should have received a copy of the GNU Lesser General Public
  20. * License along with this library; if not, write to the Free Software
  21. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
  22. * USA.
  23. *
  24. * [Java is a trademark or registered trademark of Sun Microsystems, Inc.
  25. * in the United States and other countries.]
  26. *
  27. * ------------
  28. * IOUtils.java
  29. * ------------
  30. * (C)opyright 2002-2004, by Thomas Morgner and Contributors.
  31. *
  32. * Original Author: Thomas Morgner;
  33. * Contributor(s): David Gilbert (for Object Refinery Limited);
  34. *
  35. * $Id: IOUtils.java,v 1.8 2009/01/22 08:34:58 taqua Exp $
  36. *
  37. * Changes
  38. * -------
  39. * 26-Jan-2003 : Initial version
  40. * 23-Feb-2003 : Documentation
  41. * 25-Feb-2003 : Fixed Checkstyle issues (DG);
  42. * 29-Apr-2003 : Moved to jcommon
  43. * 04-Jan-2004 : Fixed JDK 1.2.2 issues with createRelativeURL;
  44. * added support for query strings within these urls (TM);
  45. */
  46. package org.jfree.io;
  47. import java.io.File;
  48. import java.io.IOException;
  49. import java.io.InputStream;
  50. import java.io.OutputStream;
  51. import java.io.Reader;
  52. import java.io.Writer;
  53. import java.net.URL;
  54. import java.util.ArrayList;
  55. import java.util.Iterator;
  56. import java.util.List;
  57. import java.util.StringTokenizer;
  58. /**
  59. * The IOUtils provide some IO related helper methods.
  60. *
  61. * @author Thomas Morgner.
  62. */
  63. public class IOUtils {
  64. /** the singleton instance of the utility package. */
  65. private static IOUtils instance;
  66. /**
  67. * DefaultConstructor.
  68. */
  69. private IOUtils() {
  70. }
  71. /**
  72. * Gets the singleton instance of the utility package.
  73. *
  74. * @return the singleton instance.
  75. */
  76. public static IOUtils getInstance() {
  77. if (instance == null) {
  78. instance = new IOUtils();
  79. }
  80. return instance;
  81. }
  82. /**
  83. * Checks, whether the URL uses a file based protocol.
  84. *
  85. * @param url the url.
  86. * @return true, if the url is file based.
  87. */
  88. private boolean isFileStyleProtocol(final URL url) {
  89. if (url.getProtocol().equals("http")) {
  90. return true;
  91. }
  92. if (url.getProtocol().equals("https")) {
  93. return true;
  94. }
  95. if (url.getProtocol().equals("ftp")) {
  96. return true;
  97. }
  98. if (url.getProtocol().equals("file")) {
  99. return true;
  100. }
  101. if (url.getProtocol().equals("jar")) {
  102. return true;
  103. }
  104. return false;
  105. }
  106. /**
  107. * Parses the given name and returns the name elements as List of Strings.
  108. *
  109. * @param name the name, that should be parsed.
  110. * @return the parsed name.
  111. */
  112. private List parseName(final String name) {
  113. final ArrayList list = new ArrayList();
  114. final StringTokenizer strTok = new StringTokenizer(name, "/");
  115. while (strTok.hasMoreElements()) {
  116. final String s = (String) strTok.nextElement();
  117. if (s.length() != 0) {
  118. list.add(s);
  119. }
  120. }
  121. return list;
  122. }
  123. /**
  124. * Transforms the name list back into a single string, separated with "/".
  125. *
  126. * @param name the name list.
  127. * @param query the (optional) query for the URL.
  128. * @return the constructed name.
  129. */
  130. private String formatName(final List name, final String query) {
  131. final StringBuffer b = new StringBuffer();
  132. final Iterator it = name.iterator();
  133. while (it.hasNext()) {
  134. b.append(it.next());
  135. if (it.hasNext()) {
  136. b.append("/");
  137. }
  138. }
  139. if (query != null) {
  140. b.append('?');
  141. b.append(query);
  142. }
  143. return b.toString();
  144. }
  145. /**
  146. * Compares both name lists, and returns the last common index shared
  147. * between the two lists.
  148. *
  149. * @param baseName the name created using the base url.
  150. * @param urlName the target url name.
  151. * @return the number of shared elements.
  152. */
  153. private int startsWithUntil(final List baseName, final List urlName) {
  154. final int minIdx = Math.min(urlName.size(), baseName.size());
  155. for (int i = 0; i < minIdx; i++) {
  156. final String baseToken = (String) baseName.get(i);
  157. final String urlToken = (String) urlName.get(i);
  158. if (!baseToken.equals(urlToken)) {
  159. return i;
  160. }
  161. }
  162. return minIdx;
  163. }
  164. /**
  165. * Checks, whether the URL points to the same service. A service is equal
  166. * if the protocol, host and port are equal.
  167. *
  168. * @param url a url
  169. * @param baseUrl an other url, that should be compared.
  170. * @return true, if the urls point to the same host and port and use the
  171. * same protocol, false otherwise.
  172. */
  173. private boolean isSameService(final URL url, final URL baseUrl) {
  174. if (!url.getProtocol().equals(baseUrl.getProtocol())) {
  175. return false;
  176. }
  177. if (!url.getHost().equals(baseUrl.getHost())) {
  178. return false;
  179. }
  180. if (url.getPort() != baseUrl.getPort()) {
  181. return false;
  182. }
  183. return true;
  184. }
  185. /**
  186. * Creates a relative url by stripping the common parts of the the url.
  187. *
  188. * @param url the to be stripped url
  189. * @param baseURL the base url, to which the <code>url</code> is relative
  190. * to.
  191. * @return the relative url, or the url unchanged, if there is no relation
  192. * beween both URLs.
  193. */
  194. public String createRelativeURL(final URL url, final URL baseURL) {
  195. if (url == null) {
  196. throw new NullPointerException("content url must not be null.");
  197. }
  198. if (baseURL == null) {
  199. throw new NullPointerException("baseURL must not be null.");
  200. }
  201. if (isFileStyleProtocol(url) && isSameService(url, baseURL)) {
  202. // If the URL contains a query, ignore that URL; do not
  203. // attemp to modify it...
  204. final List urlName = parseName(getPath(url));
  205. final List baseName = parseName(getPath(baseURL));
  206. final String query = getQuery(url);
  207. if (!isPath(baseURL)) {
  208. baseName.remove(baseName.size() - 1);
  209. }
  210. // if both urls are identical, then return the plain file name...
  211. if (url.equals(baseURL)) {
  212. return (String) urlName.get(urlName.size() - 1);
  213. }
  214. int commonIndex = startsWithUntil(urlName, baseName);
  215. if (commonIndex == 0) {
  216. return url.toExternalForm();
  217. }
  218. if (commonIndex == urlName.size()) {
  219. // correct the base index if there is some weird mapping
  220. // detected,
  221. // fi. the file url is fully included in the base url:
  222. //
  223. // base: /file/test/funnybase
  224. // file: /file/test
  225. //
  226. // this could be a valid configuration whereever virtual
  227. // mappings are allowed.
  228. commonIndex -= 1;
  229. }
  230. final ArrayList retval = new ArrayList();
  231. if (baseName.size() >= urlName.size()) {
  232. final int levels = baseName.size() - commonIndex;
  233. for (int i = 0; i < levels; i++) {
  234. retval.add("..");
  235. }
  236. }
  237. retval.addAll(urlName.subList(commonIndex, urlName.size()));
  238. return formatName(retval, query);
  239. }
  240. return url.toExternalForm();
  241. }
  242. /**
  243. * Returns <code>true</code> if the URL represents a path, and
  244. * <code>false</code> otherwise.
  245. *
  246. * @param baseURL the URL.
  247. *
  248. * @return A boolean.
  249. */
  250. private boolean isPath(final URL baseURL) {
  251. if (getPath(baseURL).endsWith("/")) {
  252. return true;
  253. }
  254. else if (baseURL.getProtocol().equals("file")) {
  255. final File f = new File(getPath(baseURL));
  256. try {
  257. if (f.isDirectory()) {
  258. return true;
  259. }
  260. }
  261. catch (SecurityException se) {
  262. // ignored ...
  263. }
  264. }
  265. return false;
  266. }
  267. /**
  268. * Implements the JDK 1.3 method URL.getPath(). The path is defined
  269. * as URL.getFile() minus the (optional) query.
  270. *
  271. * @param url the URL
  272. * @return the path
  273. */
  274. private String getQuery (final URL url) {
  275. final String file = url.getFile();
  276. final int queryIndex = file.indexOf('?');
  277. if (queryIndex == -1) {
  278. return null;
  279. }
  280. return file.substring(queryIndex + 1);
  281. }
  282. /**
  283. * Implements the JDK 1.3 method URL.getPath(). The path is defined
  284. * as URL.getFile() minus the (optional) query.
  285. *
  286. * @param url the URL
  287. * @return the path
  288. */
  289. private String getPath (final URL url) {
  290. final String file = url.getFile();
  291. final int queryIndex = file.indexOf('?');
  292. if (queryIndex == -1) {
  293. return file;
  294. }
  295. return file.substring(0, queryIndex);
  296. }
  297. /**
  298. * Copies the InputStream into the OutputStream, until the end of the stream
  299. * has been reached. This method uses a buffer of 4096 kbyte.
  300. *
  301. * @param in the inputstream from which to read.
  302. * @param out the outputstream where the data is written to.
  303. * @throws IOException if a IOError occurs.
  304. */
  305. public void copyStreams(final InputStream in, final OutputStream out)
  306. throws IOException {
  307. copyStreams(in, out, 4096);
  308. }
  309. /**
  310. * Copies the InputStream into the OutputStream, until the end of the stream
  311. * has been reached.
  312. *
  313. * @param in the inputstream from which to read.
  314. * @param out the outputstream where the data is written to.
  315. * @param buffersize the buffer size.
  316. * @throws IOException if a IOError occurs.
  317. */
  318. public void copyStreams(final InputStream in, final OutputStream out,
  319. final int buffersize) throws IOException {
  320. // create a 4kbyte buffer to read the file
  321. final byte[] bytes = new byte[buffersize];
  322. // the input stream does not supply accurate available() data
  323. // the zip entry does not know the size of the data
  324. int bytesRead = in.read(bytes);
  325. while (bytesRead > -1) {
  326. out.write(bytes, 0, bytesRead);
  327. bytesRead = in.read(bytes);
  328. }
  329. }
  330. /**
  331. * Copies the contents of the Reader into the Writer, until the end of the
  332. * stream has been reached. This method uses a buffer of 4096 kbyte.
  333. *
  334. * @param in the reader from which to read.
  335. * @param out the writer where the data is written to.
  336. * @throws IOException if a IOError occurs.
  337. */
  338. public void copyWriter(final Reader in, final Writer out)
  339. throws IOException {
  340. copyWriter(in, out, 4096);
  341. }
  342. /**
  343. * Copies the contents of the Reader into the Writer, until the end of the
  344. * stream has been reached.
  345. *
  346. * @param in the reader from which to read.
  347. * @param out the writer where the data is written to.
  348. * @param buffersize the buffer size.
  349. *
  350. * @throws IOException if a IOError occurs.
  351. */
  352. public void copyWriter(final Reader in, final Writer out,
  353. final int buffersize)
  354. throws IOException {
  355. // create a 4kbyte buffer to read the file
  356. final char[] bytes = new char[buffersize];
  357. // the input stream does not supply accurate available() data
  358. // the zip entry does not know the size of the data
  359. int bytesRead = in.read(bytes);
  360. while (bytesRead > -1) {
  361. out.write(bytes, 0, bytesRead);
  362. bytesRead = in.read(bytes);
  363. }
  364. }
  365. /**
  366. * Extracts the file name from the URL.
  367. *
  368. * @param url the url.
  369. * @return the extracted filename.
  370. */
  371. public String getFileName(final URL url) {
  372. final String file = getPath(url);
  373. final int last = file.lastIndexOf("/");
  374. if (last < 0) {
  375. return file;
  376. }
  377. return file.substring(last + 1);
  378. }
  379. /**
  380. * Removes the file extension from the given file name.
  381. *
  382. * @param file the file name.
  383. * @return the file name without the file extension.
  384. */
  385. public String stripFileExtension(final String file) {
  386. final int idx = file.lastIndexOf(".");
  387. // handles unix hidden files and files without an extension.
  388. if (idx < 1) {
  389. return file;
  390. }
  391. return file.substring(0, idx);
  392. }
  393. /**
  394. * Returns the file extension of the given file name.
  395. * The returned value will contain the dot.
  396. *
  397. * @param file the file name.
  398. * @return the file extension.
  399. */
  400. public String getFileExtension(final String file) {
  401. final int idx = file.lastIndexOf(".");
  402. // handles unix hidden files and files without an extension.
  403. if (idx < 1) {
  404. return "";
  405. }
  406. return file.substring(idx);
  407. }
  408. /**
  409. * Checks, whether the child directory is a subdirectory of the base
  410. * directory.
  411. *
  412. * @param base the base directory.
  413. * @param child the suspected child directory.
  414. * @return true, if the child is a subdirectory of the base directory.
  415. * @throws IOException if an IOError occured during the test.
  416. */
  417. public boolean isSubDirectory(File base, File child)
  418. throws IOException {
  419. base = base.getCanonicalFile();
  420. child = child.getCanonicalFile();
  421. File parentFile = child;
  422. while (parentFile != null) {
  423. if (base.equals(parentFile)) {
  424. return true;
  425. }
  426. parentFile = parentFile.getParentFile();
  427. }
  428. return false;
  429. }
  430. }