|
From: <chr...@us...> - 2009-04-29 22:41:42
|
Revision: 5367
http://jnode.svn.sourceforge.net/jnode/?rev=5367&view=rev
Author: chrisboertien
Date: 2009-04-29 22:41:40 +0000 (Wed, 29 Apr 2009)
Log Message:
-----------
du command implementation
Submitted-by: Alexander Kerner
Signed-off-by: chrisboertien <chr...@gm...>
Modified Paths:
--------------
trunk/cli/descriptors/org.jnode.command.file.xml
trunk/cli/descriptors/org.jnode.command.util.xml
trunk/cli/src/commands/org/jnode/command/file/FindCommand.java
trunk/cli/src/commands/org/jnode/command/system/RunCommand.java
trunk/cli/src/commands/org/jnode/command/util/AbstractDirectoryWalker.java
Added Paths:
-----------
trunk/cli/src/commands/org/jnode/command/file/DuCommand.java
trunk/cli/src/commands/org/jnode/command/util/IOUtils.java
Removed Paths:
-------------
trunk/coreutils/src/commands/org/jnode/command/util/IOUtils.java
Modified: trunk/cli/descriptors/org.jnode.command.file.xml
===================================================================
--- trunk/cli/descriptors/org.jnode.command.file.xml 2009-04-29 22:40:55 UTC (rev 5366)
+++ trunk/cli/descriptors/org.jnode.command.file.xml 2009-04-29 22:41:40 UTC (rev 5367)
@@ -29,6 +29,7 @@
<alias name="del" class="org.jnode.command.file.DeleteCommand"/>
<alias name="df" class="org.jnode.command.file.DFCommand"/>
<alias name="dir" class="org.jnode.command.file.DirCommand"/>
+ <alias name="du" class="org.jnode.command.file.DuCommand"/>
<alias name="find" class="org.jnode.command.file.FindCommand"/>
<alias name="grep" class="org.jnode.command.file.GrepCommand"/>
<alias name="head" class="org.jnode.command.file.HeadCommand"/>
@@ -98,10 +99,22 @@
<empty description="list the current directory"/>
<argument argLabel="path" description="list a file or directory"/>
</syntax>
+ <syntax alias="du">
+ <sequence description="print file sizes">
+ <repeat minCount="0">
+ <argument argLabel="directory" description="directory to start printing sizes recursively"/>
+ </repeat>
+ <optionSet>
+ <option argLabel="sum" shortName="s" longName="summarize"/>
+ <option argLabel="all" shortName="a" longName="all"/>
+ <option argLabel="human-readable" shortName="h" longName="human-readable"/>
+ </optionSet>
+ </sequence>
+ </syntax>
<syntax alias="find">
<sequence description="find files or directories">
<repeat minCount="0">
- <argument argLabel="directory" description="directory to start searching from"/>
+ <argument argLabel="directory"/>
</repeat>
<optionSet>
<option argLabel="type" shortName="t" longName="type"/>
Modified: trunk/cli/descriptors/org.jnode.command.util.xml
===================================================================
--- trunk/cli/descriptors/org.jnode.command.util.xml 2009-04-29 22:40:55 UTC (rev 5366)
+++ trunk/cli/descriptors/org.jnode.command.util.xml 2009-04-29 22:41:40 UTC (rev 5367)
@@ -6,7 +6,11 @@
version="@VERSION@"
provider-name="@PROVIDER@"
license-name="lgpl">
-
+
+ <requires>
+ <import plugin="org.jnode.shell"/>
+ </requires>
+
<runtime>
<library name="jnode-cli.jar">
<export name="org.jnode.command.util.*" />
Added: trunk/cli/src/commands/org/jnode/command/file/DuCommand.java
===================================================================
--- trunk/cli/src/commands/org/jnode/command/file/DuCommand.java (rev 0)
+++ trunk/cli/src/commands/org/jnode/command/file/DuCommand.java 2009-04-29 22:41:40 UTC (rev 5367)
@@ -0,0 +1,196 @@
+/*
+ * $Id: CdCommand.java 4975 2009-02-02 08:30:52Z lsantha $
+ *
+ * Copyright (C) 2003-2009 JNode.org
+ *
+ * This library is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as published
+ * by the Free Software Foundation; either version 2.1 of the License, or
+ * (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
+ * License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this library; If not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+package org.jnode.command.file;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.TreeMap;
+import java.util.Map.Entry;
+
+import org.jnode.command.util.AbstractDirectoryWalker;
+import org.jnode.shell.AbstractCommand;
+import org.jnode.shell.syntax.Argument;
+import org.jnode.shell.syntax.FileArgument;
+import org.jnode.shell.syntax.FlagArgument;
+import org.jnode.util.NumberUtils;
+
+/*
+ * @author Alexander Kerner
+ */
+public class DuCommand extends AbstractCommand {
+
+ private static final String err_perm = "Permission denied for '%s'%n";
+
+ private abstract class Walker extends AbstractDirectoryWalker {
+
+ protected final TreeMap<File, Long> map = new TreeMap<File, Long>();
+ protected final boolean humanReadable;
+
+ Walker(boolean humanReadable) {
+ this.humanReadable = humanReadable;
+ }
+
+ @Override
+ public void handleDir(File file) {
+ handleAll(file);
+ }
+
+ @Override
+ public void handleFile(File file) {
+ handleAll(file);
+ }
+
+ @Override
+ protected void handleRestrictedFile(File file) throws IOException {
+ err.format(err_perm, file);
+ }
+
+ private void handleAll(File file) {
+ map.put(file, file.length());
+ }
+
+ protected TreeMap<File, Long> summariseIt(TreeMap<File, Long> map) {
+ TreeMap<File, Long> result = new TreeMap<File, Long>();
+ NavigableMap<File, Long> navMap = map.descendingMap();
+ Long tmpSize = 0L;
+ while (navMap.size() != 0) {
+ Entry<File, Long> e = navMap.pollFirstEntry();
+ File key = e.getKey();
+ Long value = e.getValue();
+ tmpSize += key.length();
+
+ if (key.isFile()) {
+ result.put(key, value);
+ } else if (key.isDirectory()) {
+ result.put(key, tmpSize);
+ } else {
+ // ignore unknown file type
+ }
+ }
+ return result;
+ }
+ }
+
+ private class AllWalker extends Walker {
+
+ AllWalker(boolean humanReadable) {
+ super(humanReadable);
+ }
+
+ @Override
+ protected void lastAction(boolean wasCancelled) {
+ Map<File, Long> summarisedMap = summariseIt(map);
+ for (Entry<File, Long> e : summarisedMap.entrySet()) {
+ if(humanReadable)
+ out.println(NumberUtils.toBinaryByte(e.getValue()) + "\t" + e.getKey());
+ else
+ out.println(e.getValue() + "\t" + e.getKey());
+ }
+ }
+ }
+
+ private class OnlyDirsWalker extends Walker {
+
+ OnlyDirsWalker(boolean humanReadable) {
+ super(humanReadable);
+ }
+
+ @Override
+ protected void lastAction(boolean wasCancelled) {
+ Map<File, Long> summarisedMap = summariseIt(map);
+ for (Entry<File, Long> e : summarisedMap.entrySet()) {
+ if (e.getKey().isDirectory()) {
+ if(humanReadable)
+ out.println(NumberUtils.toBinaryByte(e.getValue()) + "\t" + e.getKey());
+ else
+ out.println(e.getValue() + "\t" + e.getKey());
+ }
+ }
+ }
+ }
+
+ private class TotalWalker extends Walker {
+
+ TotalWalker(boolean humanReadable) {
+ super(humanReadable);
+ }
+
+ @Override
+ protected void lastAction(boolean wasCancelled) {
+ TreeMap<File, Long> summarisedMap = summariseIt(map);
+ Entry<File, Long> e = summarisedMap.firstEntry();
+ if(humanReadable)
+ out.println(NumberUtils.toBinaryByte(e.getValue()) + "\t" + e.getKey());
+ else
+ out.println(e.getValue() + "\t" + e.getKey());
+
+ }
+ }
+
+ private PrintWriter out;
+ private PrintWriter err;
+
+ private static final String HELP_TOTAL = "display only a total for each argument";
+ private static final String HELP_ALL = "write counts for all files, not just directories";
+ private static final String HELP_SUPER = "print file sizes";
+ private static final String HELP_DIR = "directory to start printing sizes";
+ private static final String HELP_HUMAN_READABLE = "print sizes in human readable format (e.g., 1K 234M 2G)";
+
+ private final FlagArgument totalArg;
+ private final FlagArgument allArg;
+ private final FileArgument dirArg;
+ private final FlagArgument humanReadableArg;
+
+ public DuCommand() {
+ super(HELP_SUPER);
+ totalArg = new FlagArgument("sum", Argument.OPTIONAL, HELP_TOTAL);
+ allArg = new FlagArgument("all", Argument.OPTIONAL, HELP_ALL);
+ dirArg = new FileArgument("directory", Argument.OPTIONAL | Argument.MULTIPLE, HELP_DIR);
+ humanReadableArg = new FlagArgument("human-readable", Argument.OPTIONAL, HELP_HUMAN_READABLE);
+ registerArguments(totalArg, allArg, humanReadableArg, dirArg );
+ }
+
+ public static void main(String[] args) throws IOException {
+ new DuCommand().execute();
+ }
+
+ public void execute() throws IOException {
+ out = getOutput().getPrintWriter();
+ err = getError().getPrintWriter();
+ Walker walker = null;
+ if (totalArg.isSet()) {
+ walker = new TotalWalker(humanReadableArg.isSet());
+ } else if (allArg.isSet()) {
+ walker = new AllWalker(humanReadableArg.isSet());
+ } else {
+ walker = new OnlyDirsWalker(humanReadableArg.isSet());
+ }
+
+ if (dirArg.isSet()) {
+ walker.walk(dirArg.getValues());
+ } else {
+ walker.walk(new File(System.getProperty("user.dir")));
+ }
+ }
+}
+
Modified: trunk/cli/src/commands/org/jnode/command/file/FindCommand.java
===================================================================
--- trunk/cli/src/commands/org/jnode/command/file/FindCommand.java 2009-04-29 22:40:55 UTC (rev 5366)
+++ trunk/cli/src/commands/org/jnode/command/file/FindCommand.java 2009-04-29 22:41:40 UTC (rev 5367)
@@ -94,7 +94,8 @@
public static void main(String[] args) throws IOException {
new FindCommand().execute();
}
-
+
+ @Override
public void execute() throws IOException {
out = getOutput().getPrintWriter();
err = getError().getPrintWriter();
Modified: trunk/cli/src/commands/org/jnode/command/system/RunCommand.java
===================================================================
--- trunk/cli/src/commands/org/jnode/command/system/RunCommand.java 2009-04-29 22:40:55 UTC (rev 5366)
+++ trunk/cli/src/commands/org/jnode/command/system/RunCommand.java 2009-04-29 22:41:40 UTC (rev 5367)
@@ -18,7 +18,7 @@
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
-package org.jnode.shell.command;
+package org.jnode.command.system;
import java.io.File;
import java.io.PrintWriter;
Modified: trunk/cli/src/commands/org/jnode/command/util/AbstractDirectoryWalker.java
===================================================================
--- trunk/cli/src/commands/org/jnode/command/util/AbstractDirectoryWalker.java 2009-04-29 22:40:55 UTC (rev 5366)
+++ trunk/cli/src/commands/org/jnode/command/util/AbstractDirectoryWalker.java 2009-04-29 22:41:40 UTC (rev 5367)
@@ -147,6 +147,7 @@
while (!cancelled && !stack.isEmpty()) {
handle(stack.pop());
}
+ lastAction(cancelled);
}
}
@@ -253,7 +254,7 @@
/**
* This method is called, when access to a file was denied.<br>
* Default implementation will rise a <code>IOException</code> instead of
- * <code>SecurityException</code>. Maybe overridden by extending classes to
+ * <code>SecurityException</code>. May be overridden by extending classes to
* do something else.
*
* @param file <code>File</code>-object, to which access was restricted.
@@ -265,7 +266,7 @@
/**
* This method is called, when walking is about to start.<br>
- * By default, it does nothing. Maybe overridden by extending classes to do
+ * By default, it does nothing. May be overridden by extending classes to do
* something else.
*
* @param file <code>File</code>-object, that represents starting dir.
@@ -274,6 +275,15 @@
protected void handleStartingDir(final File file) throws IOException {
// do nothing by default
}
+
+ /**
+ * This method is called, when walking has finished. <br>
+ * By default, it does nothing. May be overridden by extending classes to do something else.
+ * @param wasCancelled true, if directory walking was aborted.
+ */
+ protected void lastAction(boolean wasCancelled){
+ // do nothing by default
+ }
/**
*
Copied: trunk/cli/src/commands/org/jnode/command/util/IOUtils.java (from rev 5366, trunk/coreutils/src/commands/org/jnode/command/util/IOUtils.java)
===================================================================
--- trunk/cli/src/commands/org/jnode/command/util/IOUtils.java (rev 0)
+++ trunk/cli/src/commands/org/jnode/command/util/IOUtils.java 2009-04-29 22:41:40 UTC (rev 5367)
@@ -0,0 +1,418 @@
+/*
+ * $Id$
+ *
+ * Copyright (C) 2003-2009 JNode.org
+ *
+ * This library is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as published
+ * by the Free Software Foundation; either version 2.1 of the License, or
+ * (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
+ * License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this library; If not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+package org.jnode.command.util;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.BufferedReader;
+import java.io.Closeable;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.Flushable;
+import java.io.InputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.PrintWriter;
+import java.io.Reader;
+
+/**
+ * Convenience IO methods.
+ *
+ * @author chris boertien
+ */
+public final class IOUtils {
+
+ private static final int BUFFER_SIZE = 4096;
+
+ private static final String ex_null_param = "A required paramater is null";
+
+ /**
+ * Call the close method of a list of Closeable objects.
+ *
+ * This will not throw a NullPointerException if any of the objects are null.
+ *
+ * This is a convenience method that traps the exception from various
+ * stream close() methods.
+ *
+ * @param objs one or more Closeable objects.
+ */
+ public static void close(Closeable... objs) {
+ close(false, objs);
+ }
+
+ /**
+ * Call the close method of a list of Closeable objects.
+ *
+ * If the flush paramater is set to true, and an object implements
+ * the Flushable interface, then the flush method will be called before
+ * the close method is called.
+ *
+ * This will not throw a NullPointerException if any of the objects are null.
+ *
+ * This will not throw an IOException if either the close or flush methods throw
+ * an IOException.
+ *
+ * If calling flush causes an IOException, close will still be called.
+ *
+ * @param flush if true, check if the object is Flushable
+ * @param objs one or more Closeable objects
+ */
+ public static void close(boolean flush, Closeable... objs) {
+ for (Closeable obj : objs) {
+ if (obj != null) {
+ if (flush && (obj instanceof Flushable)) {
+ try {
+ ((Flushable) obj).flush();
+ } catch (IOException _) {
+ // ignore
+ }
+ }
+ try {
+ obj.close();
+ } catch (IOException _) {
+ // ignore
+ }
+ }
+ }
+ }
+
+ /**
+ * Copies data from an Inputstream to an OutputStream.
+ *
+ * This method allocates a 4096 byte buffer each time it is called.
+ *
+ * At the end of writing, the OutputStream will be flushed, but no streams will be closed.
+ *
+ * @param in the stream to read from
+ * @param out the stream to write to
+ * @param bufferSize the size of buffer to use for the copy
+ * @return the number of bytes read from the input stream
+ * @throws NullPointerException if either in or out are null
+ * @throws IOException if an I/O error occurs
+ */
+ public static long copyStream(InputStream in, OutputStream out) throws IOException {
+ return copyStream(in, out, new byte[BUFFER_SIZE]);
+ }
+
+ /**
+ * Copies data from an Inputstream to an OutputStream.
+ *
+ * This method allocates a buffer of 'bufferSize' when it is called.
+ *
+ * At the end of writing, the OutputStream will be flushed, but no streams will be closed.
+ *
+ * @param in the stream to read from
+ * @param out the stream to write to
+ * @param bufferSize the size of buffer to use for the copy
+ * @return the number of bytes read from the input stream
+ * @throws NullPointerException if either in or out are null
+ * @throws IOException if an I/O error occurs
+ */
+ public static long copyStream(InputStream in, OutputStream out, int bufferSize) throws IOException {
+ return copyStream(in, out, new byte[bufferSize]);
+ }
+
+ /**
+ * Copies data from an InputStream to an OutputStream
+ *
+ * If copying multiple streams, this method may be prefered to the others
+ * as a way to use the same buffer instead of allocating a new buffer on each call.
+ *
+ * At the end of writing, the OutputStream will be flushed, but no streams will be closed.
+ *
+ * @param in the stream to read from
+ * @param out the stream to write to
+ * @param buffer a pre-allocated buffer to use.
+ * @return the number of bytes read from the input stream
+ * @throws NullPointerException if either in, out or buffer are null
+ * @throws IOException if an I/O error occurs
+ */
+ public static long copyStream(InputStream in, OutputStream out, byte[] buffer) throws IOException {
+ checkNull(in, out, buffer);
+
+ long totalBytes = 0;
+ int len = 0;
+ while ((len = in.read(buffer)) > 0) {
+ out.write(buffer, 0, len);
+ totalBytes += len;
+ }
+ out.flush();
+ return totalBytes;
+ }
+
+ /**
+ * Opens an InputStream on a file for reading.
+ *
+ * This method will not throw a FileNotFoundException or SecurityException like
+ * the FileInputStream constructor would.
+ *
+ * @param file the file to open a stream on
+ * @return an InputStream on the file, or null if an exception was thrown
+ * @throws NullPointerException if file is null
+ */
+ public static InputStream openInputStream(File file) {
+ return openInputStream(file, false);
+ }
+
+ /**
+ * Opens an InputStream on a file for reading.
+ *
+ * This method will not throw a FileNotFoundException or a SecurityException like
+ * the FileInputStream constructor would.
+ *
+ * @param file the file to open a stream on
+ * @param buffer if true, wrap the stream in a buffered stream
+ * @return an InpustStream on the file, or null if an exception was thrown
+ * @throws NullPointerException if file is null
+ */
+ public static InputStream openInputStream(File file, boolean buffer) {
+ return openInputStream(file, buffer, BUFFER_SIZE);
+ }
+
+ /**
+ * Opens an InputStream on a file for reading.
+ *
+ * This method will not throw a FileNotFoundException or a SecurityException like
+ * the FileInputStream constructor would.
+ *
+ * @param file the file to open a stream on
+ * @param buffer if true, wrap the stream in a buffered stream
+ * @param bufferSize the buffer size to use if buffer is true
+ * @return an InpustStream on the file, or null if an exception was thrown
+ * @throws NullPointerException if file is null
+ * @throws IllegalArgumentException if bufferSize < 0
+ */
+ public static InputStream openInputStream(File file, boolean buffer, int bufferSize) {
+ checkNull(file);
+
+ try {
+ InputStream in = new FileInputStream(file);
+ if (buffer) {
+ in = new BufferedInputStream(in, bufferSize);
+ }
+ return in;
+ } catch (FileNotFoundException e) {
+ return null;
+ } catch (SecurityException e2) {
+ return null;
+ }
+ }
+
+ /**
+ * Opens an OutputStream on a file for writing.
+ *
+ * If the file exists and has content, it will be overwritten. That is to say the append
+ * paramater will be false.
+ *
+ * This method will not throw a FileNotFoundException or a SecurityException like
+ * the FileOutputStream constructor would.
+ *
+ * @param file the file to open a stream on
+ * @return an OutputStream on the file, or null if an exception was thrown
+ * @throws NullPointerException if file is null
+ */
+ public static OutputStream openOutputStream(File file) {
+ return openOutputStream(file, false, 0);
+ }
+
+ /**
+ * Opens an OutputStream on a file for writing.
+ *
+ * This method will not throw a FileNotFoundException or a SecurityException like
+ * the FileOutputStream constructor would.
+ *
+ * @param file the file to open a stream on
+ * @param append if true, open the stream in append mode
+ * @return an OutputStream on the file, or null if an exception was thrown
+ * @throws NullPointerException if file is null
+ */
+ public static OutputStream openOutputstream(File file, boolean append) {
+ return openOutputStream(file, append, 0);
+ }
+
+ /**
+ * Opens an OutputStream on a file for writing.
+ *
+ * The stream will be wrapped in a buffered stream if bufferSize is > 0.
+ *
+ * If the file exists and has content, it will be overwritten. That is to say the append
+ * paramater will be false.
+ *
+ * This method will not throw a FileNotFoundException or a SecurityException like
+ * the FileOutputStream constructor would.
+ *
+ * @param file the file to open a stream on
+ * @param bufferSize if this is > 0, use it as the buffer size for the stream
+ * @return an OutputStream on the file, or null if an exception was thrown
+ * @throws NullPointerException if file is null
+ * @throws IllegalArgumentException if bufferSize < 0
+ */
+ public static OutputStream openOutputStream(File file, int bufferSize) {
+ return openOutputStream(file, false, bufferSize);
+ }
+
+ /**
+ * Opens an OutputStream on a file for writing.
+ *
+ * The stream will be wrapped in a buffered stream if bufferSize is > 0.
+ *
+ * This method will not throw a FileNotFoundException or a SecurityException like
+ * the FileOutputStream constructor would.
+ *
+ * @param file the file to open a stream on
+ * @param bufferSize if this is > 0, use it as the buffer size for the stream
+ * @param append if true, open the stream in append mode
+ * @return an OutputStream on the file, or null if an exception was thrown
+ * @throws NullPointerException if file is null
+ * @throws IllegalArgumentException if bufferSize < 0
+ */
+ public static OutputStream openOutputStream(File file, boolean append, int bufferSize) {
+ checkNull(file);
+
+ try {
+ OutputStream out = new FileOutputStream(file, append);
+
+ if (bufferSize > 0) {
+ out = new BufferedOutputStream(out, bufferSize);
+ }
+ return out;
+ } catch (FileNotFoundException e) {
+ return null;
+ } catch (SecurityException e2) {
+ return null;
+ }
+ }
+
+ /**
+ * Prompt the user with a question, asking for a yes or no response.
+ *
+ * The default response if none is given will be 'yes'
+ *
+ * @param in the reader to read user input from.
+ * @param out the writer to send the prompt to the user
+ * @param str the prompt to send to the user
+ * @return true if the user said yes, false if no
+ */
+ public static boolean promptYesOrNo(Reader in, PrintWriter out, String prompt) {
+ return promptYesOrNo(in, out, prompt, true);
+ }
+
+ /**
+ * Prompt the user with a question, asking for a yes or no response.
+ *
+ * If out is not attached to a terminal, then the user will not see the prompt
+ *
+ * If in is not attached to a terminal, then this method has undefined behavior.
+ *
+ * If the user inputs an answer that does not being with an 'n', 'N', 'y' or 'Y'
+ * then it will prompt the user again. If something causes this loop to execute
+ * indefinetly, it has limited loop iterations. If this loop cap is reached, the
+ * method will return false.
+ *
+ * If the user inputs nothing, then the defaultChoice is used.
+ *
+ * If the Reader is not a BufferedReader, then it will be wrapped in one.
+ *
+ * @param in the reader to read user input from.
+ * @param out the writer to send the prompt to the user
+ * @param str the prompt to send to the user
+ * @param defaultChoice if the user inputs no reply, this value is returned
+ * @return true if the user said yes, false if no
+ * @throws NullPointerException if in, out or str are null
+ */
+ public static boolean promptYesOrNo(Reader in, PrintWriter out, String prompt, boolean defaultChoice) {
+ String input;
+
+ // put a cap on the loops so it doesn't become an infinite loop
+ // this can happen if Reader is not attached to a tty
+ for (int i = 0; i < 10; i++) {
+ input = prompt(in, out, prompt);
+
+ if (input == null) {
+ return false;
+ }
+
+ if (input.length() == 0) {
+ return defaultChoice;
+ }
+
+ switch(input.charAt(0)) {
+ case 'y' :
+ case 'Y' :
+ return true;
+ case 'n' :
+ case 'N' :
+ return false;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Prompt the user with a question and capture the response.
+ *
+ * If out is not attached to a terminal, then the user will not see the prompt
+ *
+ * If in is not attached to a terminal, then this method has undefined behavior.
+ *
+ * If the Reader is not a BufferedReader, then it will be wrapped in one.
+ *
+ * @param in the reader to read user input from.
+ * @param out the writer to send the prompt to the user
+ * @param str the prompt to send to the user
+ * @return the string captured from the user, or null if an I/O error occurred.
+ * @throws NullPointerException if in, out or str are null
+ */
+ public static String prompt(Reader in, PrintWriter out, String prompt) {
+ checkNull(in, out, prompt);
+
+ String input;
+ BufferedReader reader;
+
+ if (in instanceof BufferedReader) {
+ reader = (BufferedReader) in;
+ } else {
+ reader = new BufferedReader(in);
+ }
+
+ out.print(prompt);
+ try {
+ input = reader.readLine();
+ } catch (IOException e) {
+ return null;
+ } finally {
+ out.println();
+ }
+
+ return input;
+ }
+
+ /**
+ * Check for null objects in a list of objects.
+ */
+ private static void checkNull(Object... objs) {
+ for(Object obj : objs) {
+ if (obj == null) throw new NullPointerException(ex_null_param);
+ }
+ }
+}
Deleted: trunk/coreutils/src/commands/org/jnode/command/util/IOUtils.java
===================================================================
--- trunk/coreutils/src/commands/org/jnode/command/util/IOUtils.java 2009-04-29 22:40:55 UTC (rev 5366)
+++ trunk/coreutils/src/commands/org/jnode/command/util/IOUtils.java 2009-04-29 22:41:40 UTC (rev 5367)
@@ -1,418 +0,0 @@
-/*
- * $Id$
- *
- * Copyright (C) 2003-2009 JNode.org
- *
- * This library is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as published
- * by the Free Software Foundation; either version 2.1 of the License, or
- * (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
- * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
- * License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this library; If not, write to the Free Software Foundation, Inc.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
- */
-package org.jnode.command.util;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.BufferedReader;
-import java.io.Closeable;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.Flushable;
-import java.io.InputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.PrintWriter;
-import java.io.Reader;
-
-/**
- * Convenience IO methods.
- *
- * @author chris boertien
- */
-public final class IOUtils {
-
- private static final int BUFFER_SIZE = 4096;
-
- private static final String ex_null_param = "A required paramater is null";
-
- /**
- * Call the close method of a list of Closeable objects.
- *
- * This will not throw a NullPointerException if any of the objects are null.
- *
- * This is a convenience method that traps the exception from various
- * stream close() methods.
- *
- * @param objs one or more Closeable objects.
- */
- public static void close(Closeable... objs) {
- close(false, objs);
- }
-
- /**
- * Call the close method of a list of Closeable objects.
- *
- * If the flush paramater is set to true, and an object implements
- * the Flushable interface, then the flush method will be called before
- * the close method is called.
- *
- * This will not throw a NullPointerException if any of the objects are null.
- *
- * This will not throw an IOException if either the close or flush methods throw
- * an IOException.
- *
- * If calling flush causes an IOException, close will still be called.
- *
- * @param flush if true, check if the object is Flushable
- * @param objs one or more Closeable objects
- */
- public static void close(boolean flush, Closeable... objs) {
- for (Closeable obj : objs) {
- if (obj != null) {
- if (flush && (obj instanceof Flushable)) {
- try {
- ((Flushable) obj).flush();
- } catch (IOException _) {
- // ignore
- }
- }
- try {
- obj.close();
- } catch (IOException _) {
- // ignore
- }
- }
- }
- }
-
- /**
- * Copies data from an Inputstream to an OutputStream.
- *
- * This method allocates a 4096 byte buffer each time it is called.
- *
- * At the end of writing, the OutputStream will be flushed, but no streams will be closed.
- *
- * @param in the stream to read from
- * @param out the stream to write to
- * @param bufferSize the size of buffer to use for the copy
- * @return the number of bytes read from the input stream
- * @throws NullPointerException if either in or out are null
- * @throws IOException if an I/O error occurs
- */
- public static long copyStream(InputStream in, OutputStream out) throws IOException {
- return copyStream(in, out, new byte[BUFFER_SIZE]);
- }
-
- /**
- * Copies data from an Inputstream to an OutputStream.
- *
- * This method allocates a buffer of 'bufferSize' when it is called.
- *
- * At the end of writing, the OutputStream will be flushed, but no streams will be closed.
- *
- * @param in the stream to read from
- * @param out the stream to write to
- * @param bufferSize the size of buffer to use for the copy
- * @return the number of bytes read from the input stream
- * @throws NullPointerException if either in or out are null
- * @throws IOException if an I/O error occurs
- */
- public static long copyStream(InputStream in, OutputStream out, int bufferSize) throws IOException {
- return copyStream(in, out, new byte[bufferSize]);
- }
-
- /**
- * Copies data from an InputStream to an OutputStream
- *
- * If copying multiple streams, this method may be prefered to the others
- * as a way to use the same buffer instead of allocating a new buffer on each call.
- *
- * At the end of writing, the OutputStream will be flushed, but no streams will be closed.
- *
- * @param in the stream to read from
- * @param out the stream to write to
- * @param buffer a pre-allocated buffer to use.
- * @return the number of bytes read from the input stream
- * @throws NullPointerException if either in, out or buffer are null
- * @throws IOException if an I/O error occurs
- */
- public static long copyStream(InputStream in, OutputStream out, byte[] buffer) throws IOException {
- checkNull(in, out, buffer);
-
- long totalBytes = 0;
- int len = 0;
- while ((len = in.read(buffer)) > 0) {
- out.write(buffer, 0, len);
- totalBytes += len;
- }
- out.flush();
- return totalBytes;
- }
-
- /**
- * Opens an InputStream on a file for reading.
- *
- * This method will not throw a FileNotFoundException or SecurityException like
- * the FileInputStream constructor would.
- *
- * @param file the file to open a stream on
- * @return an InputStream on the file, or null if an exception was thrown
- * @throws NullPointerException if file is null
- */
- public static InputStream openInputStream(File file) {
- return openInputStream(file, false);
- }
-
- /**
- * Opens an InputStream on a file for reading.
- *
- * This method will not throw a FileNotFoundException or a SecurityException like
- * the FileInputStream constructor would.
- *
- * @param file the file to open a stream on
- * @param buffer if true, wrap the stream in a buffered stream
- * @return an InpustStream on the file, or null if an exception was thrown
- * @throws NullPointerException if file is null
- */
- public static InputStream openInputStream(File file, boolean buffer) {
- return openInputStream(file, buffer, BUFFER_SIZE);
- }
-
- /**
- * Opens an InputStream on a file for reading.
- *
- * This method will not throw a FileNotFoundException or a SecurityException like
- * the FileInputStream constructor would.
- *
- * @param file the file to open a stream on
- * @param buffer if true, wrap the stream in a buffered stream
- * @param bufferSize the buffer size to use if buffer is true
- * @return an InpustStream on the file, or null if an exception was thrown
- * @throws NullPointerException if file is null
- * @throws IllegalArgumentException if bufferSize < 0
- */
- public static InputStream openInputStream(File file, boolean buffer, int bufferSize) {
- checkNull(file);
-
- try {
- InputStream in = new FileInputStream(file);
- if (buffer) {
- in = new BufferedInputStream(in, bufferSize);
- }
- return in;
- } catch (FileNotFoundException e) {
- return null;
- } catch (SecurityException e2) {
- return null;
- }
- }
-
- /**
- * Opens an OutputStream on a file for writing.
- *
- * If the file exists and has content, it will be overwritten. That is to say the append
- * paramater will be false.
- *
- * This method will not throw a FileNotFoundException or a SecurityException like
- * the FileOutputStream constructor would.
- *
- * @param file the file to open a stream on
- * @return an OutputStream on the file, or null if an exception was thrown
- * @throws NullPointerException if file is null
- */
- public static OutputStream openOutputStream(File file) {
- return openOutputStream(file, false, 0);
- }
-
- /**
- * Opens an OutputStream on a file for writing.
- *
- * This method will not throw a FileNotFoundException or a SecurityException like
- * the FileOutputStream constructor would.
- *
- * @param file the file to open a stream on
- * @param append if true, open the stream in append mode
- * @return an OutputStream on the file, or null if an exception was thrown
- * @throws NullPointerException if file is null
- */
- public static OutputStream openOutputstream(File file, boolean append) {
- return openOutputStream(file, append, 0);
- }
-
- /**
- * Opens an OutputStream on a file for writing.
- *
- * The stream will be wrapped in a buffered stream if bufferSize is > 0.
- *
- * If the file exists and has content, it will be overwritten. That is to say the append
- * paramater will be false.
- *
- * This method will not throw a FileNotFoundException or a SecurityException like
- * the FileOutputStream constructor would.
- *
- * @param file the file to open a stream on
- * @param bufferSize if this is > 0, use it as the buffer size for the stream
- * @return an OutputStream on the file, or null if an exception was thrown
- * @throws NullPointerException if file is null
- * @throws IllegalArgumentException if bufferSize < 0
- */
- public static OutputStream openOutputStream(File file, int bufferSize) {
- return openOutputStream(file, false, bufferSize);
- }
-
- /**
- * Opens an OutputStream on a file for writing.
- *
- * The stream will be wrapped in a buffered stream if bufferSize is > 0.
- *
- * This method will not throw a FileNotFoundException or a SecurityException like
- * the FileOutputStream constructor would.
- *
- * @param file the file to open a stream on
- * @param bufferSize if this is > 0, use it as the buffer size for the stream
- * @param append if true, open the stream in append mode
- * @return an OutputStream on the file, or null if an exception was thrown
- * @throws NullPointerException if file is null
- * @throws IllegalArgumentException if bufferSize < 0
- */
- public static OutputStream openOutputStream(File file, boolean append, int bufferSize) {
- checkNull(file);
-
- try {
- OutputStream out = new FileOutputStream(file, append);
-
- if (bufferSize > 0) {
- out = new BufferedOutputStream(out, bufferSize);
- }
- return out;
- } catch (FileNotFoundException e) {
- return null;
- } catch (SecurityException e2) {
- return null;
- }
- }
-
- /**
- * Prompt the user with a question, asking for a yes or no response.
- *
- * The default response if none is given will be 'yes'
- *
- * @param in the reader to read user input from.
- * @param out the writer to send the prompt to the user
- * @param str the prompt to send to the user
- * @return true if the user said yes, false if no
- */
- public static boolean promptYesOrNo(Reader in, PrintWriter out, String prompt) {
- return promptYesOrNo(in, out, prompt, true);
- }
-
- /**
- * Prompt the user with a question, asking for a yes or no response.
- *
- * If out is not attached to a terminal, then the user will not see the prompt
- *
- * If in is not attached to a terminal, then this method has undefined behavior.
- *
- * If the user inputs an answer that does not being with an 'n', 'N', 'y' or 'Y'
- * then it will prompt the user again. If something causes this loop to execute
- * indefinetly, it has limited loop iterations. If this loop cap is reached, the
- * method will return false.
- *
- * If the user inputs nothing, then the defaultChoice is used.
- *
- * If the Reader is not a BufferedReader, then it will be wrapped in one.
- *
- * @param in the reader to read user input from.
- * @param out the writer to send the prompt to the user
- * @param str the prompt to send to the user
- * @param defaultChoice if the user inputs no reply, this value is returned
- * @return true if the user said yes, false if no
- * @throws NullPointerException if in, out or str are null
- */
- public static boolean promptYesOrNo(Reader in, PrintWriter out, String prompt, boolean defaultChoice) {
- String input;
-
- // put a cap on the loops so it doesn't become an infinite loop
- // this can happen if Reader is not attached to a tty
- for (int i = 0; i < 10; i++) {
- input = prompt(in, out, prompt);
-
- if (input == null) {
- return false;
- }
-
- if (input.length() == 0) {
- return defaultChoice;
- }
-
- switch(input.charAt(0)) {
- case 'y' :
- case 'Y' :
- return true;
- case 'n' :
- case 'N' :
- return false;
- }
- }
-
- return false;
- }
-
- /**
- * Prompt the user with a question and capture the response.
- *
- * If out is not attached to a terminal, then the user will not see the prompt
- *
- * If in is not attached to a terminal, then this method has undefined behavior.
- *
- * If the Reader is not a BufferedReader, then it will be wrapped in one.
- *
- * @param in the reader to read user input from.
- * @param out the writer to send the prompt to the user
- * @param str the prompt to send to the user
- * @return the string captured from the user, or null if an I/O error occurred.
- * @throws NullPointerException if in, out or str are null
- */
- public static String prompt(Reader in, PrintWriter out, String prompt) {
- checkNull(in, out, prompt);
-
- String input;
- BufferedReader reader;
-
- if (in instanceof BufferedReader) {
- reader = (BufferedReader) in;
- } else {
- reader = new BufferedReader(in);
- }
-
- out.print(prompt);
- try {
- input = reader.readLine();
- } catch (IOException e) {
- return null;
- } finally {
- out.println();
- }
-
- return input;
- }
-
- /**
- * Check for null objects in a list of objects.
- */
- private static void checkNull(Object... objs) {
- for(Object obj : objs) {
- if (obj == null) throw new NullPointerException(ex_null_param);
- }
- }
-}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|