001: /*
002: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
003: *
004: * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
005: *
006: * The contents of this file are subject to the terms of either the GNU
007: * General Public License Version 2 only ("GPL") or the Common
008: * Development and Distribution License("CDDL") (collectively, the
009: * "License"). You may not use this file except in compliance with the
010: * License. You can obtain a copy of the License at
011: * http://www.netbeans.org/cddl-gplv2.html
012: * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
013: * specific language governing permissions and limitations under the
014: * License. When distributing the software, include this License Header
015: * Notice in each file and include the License file at
016: * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
017: * particular file as subject to the "Classpath" exception as provided
018: * by Sun in the GPL Version 2 section of the License file that
019: * accompanied this code. If applicable, add the following below the
020: * License Header, with the fields enclosed by brackets [] replaced by
021: * your own identifying information:
022: * "Portions Copyrighted [year] [name of copyright owner]"
023: *
024: * Contributor(s):
025: *
026: * The Original Software is NetBeans. The Initial Developer of the Original
027: * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
028: * Microsystems, Inc. All Rights Reserved.
029: *
030: * If you wish your version of this file to be governed by only the CDDL
031: * or only the GPL Version 2, indicate your decision by adding
032: * "[Contributor] elects to include this software in this distribution
033: * under the [CDDL or GPL Version 2] license." If you do not indicate a
034: * single choice of license, a recipient has the option to distribute
035: * your version of this file under either the CDDL, the GPL Version 2 or
036: * to extend the choice of license to its licensees as provided above.
037: * However, if you add GPL Version 2 code and therefore, elected the GPL
038: * Version 2 license, then the option applies only if the new code is
039: * made subject to such option by the copyright holder.
040: */
041:
042: package org.netbeans.lib.collab.util;
043:
044: import java.util.*;
045: import java.net.*;
046: import java.io.*;
047: import java.nio.channels.FileChannel;
048:
049: /**
050: *
051: */
052: public class FileUtility {
053:
054: /**
055: * Thread object to save files in separate thread
056: */
057: static class SaveStringRunnable implements Runnable {
058: private String s;
059: private File f = null;
060:
061: public SaveStringRunnable(File f, String s) {
062: this .s = s;
063: this .f = f;
064: }
065:
066: public void run() {
067: FileUtility.writeString(f, s);
068: }
069: }
070:
071: /**
072: * Writes a string to a txt file given a File Object
073: * File is written using Buffered Writer
074: * @param java.io.File file, String s
075: */
076: static public void writeString(java.io.File file, String s) {
077: if (file == null)
078: return;
079: try {
080: //FileWriter fw = new FileWriter(file);
081: BufferedWriter out = new BufferedWriter(
082: new FileWriter(file));
083: out.write(s);
084: out.close();
085: //fw.close();
086: } catch (Exception e) {
087: System.out.println("writeString:" + e);
088: }
089: }
090:
091: /**
092: * Saves a String to a txt file given String filename
093: * if Thread Worker paramerter is not null, string is saved in other thread
094: * @param String path, String s, Worker w
095: */
096: final static public void save(String path, String s, Worker w) {
097: save(new File(path), s, w);
098: }
099:
100: /**
101: * Saves a String to a txt file given a File object
102: * if Thread Worker paramerter is not null, string is saved in other thread
103: * @param java.io.File file, String s, Worker w
104: */
105: static public void save(java.io.File file, String s, Worker w) {
106: if (w != null) {
107: w.addRunnable(new SaveStringRunnable(file, s));
108: //Thread t = new Thread(new SaveStringRunnable(file, s));
109: //t.start();
110: } else {
111: writeString(file, s);
112: }
113: }
114:
115: /**
116: * writes/appends the given array of bytes to a file.
117: * @param java.io.File file, byte[] b, boolean append
118: */
119: static public void writeByte(java.io.File file, byte[] b,
120: boolean append) {
121: if (file == null)
122: return;
123: try {
124: FileOutputStream w = new FileOutputStream(file
125: .getAbsolutePath(), append);
126: w.write(b);
127: w.close();
128: } catch (Exception e) {
129: System.out
130: .println("FileUtility.writeByte(): Exception thrown: "
131: + e);
132: }
133: }
134:
135: /**
136: * saves an array of bytes to a given File object
137: * @param java.io.File file, byte[] b
138: */
139: static private void writeByte(java.io.File file, byte[] b) {
140: writeByte(file, b, false);
141: }
142:
143: /**
144: * writes/appends the given array of bytes to a file.
145: * @param String path, byte[] b, boolean append
146: */
147: static public void writeByte(String path, byte[] b, boolean append) {
148: writeByte(new File(path), b, append);
149: }
150:
151: /**
152: * Saves an array of bytes to file given a String path
153: * @param String path, byte[] b
154: */
155: final static public void save(String path, byte[] b) {
156: save(new File(path), b);
157: }
158:
159: /**
160: * Saves an array of bytes to file given a File Object
161: * @param java.io.File file, byte[] b
162: */
163: final static public void save(java.io.File file, byte[] b) {
164: writeByte(file, b);
165: }
166:
167: /**
168: * Reads the file given the path of the file
169: * @param java.lang.String path
170: * @returns byte[]
171: */
172: final static public byte[] readByte(String path) {
173: try {
174: File f = new File(path);
175: if (!f.exists())
176: return null;
177: byte[] b = new byte[(int) f.length()];
178: FileInputStream is = new FileInputStream(f);
179: int len = is.read(b);
180: is.close();
181: return b;
182: } catch (FileNotFoundException e) {
183: System.out
184: .println("FileUtility.readByte(): FileNotFoundException thrown: "
185: + e);
186: } catch (IOException e) {
187: System.out
188: .println("FileUtility.readByte(): IOException thrown: "
189: + e);
190: }
191: return null;
192: }
193:
194: public final static class ReplaceEntry implements Comparable {
195: private String key;
196: private String value;
197:
198: public ReplaceEntry(String key, String value) {
199: this .key = key;
200: this .value = value;
201: }
202:
203: private boolean isEqual(String a, String b) {
204: return (null == a && null == b)
205: || (null != a && a.equals(b));
206: }
207:
208: public boolean equals(Object obj) {
209: return null != obj && (obj instanceof ReplaceEntry)
210: && isEqual(key, ((ReplaceEntry) obj).key);
211: }
212:
213: public int compareTo(Object other) {
214: if (!(other instanceof ReplaceEntry)) {
215: throw new IllegalArgumentException(
216: "compareTo with unknown object : "
217: + other.getClass());
218: }
219: ReplaceEntry entry = (ReplaceEntry) other;
220: // null checking not really required.
221: if (null == key && null == entry.key) {
222: return 0;
223: }
224: if (null == key) {
225: return 1;
226: }
227: if (null == entry.key) {
228: return -1;
229: }
230: // invert it - so longer comes before shorter.
231: return -key.compareTo(entry.key);
232: }
233:
234: public String getKey() {
235: return key;
236: }
237:
238: public String getValue() {
239: return value;
240: }
241: };
242:
243: /*
244: * does a set of global substitutions in a file
245: * @param infile input (template) file
246: * @param outfile resulting file to be created. It shoud be empty.
247: * @param substitutions substitusion map. keys are macros, and values
248: * are the strings to use to replace the macros
249: * @param match the substitution is done only if the line contains this
250: * String. Pass null to do the substitutions on all lines.
251: * @param encoding character encoding to use to read the input file
252: * and generate the output file.
253: */
254: final public static void findReplace(File infile, File outfile,
255: Map substitutions, String match, String encoding)
256: throws IOException {
257: boolean isSameFile = infile.equals(outfile);
258: File tmpfile = outfile;
259: if (isSameFile) {
260: tmpfile = new File(outfile.getAbsolutePath() + ".tmp");
261: }
262:
263: FileInputStream fis = new FileInputStream(infile);
264: BufferedReader in = new BufferedReader(new InputStreamReader(
265: fis, encoding));
266: FileOutputStream fos = new FileOutputStream(tmpfile);
267: BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
268: fos, encoding));
269: PrintWriter out = new PrintWriter(bw);
270:
271: // We need to order the substitutions map as a list such that
272: // longer matches are tested before shorter matches.
273: List list = new ArrayList();
274: for (Iterator i = substitutions.entrySet().iterator(); i
275: .hasNext();) {
276: Map.Entry e = (Map.Entry) i.next();
277: list.add(new ReplaceEntry((String) e.getKey(), (String) e
278: .getValue()));
279: }
280: Collections.sort(list);
281:
282: for (;;) {
283: String line = in.readLine();
284: //System.out.println("DEBUG:: read line: " + line);
285: if (line == null)
286: break;
287:
288: String replaced = line;
289: if ((match == null)
290: || (match != null && line.indexOf(match) >= 0)) {
291: Iterator iter = list.iterator();
292: while (iter.hasNext()) {
293: ReplaceEntry entry = (ReplaceEntry) iter.next();
294: replaced = StringUtility.substitute(replaced, entry
295: .getKey(), entry.getValue());
296: }
297: }
298: //System.out.println("DEBUG:: replaced: " + replaced);
299: out.println(replaced);
300: }
301:
302: in.close();
303: out.flush();
304: out.close();
305:
306: if (isSameFile) {
307: boolean rc = tmpfile.renameTo(outfile);
308: //System.out.println("DEBUG:: renamed: " + rc);
309: }
310: }
311:
312: /**
313: * set the permissions on platform where it is possible
314: * @param file file on which to set permission
315: * @param mode unix-style numerical file permission mode. Example
316: * 0644, 0600, 0755, etc....
317: */
318: final public static boolean setFilePermissions(File f, String mode) {
319: try {
320: if (PlatformUtil.isUnix() && f.exists()) {
321: String[] args = { "/bin/chmod", mode,
322: f.getAbsolutePath() };
323: Runtime.getRuntime().exec(args);
324: }
325: return true;
326: } catch (IOException e) {
327: return false;
328: }
329: }
330:
331: // public static void main(String[] args)
332: // {
333: // try {
334: // java.util.HashMap map = new java.util.HashMap();
335: // map.put("a", "z");
336: // findReplace(new File(args[0]), new File(args[1]), map, null, "UTF-8");
337: // } catch (Exception e) {
338: // e.printStackTrace();
339: // }
340: // }
341:
342: /**
343: * Copies the src file to dest file.
344: * @return true if the copy was successful
345: */
346: public static boolean copyFile(File src, File dest) {
347: if (!src.exists() || !src.isFile())
348: return false;
349: try {
350: FileChannel srcChannel = (new FileInputStream(src))
351: .getChannel();
352: FileChannel destChannel = (new FileOutputStream(dest))
353: .getChannel();
354: destChannel.transferFrom(srcChannel, 0, srcChannel.size());
355: srcChannel.close();
356: destChannel.close();
357: return true;
358: } catch (Exception e) {
359: e.printStackTrace();
360: return false;
361: }
362: }
363:
364: /**
365: * Creates a new non existing file based on the name parameter. The new file name will
366: * be {oldfilename}-i where the value of i will start from 0 till a name is found which
367: * does not already exists. The ext of the old file will however be preserved.
368: */
369: public static File getNewFile(File dir, String name) {
370: File f = new File(dir, name);
371: int extIndex = name.lastIndexOf('.');
372: String ext = "";
373: if (extIndex != -1) {
374: ext = name.substring(extIndex);
375: name = name.substring(0, extIndex);
376: }
377: int i = 0;
378: while (f.exists()) {
379: f = new File(dir, name + "-" + i++ + ext);
380: }
381: return f;
382: }
383:
384: public static boolean deleteDirectory(File dir) {
385: File[] list = dir.listFiles();
386: if (null != list) {
387: int count = 0;
388: while (count < list.length) {
389: if (!deleteDirectory(list[count])) {
390: return false;
391: }
392: count++;
393: }
394: }
395: return dir.delete();
396: }
397:
398: public static String emptyDirectory(String dir) {
399: File root = new File(dir);
400: if (!root.exists())
401: return dir;
402: File[] subs = root.listFiles();
403: if (null == subs)
404: return null;
405: int count = 0;
406: while (count < subs.length) {
407: boolean res = deltree(subs[count]);
408: if (!res) {
409: return null;
410: }
411: count++;
412: }
413: return dir;
414: }
415:
416: private static boolean deltree(File file) {
417: if (file.isFile())
418: return file.delete();
419: if (!file.isDirectory())
420: return file.delete();
421: // return false;
422:
423: File[] subs = file.listFiles();
424: if (null == subs)
425: return false;
426:
427: int count = 0;
428: while (count < subs.length) {
429: boolean res = deltree(subs[count]);
430: if (!res)
431: return res;
432: count++;
433: }
434: return file.delete();
435: }
436:
437: public static boolean mkdirs(File file) {
438: if (file.exists() || file.mkdir()) {
439: return true;
440: }
441:
442: File canonFile = null;
443: try {
444: canonFile = file.getCanonicalFile();
445: } catch (IOException e) {
446: return false;
447: }
448:
449: File parent = canonFile.getParentFile();
450: return (parent != null && mkdirs(parent) && (canonFile.mkdir() || canonFile
451: .exists()));
452: }
453: }
|