From: <ls...@us...> - 2007-10-28 18:49:31
|
Revision: 3574 http://jnode.svn.sourceforge.net/jnode/?rev=3574&view=rev Author: lsantha Date: 2007-10-28 11:49:30 -0700 (Sun, 28 Oct 2007) Log Message: ----------- Improved FSEntry caching by Andrei Dore. Modified Paths: -------------- trunk/core/.classpath trunk/fs/src/fs/org/jnode/fs/service/def/FSEntryCache.java trunk/fs/src/fs/org/jnode/fs/service/def/FileSystemAPIImpl.java Modified: trunk/core/.classpath =================================================================== --- trunk/core/.classpath 2007-10-28 17:06:32 UTC (rev 3573) +++ trunk/core/.classpath 2007-10-28 18:49:30 UTC (rev 3574) @@ -11,7 +11,6 @@ <classpathentry kind="src" path="src/classpath/tools"/> <classpathentry kind="src" path="src/classpath/java"/> <classpathentry kind="src" path="src/classpath/javax"/> - <classpathentry kind="src" path="src/classpath/org"/> <classpathentry kind="src" path="src/classpath/ext"/> <classpathentry kind="src" path="src/classpath/vm"/> <classpathentry kind="src" path="src/core"/> Modified: trunk/fs/src/fs/org/jnode/fs/service/def/FSEntryCache.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/service/def/FSEntryCache.java 2007-10-28 17:06:32 UTC (rev 3573) +++ trunk/fs/src/fs/org/jnode/fs/service/def/FSEntryCache.java 2007-10-28 18:49:30 UTC (rev 3574) @@ -22,7 +22,9 @@ package org.jnode.fs.service.def; import java.util.ArrayList; -import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Map.Entry; import org.jnode.fs.FSEntry; @@ -32,7 +34,14 @@ final class FSEntryCache { /** The actual cache */ - private final HashMap<String, FSEntry> entries = new HashMap<String, FSEntry>(); + private final Map<String, FSEntry> entries = new LinkedHashMap<String, FSEntry>(){ + + @Override + protected boolean removeEldestEntry(Entry<String, FSEntry> eldest) { + return size() > 100; + } + + }; /** * Create a new instance Modified: trunk/fs/src/fs/org/jnode/fs/service/def/FileSystemAPIImpl.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/service/def/FileSystemAPIImpl.java 2007-10-28 17:06:32 UTC (rev 3573) +++ trunk/fs/src/fs/org/jnode/fs/service/def/FileSystemAPIImpl.java 2007-10-28 18:49:30 UTC (rev 3574) @@ -280,6 +280,8 @@ //if they exist by any chance if ( name.equals(".") || name.equals("..") ) continue; + + entryCache.setEntry(directory+File.separatorChar+name, child); list.add(name); } @@ -334,6 +336,11 @@ if (parentEntry != null) { try { entry = parentEntry.getEntry(stripParentPath(path)); + + if(entry==null){ + return null; + } + entryCache.setEntry(path, entry); return entry; } catch (IOException ex) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2007-11-03 20:31:25
|
Revision: 3580 http://jnode.svn.sourceforge.net/jnode/?rev=3580&view=rev Author: lsantha Date: 2007-11-03 13:31:24 -0700 (Sat, 03 Nov 2007) Log Message: ----------- Various shell and command refactorings by crawley. Modified Paths: -------------- trunk/core/src/core/org/jnode/plugin/manager/DefaultPluginManager.java trunk/fs/src/fs/org/jnode/fs/command/CatCommand.java trunk/fs/src/fs/org/jnode/fs/command/CdCommand.java trunk/fs/src/fs/org/jnode/fs/command/DeleteCommand.java trunk/fs/src/fs/org/jnode/fs/command/DirCommand.java trunk/fs/src/fs/org/jnode/fs/command/EjectCommand.java trunk/fs/src/fs/org/jnode/fs/command/FormatCommand.java trunk/fs/src/fs/org/jnode/fs/command/HexdumpCommand.java trunk/fs/src/fs/org/jnode/fs/command/MkdirCommand.java trunk/fs/src/fs/org/jnode/fs/command/MountCommand.java trunk/fs/src/fs/org/jnode/fs/command/PwdCommand.java trunk/fs/src/fs/org/jnode/fs/command/TouchCommand.java trunk/fs/src/fs/org/jnode/fs/ftpfs/command/FTPMountCommand.java trunk/fs/src/fs/org/jnode/fs/ftpfs/command/MakeFTPDeviceCommand.java trunk/fs/src/fs/org/jnode/fs/jfat/command/FatFormatCommand.java trunk/fs/src/fs/org/jnode/fs/jfat/command/JGrubInstallCommand.java trunk/fs/src/fs/org/jnode/fs/jifs/command/createJIFS.java trunk/fs/src/fs/org/jnode/fs/nfs/command/NFSMountCommand.java trunk/fs/src/fs/org/jnode/fs/smbfs/command/MakeSMBDeviceCommand.java trunk/fs/src/fs/org/jnode/fs/smbfs/command/SMBMountCommand.java trunk/net/src/net/org/jnode/net/command/ArpCommand.java trunk/net/src/net/org/jnode/net/command/BootpCommand.java trunk/net/src/net/org/jnode/net/command/DhcpCommand.java trunk/net/src/net/org/jnode/net/command/IfconfigCommand.java trunk/net/src/net/org/jnode/net/command/NetCommand.java trunk/net/src/net/org/jnode/net/command/NetstatCommand.java trunk/net/src/net/org/jnode/net/command/ResolverCommand.java trunk/net/src/net/org/jnode/net/command/RouteCommand.java trunk/net/src/net/org/jnode/net/command/RpcInfoCommand.java trunk/net/src/net/org/jnode/net/command/TftpCommand.java trunk/net/src/net/org/jnode/net/command/WLanCtlCommand.java trunk/shell/src/shell/org/jnode/shell/AsyncCommandInvoker.java trunk/shell/src/shell/org/jnode/shell/Command.java trunk/shell/src/shell/org/jnode/shell/CommandInvoker.java trunk/shell/src/shell/org/jnode/shell/CommandLine.java trunk/shell/src/shell/org/jnode/shell/CommandShell.java trunk/shell/src/shell/org/jnode/shell/CommandThread.java trunk/shell/src/shell/org/jnode/shell/DefaultCommandInvoker.java trunk/shell/src/shell/org/jnode/shell/DefaultInterpreter.java trunk/shell/src/shell/org/jnode/shell/ProcletCommandInvoker.java trunk/shell/src/shell/org/jnode/shell/RedirectingInterpreter.java trunk/shell/src/shell/org/jnode/shell/ThreadCommandInvoker.java trunk/shell/src/shell/org/jnode/shell/ThreadExitListener.java trunk/shell/src/shell/org/jnode/shell/command/AliasCommand.java trunk/shell/src/shell/org/jnode/shell/command/EchoCommand.java trunk/shell/src/shell/org/jnode/shell/command/EnvCommand.java trunk/shell/src/shell/org/jnode/shell/command/ExecCommand.java trunk/shell/src/shell/org/jnode/shell/command/ExitCommand.java trunk/shell/src/shell/org/jnode/shell/command/GcCommand.java trunk/shell/src/shell/org/jnode/shell/command/GrepCommand.java trunk/shell/src/shell/org/jnode/shell/command/JavaCommand.java trunk/shell/src/shell/org/jnode/shell/command/KillCommand.java trunk/shell/src/shell/org/jnode/shell/command/LoadkeysCommand.java trunk/shell/src/shell/org/jnode/shell/command/MemoryCommand.java trunk/shell/src/shell/org/jnode/shell/command/NamespaceCommand.java trunk/shell/src/shell/org/jnode/shell/command/OnHeapCommand.java trunk/shell/src/shell/org/jnode/shell/command/RunCommand.java trunk/shell/src/shell/org/jnode/shell/command/SetCommand.java trunk/shell/src/shell/org/jnode/shell/command/ThreadCommand.java trunk/shell/src/shell/org/jnode/shell/command/bsh/BshCommand.java trunk/shell/src/shell/org/jnode/shell/command/debug/UDPOutputCommand.java trunk/shell/src/shell/org/jnode/shell/command/driver/console/ConsoleCommand.java trunk/shell/src/shell/org/jnode/shell/command/system/CpuIDCommand.java trunk/shell/src/shell/org/jnode/shell/help/Syntax.java Added Paths: ----------- trunk/shell/src/shell/org/jnode/shell/AbstractCommand.java trunk/shell/src/shell/org/jnode/shell/CommandRunner.java trunk/shell/src/shell/org/jnode/shell/NoTokensAvailableException.java trunk/shell/src/shell/org/jnode/shell/StreamMarker.java trunk/shell/src/shell/org/jnode/shell/command/unix/ trunk/shell/src/shell/org/jnode/shell/command/unix/UnixTestCommand.java Modified: trunk/core/src/core/org/jnode/plugin/manager/DefaultPluginManager.java =================================================================== --- trunk/core/src/core/org/jnode/plugin/manager/DefaultPluginManager.java 2007-11-03 18:16:58 UTC (rev 3579) +++ trunk/core/src/core/org/jnode/plugin/manager/DefaultPluginManager.java 2007-11-03 20:31:24 UTC (rev 3580) @@ -123,6 +123,7 @@ // 2 loops, first start all system plugins, // then start all auto-start plugins for (int type = 0; type < 2; type++) { + BootLog.info("Starting " + ((type == 0) ? "system" : "auto-start") + " plugins"); for (PluginDescriptor descr : descrList) { try { final boolean start; Modified: trunk/fs/src/fs/org/jnode/fs/command/CatCommand.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/command/CatCommand.java 2007-11-03 18:16:58 UTC (rev 3579) +++ trunk/fs/src/fs/org/jnode/fs/command/CatCommand.java 2007-11-03 20:31:24 UTC (rev 3580) @@ -30,6 +30,7 @@ import java.net.MalformedURLException; import java.net.URL; +import org.jnode.shell.AbstractCommand; import org.jnode.shell.Command; import org.jnode.shell.CommandLine; import org.jnode.shell.help.Argument; @@ -44,7 +45,7 @@ * @author Stephen Crawley * @author Fabien DUMINY (fd...@jn...) */ -public class CatCommand implements Command { +public class CatCommand extends AbstractCommand { static final Argument ARG_FILE = new FileArgument("file", "the files (or URLs) to be concatenated", true); @@ -59,11 +60,11 @@ public static void main(String[] args) throws Exception { - new CatCommand().execute(new CommandLine(args), System.in, System.out, System.err); + new CatCommand().execute(args); } public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) throws Exception { - ParsedArguments cmdLine = HELP_INFO.parse(commandLine.toStringArray()); + ParsedArguments cmdLine = HELP_INFO.parse(commandLine); String[] fileNames = ARG_FILE.getValues(cmdLine); boolean ok = true; try { @@ -117,7 +118,7 @@ ok = false; } if (!ok) { - System.exit(1); + exit(1); } } Modified: trunk/fs/src/fs/org/jnode/fs/command/CdCommand.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/command/CdCommand.java 2007-11-03 18:16:58 UTC (rev 3579) +++ trunk/fs/src/fs/org/jnode/fs/command/CdCommand.java 2007-11-03 20:31:24 UTC (rev 3580) @@ -25,6 +25,7 @@ import java.io.InputStream; import java.io.PrintStream; +import org.jnode.shell.AbstractCommand; import org.jnode.shell.Command; import org.jnode.shell.CommandLine; import org.jnode.shell.help.Help; @@ -36,29 +37,36 @@ * @author Ewout Prangsma (ep...@us...) * @author Andreas H\u00e4nel */ -public class CdCommand implements Command{ +public class CdCommand extends AbstractCommand { static final FileArgument ARG_DIR = new FileArgument("directory", "the directory to switch to"); - public static Help.Info HELP_INFO = new Help.Info("cd", "Go to the given directory", new Parameter[] { new Parameter(ARG_DIR, Parameter.MANDATORY)}); + public static Help.Info HELP_INFO = new Help.Info("cd", "Go to the given directory", + new Parameter[] { new Parameter(ARG_DIR, Parameter.MANDATORY)}); public static void main(String[] args) throws Exception { - new DirCommand().execute(new CommandLine(args), System.in, System.out, System.err); + new CdCommand().execute(args); } - public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) throws Exception { - ParsedArguments cmdLine = HELP_INFO.parse(commandLine.toStringArray()); + public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) + throws Exception { + ParsedArguments cmdLine = HELP_INFO.parse(commandLine); String dir_str = ARG_DIR.getValue(cmdLine); - if (((dir_str == null)&&(System.getProperty("user.dir").equals("/")))||((dir_str != null)&&(dir_str.equals("/")))){ - //System.getProperties().setProperty("user.dir", "/"); + // FIXME the following seems to cater for an optional <directory> argument, but the + // HELP_INFO syntax declares it as mandatoty. + if ((dir_str == null && System.getProperty("user.dir").equals("/")) || + (dir_str != null && dir_str.equals("/"))) { System.setProperty("user.dir", "/"); } else { File dir = ARG_DIR.getFile(cmdLine); - if (dir==null) dir = new File(System.getProperty("user.dir")); + if (dir == null) { + dir = new File(System.getProperty("user.dir")); + } if (dir.exists() && dir.isDirectory()) { System.setProperty("user.dir", dir.getAbsoluteFile().getCanonicalPath()); } else { System.err.println(dir + " is not a valid directory"); + exit(1); } } Modified: trunk/fs/src/fs/org/jnode/fs/command/DeleteCommand.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/command/DeleteCommand.java 2007-11-03 18:16:58 UTC (rev 3579) +++ trunk/fs/src/fs/org/jnode/fs/command/DeleteCommand.java 2007-11-03 20:31:24 UTC (rev 3580) @@ -27,7 +27,7 @@ import org.jnode.fs.service.FileSystemService; import org.jnode.naming.InitialNaming; -import org.jnode.shell.Command; +import org.jnode.shell.AbstractCommand; import org.jnode.shell.CommandLine; import org.jnode.shell.help.Help; import org.jnode.shell.help.Parameter; @@ -43,7 +43,7 @@ * @author Andreas H\u00e4nel * @author Levente S\u00e1ntha */ -public class DeleteCommand implements Command { +public class DeleteCommand extends AbstractCommand { static final FileArgument ARG_DIR = new FileArgument("file/dir", "delete the file or directory", true); @@ -53,24 +53,27 @@ ARG_DIR, Parameter.MANDATORY) }); public static void main(String[] args) throws Exception { - new DeleteCommand().execute(new CommandLine(args), System.in, - System.out, System.err); + new DeleteCommand().execute(args); } public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) throws Exception { - ParsedArguments cmdLine = HELP_INFO.parse(commandLine.toStringArray()); + ParsedArguments cmdLine = HELP_INFO.parse(commandLine); File[] file_arr = ARG_DIR.getFiles(cmdLine); - for(File file : file_arr) - deleteFile(file, err); + boolean ok = true; + for (File file : file_arr) { + boolean tmp = deleteFile(file, err); + ok &= tmp; + } + if (!ok) { + exit(1); + } } - private void deleteFile(File file, PrintStream err) throws NameNotFoundException { - boolean deleteOk = false; - + private boolean deleteFile(File file, PrintStream err) throws NameNotFoundException { if (!file.exists()) { err.println(file + " does not exist"); - return; + return false; } // Lookup the Filesystem service @@ -78,21 +81,24 @@ // for this time, delete only empty directory (wait implementation of -r // option) + boolean deleteOk = true; if (file.isDirectory() && !fss.isMount(file.getAbsolutePath())) { final File[] subFiles = file.listFiles(); for (File f : subFiles) { final String name = f.getName(); if (!name.equals(".") && !name.equals("..")) { err.println("Directory is not empty " + file); + deleteOk = false; break; } } } - + if (deleteOk) { deleteOk = file.delete(); - if (!deleteOk) { err.println(file + " was not deleted"); } } + return deleteOk; + } } Modified: trunk/fs/src/fs/org/jnode/fs/command/DirCommand.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/command/DirCommand.java 2007-11-03 18:16:58 UTC (rev 3579) +++ trunk/fs/src/fs/org/jnode/fs/command/DirCommand.java 2007-11-03 20:31:24 UTC (rev 3580) @@ -21,13 +21,13 @@ package org.jnode.fs.command; +import org.jnode.shell.AbstractCommand; import org.jnode.shell.Command; import org.jnode.shell.CommandLine; import org.jnode.shell.help.Help; import org.jnode.shell.help.Parameter; import org.jnode.shell.help.ParsedArguments; import org.jnode.shell.help.argument.FileArgument; -import org.jnode.util.NumberUtils; import java.io.File; import java.io.InputStream; @@ -43,7 +43,7 @@ * @author Martin Husted Hartvig (ha...@jn...) * @author Levente S\u00e1ntha */ -public class DirCommand implements Command { +public class DirCommand extends AbstractCommand { private static final int LEFT_MARGIN = 14; private static final SimpleDateFormat df = new SimpleDateFormat("yyyy MMM dd HH:mm"); @@ -56,11 +56,11 @@ new Parameter[]{new Parameter(ARG_PATH, Parameter.OPTIONAL)}); public static void main(String[] args) throws Exception { - new DirCommand().execute(new CommandLine(args), System.in, System.out, System.err); + new DirCommand().execute(args); } public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) throws Exception { - ParsedArguments cmdLine = HELP_INFO.parse(commandLine.toStringArray()); + ParsedArguments cmdLine = HELP_INFO.parse(commandLine); String userDir = System.getProperty("user.dir"); File path = ARG_PATH.getFile(cmdLine); if (path == null) path = new File(userDir); @@ -71,6 +71,7 @@ this.printList(new File[]{path}, out); } else { err.println("No such path " + path); + exit(1); } } Modified: trunk/fs/src/fs/org/jnode/fs/command/EjectCommand.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/command/EjectCommand.java 2007-11-03 18:16:58 UTC (rev 3579) +++ trunk/fs/src/fs/org/jnode/fs/command/EjectCommand.java 2007-11-03 20:31:24 UTC (rev 3580) @@ -26,6 +26,7 @@ import org.jnode.driver.Device; import org.jnode.driver.RemovableDeviceAPI; +import org.jnode.shell.AbstractCommand; import org.jnode.shell.Command; import org.jnode.shell.CommandLine; import org.jnode.shell.help.Help; @@ -37,21 +38,20 @@ /** * @author Ewout Prangsma (ep...@us...) */ -public class EjectCommand implements Command { +public class EjectCommand extends AbstractCommand { static final DeviceArgument ARG_DEVICE = new DeviceArgument("device", "device to eject the medium from"); public static Help.Info HELP_INFO = new Help.Info("eject", "Eject the medium from a given device", new Parameter[] { new Parameter(ARG_DEVICE, Parameter.MANDATORY)}); public static void main(String[] args) throws Exception { - new EjectCommand().execute(new CommandLine(args), System.in, System.out, System.err); + new EjectCommand().execute(args); } public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) throws Exception { - ParsedArguments cmdLine = HELP_INFO.parse(commandLine.toStringArray()); + ParsedArguments cmdLine = HELP_INFO.parse(commandLine); final Device dev = ARG_DEVICE.getDevice(cmdLine); final RemovableDeviceAPI api = dev.getAPI(RemovableDeviceAPI.class); api.eject(); - } } Modified: trunk/fs/src/fs/org/jnode/fs/command/FormatCommand.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/command/FormatCommand.java 2007-11-03 18:16:58 UTC (rev 3579) +++ trunk/fs/src/fs/org/jnode/fs/command/FormatCommand.java 2007-11-03 20:31:24 UTC (rev 3580) @@ -38,6 +38,7 @@ import org.jnode.fs.fat.FatFileSystemType; import org.jnode.fs.service.FileSystemService; import org.jnode.naming.InitialNaming; +import org.jnode.shell.AbstractCommand; import org.jnode.shell.Command; import org.jnode.shell.CommandLine; import org.jnode.shell.help.Help; @@ -50,7 +51,7 @@ /** * @author gbin */ -public class FormatCommand implements Command { +public class FormatCommand extends AbstractCommand { static final OptionArgument TYPE = new OptionArgument("action", "Type parameter", @@ -90,12 +91,12 @@ PARAM_BS_VAL }) }); public static void main(String[] args) throws Exception { - new FormatCommand().execute(new CommandLine(args), System.in, System.out, System.err); + new FormatCommand().execute(args); } public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) throws Exception { try { - ParsedArguments cmdLine = HELP_INFO.parse(commandLine.toStringArray()); + ParsedArguments cmdLine = HELP_INFO.parse(commandLine); String device = ARG_DEVICE.getValue(cmdLine); String FSType = FS.getValue(cmdLine).intern(); @@ -147,13 +148,16 @@ } catch (NameNotFoundException e) { e.printStackTrace(); + exit(1); } catch (DeviceNotFoundException e) { e.printStackTrace(); + exit(2); } catch (DriverException e) { e.printStackTrace(); + exit(3); } catch (FileSystemException e) { - // e.printStackTrace(); + exit(4); } } } Modified: trunk/fs/src/fs/org/jnode/fs/command/HexdumpCommand.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/command/HexdumpCommand.java 2007-11-03 18:16:58 UTC (rev 3579) +++ trunk/fs/src/fs/org/jnode/fs/command/HexdumpCommand.java 2007-11-03 20:31:24 UTC (rev 3580) @@ -4,7 +4,7 @@ package org.jnode.fs.command; -import org.jnode.shell.Command; +import org.jnode.shell.AbstractCommand; import org.jnode.shell.CommandLine; import org.jnode.shell.help.Argument; import org.jnode.shell.help.Help; @@ -22,7 +22,7 @@ /** * @author gvt */ -public class HexdumpCommand implements Command { +public class HexdumpCommand extends AbstractCommand { static final Argument ARG_FILE = new FileArgument("file", "the file (or URL) to print out"); @@ -31,17 +31,18 @@ new Parameter[]{new Parameter(ARG_FILE, Parameter.MANDATORY)}); public static void main(String[] args) throws Exception { - new HexdumpCommand().execute(new CommandLine(args), System.in, System.out, System.err); + new HexdumpCommand().execute(args); } public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) throws Exception { - ParsedArguments cmdLine = HELP_INFO.parse(commandLine.toStringArray()); + ParsedArguments cmdLine = HELP_INFO.parse(commandLine); URL url = openURL(ARG_FILE.getValue(cmdLine)); InputStream is = url.openStream(); if (is == null) { err.println("Not found " + ARG_FILE.getValue(cmdLine)); + exit(1); } else { final int rowlen = 16; int prt = 0; Modified: trunk/fs/src/fs/org/jnode/fs/command/MkdirCommand.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/command/MkdirCommand.java 2007-11-03 18:16:58 UTC (rev 3579) +++ trunk/fs/src/fs/org/jnode/fs/command/MkdirCommand.java 2007-11-03 20:31:24 UTC (rev 3580) @@ -25,7 +25,7 @@ import java.io.InputStream; import java.io.PrintStream; -import org.jnode.shell.Command; +import org.jnode.shell.AbstractCommand; import org.jnode.shell.CommandLine; import org.jnode.shell.help.Help; import org.jnode.shell.help.Parameter; @@ -36,7 +36,7 @@ * @author Guillaume BINET (gb...@us...) * @author Andreas H\u00e4nel */ -public class MkdirCommand implements Command{ +public class MkdirCommand extends AbstractCommand { static final FileArgument ARG_DIR = new FileArgument("directory", "the directory to create"); public static Help.Info HELP_INFO = @@ -46,17 +46,16 @@ new Parameter[] { new Parameter(ARG_DIR, Parameter.MANDATORY)}); public static void main(String[] args) throws Exception { - new MkdirCommand().execute(new CommandLine(args), System.in, System.out, System.err); + new MkdirCommand().execute(args); } public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) throws Exception { - ParsedArguments cmdLine = HELP_INFO.parse(commandLine.toStringArray()); + ParsedArguments cmdLine = HELP_INFO.parse(commandLine); File dir = ARG_DIR.getFile(cmdLine); - boolean mkOk = false; - mkOk=dir.mkdir(); - if(!mkOk){ + if (dir.mkdir()) { err.println("Can't create directory."); + exit(1); } } } Modified: trunk/fs/src/fs/org/jnode/fs/command/MountCommand.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/command/MountCommand.java 2007-11-03 18:16:58 UTC (rev 3579) +++ trunk/fs/src/fs/org/jnode/fs/command/MountCommand.java 2007-11-03 20:31:24 UTC (rev 3580) @@ -28,7 +28,7 @@ import org.jnode.fs.FileSystem; import org.jnode.fs.service.FileSystemService; import org.jnode.naming.InitialNaming; -import org.jnode.shell.Command; +import org.jnode.shell.AbstractCommand; import org.jnode.shell.CommandLine; import org.jnode.shell.help.Help; import org.jnode.shell.help.Parameter; @@ -39,7 +39,7 @@ /** * @author Ewout Prangsma (ep...@us...) */ -public class MountCommand implements Command { +public class MountCommand extends AbstractCommand { private static final DeviceArgument ARG_DEV = new DeviceArgument("device", "the device to mount"); @@ -56,13 +56,12 @@ new Parameter(ARG_FSPATH, Parameter.OPTIONAL) }); public static void main(String[] args) throws Exception { - new MountCommand().execute(new CommandLine(args), System.in, - System.out, System.err); + new MountCommand().execute(args); } public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) throws Exception { - ParsedArguments cmdLine = HELP_INFO.parse(commandLine.toStringArray()); + ParsedArguments cmdLine = HELP_INFO.parse(commandLine); // Get the parameters final Device dev = ARG_DEV.getDevice(cmdLine); @@ -76,6 +75,7 @@ final FileSystem fs = fss.getFileSystem(dev); if (fs == null) { err.println("No filesystem found on " + dev.getId()); + exit(1); } else { // Mount it fss.mount(mountPoint, fs, fsPath); Modified: trunk/fs/src/fs/org/jnode/fs/command/PwdCommand.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/command/PwdCommand.java 2007-11-03 18:16:58 UTC (rev 3579) +++ trunk/fs/src/fs/org/jnode/fs/command/PwdCommand.java 2007-11-03 20:31:24 UTC (rev 3580) @@ -25,20 +25,20 @@ import java.io.InputStream; import java.io.PrintStream; -import org.jnode.shell.Command; +import org.jnode.shell.AbstractCommand; import org.jnode.shell.CommandLine; import org.jnode.shell.help.Help; /** * @author Martin Husted Hartvig (ha...@jn...) */ -public class PwdCommand implements Command +public class PwdCommand extends AbstractCommand { public static Help.Info HELP_INFO = new Help.Info("pwd", "show the name of current working directory"); public static void main(String[] args) throws Exception { - new PwdCommand().execute(new CommandLine(args), System.in, System.out, System.err); + new PwdCommand().execute(args); } public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) throws Exception Modified: trunk/fs/src/fs/org/jnode/fs/command/TouchCommand.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/command/TouchCommand.java 2007-11-03 18:16:58 UTC (rev 3579) +++ trunk/fs/src/fs/org/jnode/fs/command/TouchCommand.java 2007-11-03 20:31:24 UTC (rev 3580) @@ -25,7 +25,7 @@ import java.io.InputStream; import java.io.PrintStream; -import org.jnode.shell.Command; +import org.jnode.shell.AbstractCommand; import org.jnode.shell.CommandLine; import org.jnode.shell.help.Help; import org.jnode.shell.help.Parameter; @@ -40,7 +40,7 @@ * @author Yves Galante (yve...@jm...) * @author Andreas H\u00e4nel */ -public class TouchCommand implements Command{ +public class TouchCommand extends AbstractCommand { static final FileArgument ARG_TOUCH = new FileArgument("file", "the file to touch"); @@ -50,11 +50,12 @@ Parameter.MANDATORY)}); public static void main(String[] args) throws Exception { - new TouchCommand().execute(new CommandLine(args), System.in, System.out, System.err); + new TouchCommand().execute(args); } - public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) throws Exception { - ParsedArguments cmdLine = HELP_INFO.parse(commandLine.toStringArray()); + public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) + throws Exception { + ParsedArguments cmdLine = HELP_INFO.parse(commandLine); File file = ARG_TOUCH.getFile(cmdLine); File parentFile = file.getParentFile(); @@ -62,12 +63,14 @@ if (parentFile!=null && !parentFile.exists()) { if (!parentFile.mkdirs()) { err.println("Parent dirs can't create"); + exit(2); } } if (file.createNewFile()) { out.println("File created"); } else { err.println("File can't create"); + exit(1); } } else { out.println("File already exist"); Modified: trunk/fs/src/fs/org/jnode/fs/ftpfs/command/FTPMountCommand.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/ftpfs/command/FTPMountCommand.java 2007-11-03 18:16:58 UTC (rev 3579) +++ trunk/fs/src/fs/org/jnode/fs/ftpfs/command/FTPMountCommand.java 2007-11-03 20:31:24 UTC (rev 3580) @@ -30,8 +30,8 @@ import org.jnode.fs.ftpfs.FTPFileSystemType; import org.jnode.fs.service.FileSystemService; import org.jnode.naming.InitialNaming; +import org.jnode.shell.AbstractCommand; import org.jnode.shell.CommandLine; -import org.jnode.shell.Command; import org.jnode.shell.help.Argument; import org.jnode.shell.help.Help; import org.jnode.shell.help.Parameter; @@ -44,7 +44,7 @@ /** * @author Levente S\u00e1ntha */ -public class FTPMountCommand implements Command { +public class FTPMountCommand extends AbstractCommand { private static final FileArgument MOUNTPOINT_ARG = new FileArgument("directory", "the mountpoint"); private static final Argument HOST_ARG = new Argument("host", "FTP host"); private static final Argument USERNAME_ARG = new Argument("username", "FTP user"); @@ -56,13 +56,12 @@ new Parameter(PASSWORD_ARG, Parameter.OPTIONAL)}); public static void main(String[] args) throws Exception { - new FTPMountCommand().execute(new CommandLine(args), System.in, - System.out, System.err); + new FTPMountCommand().execute(args); } public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) throws Exception { - ParsedArguments cmdLine = HELP_INFO.parse(commandLine.toStringArray()); + ParsedArguments cmdLine = HELP_INFO.parse(commandLine); final String mount_point = MOUNTPOINT_ARG.getValue(cmdLine); final String host = HOST_ARG.getValue(cmdLine); Modified: trunk/fs/src/fs/org/jnode/fs/ftpfs/command/MakeFTPDeviceCommand.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/ftpfs/command/MakeFTPDeviceCommand.java 2007-11-03 18:16:58 UTC (rev 3579) +++ trunk/fs/src/fs/org/jnode/fs/ftpfs/command/MakeFTPDeviceCommand.java 2007-11-03 20:31:24 UTC (rev 3580) @@ -29,7 +29,7 @@ import org.jnode.fs.service.FileSystemService; import org.jnode.fs.FileSystemType; import org.jnode.fs.FileSystem; -import org.jnode.shell.Command; +import org.jnode.shell.AbstractCommand; import org.jnode.shell.CommandLine; import org.jnode.shell.help.Argument; import org.jnode.shell.help.Help; @@ -43,7 +43,7 @@ /** * @author Levente S\u00e1ntha */ -public class MakeFTPDeviceCommand implements Command { +public class MakeFTPDeviceCommand extends AbstractCommand { private static final Argument HOST_ARG = new Argument("host", "FTP host"); private static final Argument USERNAME_ARG = new Argument("username", "FTP username"); private static final Argument PASSWORD_ARG = new Argument("password", "FTP password"); @@ -54,8 +54,7 @@ new Parameter(PASSWORD_ARG, Parameter.OPTIONAL) }); public static void main(String[] args) throws Exception { - new MakeFTPDeviceCommand().execute(new CommandLine(args), System.in, - System.out, System.err); + new MakeFTPDeviceCommand().execute(args); } /** * This will be execute'ed when the command is called. @@ -67,7 +66,7 @@ * @throws Exception */ public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) throws Exception { - ParsedArguments cmdLine = HELP_INFO.parse(commandLine.toStringArray()); + ParsedArguments cmdLine = HELP_INFO.parse(commandLine); // Get the parameters final String host = HOST_ARG.getValue(cmdLine); Modified: trunk/fs/src/fs/org/jnode/fs/jfat/command/FatFormatCommand.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/jfat/command/FatFormatCommand.java 2007-11-03 18:16:58 UTC (rev 3579) +++ trunk/fs/src/fs/org/jnode/fs/jfat/command/FatFormatCommand.java 2007-11-03 20:31:24 UTC (rev 3580) @@ -35,7 +35,7 @@ import org.jnode.fs.jfat.FatFileSystemType; import org.jnode.fs.service.FileSystemService; import org.jnode.naming.InitialNaming; -import org.jnode.shell.Command; +import org.jnode.shell.AbstractCommand; import org.jnode.shell.CommandLine; import org.jnode.shell.help.argument.DeviceArgument; import org.jnode.shell.help.Help; @@ -50,7 +50,7 @@ * The FAT32 formating command. * */ -public class FatFormatCommand implements Command{ +public class FatFormatCommand extends AbstractCommand { private static final Logger log = Logger.getLogger ( FatFormatCommand.class ); @@ -84,13 +84,13 @@ public static void main(String[] args) throws Exception{ - new FatFormatCommand().execute(new CommandLine(args), System.in, System.out, System.err); + new FatFormatCommand().execute(args); } public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) throws Exception { try { System.out.println("mkjfat:JFAT Formatter. Version :1.0"); - ParsedArguments cmdLine = HELP_INFO.parse(commandLine.toStringArray()); + ParsedArguments cmdLine = HELP_INFO.parse(commandLine); String device = ARG_DEVICE.getValue(cmdLine); Integer bsize; Modified: trunk/fs/src/fs/org/jnode/fs/jfat/command/JGrubInstallCommand.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/jfat/command/JGrubInstallCommand.java 2007-11-03 18:16:58 UTC (rev 3579) +++ trunk/fs/src/fs/org/jnode/fs/jfat/command/JGrubInstallCommand.java 2007-11-03 20:31:24 UTC (rev 3580) @@ -29,7 +29,7 @@ import org.jnode.driver.DeviceNotFoundException; import org.jnode.driver.DriverException; import org.jnode.naming.InitialNaming; -import org.jnode.shell.Command; +import org.jnode.shell.AbstractCommand; import org.jnode.shell.CommandLine; import org.jnode.shell.help.Help; import org.jnode.shell.help.Parameter; @@ -50,7 +50,7 @@ * Adding more command support for grub insallation. * @author Tango Devian */ -public class JGrubInstallCommand implements Command { +public class JGrubInstallCommand extends AbstractCommand { static final DeviceArgument ARG_DEVICE = new DeviceArgument("device", "device where grub will be installed"); static final FileArgument ARG_DIR = new FileArgument("directory", "the directory for stage2 and menu.lst"); static final OptionArgument TYPE = new OptionArgument("action","Type parameter", @@ -76,7 +76,7 @@ * @throws Exception */ public static void main(String... args) throws Exception { - new JGrubInstallCommand().execute(new CommandLine(args), System.in, System.out, System.err); + new JGrubInstallCommand().execute(args); } /** @@ -84,7 +84,7 @@ */ public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) throws Exception { try { - ParsedArguments cmdLine = HELP_INFO.parse(commandLine.toStringArray()); + ParsedArguments cmdLine = HELP_INFO.parse(commandLine); String device = ARG_DEVICE.getValue(cmdLine); File destDir = ARG_DIR.getFile(cmdLine); Modified: trunk/fs/src/fs/org/jnode/fs/jifs/command/createJIFS.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/jifs/command/createJIFS.java 2007-11-03 18:16:58 UTC (rev 3579) +++ trunk/fs/src/fs/org/jnode/fs/jifs/command/createJIFS.java 2007-11-03 20:31:24 UTC (rev 3580) @@ -38,6 +38,7 @@ import org.jnode.shell.help.Syntax; import org.jnode.shell.help.argument.OptionArgument; +//todo fix class name /** * Just mounts initial JIFS on /Jifs * @@ -62,7 +63,7 @@ new Parameter[] { PARAM_ACTION })}); public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) throws Exception { - ParsedArguments cmdLine = HELP_INFO.parse(commandLine.toStringArray()); + ParsedArguments cmdLine = HELP_INFO.parse(commandLine); String Act = ACTION.getValue(cmdLine); try{ Modified: trunk/fs/src/fs/org/jnode/fs/nfs/command/NFSMountCommand.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/nfs/command/NFSMountCommand.java 2007-11-03 18:16:58 UTC (rev 3579) +++ trunk/fs/src/fs/org/jnode/fs/nfs/command/NFSMountCommand.java 2007-11-03 20:31:24 UTC (rev 3580) @@ -34,7 +34,7 @@ import org.jnode.fs.nfs.nfs2.NFS2Device.Protocol; import org.jnode.fs.service.FileSystemService; import org.jnode.naming.InitialNaming; -import org.jnode.shell.Command; +import org.jnode.shell.AbstractCommand; import org.jnode.shell.CommandLine; import org.jnode.shell.help.Help; import org.jnode.shell.help.Parameter; @@ -48,7 +48,7 @@ /** * @author Andrei Dore */ -public class NFSMountCommand implements Command { +public class NFSMountCommand extends AbstractCommand { private static final FileArgument MOUNTPOINT_ARG = new FileArgument("directory", "the mountpoint"); private static final HostNameArgument HOST_ARG = new HostNameArgument("host", "NFS host"); private static final FileArgument REMOTE_DIRECTORY_ARG = new FileArgument("remoteDir", "remote directory"); @@ -76,11 +76,11 @@ PARAMETER_USER_ID, PARAMETER_GROUP_ID, PARAMETER_PROTOCOL })); public static void main(String[] args) throws Exception { - new NFSMountCommand().execute(new CommandLine(args), System.in, System.out, System.err); + new NFSMountCommand().execute(args); } public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) throws Exception { - ParsedArguments cmdLine = HELP_INFO.parse(commandLine.toStringArray()); + ParsedArguments cmdLine = HELP_INFO.parse(commandLine); final String mount_point = MOUNTPOINT_ARG.getValue(cmdLine); final String host = HOST_ARG.getValue(cmdLine); Modified: trunk/fs/src/fs/org/jnode/fs/smbfs/command/MakeSMBDeviceCommand.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/smbfs/command/MakeSMBDeviceCommand.java 2007-11-03 18:16:58 UTC (rev 3579) +++ trunk/fs/src/fs/org/jnode/fs/smbfs/command/MakeSMBDeviceCommand.java 2007-11-03 20:31:24 UTC (rev 3580) @@ -30,6 +30,7 @@ import org.jnode.fs.smbfs.SMBFSDriver; import org.jnode.fs.smbfs.SMBFileSystemType; import org.jnode.naming.InitialNaming; +import org.jnode.shell.AbstractCommand; import org.jnode.shell.CommandLine; import org.jnode.shell.help.Argument; import org.jnode.shell.help.Help; @@ -42,7 +43,7 @@ /** * @author Levente S\u00e1ntha */ -public class MakeSMBDeviceCommand { +public class MakeSMBDeviceCommand extends AbstractCommand { private static final Argument HOST_ARG = new Argument("host", "Samba host"); private static final Argument PATH_ARG = new Argument("path", "Samba path"); private static final Argument USERNAME_ARG = new Argument("username", "Samba username"); @@ -55,8 +56,7 @@ new Parameter(PASSWORD_ARG, Parameter.OPTIONAL)}); public static void main(String[] args) throws Exception { - new MakeSMBDeviceCommand().execute(new CommandLine(args), System.in, - System.out, System.err); + new MakeSMBDeviceCommand().execute(args); } /** @@ -69,7 +69,7 @@ * @throws Exception */ public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) throws Exception { - ParsedArguments cmdLine = HELP_INFO.parse(commandLine.toStringArray()); + ParsedArguments cmdLine = HELP_INFO.parse(commandLine); // Get the parameters final String host = HOST_ARG.getValue(cmdLine); Modified: trunk/fs/src/fs/org/jnode/fs/smbfs/command/SMBMountCommand.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/smbfs/command/SMBMountCommand.java 2007-11-03 18:16:58 UTC (rev 3579) +++ trunk/fs/src/fs/org/jnode/fs/smbfs/command/SMBMountCommand.java 2007-11-03 20:31:24 UTC (rev 3580) @@ -26,6 +26,7 @@ import org.jnode.shell.help.Parameter; import org.jnode.shell.help.ParsedArguments; import org.jnode.shell.help.argument.FileArgument; +import org.jnode.shell.AbstractCommand; import org.jnode.shell.CommandLine; import org.jnode.fs.service.FileSystemService; import org.jnode.fs.FileSystemType; @@ -43,7 +44,7 @@ /** * @author Levente S\u00e1ntha */ -public class SMBMountCommand { +public class SMBMountCommand extends AbstractCommand { private static final FileArgument MOUNTPOINT_ARG = new FileArgument("directory", "the mountpoint"); private static final Argument HOST_ARG = new Argument("host", "Samba host"); private static final Argument PATH_ARG = new Argument("path", "Samba path"); @@ -57,13 +58,12 @@ new Parameter(PASSWORD_ARG, Parameter.OPTIONAL)}); public static void main(String[] args) throws Exception { - new SMBMountCommand().execute(new CommandLine(args), System.in, - System.out, System.err); + new SMBMountCommand().execute(args); } public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) throws Exception { - ParsedArguments cmdLine = HELP_INFO.parse(commandLine.toStringArray()); + ParsedArguments cmdLine = HELP_INFO.parse(commandLine); final String mount_point = MOUNTPOINT_ARG.getValue(cmdLine); final String host = HOST_ARG.getValue(cmdLine); Modified: trunk/net/src/net/org/jnode/net/command/ArpCommand.java =================================================================== --- trunk/net/src/net/org/jnode/net/command/ArpCommand.java 2007-11-03 18:16:58 UTC (rev 3579) +++ trunk/net/src/net/org/jnode/net/command/ArpCommand.java 2007-11-03 20:31:24 UTC (rev 3580) @@ -28,7 +28,7 @@ import org.jnode.net.arp.ARPNetworkLayer; import org.jnode.net.ethernet.EthernetConstants; import org.jnode.net.util.NetUtils; -import org.jnode.shell.Command; +import org.jnode.shell.AbstractCommand; import org.jnode.shell.CommandLine; import org.jnode.shell.help.Help; import org.jnode.shell.help.Parameter; @@ -38,7 +38,7 @@ /** * @author epr */ -public class ArpCommand implements Command { +public class ArpCommand extends AbstractCommand { static final Parameter PARAM_DELETE = new Parameter("d", "delete the ARP cache", Parameter.MANDATORY); @@ -52,11 +52,11 @@ * Execute this command */ public static void main(String[] args) throws Exception { - new ArpCommand().execute(new CommandLine(args), System.in, System.out, System.err); + new ArpCommand().execute(args); } public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) throws Exception { - ParsedArguments cmdLine = HELP_INFO.parse(commandLine.toStringArray()); + ParsedArguments cmdLine = HELP_INFO.parse(commandLine); ARPNetworkLayer arp = (ARPNetworkLayer) NetUtils.getNLM().getNetworkLayer(EthernetConstants.ETH_P_ARP); if (PARAM_DELETE.isSet(cmdLine)) { Modified: trunk/net/src/net/org/jnode/net/command/BootpCommand.java =================================================================== --- trunk/net/src/net/org/jnode/net/command/BootpCommand.java 2007-11-03 18:16:58 UTC (rev 3579) +++ trunk/net/src/net/org/jnode/net/command/BootpCommand.java 2007-11-03 20:31:24 UTC (rev 3580) @@ -28,7 +28,7 @@ import org.jnode.driver.net.NetDeviceAPI; import org.jnode.naming.InitialNaming; import org.jnode.net.ipv4.config.IPv4ConfigurationService; -import org.jnode.shell.Command; +import org.jnode.shell.AbstractCommand; import org.jnode.shell.CommandLine; import org.jnode.shell.help.Help; import org.jnode.shell.help.Parameter; @@ -38,7 +38,7 @@ /** * @author epr */ -public class BootpCommand implements Command { +public class BootpCommand extends AbstractCommand { static final DeviceArgument ARG_DEVICE = new DeviceArgument("device", "the device to boot from", NetDeviceAPI.class); @@ -52,11 +52,11 @@ public static void main(String[] args) throws Exception { - new BootpCommand().execute(new CommandLine(args), System.in, System.out, System.err); + new BootpCommand().execute(args); } public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) throws Exception { - ParsedArguments cmdLine = HELP_INFO.parse(commandLine.toStringArray()); + ParsedArguments cmdLine = HELP_INFO.parse(commandLine); final Device dev = ARG_DEVICE.getDevice(cmdLine); System.out.println("Trying to configure " + dev.getId() + "..."); Modified: trunk/net/src/net/org/jnode/net/command/DhcpCommand.java =================================================================== --- trunk/net/src/net/org/jnode/net/command/DhcpCommand.java 2007-11-03 18:16:58 UTC (rev 3579) +++ trunk/net/src/net/org/jnode/net/command/DhcpCommand.java 2007-11-03 20:31:24 UTC (rev 3580) @@ -28,7 +28,7 @@ import org.jnode.driver.net.NetDeviceAPI; import org.jnode.naming.InitialNaming; import org.jnode.net.ipv4.config.IPv4ConfigurationService; -import org.jnode.shell.Command; +import org.jnode.shell.AbstractCommand; import org.jnode.shell.CommandLine; import org.jnode.shell.help.Help; import org.jnode.shell.help.Parameter; @@ -38,7 +38,7 @@ /** * @author markhale */ -public class DhcpCommand implements Command { +public class DhcpCommand extends AbstractCommand { static final DeviceArgument ARG_DEVICE = new DeviceArgument("device", "the device to boot from", NetDeviceAPI.class); @@ -52,11 +52,11 @@ public static void main(String[] args) throws Exception { - new DhcpCommand().execute(new CommandLine(args), System.in, System.out, System.err); + new DhcpCommand().execute(args); } public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) throws Exception { - ParsedArguments cmdLine = HELP_INFO.parse(commandLine.toStringArray()); + ParsedArguments cmdLine = HELP_INFO.parse(commandLine); final Device dev = ARG_DEVICE.getDevice(cmdLine); System.out.println("Trying to configure " + dev.getId() + "..."); Modified: trunk/net/src/net/org/jnode/net/command/IfconfigCommand.java =================================================================== --- trunk/net/src/net/org/jnode/net/command/IfconfigCommand.java 2007-11-03 18:16:58 UTC (rev 3579) +++ trunk/net/src/net/org/jnode/net/command/IfconfigCommand.java 2007-11-03 20:31:24 UTC (rev 3580) @@ -32,7 +32,7 @@ import org.jnode.net.help.argument.HostArgument; import org.jnode.net.ipv4.IPv4Address; import org.jnode.net.ipv4.config.IPv4ConfigurationService; -import org.jnode.shell.Command; +import org.jnode.shell.AbstractCommand; import org.jnode.shell.CommandLine; import org.jnode.shell.help.Help; import org.jnode.shell.help.Parameter; @@ -43,7 +43,7 @@ /** * @author epr */ -public class IfconfigCommand implements Command { +public class IfconfigCommand extends AbstractCommand { static final DeviceArgument ARG_DEVICE = new DeviceArgument("device", "the device", NetDeviceAPI.class); static final HostArgument ARG_IP_ADDRESS = new HostArgument("ip-address", "the IP address to bind the device to"); @@ -69,11 +69,11 @@ public static void main(String[] args) throws Exception { - new IfconfigCommand().execute(new CommandLine(args), System.in, System.out, System.err); + new IfconfigCommand().execute(args); } public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) throws Exception { - ParsedArguments cmdLine = HELP_INFO.parse(commandLine.toStringArray()); + ParsedArguments cmdLine = HELP_INFO.parse(commandLine); if( cmdLine.size() == 0 ) { final DeviceManager dm = (DeviceManager)InitialNaming.lookup(DeviceManager.NAME); Modified: trunk/net/src/net/org/jnode/net/command/NetCommand.java =================================================================== --- trunk/net/src/net/org/jnode/net/command/NetCommand.java 2007-11-03 18:16:58 UTC (rev 3579) +++ trunk/net/src/net/org/jnode/net/command/NetCommand.java 2007-11-03 20:31:24 UTC (rev 3580) @@ -11,6 +11,7 @@ import javax.net.ServerSocketFactory; import javax.net.SocketFactory; +import org.jnode.shell.AbstractCommand; import org.jnode.shell.CommandLine; import org.jnode.shell.help.Help; import org.jnode.shell.help.Parameter; @@ -19,7 +20,7 @@ import org.jnode.shell.help.argument.InetAddressArgument; import org.jnode.shell.help.argument.IntegerArgument; -public class NetCommand { +public class NetCommand extends AbstractCommand { private static final InetAddressArgument ARG_HOST = new InetAddressArgument( "ip-address", "the IP-address of the server to contact"); @@ -40,13 +41,13 @@ /** * @param args */ - public static void main(String[] sArgs) throws Exception { - new NetCommand().execute(new CommandLine(sArgs), System.in, System.out, System.err); + public static void main(String[] args) throws Exception { + new NetCommand().execute(args); } public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) throws Exception { - ParsedArguments args = HELP_INFO.parse(commandLine.toStringArray()); + ParsedArguments args = HELP_INFO.parse(commandLine); Socket socket = null; if (PARAM_LISTEN.isSet(args)) { Modified: trunk/net/src/net/org/jnode/net/command/NetstatCommand.java =================================================================== --- trunk/net/src/net/org/jnode/net/command/NetstatCommand.java 2007-11-03 18:16:58 UTC (rev 3579) +++ trunk/net/src/net/org/jnode/net/command/NetstatCommand.java 2007-11-03 20:31:24 UTC (rev 3580) @@ -29,7 +29,7 @@ import org.jnode.net.NetworkLayerManager; import org.jnode.net.TransportLayer; import org.jnode.net.util.NetUtils; -import org.jnode.shell.Command; +import org.jnode.shell.AbstractCommand; import org.jnode.shell.CommandLine; import org.jnode.shell.help.Help; import org.jnode.util.Statistic; @@ -38,7 +38,7 @@ /** * @author epr */ -public class NetstatCommand implements Command { +public class NetstatCommand extends AbstractCommand { public static Help.Info HELP_INFO = new Help.Info( "netstat", @@ -47,7 +47,7 @@ public static void main(String[] args) throws Exception { - new NetstatCommand().execute(new CommandLine(args), System.in, System.out, System.err); + new NetstatCommand().execute(args); } /** Modified: trunk/net/src/net/org/jnode/net/command/ResolverCommand.java =================================================================== --- trunk/net/src/net/org/jnode/net/command/ResolverCommand.java 2007-11-03 18:16:58 UTC (rev 3579) +++ trunk/net/src/net/org/jnode/net/command/ResolverCommand.java 2007-11-03 20:31:24 UTC (rev 3580) @@ -28,7 +28,7 @@ import org.jnode.net.help.argument.HostArgument; import org.jnode.net.ipv4.IPv4Address; import org.jnode.net.ipv4.util.ResolverImpl; -import org.jnode.shell.Command; +import org.jnode.shell.AbstractCommand; import org.jnode.shell.CommandLine; import org.jnode.shell.help.Help; import org.jnode.shell.help.Parameter; @@ -37,7 +37,7 @@ import org.jnode.shell.help.argument.OptionArgument; -public class ResolverCommand implements Command +public class ResolverCommand extends AbstractCommand { private static final String FUNC_ADD = "add"; private static final String FUNC_DEL = "del"; @@ -67,12 +67,12 @@ public static void main(String[] args) throws Exception { - new ResolverCommand().execute(new CommandLine(args), System.in, System.out, System.err); + new ResolverCommand().execute(args); } public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) throws Exception { - ParsedArguments cmdLine = HELP_INFO.parse(commandLine.toStringArray()); + ParsedArguments cmdLine = HELP_INFO.parse(commandLine); if (cmdLine.size() == 0) { Modified: trunk/net/src/net/org/jnode/net/command/RouteCommand.java =================================================================== --- trunk/net/src/net/org/jnode/net/command/RouteCommand.java 2007-11-03 18:16:58 UTC (rev 3579) +++ trunk/net/src/net/org/jnode/net/command/RouteCommand.java 2007-11-03 20:31:24 UTC (rev 3580) @@ -33,7 +33,7 @@ import org.jnode.net.ipv4.config.IPv4ConfigurationService; import org.jnode.net.ipv4.layer.IPv4NetworkLayer; import org.jnode.net.util.NetUtils; -import org.jnode.shell.Command; +import org.jnode.shell.AbstractCommand; import org.jnode.shell.CommandLine; import org.jnode.shell.help.Help; import org.jnode.shell.help.Parameter; @@ -45,8 +45,8 @@ /** * @author epr */ -public class RouteCommand implements EthernetConstants, Command { - +public class RouteCommand extends AbstractCommand implements EthernetConstants { + // FIXME the "constants interface" anti-pattern. static final String FUNC_ADD = "add"; static final String FUNC_DEL = "del"; @@ -75,11 +75,11 @@ }); public static void main(String[] args) throws Exception { - new RouteCommand().execute(new CommandLine(args), System.in, System.out, System.err); + new RouteCommand().execute(args); } public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) throws Exception { - ParsedArguments cmdLine = HELP_INFO.parse(commandLine.toStringArray()); + ParsedArguments cmdLine = HELP_INFO.parse(commandLine); final IPv4NetworkLayer ipNL = (IPv4NetworkLayer) NetUtils.getNLM().getNetworkLayer(ETH_P_IP); Modified: trunk/net/src/net/org/jnode/net/command/RpcInfoCommand.java =================================================================== --- trunk/net/src/net/org/jnode/net/command/RpcInfoCommand.java 2007-11-03 18:16:58 UTC (rev 3579) +++ trunk/net/src/net/org/jnode/net/command/RpcInfoCommand.java 2007-11-03 20:31:24 UTC (rev 3580) @@ -30,6 +30,7 @@ import org.acplt.oncrpc.OncRpcPortmapClient; import org.acplt.oncrpc.OncRpcProtocols; import org.acplt.oncrpc.OncRpcServerIdent; +import org.jnode.shell.AbstractCommand; import org.jnode.shell.CommandLine; import org.jnode.shell.help.Help; import org.jnode.shell.help.Parameter; @@ -42,7 +43,7 @@ * * @author Andrei Dore */ -public class RpcInfoCommand { +public class RpcInfoCommand extends AbstractCommand { private static final String LIST_SERVICES_FORMAT = "%1$10s %2$10s %3$10s %4$10s %5$10s"; @@ -54,7 +55,7 @@ public static void main(String[] args) throws Exception { - new RpcInfoCommand().execute(new CommandLine(args), System.in, System.out, System.err); + new RpcInfoCommand().execute(args); } @@ -63,7 +64,7 @@ public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) throws Exception { - ParsedArguments parsedArguments = HELP_INFO.parse(commandLine.toStringArray()); + ParsedArguments parsedArguments = HELP_INFO.parse(commandLine); InetAddress host = HOST.getAddress(parsedArguments); @@ -93,8 +94,10 @@ } } catch (OncRpcException e) { err.println("Can not make the rpc call to the host " + host.getHostAddress()); + exit(1); } catch (IOException e) { err.println("Can not connect to the host " + host.getHostAddress()); + exit(1); } finally { if (client != null) { try { Modified: trunk/net/src/net/org/jnode/net/command/TftpCommand.java =================================================================== --- trunk/net/src/net/org/jnode/net/command/TftpCommand.java 2007-11-03 18:16:58 UTC (rev 3579) +++ trunk/net/src/net/org/jnode/net/command/TftpCommand.java 2007-11-03 20:31:24 UTC (rev 3580) @@ -26,7 +26,7 @@ import org.jnode.net.help.argument.HostArgument; import org.jnode.net.ipv4.tftp.TFTPClient; -import org.jnode.shell.Command; +import org.jnode.shell.AbstractCommand; import org.jnode.shell.CommandLine; import org.jnode.shell.help.Argument; import org.jnode.shell.help.Help; @@ -37,7 +37,7 @@ /** * @author markhale */ -public class TftpCommand implements Command { +public class TftpCommand extends AbstractCommand { private static final OptionArgument.Option[] COMMAND_OPTIONS = new OptionArgument.Option[] { new OptionArgument.Option("put", "transfer a file to a server"), @@ -68,11 +68,11 @@ ); public static void main(String[] args) throws Exception { - new TftpCommand().execute(new CommandLine(args), System.in, System.out, System.err); + new TftpCommand().execute(args); } public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) throws Exception { - TFTPClient.main(commandLine.toStringArray()); + TFTPClient.main(commandLine.getArguments()); System.out.println(); } } Modified: trunk/net/src/net/org/jnode/net/command/WLanCtlCommand.java =================================================================== --- trunk/net/src/net/org/jnode/net/command/WLanCtlCommand.java 2007-11-03 18:16:58 UTC (rev 3579) +++ trunk/net/src/net/org/jnode/net/command/WLanCtlCommand.java 2007-11-03 20:31:24 UTC (rev 3580) @@ -29,7 +29,7 @@ import org.jnode.driver.Device; import org.jnode.driver.net.NetworkException; import org.jnode.driver.net.WirelessNetDeviceAPI; -import org.jnode.shell.Command; +import org.jnode.shell.AbstractCommand; import org.jnode.shell.CommandLine; import org.jnode.shell.help.Argument; import org.jnode.shell.help.Help; @@ -42,7 +42,7 @@ /** * @author Ewout Prangsma (ep...@us...) */ -public class WLanCtlCommand implements Command { +public class WLanCtlCommand extends AbstractCommand { private static final String FUNC_SETESSID = "setessid"; @@ -66,7 +66,7 @@ private static final Logger log = Logger.getLogger(HELP_INFO.getName()); public static void main(String[] args) throws Exception, SyntaxErrorException { - new WLanCtlCommand().execute(new CommandLine(args), System.in, System.out, System.err); + new WLanCtlCommand().execute(args); } private static void setESSID(Device dev, WirelessNetDeviceAPI api, @@ -77,7 +77,7 @@ } public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) throws Exception { - ParsedArguments cmdLine = HELP_INFO.parse(commandLine.toStringArray()); + ParsedArguments cmdLine = HELP_INFO.parse(commandLine); final Device dev = ARG_DEVICE.getDevice(cmdLine); final WirelessNetDeviceAPI api; @@ -86,7 +86,8 @@ } catch (ApiNotFoundException e) { System.err.println("Device " + dev.getId() + " is not a wireless network device"); - return; + exit(2); + return; // not reached } // Get the function @@ -96,11 +97,13 @@ setESSID(dev, api, cmdLine); } else { System.err.println("Unknown function " + function); + exit(3); } } catch (NetworkException ex) { System.err.println("Function " + function + " failed: " + ex.getMessage()); log.debug("Function " + function + " failed", ex); + exit(1); } } } Added: trunk/shell/src/shell/org/jnode/shell/AbstractCommand.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/AbstractCommand.java (rev 0) +++ trunk/shell/src/shell/org/jnode/shell/AbstractCommand.java 2007-11-03 20:31:24 UTC (rev 3580) @@ -0,0 +1,20 @@ +package org.jnode.shell; + +import org.jnode.vm.VmExit; + +public abstract class AbstractCommand implements Command { + + @SuppressWarnings("deprecation") + public final void execute(String[] args) throws Exception { + execute(new CommandLine(args), System.in, System.out, System.err); + } + + + /** + * Exit this command with the given return code. + * @param rc + */ + protected void exit(int rc) { + throw new VmExit(rc); + } +} Modified: trunk/shell/src/shell/org/jnode/shell/AsyncCommandInvoker.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/AsyncCommandInvoker.java 2007-11-03 18:16:58 UTC (rev 3579) +++ trunk/shell/src/shell/org/jnode/shell/AsyncCommandInvoker.java 2007-11-03 20:31:24 UTC (rev 3580) @@ -25,7 +25,6 @@ import java.awt.event.KeyEvent; import java.io.Closeable; import java.io.InputStream; -import java.io.OutputStream; import java.io.PrintStream; import java.lang.reflect.Method; import java.lang.reflect.Modifier; @@ -68,7 +67,7 @@ public AsyncCommandInvoker(CommandShell commandShell) { this.commandShell = commandShell; - this.err = commandShell.getErrorStream(); + this.err = commandShell.resolvePrintStream(CommandLine.DEFAULT_STDERR); commandShell.getConsole().addKeyboardListener(this);// listen for // ctrl-c } @@ -78,7 +77,7 @@ if (cmdInfo == null) { return 0; } - Runnable cr = setup(cmdLine, cmdInfo); + CommandRunner cr = set... [truncated message content] |
From: <ls...@us...> - 2007-11-03 21:23:09
|
Revision: 3581 http://jnode.svn.sourceforge.net/jnode/?rev=3581&view=rev Author: lsantha Date: 2007-11-03 14:23:08 -0700 (Sat, 03 Nov 2007) Log Message: ----------- Initial version of the Bjorne shell implementation by crawley. Modified Paths: -------------- trunk/all/conf/full-plugin-list.xml Added Paths: ----------- trunk/shell/descriptors/org.jnode.shell.bjorne.xml trunk/shell/descriptors/org.jnode.shell.command.unix.xml trunk/shell/src/shell/org/jnode/shell/bjorne/ trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneBuiltin.java trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneContext.java trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneContextTests.java trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneControlException.java trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneInterpreter.java trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneParser.java trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneParserTests.java trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneShellPlugin.java trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneToken.java trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneTokenizer.java trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneTokenizerTests.java trunk/shell/src/shell/org/jnode/shell/bjorne/BreakBuiltin.java trunk/shell/src/shell/org/jnode/shell/bjorne/CaseCommandNode.java trunk/shell/src/shell/org/jnode/shell/bjorne/CaseItemNode.java trunk/shell/src/shell/org/jnode/shell/bjorne/CommandNode.java trunk/shell/src/shell/org/jnode/shell/bjorne/ContinueBuiltin.java trunk/shell/src/shell/org/jnode/shell/bjorne/ExitBuiltin.java trunk/shell/src/shell/org/jnode/shell/bjorne/ForCommandNode.java trunk/shell/src/shell/org/jnode/shell/bjorne/FunctionDefinitionNode.java trunk/shell/src/shell/org/jnode/shell/bjorne/IfCommandNode.java trunk/shell/src/shell/org/jnode/shell/bjorne/ListCommandNode.java trunk/shell/src/shell/org/jnode/shell/bjorne/LoopCommandNode.java trunk/shell/src/shell/org/jnode/shell/bjorne/Redirection.java trunk/shell/src/shell/org/jnode/shell/bjorne/RedirectionNode.java trunk/shell/src/shell/org/jnode/shell/bjorne/ReturnBuiltin.java trunk/shell/src/shell/org/jnode/shell/bjorne/SimpleCommandNode.java trunk/shell/src/shell/org/jnode/shell/bjorne/SourceBuiltin.java Modified: trunk/all/conf/full-plugin-list.xml =================================================================== --- trunk/all/conf/full-plugin-list.xml 2007-11-03 20:31:24 UTC (rev 3580) +++ trunk/all/conf/full-plugin-list.xml 2007-11-03 21:23:08 UTC (rev 3581) @@ -28,4 +28,7 @@ <plugin id="thinlet"/> + + <plugin id="org.jnode.shell.bjorne"/> + <plugin id="org.jnode.shell.command.unix"/> </plugin-list> Added: trunk/shell/descriptors/org.jnode.shell.bjorne.xml =================================================================== --- trunk/shell/descriptors/org.jnode.shell.bjorne.xml (rev 0) +++ trunk/shell/descriptors/org.jnode.shell.bjorne.xml 2007-11-03 21:23:08 UTC (rev 3581) @@ -0,0 +1,32 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plugin SYSTEM "jnode.dtd"> + +<plugin id="org.jnode.shell.bjorne" + name="JNode Bjorne Shell" + version="@VERSION@" + license-name="lgpl" + provider-name="JNode.org" + class="org.jnode.shell.bjorne.BjorneShellPlugin"> + + <requires> + <import plugin="org.jnode.shell.help"/> + <import plugin="org.jnode.shell"/> + </requires> + + <runtime> + <library name="jnode-shell.jar"> + <export name="org.jnode.shell.bjorne.*"/> + </library> + </runtime> + + <extension point="org.jnode.security.permissions"> + <permission class="java.io.FilePermission" name="<<ALL FILES>>" actions="read,write"/> + <permission class="java.lang.RuntimePermission" name="setSecurityManager" actions="*" /> + <permission class="java.lang.RuntimePermission" name="createClassLoader" actions="*" /> + <permission class="java.lang.RuntimePermission" name="setIO" actions="*" /> + <permission class="java.lang.RuntimePermission" name="exitVM" actions="*" /> + <permission class="org.jnode.security.JNodePermission" name="getVmClass" actions="*" /> + <permission class="java.util.PropertyPermission" name="*" actions="read,write"/> + </extension> + +</plugin> Added: trunk/shell/descriptors/org.jnode.shell.command.unix.xml =================================================================== --- trunk/shell/descriptors/org.jnode.shell.command.unix.xml (rev 0) +++ trunk/shell/descriptors/org.jnode.shell.command.unix.xml 2007-11-03 21:23:08 UTC (rev 3581) @@ -0,0 +1,42 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plugin SYSTEM "jnode.dtd"> + +<plugin id="org.jnode.shell.command.unix" + name="JNode System Commands" + version="@VERSION@" + license-name="lgpl" + provider-name="JNode.org"> + + <requires> + <import plugin="org.jnode.shell.help"/> + </requires> + + <runtime> + <library name="jnode-shell.jar"> + <export name="org.jnode.shell.command.unix.*"/> + </library> + </runtime> + + <extension point="org.jnode.shell.aliases"> + <alias name="test" class="org.jnode.shell.command.unix.UnixTestCommand"/> + <alias name="[" class="org.jnode.shell.command.unix.UnixTestCommand"/> + </extension> + + <extension point="org.jnode.security.permissions"> + <permission class="java.util.PropertyPermission" name="*" actions="read,write"/> + <permission class="java.lang.RuntimePermission" name="getProtectionDomain"/> + <permission class="java.lang.RuntimePermission" name="createClassLoader"/> + <permission class="java.lang.RuntimePermission" name="setContextClassLoader"/> + <permission class="java.lang.RuntimePermission" name="modifyThreadGroup"/> + <permission class="java.lang.RuntimePermission" name="setIO" actions="*" /> + <permission class="java.lang.RuntimePermission" name="exitVM" actions="*" /> + <permission class="java.io.FilePermission" name="<<ALL FILES>>" actions="read,write"/> + <permission class="org.jnode.security.JNodePermission" name="getVmThread"/> + <permission class="org.jnode.security.JNodePermission" name="getVmClass"/> + <permission class="java.net.SocketPermission" name="*" actions="resolve"/> + <permission class="java.net.SocketPermission" name="*:0-" actions="connect,resolve"/> + <permission class="java.lang.RuntimePermission" name="writeFileDescriptor"/> + <permission class="java.lang.RuntimePermission" name="readFileDescriptor"/> + </extension> + +</plugin> Added: trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneBuiltin.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneBuiltin.java (rev 0) +++ trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneBuiltin.java 2007-11-03 21:23:08 UTC (rev 3581) @@ -0,0 +1,15 @@ +package org.jnode.shell.bjorne; + +import org.jnode.shell.CommandLine; +import org.jnode.shell.ShellException; + +abstract class BjorneBuiltin { + + abstract int invoke(CommandLine command, BjorneInterpreter interpreter, + BjorneContext context) throws ShellException; + + void error(String msg, BjorneContext context) { + context.resolvePrintStream(context.getStream(2)).println(msg); + } + +} Added: trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneContext.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneContext.java (rev 0) +++ trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneContext.java 2007-11-03 21:23:08 UTC (rev 3581) @@ -0,0 +1,943 @@ +package org.jnode.shell.bjorne; + +import static org.jnode.shell.bjorne.BjorneInterpreter.REDIR_CLOBBER; +import static org.jnode.shell.bjorne.BjorneInterpreter.REDIR_DGREAT; +import static org.jnode.shell.bjorne.BjorneInterpreter.REDIR_DLESS; +import static org.jnode.shell.bjorne.BjorneInterpreter.REDIR_DLESSDASH; +import static org.jnode.shell.bjorne.BjorneInterpreter.REDIR_GREAT; +import static org.jnode.shell.bjorne.BjorneInterpreter.REDIR_GREATAND; +import static org.jnode.shell.bjorne.BjorneInterpreter.REDIR_LESS; +import static org.jnode.shell.bjorne.BjorneInterpreter.REDIR_LESSAND; +import static org.jnode.shell.bjorne.BjorneInterpreter.REDIR_LESSGREAT; + +import java.io.ByteArrayOutputStream; +import java.io.Closeable; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.jnode.shell.CommandLine; +import org.jnode.shell.CommandThread; +import org.jnode.shell.ShellException; +import org.jnode.shell.ShellFailureException; +import org.jnode.shell.ShellSyntaxException; +import org.jnode.shell.StreamMarker; + +/** + * This class holds the shell variable and stream state for a bjorne shell + * context. A parent context persists between calls to the shell's + * <code>interpret</code> method to hold the global shell variables. Others + * are created as required to hold the (umm) lexically scoped state for + * individual commands, pipelines, subshells and function calls. + * + * @author cr...@jn... + */ +public class BjorneContext { + + public static final StreamMarker PIPE_IN = new StreamMarker("PIPEIN"); + + public static final StreamMarker PIPE_OUT = new StreamMarker("PIPEOUT"); + + private static final int NONE = 0; + + private static final int PREHASH = 1; + + private static final int HASH = 2; + + private static final int DHASH = 3; + + private static final int PERCENT = 4; + + private static final int DPERCENT = 5; + + private static final int HYPHEN = 6; + + private static final int COLONHYPHEN = 7; + + private static final int EQUALS = 8; + + private static final int COLONEQUALS = 9; + + private static final int PLUS = 10; + + private static final int COLONPLUS = 11; + + private static final int QUERY = 12; + + private static final int COLONQUERY = 13; + + private final BjorneInterpreter interpreter; + + private Map<String, VariableSlot> variables; + + private String command = ""; + + private List<String> args = new ArrayList<String>(); + + private int lastReturnCode; + + private int shellPid; + + private int lastAsyncPid; + + private String options = ""; + + private StreamHolder[] holders; + + private static class VariableSlot { + public String value; + + public boolean exported; + + public VariableSlot(String value, boolean exported) { + if (value == null) { + throw new ShellFailureException("null value"); + } + this.value = value; + this.exported = exported; + } + + public VariableSlot(VariableSlot other) { + this.value = other.value; + this.exported = other.exported; + } + } + + static class StreamHolder { + public final Closeable stream; + + private boolean isMine; + + public StreamHolder(Closeable stream, boolean isMine) { + this.stream = stream; + this.isMine = isMine; + } + + public StreamHolder(StreamHolder other) { + this.stream = other.stream; + this.isMine = false; + } + + public void close() { + if (isMine) { + try { + isMine = false; // just in case we call close twice + stream.close(); + } catch (IOException ex) { + // FIXME - should we squash or report this? + } + } + } + + public boolean isMine() { + return isMine; + } + } + + private static class CharIterator { + CharSequence str; + + int pos; + + int start; + + int limit; + + public CharIterator(CharSequence str) { + this.str = str; + this.start = pos = 0; + this.limit = str.length(); + } + + public CharIterator(CharSequence str, int start, int limit) { + this.str = str; + this.start = pos = start; + this.limit = limit; + } + + public int nextCh() { + return (pos >= limit) ? -1 : str.charAt(pos++); + } + + public int peekCh() { + return (pos >= limit) ? -1 : str.charAt(pos); + } + + public int lastCh() { + return (pos > start) ? str.charAt(pos - 1) : -1; + } + } + + /** + * Crreat a copy of a context with the same initial variable bindings and + * streams. Stream ownership is not transferred. + * + * @param parent + * the context that gives us our initial state. + */ + public BjorneContext(BjorneContext parent) { + this.interpreter = parent.interpreter; + this.holders = copyStreamHolders(parent.holders); + this.variables = copyVariables(parent.variables); + } + + /** + * Create a deep copy of some variable bindings + */ + private Map<String, VariableSlot> copyVariables( + Map<String, VariableSlot> variables) { + Map<String, VariableSlot> res = new HashMap<String, VariableSlot>( + variables.size()); + for (Map.Entry<String, VariableSlot> entry : variables.entrySet()) { + res.put(entry.getKey(), new VariableSlot(entry.getValue())); + } + return res; + } + + /** + * Create a copy of some stream holders without passing ownership. + */ + public static StreamHolder[] copyStreamHolders(StreamHolder[] holders) { + StreamHolder[] res = new StreamHolder[holders.length]; + for (int i = 0; i < res.length; i++) { + res[i] = new StreamHolder(holders[i]); + } + return res; + } + + StreamHolder[] getCopyOfHolders() { + return copyStreamHolders(holders); + } + + public BjorneContext(BjorneInterpreter interpreter, StreamHolder[] holders) { + this.interpreter = interpreter; + this.holders = holders; + this.variables = new HashMap<String, VariableSlot>(); + } + + public BjorneContext(BjorneInterpreter interpreter) { + this(interpreter, new StreamHolder[] { + new StreamHolder(CommandLine.DEFAULT_STDIN, false), + new StreamHolder(CommandLine.DEFAULT_STDOUT, false), + new StreamHolder(CommandLine.DEFAULT_STDERR, false) }); + } + + /** + * This method implements 'NAME=VALUE'. If variable NAME does not exist, it + * is created as an unexported shell variable. + * + * @param name + * the name of the variable to be set + * @param value + * a non-null value for the variable + */ + public void setVariable(String name, String value) { + value.length(); // Check that the value is non-null. + VariableSlot var = variables.get(name); + if (var == null) { + variables.put(name, new VariableSlot(value, false)); + } else { + var.value = value; + } + } + + /** + * Test if the variable is currently set here on in an ancestor context. + * + * @param name + * the name of the variable to be tested + * @return <code>true</code> if the variable is set. + */ + public boolean isVariableSet(String name) { + return variables.get(name) != null; + } + + /** + * This method implements 'unset NAME' + * + * @param name + * the name of the variable to be unset + */ + public void unsetVariableValue(String name) { + variables.remove(name); + } + + /** + * This method implements 'export NAME' or 'unexport NAME'. + * + * @param name + * the name of the variable to be exported / unexported + */ + public void setExported(String name, boolean exported) { + VariableSlot var = variables.get(name); + if (var == null) { + if (exported) { + variables.put(name, new VariableSlot("", exported)); + } + } else { + var.exported = exported; + } + } + + /** + * Perform expand-and-split processing on an array of word/name tokens + * + * @param tokens + * the tokens to be expanded and split into words + * @return the resulting words + * @throws ShellException + */ + public CommandLine expandAndSplit(BjorneToken[] tokens) + throws ShellException { + StringBuffer sb = new StringBuffer(); + for (BjorneToken token : tokens) { + if (sb.length() != 0) { + sb.append(' '); + } + sb.append(expand(token.getText())); + } + LinkedList<String> words = split(sb); + return makeCommandLine(words); + } + + /** + * Perform expand-and-split processing on sequence of characters + * + * @param text + * the characters to be split + * @return the resulting words + * @throws ShellException + */ + public CommandLine expandAndSplit(CharSequence text) throws ShellException { + LinkedList<String> words = split(expand(text)); + return makeCommandLine(words); + } + + private CommandLine makeCommandLine(LinkedList<String> words) { + int nosWords = words.size(); + if (nosWords == 0) { + return new CommandLine(null, null); + } else if (nosWords == 1) { + return new CommandLine(words.get(0), null); + } else { + String commandName = words.removeFirst(); + return new CommandLine(commandName, words + .toArray(new String[nosWords - 1])); + } + } + + /** + * Split a character sequence into words, dealing with and removing any + * non-literal quotes. + * + * @param text + * the characters to be split + * @return the resulting list of words. + * @throws ShellException + */ + public LinkedList<String> split(CharSequence text) throws ShellException { + LinkedList<String> words = new LinkedList<String>(); + StringBuffer sb = null; + int len = text.length(); + int quote = 0; + int quoteStart = -1; + for (int i = 0; i < len; i++) { + char ch = text.charAt(i); + switch (ch) { + case '"': + case '`': + case '\'': + if (quote == 0) { + quote = ch; + if (sb == null) { + sb = new StringBuffer(); + } + quoteStart = sb.length(); + } else if (quote == ch) { + if (quote == '`') { + String backtickResult = runBacktickCommand(sb + .substring(quoteStart)); + sb.replace(quoteStart, sb.length(), backtickResult); + } + quote = 0; + } else { + sb = accumulate(sb, ch); + } + break; + case ' ': + case '\t': + if (quote == 0) { + if (sb != null) { + words.add(sb.toString()); + sb = null; + } + } else { + sb = accumulate(sb, ch); + } + break; + case '\\': + if (i + 1 < len) { + ch = text.charAt(++i); + } + sb = accumulate(sb, ch); + break; + default: + sb = accumulate(sb, ch); + } + } + if (sb != null) { + words.add(sb.toString()); + } + return words; + } + + private String runBacktickCommand(String commandLine) throws ShellException { + ByteArrayOutputStream capture = new ByteArrayOutputStream(); + interpreter.interpret(interpreter.getShell(), commandLine, capture, + false); + String output = capture.toString(); + int i; + for (i = output.length(); i > 0 && output.charAt(i - 1) == '\n'; i--) { /**/ + } + return output.substring(0, i); + } + + private StringBuffer accumulate(StringBuffer sb, char ch) { + if (sb == null) { + sb = new StringBuffer(); + } + sb.append(ch); + return sb; + } + + /** + * Perform '$' expansions. Any quotes and escapes should be preserved. + * + * @param text + * the characters to be expanded + * @return the result of the expansion. + * @throws ShellException + */ + public CharSequence expand(CharSequence text) throws ShellException { + if (text instanceof String && ((String) text).indexOf('$') == -1) { + return text; + } + if (text instanceof StringBuffer + && ((StringBuffer) text).indexOf("$") == -1) { + return text; + } + CharIterator ci = new CharIterator(text); + StringBuffer sb = new StringBuffer(text.length()); + char quote = 0; + int ch = ci.nextCh(); + while (ch != -1) { + switch (ch) { + case '"': + case '\'': + if (quote == 0) { + quote = (char) ch; + } else if (quote == ch) { + quote = 0; + } + sb.append((char) ch); + break; + case '`': + sb.append((char) ch); + break; + case ' ': + case '\t': + sb.append(' '); + while ((ch = ci.peekCh()) == ' ' || ch == '\t') { + ci.nextCh(); + } + break; + case '\\': + sb.append((char) ch); + if ((ch = ci.nextCh()) != -1) { + sb.append((char) ch); + } + break; + case '$': + if (quote == '\'') { + sb.append('$'); + } else { + sb.append(dollarExpansion(ci, quote)); + } + break; + + default: + sb.append((char) ch); + } + ch = ci.nextCh(); + } + return sb; + } + + private String dollarExpansion(CharIterator ci, char quote) + throws ShellSyntaxException { + int ch = ci.nextCh(); + switch (ch) { + case -1: + return "$"; + case '{': + return dollarBraceExpansion(ci); + case '(': + return dollarParenExpansion(ci); + case '$': + case '#': + case '@': + case '*': + case '?': + case '!': + case '-': + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + return specialVariable(ch); + default: + StringBuffer sb = new StringBuffer().append((char) ch); + ch = ci.peekCh(); + while ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') + || (ch >= 'a' && ch <= 'z') || ch == '_') { + sb.append((char) ch); + ci.nextCh(); + ch = ci.peekCh(); + } + VariableSlot var = variables.get(sb.toString()); + return (var != null) ? var.value : ""; + } + } + + private String dollarBraceExpansion(CharIterator ci) + throws ShellSyntaxException { + // Scan to the '}' that matches the '${' + StringBuffer sb = new StringBuffer(); + int braceLevel = 1; + int ch = ci.nextCh(); + int quote = 0; + LOOP: while (ch != -1) { + switch (ch) { + case '}': + if (quote == 0) { + braceLevel--; + if (braceLevel == 0) { + break LOOP; + } + } + break; + case '{': + if (quote == 0) { + braceLevel++; + } + break; + case '\\': + sb.append((char) ch); + ch = ci.nextCh(); + break; + case '"': + case '\'': + if (quote == 0) { + quote = ch; + } else if (quote == ch) { + quote = 0; + } + break; + default: + } + if (ch != -1) { + sb.append((char) ch); + } + ch = ci.nextCh(); + } + + // Deal with case where the braces are empty ... + if (sb.length() == 0) { + return ""; + } + + // Extract the parameter name, noting a leading '#' operator + int operator = NONE; + int i; + LOOP: for (i = 0; i < sb.length(); i++) { + char ch2 = sb.charAt(i); + switch (ch2) { + case '#': + if (i == 0) { + operator = PREHASH; + } else { + break LOOP; + } + break; + case '%': + case ':': + case '=': + case '?': + case '+': + case '-': + break LOOP; + default: + // Include this in the parameter name for now. + } + } + + String parameter = sb.substring(operator == NONE ? 0 : 1, i); + String word = null; + + if (i < sb.length()) { + // Work out what the operator is ... + char opch = sb.charAt(i); + char opch2 = (i + 1 < sb.length()) ? sb.charAt(i + 1) : (char) 0; + switch (opch) { + case '#': + operator = (opch2 == '#') ? DHASH : HASH; + break; + case '%': + operator = (opch2 == '%') ? DPERCENT : PERCENT; + break; + case ':': + switch (opch2) { + case '=': + operator = COLONEQUALS; + break; + case '+': + operator = COLONPLUS; + break; + case '?': + operator = COLONQUERY; + break; + case '-': + operator = COLONHYPHEN; + break; + default: + throw new ShellSyntaxException("bad substitution"); + } + break; + case '=': + operator = EQUALS; + break; + case '?': + operator = QUERY; + break; + case '+': + operator = PLUS; + break; + case '-': + operator = HYPHEN; + break; + default: + throw new ShellFailureException("bad state"); + } + // Adjust for two-character operators + switch (operator) { + case EQUALS: + case QUERY: + case PLUS: + case HYPHEN: + case HASH: + case PERCENT: + break; + default: + i++; + } + // Extract the word + if (i >= sb.length()) { + throw new ShellSyntaxException("bad substitution"); + } + word = sb.substring(i); + } + String value = variable(parameter); + switch (operator) { + case NONE: + return (value != null) ? value : ""; + case PREHASH: + return (value != null) ? Integer.toString(value.length()) : "0"; + default: + throw new ShellFailureException("not implemented"); + } + } + + private String variable(String parameter) throws ShellSyntaxException { + if (parameter.length() == 1) { + String tmp = specialVariable(parameter.charAt(0)); + if (tmp != null) { + return tmp; + } + } + if (BjorneToken.isName(parameter)) { + VariableSlot var = variables.get(parameter); + return (var != null) ? var.value : null; + } else { + try { + int argNo = Integer.parseInt(parameter); + return argVariable(argNo); + } catch (NumberFormatException ex) { + throw new ShellSyntaxException("bad substitution"); + } + } + } + + private String specialVariable(int ch) { + switch (ch) { + case '$': + return Integer.toString(shellPid); + case '#': + return Integer.toString(args.size()); + case '@': + case '*': + throw new ShellFailureException("not implemented"); + case '?': + return Integer.toString(lastReturnCode); + case '!': + return Integer.toString(lastAsyncPid); + case '-': + return options; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + return argVariable(ch - '0'); + default: + return null; + } + } + + private String argVariable(int argNo) { + if (argNo == 0) { + return command; + } else if (argNo <= args.size()) { + return args.get(argNo); + } else { + return ""; + } + } + + public boolean isSet(String name) { + return variables.get(name) != null; + } + + private String dollarParenExpansion(CharIterator ci) { + throw new ShellFailureException("not implemented"); + } + + int execute(CommandLine command, Closeable[] streams) throws ShellException { + lastReturnCode = interpreter.executeCommand(command, this, streams); + return lastReturnCode; + } + + PrintStream resolvePrintStream(Closeable stream) { + return interpreter.resolvePrintStream(stream); + } + + InputStream resolveInputStream(Closeable stream) { + return interpreter.resolveInputStream(stream); + } + + Closeable getStream(int index) { + if (index < 0) { + throw new ShellFailureException("negative stream index"); + } else if (index < holders.length) { + return holders[index].stream; + } else { + return null; + } + } + + public boolean isNoClobber() { + return isVariableSet("NOCLOBBER"); + } + + final int getLastAsyncPid() { + return lastAsyncPid; + } + + final int getLastReturnCode() { + return lastReturnCode; + } + + final int getShellPid() { + return shellPid; + } + + void performAssignments(BjorneToken[] assignments) throws ShellException { + if (assignments != null) { + for (int i = 0; i < assignments.length; i++) { + String assignment = assignments[i].getText(); + int pos = assignment.indexOf('='); + if (pos <= 0) { + throw new ShellFailureException( + "misplaced '=' in assignment"); + } + String name = assignment.substring(0, pos); + String value = this.expand(assignment.substring(pos + 1)) + .toString(); + this.setVariable(name, value); + } + } + } + + /** + * Evaluate the redirections for this command. + * + * @param redirects the redirection nodes to be evaluated + * @return an array representing the mapping of logical fds to + * input/outputStreamTuple streams for this command. + * @throws ShellException + */ + StreamHolder[] evaluateRedirections(RedirectionNode[] redirects) + throws ShellException { + return evaluateRedirections(redirects, copyStreamHolders(holders)); + } + + /** + * Evaluate the redirections for this command. + * + * @param redirects the redirection nodes to be evaluated + * @param holders the initial stream state which we will mutate + * @return the stream state after redirections + * @throws ShellException + */ + StreamHolder[] evaluateRedirections( + RedirectionNode[] redirects, StreamHolder[] holders) + throws ShellException { + if (redirects == null) { + return holders; + } + boolean ok = false; + try { + for (int i = 0; i < redirects.length; i++) { + RedirectionNode redir = redirects[i]; + // Work out which fd to redirect ... + int fd; + BjorneToken io = redir.getIo(); + if (io == null) { + switch (redir.getRedirectionType()) { + case REDIR_DLESS: + case REDIR_DLESSDASH: + case REDIR_LESS: + case REDIR_LESSAND: + case REDIR_LESSGREAT: + fd = 0; + break; + default: + fd = 1; + } + } else { + try { + fd = Integer.parseInt(io.getText()); + } catch (NumberFormatException ex) { + throw new ShellFailureException("Invalid &fd number"); + } + } + // If necessary, grow the fd table. + if (fd >= holders.length) { + StreamHolder[] tmp = new StreamHolder[fd + 1]; + System.arraycopy(holders, 0, tmp, 0, fd + 1); + holders = tmp; + } + + StreamHolder stream; + switch (redir.getRedirectionType()) { + case REDIR_DLESS: + throw new UnsupportedOperationException("<<"); + case REDIR_DLESSDASH: + throw new UnsupportedOperationException("<<-"); + + case REDIR_GREAT: + try { + File file = new File(redir.getArg().getText()); + if (isNoClobber() && file.exists()) { + throw new ShellException("File already exists"); + } + stream = new StreamHolder(new FileOutputStream(file), + true); + } catch (IOException ex) { + throw new ShellException("Cannot open input file", ex); + } + break; + + case REDIR_CLOBBER: + case REDIR_DGREAT: + try { + stream = new StreamHolder(new FileOutputStream(redir + .getArg().getText(), + redir.getRedirectionType() == REDIR_DGREAT), + true); + } catch (IOException ex) { + throw new ShellException("Cannot open input file", ex); + } + break; + + case REDIR_LESS: + try { + File file = new File(redir.getArg().getText()); + stream = new StreamHolder(new FileInputStream(file), + true); + } catch (IOException ex) { + throw new ShellException("Cannot open input file", ex); + } + break; + + case REDIR_LESSAND: + try { + int fromFd = Integer.parseInt(redir.getArg().getText()); + stream = (fromFd >= holders.length) ? null + : new StreamHolder(holders[fromFd]); + } catch (NumberFormatException ex) { + throw new ShellException("Invalid fd after >&"); + } + break; + + case REDIR_GREATAND: + try { + int fromFd = Integer.parseInt(redir.getArg().getText()); + stream = (fromFd >= holders.length) ? null + : new StreamHolder(holders[fromFd]); + } catch (NumberFormatException ex) { + throw new ShellException("Invalid fd after >&"); + } + break; + + case REDIR_LESSGREAT: + throw new UnsupportedOperationException("<>"); + default: + throw new ShellFailureException("unknown redirection type"); + } + holders[fd] = stream; + } + ok = true; + } finally { + if (!ok) { + for (StreamHolder holder : holders) { + holder.close(); + } + } + } + return holders; + } + + public CommandThread fork(CommandLine command, Closeable[] streams) + throws ShellException { + return interpreter.fork(command, streams); + } +} Added: trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneContextTests.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneContextTests.java (rev 0) +++ trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneContextTests.java 2007-11-03 21:23:08 UTC (rev 3581) @@ -0,0 +1,115 @@ +package org.jnode.shell.bjorne; + +import java.util.Iterator; + +import junit.framework.TestCase; + +import org.jnode.shell.CommandLine; +import org.jnode.shell.ShellException; + +public class BjorneContextTests extends TestCase { + + public void testContext() { + new BjorneContext(null, null); + } + + public void testExpand1() throws ShellException { + BjorneContext context = new BjorneContext(null, null); + CommandLine expansion = context.expandAndSplit(""); + checkExpansion(expansion, new String[] {}); + } + + public void testExpand2() throws ShellException { + BjorneContext context = new BjorneContext(null, null); + CommandLine expansion = context.expandAndSplit(" "); + checkExpansion(expansion, new String[] {}); + } + + public void testExpand3() throws ShellException { + BjorneContext context = new BjorneContext(null, null); + CommandLine expansion = context.expandAndSplit("hi"); + checkExpansion(expansion, new String[] { "hi" }); + } + + public void testExpand4() throws ShellException { + BjorneContext context = new BjorneContext(null, null); + CommandLine expansion = context.expandAndSplit("hi there "); + checkExpansion(expansion, new String[] { "hi", "there" }); + } + + public void testExpand5() throws ShellException { + BjorneContext context = new BjorneContext(null, null); + CommandLine expansion = context.expandAndSplit("'hi there '"); + checkExpansion(expansion, new String[] { "hi there " }); + } + + public void testExpand6() throws ShellException { + BjorneContext context = new BjorneContext(null, null); + CommandLine expansion = context.expandAndSplit("\"hi there \" "); + checkExpansion(expansion, new String[] { "hi there " }); + } + + public void testExpand7() throws ShellException { + BjorneContext context = new BjorneContext(null, null); + CommandLine expansion = context.expandAndSplit("hi\\ there"); + checkExpansion(expansion, new String[] { "hi there" }); + } + + public void testExpand8() throws ShellException { + BjorneContext context = new BjorneContext(null, null); + CommandLine expansion = context.expandAndSplit("\\\"hi\\ there\\\""); + checkExpansion(expansion, new String[] { "\"hi there\"" }); + } + + public void testExpand9() throws ShellException { + BjorneContext context = new BjorneContext(null, null); + CommandLine expansion = context.expandAndSplit("$?"); + checkExpansion(expansion, new String[] { "0" }); + } + + public void testExpand10() throws ShellException { + BjorneContext context = new BjorneContext(null, null); + context.setVariable("A", "A"); + CommandLine expansion = context.expandAndSplit("$A"); + checkExpansion(expansion, new String[] { "A" }); + } + + public void testExpand11() throws ShellException { + BjorneContext context = new BjorneContext(null, null); + context.setVariable("A", "A"); + CommandLine expansion = context.expandAndSplit("\\$A"); + checkExpansion(expansion, new String[] { "$A" }); + } + + public void testExpand12() throws ShellException { + BjorneContext context = new BjorneContext(null, null); + context.setVariable("A", "A"); + CommandLine expansion = context.expandAndSplit("\"$A\""); + checkExpansion(expansion, new String[] { "A" }); + } + + public void testExpand13() throws ShellException { + BjorneContext context = new BjorneContext(null, null); + context.setVariable("A", "A"); + CommandLine expansion = context.expandAndSplit("'$A'"); + checkExpansion(expansion, new String[] { "$A" }); + } + + private void checkExpansion(CommandLine expansion, String[] expected) { + int i; + Iterator<String> it = expansion.iterator(); + for (i = 0; i < expected.length; i++) { + if (it.hasNext()) { + assertEquals("incorrect expansion at word " + i, expected[i], + it.next()); + } else { + fail("Too few words in expansion at word " + i + + ": expecting '" + expected[i] + "'"); + } + } + if (it.hasNext()) { + fail("Too many words in expansion at word " + i + ": '" + it.next() + + "'"); + } + } +} Added: trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneControlException.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneControlException.java (rev 0) +++ trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneControlException.java 2007-11-03 21:23:08 UTC (rev 3581) @@ -0,0 +1,31 @@ +package org.jnode.shell.bjorne; + +import org.jnode.shell.ShellException; + +class BjorneControlException extends ShellException { + + private static final long serialVersionUID = 1L; + + private final int control; + + private int count; + + BjorneControlException(final int control, final int count) { + super(); + this.control = control; + this.count = count; + } + + final int getControl() { + return control; + } + + final int getCount() { + return count; + } + + final void decrementCount() { + count--; + } + +} Added: trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneInterpreter.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneInterpreter.java (rev 0) +++ trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneInterpreter.java 2007-11-03 21:23:08 UTC (rev 3581) @@ -0,0 +1,205 @@ +package org.jnode.shell.bjorne; + +import static org.jnode.shell.bjorne.BjorneToken.TOK_CLOBBER; +import static org.jnode.shell.bjorne.BjorneToken.TOK_DGREAT; +import static org.jnode.shell.bjorne.BjorneToken.TOK_DLESS; +import static org.jnode.shell.bjorne.BjorneToken.TOK_DLESSDASH; +import static org.jnode.shell.bjorne.BjorneToken.TOK_GREAT; +import static org.jnode.shell.bjorne.BjorneToken.TOK_GREATAND; +import static org.jnode.shell.bjorne.BjorneToken.TOK_LESS; +import static org.jnode.shell.bjorne.BjorneToken.TOK_LESSAND; +import static org.jnode.shell.bjorne.BjorneToken.TOK_LESSGREAT; + +import java.io.Closeable; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintStream; +import java.util.HashMap; + +import org.jnode.shell.CommandInterpreter; +import org.jnode.shell.CommandLine; +import org.jnode.shell.CommandShell; +import org.jnode.shell.CommandThread; +import org.jnode.shell.Completable; +import org.jnode.shell.ShellException; +import org.jnode.shell.ShellFailureException; +import org.jnode.shell.ShellSyntaxException; + +/** + * This is a Java implementation of the Bourne Shell language. + * + * @author cr...@jn... + * + */ +public class BjorneInterpreter implements CommandInterpreter { + + public static final int CMD_EMPTY = 0; + + public static final int CMD_COMMAND = 1; + + public static final int CMD_LIST = 2; + + public static final int CMD_FOR = 3; + + public static final int CMD_WHILE = 4; + + public static final int CMD_UNTIL = 5; + + public static final int CMD_IF = 6; + + public static final int CMD_ELIF = 7; + + public static final int CMD_ELSE = 8; + + public static final int CMD_CASE = 9; + + public static final int CMD_SUBSHELL = 10; + + public static final int CMD_BRACE_GROUP = 11; + + public static final int CMD_FUNCTION_DEF = 12; + + public static final int BRANCH_BREAK = 1; + + public static final int BRANCH_CONTINUE = 2; + + public static final int BRANCH_EXIT = 3; + + public static final int BRANCH_RETURN = 4; + + public static final int REDIR_LESS = TOK_LESS; + + public static final int REDIR_GREAT = TOK_GREAT; + + public static final int REDIR_DLESS = TOK_DLESS; + + public static final int REDIR_DLESSDASH = TOK_DLESSDASH; + + public static final int REDIR_DGREAT = TOK_DGREAT; + + public static final int REDIR_LESSAND = TOK_LESSAND; + + public static final int REDIR_GREATAND = TOK_GREATAND; + + public static final int REDIR_LESSGREAT = TOK_LESSGREAT; + + public static final int REDIR_CLOBBER = TOK_CLOBBER; + + public static final int FLAG_ASYNC = 0x0001; + + public static final int FLAG_AND_IF = 0x0002; + + public static final int FLAG_OR_IF = 0x0004; + + public static final int FLAG_BANG = 0x0008; + + public static final int FLAG_PIPE = 0x0010; + + public static final CommandNode EMPTY = new SimpleCommandNode(CMD_EMPTY, + new BjorneToken[0]); + + private static HashMap<String, BjorneBuiltin> BUILTINS = new HashMap<String, BjorneBuiltin>(); + + private static boolean DEBUG = false; + + static { + BUILTINS.put("break", new BreakBuiltin()); + BUILTINS.put("continue", new ContinueBuiltin()); + BUILTINS.put("exit", new ExitBuiltin()); + BUILTINS.put("return", new ReturnBuiltin()); + BUILTINS.put("source", new SourceBuiltin()); + } + + private CommandShell shell; + + private BjorneContext context; + + public BjorneInterpreter() { + } + + public String getName() { + return "bjorne"; + } + + public int interpret(CommandShell shell, String command) + throws ShellException { + return interpret(shell, command, null, false); + } + + public Completable parsePartial(CommandShell shell, String partial) + throws ShellSyntaxException { + // TODO Auto-generated method stub + return null; + } + + int interpret(CommandShell shell, String command, OutputStream capture, + boolean source) throws ShellException { + BjorneContext myContext; + if (capture == null) { + if (this.shell != shell) { + if (this.shell != null) { + throw new ShellFailureException("my shell changed"); + } + this.shell = shell; + this.context = new BjorneContext(this); + } + myContext = this.context; + } else { + myContext = new BjorneContext(this); + } + BjorneTokenizer tokens = new BjorneTokenizer(command); + CommandNode tree = new BjorneParser(tokens).parse(); + if (DEBUG) { + System.err.println(tree); + } + try { + return tree.execute((BjorneContext) myContext); + } catch (BjorneControlException ex) { + switch (ex.getControl()) { + case BRANCH_EXIT: + return ex.getCount(); + case BRANCH_BREAK: + case BRANCH_CONTINUE: + return 0; + case BRANCH_RETURN: + return (source) ? ex.getCount() : 1; + default: + throw new ShellFailureException("unknown control " + + ex.getControl()); + } + } + } + + int executeCommand(CommandLine command, BjorneContext context, + Closeable[] streams) throws ShellException { + BjorneBuiltin builtin = BUILTINS.get(command.getCommandName()); + if (builtin != null) { + return builtin.invoke(command, this, context); + } else { + command.setStreams(streams); + return shell.invoke(command); + } + } + + public BjorneContext createContext() throws ShellFailureException { + return new BjorneContext(this); + } + + public CommandShell getShell() { + return shell; + } + + public PrintStream resolvePrintStream(Closeable stream) { + return shell.resolvePrintStream(stream); + } + + public InputStream resolveInputStream(Closeable stream) { + return shell.resolveInputStream(stream); + } + + public CommandThread fork(CommandLine command, Closeable[] streams) + throws ShellException { + command.setStreams(streams); + return shell.invokeAsynchronous(command); + } +} Added: trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneParser.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneParser.java (rev 0) +++ trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneParser.java 2007-11-03 21:23:08 UTC (rev 3581) @@ -0,0 +1,683 @@ +package org.jnode.shell.bjorne; + +import static org.jnode.shell.bjorne.BjorneToken.TOK_END_OF_LINE; +import static org.jnode.shell.bjorne.BjorneToken.TOK_END_OF_STREAM; +import static org.jnode.shell.bjorne.BjorneInterpreter.CMD_BRACE_GROUP; +import static org.jnode.shell.bjorne.BjorneInterpreter.CMD_COMMAND; +import static org.jnode.shell.bjorne.BjorneInterpreter.CMD_ELIF; +import static org.jnode.shell.bjorne.BjorneInterpreter.CMD_IF; +import static org.jnode.shell.bjorne.BjorneInterpreter.CMD_LIST; +import static org.jnode.shell.bjorne.BjorneInterpreter.CMD_SUBSHELL; +import static org.jnode.shell.bjorne.BjorneInterpreter.CMD_UNTIL; +import static org.jnode.shell.bjorne.BjorneInterpreter.CMD_WHILE; +import static org.jnode.shell.bjorne.BjorneInterpreter.FLAG_AND_IF; +import static org.jnode.shell.bjorne.BjorneInterpreter.FLAG_ASYNC; +import static org.jnode.shell.bjorne.BjorneInterpreter.FLAG_BANG; +import static org.jnode.shell.bjorne.BjorneInterpreter.FLAG_OR_IF; +import static org.jnode.shell.bjorne.BjorneInterpreter.FLAG_PIPE; +import static org.jnode.shell.bjorne.BjorneToken.RULE_1_CONTEXT; +import static org.jnode.shell.bjorne.BjorneToken.RULE_5_CONTEXT; +import static org.jnode.shell.bjorne.BjorneToken.RULE_6_CONTEXT; +import static org.jnode.shell.bjorne.BjorneToken.RULE_7a_CONTEXT; +import static org.jnode.shell.bjorne.BjorneToken.RULE_7b_CONTEXT; +import static org.jnode.shell.bjorne.BjorneToken.RULE_8_CONTEXT; +import static org.jnode.shell.bjorne.BjorneToken.TOK_AMP; +import static org.jnode.shell.bjorne.BjorneToken.TOK_AND_IF; +import static org.jnode.shell.bjorne.BjorneToken.TOK_ASSIGNMENT; +import static org.jnode.shell.bjorne.BjorneToken.TOK_BANG; +import static org.jnode.shell.bjorne.BjorneToken.TOK_BAR; +import static org.jnode.shell.bjorne.BjorneToken.TOK_CASE; +import static org.jnode.shell.bjorne.BjorneToken.TOK_CLOBBER; +import static org.jnode.shell.bjorne.BjorneToken.TOK_DGREAT; +import static org.jnode.shell.bjorne.BjorneToken.TOK_DLESS; +import static org.jnode.shell.bjorne.BjorneToken.TOK_DLESSDASH; +import static org.jnode.shell.bjorne.BjorneToken.TOK_DO; +import static org.jnode.shell.bjorne.BjorneToken.TOK_DONE; +import static org.jnode.shell.bjorne.BjorneToken.TOK_DSEMI; +import static org.jnode.shell.bjorne.BjorneToken.TOK_ELIF; +import static org.jnode.shell.bjorne.BjorneToken.TOK_ELSE; +import static org.jnode.shell.bjorne.BjorneToken.TOK_ESAC; +import static org.jnode.shell.bjorne.BjorneToken.TOK_FI; +import static org.jnode.shell.bjorne.BjorneToken.TOK_FOR; +import static org.jnode.shell.bjorne.BjorneToken.TOK_GREAT; +import static org.jnode.shell.bjorne.BjorneToken.TOK_GREATAND; +import static org.jnode.shell.bjorne.BjorneToken.TOK_IF; +import static org.jnode.shell.bjorne.BjorneToken.TOK_IN; +import static org.jnode.shell.bjorne.BjorneToken.TOK_IO_NUMBER; +import static org.jnode.shell.bjorne.BjorneToken.TOK_LBRACE; +import static org.jnode.shell.bjorne.BjorneToken.TOK_LESS; +import static org.jnode.shell.bjorne.BjorneToken.TOK_LESSAND; +import static org.jnode.shell.bjorne.BjorneToken.TOK_LESSGREAT; +import static org.jnode.shell.bjorne.BjorneToken.TOK_LPAREN; +import static org.jnode.shell.bjorne.BjorneToken.TOK_NAME; +import static org.jnode.shell.bjorne.BjorneToken.TOK_OR_IF; +import static org.jnode.shell.bjorne.BjorneToken.TOK_RBRACE; +import static org.jnode.shell.bjorne.BjorneToken.TOK_RPAREN; +import static org.jnode.shell.bjorne.BjorneToken.TOK_SEMI; +import static org.jnode.shell.bjorne.BjorneToken.TOK_THEN; +import static org.jnode.shell.bjorne.BjorneToken.TOK_UNTIL; +import static org.jnode.shell.bjorne.BjorneToken.TOK_WHILE; +import static org.jnode.shell.bjorne.BjorneToken.TOK_WORD; + +import java.util.LinkedList; +import java.util.List; + +import org.jnode.shell.ShellFailureException; +import org.jnode.shell.ShellSyntaxException; + +public class BjorneParser { + private final BjorneTokenizer tokens; + + public BjorneParser(BjorneTokenizer tokens) { + this.tokens = tokens; + } + + /** + * Parse 'complete_command ::= list separator | list' + * + * @param tokens + * @return + * @throws ShellSyntaxException + */ + public CommandNode parse() throws ShellSyntaxException { + List<CommandNode> commands = new LinkedList<CommandNode>(); + while (tokens.peek().getTokenType() != TOK_END_OF_STREAM) { + CommandNode command = parseList(); + commands.add(command); + tokens.next(); + skipLineBreaks(); + } + return listToNode(commands); + } + + /** + * Parse 'list ::= list separator_op and_or | and_or' + * + * @param tokens + * @return + * @throws ShellSyntaxException + */ + private CommandNode parseList() throws ShellSyntaxException { + List<CommandNode> commands = new LinkedList<CommandNode>(); + CommandNode command = parseAndOr(); + LOOP: while (command != null) { + commands.add(command); + switch (tokens.peek().getTokenType()) { + case TOK_SEMI: + break; + case TOK_AMP: + command.setFlag(FLAG_ASYNC); + break; + case TOK_END_OF_LINE: + case TOK_END_OF_STREAM: + break LOOP; + default: + throw new ShellSyntaxException("unexpected token: " + + tokens.peek()); + } + tokens.next(); + command = parseOptAndOr(); + } + return listToNode(commands); + } + + /** + * Parse 'and_or ::= pipeline | and_or AND_IF linebreak pipeline | and_or + * OR_IF linebreak pipeline' + * + * @param tokens + * @return + * @throws ShellSyntaxException + */ + private CommandNode parseAndOr() throws ShellSyntaxException { + List<CommandNode> commands = new LinkedList<CommandNode>(); + int flag = 0; + LOOP: while (true) { + CommandNode command = parsePipeline(); + command.setFlag(flag); + BjorneToken token = tokens.peek(); + int type = token.getTokenType(); + switch (type) { + case TOK_AND_IF: + flag = FLAG_AND_IF; + break; + case TOK_OR_IF: + flag = FLAG_OR_IF; + break; + default: + commands.add(command); + break LOOP; + } + commands.add(command); + tokens.next(); + skipLineBreaks(); + } + return listToNode(commands); + } + + private CommandNode parseOptAndOr() throws ShellSyntaxException { + switch (tokens.peek(RULE_1_CONTEXT).getTokenType()) { + case TOK_LBRACE: + case TOK_LPAREN: + case TOK_WORD: + case TOK_IF: + case TOK_WHILE: + case TOK_UNTIL: + case TOK_CASE: + case TOK_FOR: + case TOK_IO_NUMBER: + case TOK_LESS: + case TOK_GREAT: + case TOK_DLESS: + case TOK_DGREAT: + case TOK_LESSAND: + case TOK_GREATAND: + case TOK_LESSGREAT: + case TOK_CLOBBER: + return parseAndOr(); + default: + return null; + } + } + + /** + * Parse 'pipeline ::= '!' pipe_sequence | pipe_sequence' + * + * @param tokens + * @return + */ + private CommandNode parsePipeline() throws ShellSyntaxException { + boolean bang = (tokens.peek().getTokenType() == TOK_BANG); + if (bang) { + tokens.next(); + } + CommandNode pipeSeq = parsePipeSequence(); + if (bang) { + pipeSeq.setFlag(FLAG_BANG); + } + return pipeSeq; + } + + /** + * Parse 'pipe_sequence ::= command | pipe_sequence '|' linebreak command' + * + * @param tokens + * @return + */ + private CommandNode parsePipeSequence() throws ShellSyntaxException { + List<CommandNode> commands = new LinkedList<CommandNode>(); + commands.add(parseCommand()); + while (tokens.peek().getTokenType() == TOK_BAR) { + tokens.next(); + skipLineBreaks(); + commands.add(parseCommand()); + } + CommandNode res = listToNode(commands); + if (res instanceof ListCommandNode) { + res.setFlag(FLAG_PIPE); + } + return res; + } + + /** + * Parse 'command ::= simple_command_or_function_definition | + * compound_command_with_opt_redirects ' + * + * @param tokens + * @return + * @throws ShellSyntaxException + */ + private CommandNode parseCommand() throws ShellSyntaxException { + switch (tokens.peek(RULE_7a_CONTEXT).getTokenType()) { + case TOK_IF: + case TOK_WHILE: + case TOK_UNTIL: + case TOK_FOR: + case TOK_CASE: + case TOK_LBRACE: + case TOK_LPAREN: + return parseCompoundCommand(); + default: + CommandNode tmp = parseFunctionDefinition(); + if (tmp != null) { + return tmp; + } + return parseSimpleCommand(); + } + } + + private CommandNode parseSimpleCommand() throws ShellSyntaxException { + List<BjorneToken> assignments = new LinkedList<BjorneToken>(); + List<RedirectionNode> redirects = new LinkedList<RedirectionNode>(); + List<BjorneToken> words = new Link... [truncated message content] |
From: <fd...@us...> - 2007-12-30 22:20:09
|
Revision: 3668 http://jnode.svn.sourceforge.net/jnode/?rev=3668&view=rev Author: fduminy Date: 2007-12-30 14:20:07 -0800 (Sun, 30 Dec 2007) Log Message: ----------- refactoring of fs format : - removed need for error-prone format option of type Object in FileSystemType.format - extracted format command from FileSystemType (which has no sense for lot of fs) -> created interface Formatter instead - splitted format commands per filesystem (simplify the syntax of these commands) - created an abstract format command that do common parts of formatting job Modified Paths: -------------- trunk/all/conf/default-plugin-list.xml trunk/all/conf/install-plugin-list_disabled.xml trunk/fs/descriptors/org.jnode.fs.command.xml trunk/fs/descriptors/org.jnode.fs.jfat.command.xml trunk/fs/src/driver/org/jnode/driver/block/ramdisk/command/RamDiskCommand.java trunk/fs/src/fs/org/jnode/fs/FileSystemType.java trunk/fs/src/fs/org/jnode/fs/ext2/Ext2FileSystemType.java trunk/fs/src/fs/org/jnode/fs/fat/FatFileSystemType.java trunk/fs/src/fs/org/jnode/fs/ftpfs/FTPFileSystemType.java trunk/fs/src/fs/org/jnode/fs/initrd/InitRamdisk.java trunk/fs/src/fs/org/jnode/fs/iso9660/ISO9660FileSystemType.java trunk/fs/src/fs/org/jnode/fs/jarfs/JarFileSystemType.java trunk/fs/src/fs/org/jnode/fs/jfat/FatFileSystemType.java trunk/fs/src/fs/org/jnode/fs/jfat/command/FatFormatCommand.java trunk/fs/src/fs/org/jnode/fs/jifs/JIFileSystemType.java trunk/fs/src/fs/org/jnode/fs/nfs/nfs2/NFS2FileSystemType.java trunk/fs/src/fs/org/jnode/fs/ntfs/NTFSFileSystemType.java trunk/fs/src/fs/org/jnode/fs/ramfs/RAMFileSystem.java trunk/fs/src/fs/org/jnode/fs/ramfs/RAMFileSystemType.java trunk/fs/src/fs/org/jnode/fs/smbfs/SMBFileSystemType.java trunk/fs/src/test/org/jnode/test/fs/filesystem/FSConfigurations.java trunk/fs/src/test/org/jnode/test/fs/filesystem/config/FS.java trunk/fs/src/test/org/jnode/test/fs/filesystem/config/FSType.java Added Paths: ----------- trunk/fs/descriptors/org.jnode.fs.ext2.command.xml trunk/fs/descriptors/org.jnode.fs.fat.command.xml trunk/fs/src/fs/org/jnode/fs/Formatter.java trunk/fs/src/fs/org/jnode/fs/command/AbstractFormatCommand.java trunk/fs/src/fs/org/jnode/fs/ext2/Ext2FileSystemFormatter.java trunk/fs/src/fs/org/jnode/fs/ext2/command/ trunk/fs/src/fs/org/jnode/fs/ext2/command/FormatExt2Command.java trunk/fs/src/fs/org/jnode/fs/fat/FatFileSystemFormatter.java trunk/fs/src/fs/org/jnode/fs/fat/command/ trunk/fs/src/fs/org/jnode/fs/fat/command/FormatFatCommand.java trunk/fs/src/fs/org/jnode/fs/jfat/FatFileSystemFormatter.java Removed Paths: ------------- trunk/fs/src/fs/org/jnode/fs/command/FormatCommand.java Modified: trunk/all/conf/default-plugin-list.xml =================================================================== --- trunk/all/conf/default-plugin-list.xml 2007-12-30 21:55:52 UTC (rev 3667) +++ trunk/all/conf/default-plugin-list.xml 2007-12-30 22:20:07 UTC (rev 3668) @@ -101,7 +101,9 @@ <plugin id="org.jnode.fs"/> <plugin id="org.jnode.fs.command"/> <plugin id="org.jnode.fs.ext2"/> + <plugin id="org.jnode.fs.ext2.command"/> <plugin id="org.jnode.fs.fat"/> + <plugin id="org.jnode.fs.fat.command"/> <plugin id="org.jnode.fs.jfat"/> <plugin id="org.jnode.fs.jfat.command"/> <plugin id="org.jnode.fs.ramfs"/> Modified: trunk/all/conf/install-plugin-list_disabled.xml =================================================================== --- trunk/all/conf/install-plugin-list_disabled.xml 2007-12-30 21:55:52 UTC (rev 3667) +++ trunk/all/conf/install-plugin-list_disabled.xml 2007-12-30 22:20:07 UTC (rev 3668) @@ -71,6 +71,7 @@ <plugin id="org.jnode.partitions.ibm"/> <plugin id="org.jnode.shell.help"/> + <plugin id="org.jnode.fs.command"/> <!-- needed by JFat format command--> <plugin id="org.jnode.fs.jfat"/> <plugin id="org.jnode.fs.jfat.command"/> <plugin id="org.jnode.install"/> Modified: trunk/fs/descriptors/org.jnode.fs.command.xml =================================================================== --- trunk/fs/descriptors/org.jnode.fs.command.xml 2007-12-30 21:55:52 UTC (rev 3667) +++ trunk/fs/descriptors/org.jnode.fs.command.xml 2007-12-30 22:20:07 UTC (rev 3668) @@ -1,23 +1,23 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plugin SYSTEM "jnode.dtd"> -<plugin id="org.jnode.fs.command" +<plugin id="org.jnode.fs.command" name="JNode filesystem commands" version="@VERSION@" license-name="lgpl" provider-name="JNode.org"> - + <requires> <import plugin="org.jnode.fs"/> <import plugin="org.jnode.shell.help"/> </requires> - + <runtime> <library name="jnode-fs.jar"> <export name="org.jnode.fs.command.*"/> </library> </runtime> - + <extension point="org.jnode.shell.aliases"> <alias name="cat" class="org.jnode.fs.command.CatCommand"/> <alias name="cd" class="org.jnode.fs.command.CdCommand"/> @@ -26,7 +26,6 @@ <alias name="dir" class="org.jnode.fs.command.DirCommand"/> <alias name="ls" class="org.jnode.fs.command.DirCommand"/> <alias name="eject" class="org.jnode.fs.command.EjectCommand"/> - <alias name="format" class="org.jnode.fs.command.FormatCommand"/> <alias name="mkdir" class="org.jnode.fs.command.MkdirCommand"/> <alias name="mount" class="org.jnode.fs.command.MountCommand"/> <alias name="pwd" class="org.jnode.fs.command.PwdCommand"/> @@ -39,9 +38,10 @@ <permission class="java.net.SocketPermission" name="*:0-" actions="connect,resolve"/> <permission class="java.util.PropertyPermission" name="user.dir" actions="read,write"/> <permission class="java.util.PropertyPermission" name="*" actions="read,write"/> - <permission class="java.net.NetPermission" name="specifyStreamHandler"/> - <permission class="java.lang.RuntimePermission" name="modifyThreadGroup"/> - <permission class="java.lang.RuntimePermission" name="exitVM"/> + <permission class="java.net.NetPermission" name="specifyStreamHandler"/> + <permission class="java.lang.RuntimePermission" name="modifyThreadGroup"/> + <permission class="java.lang.RuntimePermission" name="exitVM"/> + <permission class="org.jnode.security.JNodePermission" name="getVmClass"/> </extension> - + </plugin> Added: trunk/fs/descriptors/org.jnode.fs.ext2.command.xml =================================================================== --- trunk/fs/descriptors/org.jnode.fs.ext2.command.xml (rev 0) +++ trunk/fs/descriptors/org.jnode.fs.ext2.command.xml 2007-12-30 22:20:07 UTC (rev 3668) @@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plugin SYSTEM "jnode.dtd"> + +<plugin id="org.jnode.fs.ext2.command" + name="Ext2 specific commands" + version="@VERSION@" + provider-name="JNode.org" + license-name="lgpl"> + + <requires> + <import plugin="org.jnode.fs.ext2"/> + <import plugin="org.jnode.fs.command"/> + <import plugin="org.jnode.shell.help"/> + </requires> + + <runtime> + <library name="jnode-fs.jar"> + <export name="org.jnode.fs.ext2.command.*"/> + </library> + </runtime> + + <extension point="org.jnode.shell.aliases"> + <alias name="formatExt2" class="org.jnode.fs.ext2.command.FormatExt2Command"/> + </extension> +</plugin> \ No newline at end of file Added: trunk/fs/descriptors/org.jnode.fs.fat.command.xml =================================================================== --- trunk/fs/descriptors/org.jnode.fs.fat.command.xml (rev 0) +++ trunk/fs/descriptors/org.jnode.fs.fat.command.xml 2007-12-30 22:20:07 UTC (rev 3668) @@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plugin SYSTEM "jnode.dtd"> + +<plugin id="org.jnode.fs.fat.command" + name="FAT specific commands" + version="@VERSION@" + provider-name="JNode.org" + license-name="lgpl"> + + <requires> + <import plugin="org.jnode.fs.fat"/> + <import plugin="org.jnode.fs.command"/> + <import plugin="org.jnode.shell.help"/> + </requires> + + <runtime> + <library name="jnode-fs.jar"> + <export name="org.jnode.fs.fat.command.*"/> + </library> + </runtime> + + <extension point="org.jnode.shell.aliases"> + <alias name="formatFat" class="org.jnode.fs.fat.command.FormatFatCommand"/> + </extension> +</plugin> \ No newline at end of file Modified: trunk/fs/descriptors/org.jnode.fs.jfat.command.xml =================================================================== --- trunk/fs/descriptors/org.jnode.fs.jfat.command.xml 2007-12-30 21:55:52 UTC (rev 3667) +++ trunk/fs/descriptors/org.jnode.fs.jfat.command.xml 2007-12-30 22:20:07 UTC (rev 3668) @@ -2,26 +2,28 @@ <!DOCTYPE plugin SYSTEM "jnode.dtd"> <plugin id="org.jnode.fs.jfat.command" - name="JFAT speciffic commands" + name="JFAT specific commands" version="@VERSION@" provider-name="JNode.org" license-name="lgpl"> - + <requires> <import plugin="org.jnode.fs.jfat"/> + <import plugin="org.jnode.fs.command"/> <import plugin="org.jnode.shell.help"/> </requires> - + <runtime> <library name="jnode-fs.jar"> <export name="org.jnode.fs.jfat.command.*"/> </library> </runtime> - + <extension point="org.jnode.shell.aliases"> <alias name="grub" class="org.jnode.fs.jfat.command.JGrubInstallCommand"/> + <alias name="formatJFat" class="org.jnode.fs.jfat.command.FatFormatCommand"/> </extension> - + <extension point="org.jnode.security.permissions"> <permission class="java.io.FilePermission" name="<<ALL FILES>>" actions="read,write,delete"/> </extension> Modified: trunk/fs/src/driver/org/jnode/driver/block/ramdisk/command/RamDiskCommand.java =================================================================== --- trunk/fs/src/driver/org/jnode/driver/block/ramdisk/command/RamDiskCommand.java 2007-12-30 21:55:52 UTC (rev 3667) +++ trunk/fs/src/driver/org/jnode/driver/block/ramdisk/command/RamDiskCommand.java 2007-12-30 22:20:07 UTC (rev 3668) @@ -9,16 +9,16 @@ * 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 + * 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 + * 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., + * 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.driver.block.ramdisk.command; import org.jnode.driver.DeviceManager; @@ -37,7 +37,7 @@ * @author Ewout Prangsma (ep...@us...) */ public class RamDiskCommand { - + static final OptionArgument ARG_ACTION = new OptionArgument( "action", @@ -46,11 +46,9 @@ new OptionArgument.Option("create", "Create a ramdisk"), }); - static final DeviceArgument ARG_DEVICE = new DeviceArgument("device-id", "the device to print informations about"); static final IntegerArgument ARG_SIZE = new IntegerArgument("size", "the size of the ramdisk"); - + static final Parameter PARAM_ACTION = new Parameter(ARG_ACTION, Parameter.MANDATORY); - static final Parameter PARAM_DEVICE = new Parameter(ARG_DEVICE, Parameter.MANDATORY); static final Parameter PARAM_SIZE = new Parameter(ARG_SIZE, Parameter.OPTIONAL); public static Help.Info HELP_INFO = @@ -60,10 +58,10 @@ new Syntax("Create a ramdisk", new Parameter[] { PARAM_ACTION, PARAM_SIZE }) }); - public static void main(String[] args) + public static void main(String[] args) throws Exception { final ParsedArguments cmdLine = HELP_INFO.parse(args); - + final DeviceManager dm = InitialNaming.lookup(DeviceManager.NAME); if (PARAM_ACTION.isSet(cmdLine)) { // Create Modified: trunk/fs/src/fs/org/jnode/fs/FileSystemType.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/FileSystemType.java 2007-12-30 21:55:52 UTC (rev 3667) +++ trunk/fs/src/fs/org/jnode/fs/FileSystemType.java 2007-12-30 22:20:07 UTC (rev 3668) @@ -9,16 +9,16 @@ * 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 + * 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 + * 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., + * 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.fs; import org.jnode.driver.Device; @@ -28,7 +28,7 @@ /** * Descriptor and entry point for a class of filesystems. Samples of * FileSystemType's are FAT16, EXT3. - * + * * @author epr */ public interface FileSystemType<T extends FileSystem> { @@ -41,7 +41,7 @@ /** * Can this file system type be used on the given first sector of a * blockdevice? - * + * * @param pte * The partition table entry, if any. If null, there is no * partition table entry. @@ -51,21 +51,9 @@ /** * Create a filesystem from a given device. - * + * * @param device * @param readOnly */ public T create(Device device, boolean readOnly) throws FileSystemException; - - /** - * Format a filesystem for a given device according to its Partition table entry. - * - * @param device The device on which you want to format with this FileSystemType - * @param specificOptions the specific options for this filesystemType - * @return the newly created FileSystem - * @throws FileSystemException - */ - public T format(Device device, Object specificOptions) throws FileSystemException; - - } Added: trunk/fs/src/fs/org/jnode/fs/Formatter.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/Formatter.java (rev 0) +++ trunk/fs/src/fs/org/jnode/fs/Formatter.java 2007-12-30 22:20:07 UTC (rev 3668) @@ -0,0 +1,20 @@ +package org.jnode.fs; + +import org.jnode.driver.Device; + +/** + * + * @author Fabien DUMINY (fduminy at jnode.org) + * + * @param <T> + */ +public interface Formatter<T extends FileSystem> { + /** + * Format the given device + * + * @param device The device we want to format + * @return the newly created FileSystem + * @throws FileSystemException + */ + public T format(Device device) throws FileSystemException; +} Added: trunk/fs/src/fs/org/jnode/fs/command/AbstractFormatCommand.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/command/AbstractFormatCommand.java (rev 0) +++ trunk/fs/src/fs/org/jnode/fs/command/AbstractFormatCommand.java 2007-12-30 22:20:07 UTC (rev 3668) @@ -0,0 +1,92 @@ +/* + * $Id: FormatCommand.java 3585 2007-11-13 13:31:18Z galatnm $ + * + * JNode.org + * Copyright (C) 2003-2006 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.fs.command; + +import java.io.InputStream; +import java.io.PrintStream; + +import javax.naming.NameNotFoundException; + +import org.jnode.driver.Device; +import org.jnode.driver.DeviceManager; +import org.jnode.driver.DeviceNotFoundException; +import org.jnode.driver.DriverException; +import org.jnode.driver.block.FSBlockDeviceAPI; +import org.jnode.fs.FileSystem; +import org.jnode.fs.FileSystemException; +import org.jnode.fs.Formatter; +import org.jnode.naming.InitialNaming; +import org.jnode.shell.AbstractCommand; +import org.jnode.shell.CommandLine; +import org.jnode.shell.help.Parameter; +import org.jnode.shell.help.ParsedArguments; +import org.jnode.shell.help.SyntaxErrorException; +import org.jnode.shell.help.argument.DeviceArgument; + +/** + * @author Fabien DUMINY (fduminy at jnode.org) + * + */ +abstract public class AbstractFormatCommand<T extends FileSystem> extends AbstractCommand { + private static final DeviceArgument ARG_DEVICE = new DeviceArgument("device-id", + "the device to format"); + + protected static final Parameter PARAM_DEVICE = new Parameter(ARG_DEVICE, + Parameter.MANDATORY); + + abstract protected ParsedArguments parse(CommandLine commandLine) throws SyntaxErrorException; + abstract protected Formatter<T> getFormatter(ParsedArguments cmdLine); + + final public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) throws Exception { + try { + ParsedArguments cmdLine = parse(commandLine); + + String device = ARG_DEVICE.getValue(cmdLine); + Formatter<T> formatter = getFormatter(cmdLine); + + DeviceManager dm = InitialNaming.lookup(DeviceManager.NAME); + + Device dev = dm.getDevice(device); + if(!(dev.getDriver() instanceof FSBlockDeviceAPI)){ + throw new FileSystemException( + "device unsupported by format command"); + } + formatter.format(dev); + + // restart the device + dm.stop(dev); + dm.start(dev); + } catch (NameNotFoundException e) { + e.printStackTrace(); + exit(1); + } catch (DeviceNotFoundException e) { + e.printStackTrace(); + exit(2); + } catch (DriverException e) { + e.printStackTrace(); + exit(3); + } catch (FileSystemException e) { + e.printStackTrace(); + exit(4); + } + } +} Deleted: trunk/fs/src/fs/org/jnode/fs/command/FormatCommand.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/command/FormatCommand.java 2007-12-30 21:55:52 UTC (rev 3667) +++ trunk/fs/src/fs/org/jnode/fs/command/FormatCommand.java 2007-12-30 22:20:07 UTC (rev 3668) @@ -1,161 +0,0 @@ -/* - * $Id$ - * - * JNode.org - * Copyright (C) 2003-2006 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.fs.command; - -import java.io.InputStream; -import java.io.PrintStream; - -import javax.naming.NameNotFoundException; - -import org.jnode.driver.Device; -import org.jnode.driver.DeviceManager; -import org.jnode.driver.DeviceNotFoundException; -import org.jnode.driver.DriverException; -import org.jnode.driver.block.FSBlockDeviceAPI; -import org.jnode.fs.FileSystemException; -import org.jnode.fs.FileSystemType; -import org.jnode.fs.ext2.Ext2FileSystemType; -import org.jnode.fs.fat.Fat; -import org.jnode.fs.fat.FatFileSystemType; -import org.jnode.fs.service.FileSystemService; -import org.jnode.naming.InitialNaming; -import org.jnode.shell.AbstractCommand; -import org.jnode.shell.CommandLine; -import org.jnode.shell.help.Help; -import org.jnode.shell.help.Parameter; -import org.jnode.shell.help.ParsedArguments; -import org.jnode.shell.help.Syntax; -import org.jnode.shell.help.argument.DeviceArgument; -import org.jnode.shell.help.argument.OptionArgument; - -/** - * @author gbin - */ -public class FormatCommand extends AbstractCommand { - - static final OptionArgument TYPE = new OptionArgument("action", - "Type parameter", - new OptionArgument.Option[] { new OptionArgument.Option("-t", - "Specify fs type") }); - - static final OptionArgument FS = new OptionArgument("fstype", - "File system type", new OptionArgument.Option[] { - new OptionArgument.Option("fat16", "FAT 16 filesystem"), - new OptionArgument.Option("fat12", "FAT 12 filesystem"), - new OptionArgument.Option("ext2", "EXT2 filesystem")}); - - static final OptionArgument BS_VAL = new OptionArgument("blocksize", - "block size for ext2 filesystem", new OptionArgument.Option[] { - new OptionArgument.Option("1", "1Kb"), - new OptionArgument.Option("2", "2Kb"), - new OptionArgument.Option("4", "4Kb"), }); - - static final DeviceArgument ARG_DEVICE = new DeviceArgument("device-id", - "the device to print informations about"); - - static final Parameter PARAM_TYPE = new Parameter(TYPE, Parameter.MANDATORY); - - static final Parameter PARAM_FS = new Parameter(FS, Parameter.MANDATORY); - - static final Parameter PARAM_BS_VAL = new Parameter(BS_VAL, - Parameter.OPTIONAL); - - static final Parameter PARAM_DEVICE = new Parameter(ARG_DEVICE, - Parameter.MANDATORY); - - public static Help.Info HELP_INFO = new Help.Info("format", - new Syntax[] { new Syntax( - "Format a block device with a specified type", - new Parameter[] { PARAM_TYPE, PARAM_FS, PARAM_DEVICE, - PARAM_BS_VAL }) }); - - public static void main(String[] args) throws Exception { - new FormatCommand().execute(args); - } - - public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) throws Exception { - try { - ParsedArguments cmdLine = HELP_INFO.parse(commandLine); - - String device = ARG_DEVICE.getValue(cmdLine); - String FSType = FS.getValue(cmdLine).intern(); - Integer bsize; - try { - bsize = Integer.valueOf(BS_VAL.getValue(cmdLine)); - } catch (NumberFormatException nfe) { - bsize = new Integer(4); - } - - String fsTypeName; - Object params; - - int fatSize = 0; - if (FSType == "fat16") { - fatSize = Fat.FAT16; - fsTypeName = FatFileSystemType.NAME; - params = new Integer(fatSize); - } else if (FSType == "fat12") { - fatSize = Fat.FAT12; - fsTypeName = FatFileSystemType.NAME; - params = new Integer(fatSize); - } else if (FSType == "ext2") { - fsTypeName = Ext2FileSystemType.NAME; - params = bsize; - } else - throw new FileSystemException( - "Unsupported FS by format command"); - - DeviceManager dm; - - dm = InitialNaming.lookup(DeviceManager.NAME); - - Device dev = dm.getDevice(device); - if(!(dev.getDriver() instanceof FSBlockDeviceAPI)){ - throw new FileSystemException( - "Unsupported device by format command"); - - } - FileSystemService fileSystemService = InitialNaming - .lookup(FileSystemService.NAME); - FileSystemType type = fileSystemService - .getFileSystemTypeForNameSystemTypes(fsTypeName); - type.format(dev, params); - - // restart the device - dm.stop(dev); - dm.start(dev); - - } catch (NameNotFoundException e) { - e.printStackTrace(); - exit(1); - } catch (DeviceNotFoundException e) { - e.printStackTrace(); - exit(2); - } catch (DriverException e) { - e.printStackTrace(); - exit(3); - } catch (FileSystemException e) { - e.printStackTrace(); - exit(4); - } - } -} Added: trunk/fs/src/fs/org/jnode/fs/ext2/Ext2FileSystemFormatter.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/ext2/Ext2FileSystemFormatter.java (rev 0) +++ trunk/fs/src/fs/org/jnode/fs/ext2/Ext2FileSystemFormatter.java 2007-12-30 22:20:07 UTC (rev 3668) @@ -0,0 +1,53 @@ +/* + * $Id: Ext2FileSystemType.java 3530 2007-09-26 20:16:47Z konkubinaten $ + * + * JNode.org + * Copyright (C) 2003-2006 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.fs.ext2; + +import org.jnode.driver.Device; +import org.jnode.fs.FileSystemException; +import org.jnode.fs.Formatter; +import org.jnode.util.BinaryPrefix; + +/** + * @author Andras Nagy + */ +public class Ext2FileSystemFormatter implements Formatter<Ext2FileSystem> { + + private int blockSize; + + /** + * + * @param blockSizeKb size of blocks in KB + */ + public Ext2FileSystemFormatter(int blockSizeKb) + { + this.blockSize = (int) (blockSizeKb * BinaryPrefix.K.getMultiplier()); //Converted into KB + } + + /** + * + */ + public synchronized Ext2FileSystem format(Device device) throws FileSystemException { + Ext2FileSystem fs = new Ext2FileSystem(device, false); + fs.create(blockSize); + return fs; + } +} Modified: trunk/fs/src/fs/org/jnode/fs/ext2/Ext2FileSystemType.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/ext2/Ext2FileSystemType.java 2007-12-30 21:55:52 UTC (rev 3667) +++ trunk/fs/src/fs/org/jnode/fs/ext2/Ext2FileSystemType.java 2007-12-30 22:20:07 UTC (rev 3668) @@ -9,16 +9,16 @@ * 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 + * 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 + * 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., + * 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.fs.ext2; import java.io.IOException; @@ -66,7 +66,7 @@ return false; } - //need to check the magic + //need to check the magic ByteBuffer magic = ByteBuffer.allocate(2); try{ devApi.read(1024+56, magic); @@ -75,18 +75,4 @@ } return (Ext2Utils.get16(magic.array(), 0) == 0xEF53); } - - /** - * @see org.jnode.fs.FileSystemType#format(org.jnode.driver.Device, java.lang.Object) - */ - public synchronized Ext2FileSystem format(Device device, Object specificOptions) throws FileSystemException { - //throw new FileSystemException("Not ye implemented"); - - //currently the only option is the block size - int blockSize = 1024*((Integer)specificOptions).intValue(); - - Ext2FileSystem fs = new Ext2FileSystem(device, false); - fs.create(blockSize); - return fs; - } } Added: trunk/fs/src/fs/org/jnode/fs/ext2/command/FormatExt2Command.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/ext2/command/FormatExt2Command.java (rev 0) +++ trunk/fs/src/fs/org/jnode/fs/ext2/command/FormatExt2Command.java 2007-12-30 22:20:07 UTC (rev 3668) @@ -0,0 +1,74 @@ +/* + * $Id: FormatCommand.java 3585 2007-11-13 13:31:18Z galatnm $ + * + * JNode.org + * Copyright (C) 2003-2006 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.fs.ext2.command; + +import org.jnode.fs.command.AbstractFormatCommand; +import org.jnode.fs.ext2.Ext2FileSystem; +import org.jnode.fs.ext2.Ext2FileSystemFormatter; +import org.jnode.shell.CommandLine; +import org.jnode.shell.help.Help; +import org.jnode.shell.help.Parameter; +import org.jnode.shell.help.ParsedArguments; +import org.jnode.shell.help.Syntax; +import org.jnode.shell.help.SyntaxErrorException; +import org.jnode.shell.help.argument.OptionArgument; + +/** + * @author gbin + */ +public class FormatExt2Command extends AbstractFormatCommand<Ext2FileSystem> { + static final OptionArgument BS_VAL = new OptionArgument("blocksize", + "block size for ext2 filesystem", new OptionArgument.Option[] { + new OptionArgument.Option("1", "1Kb"), + new OptionArgument.Option("2", "2Kb"), + new OptionArgument.Option("4", "4Kb"), }); + + static final Parameter PARAM_BS_VAL = new Parameter(BS_VAL, + Parameter.OPTIONAL); + + public static Help.Info HELP_INFO = new Help.Info("format", + new Syntax[] { new Syntax( + "Format a block device with ext2 filesystem", + new Parameter[] { PARAM_DEVICE, PARAM_BS_VAL }) }); + + public static void main(String[] args) throws Exception { + new FormatExt2Command().execute(args); + } + + @Override + protected Ext2FileSystemFormatter getFormatter(ParsedArguments cmdLine) { + int bsize; + try { + bsize = Integer.parseInt(BS_VAL.getValue(cmdLine)); + } catch (NumberFormatException nfe) { + bsize = 4; + } + + return new Ext2FileSystemFormatter(bsize); + } + + @Override + protected ParsedArguments parse(CommandLine commandLine) + throws SyntaxErrorException { + return HELP_INFO.parse(commandLine); + } +} Added: trunk/fs/src/fs/org/jnode/fs/fat/FatFileSystemFormatter.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/fat/FatFileSystemFormatter.java (rev 0) +++ trunk/fs/src/fs/org/jnode/fs/fat/FatFileSystemFormatter.java 2007-12-30 22:20:07 UTC (rev 3668) @@ -0,0 +1,615 @@ +/* + * $Id: FatFileSystemType.java 3117 2007-02-11 22:19:06Z fduminy $ + * + * JNode.org + * Copyright (C) 2003-2006 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.fs.fat; + +import java.io.IOException; + +import org.jnode.driver.ApiNotFoundException; +import org.jnode.driver.Device; +import org.jnode.driver.block.BlockDeviceAPI; +import org.jnode.driver.block.FSBlockDeviceAPI; +import org.jnode.fs.FileSystem; +import org.jnode.fs.FileSystemException; +import org.jnode.fs.FileSystemType; +import org.jnode.fs.Formatter; +import org.jnode.partitions.PartitionTableEntry; +import org.jnode.partitions.ibm.IBMPartitionTableEntry; +import org.jnode.partitions.ibm.IBMPartitionTypes; + +import bsh.This; + +/** + * @author epr + */ +public class FatFileSystemFormatter implements Formatter<FatFileSystem> { + private static final int NB_HEADS = 255; + private static final int SECTOR_PER_TRACK = 63; + + private int fatSize; + + public FatFileSystemFormatter(int fatSize) + { + this.fatSize = fatSize; + } + + /** + * + * @param device + * @return + * @throws FileSystemException + */ + public FatFileSystem format(Device device) throws FileSystemException { + try { + long numberOfSectors; + long offset; + + FSBlockDeviceAPI api = (FSBlockDeviceAPI)device.getAPI(BlockDeviceAPI.class); + int sectorSize = api.getSectorSize(); + + PartitionTableEntry entry = api.getPartitionTableEntry(); + + // if we can deduce partitiontable/fat dependencies do it otherwise + // guess it. + if (entry != null && entry instanceof IBMPartitionTableEntry) { + numberOfSectors = ((IBMPartitionTableEntry)entry).getNrSectors(); + offset = ((IBMPartitionTableEntry)entry).getStartLba(); + } else { + numberOfSectors = api.getLength() / sectorSize; + offset = 0; + } + + FatFormatter ff = + FatFormatter.HDFormatter( + sectorSize, + (int)numberOfSectors, + SECTOR_PER_TRACK, + NB_HEADS, + fatSize, + (int)offset, + 1, + FAT_STANDARD_BS); + ff.format(api); + + return new FatFileSystem(device, false); // not readOnly ! + } catch (IOException ioe) { + throw new FileSystemException("Formating problem", ioe); + } catch (ApiNotFoundException e) { + throw new FileSystemException("Formating problem", e); + } + } + + private static final BootSector FAT_STANDARD_BS = + new BootSector( + new byte[] { + (byte)0xEB, + (byte)0x48, + (byte)0x90, + (byte)0x4A, + (byte)0x4E, + (byte)0x6F, + (byte)0x64, + (byte)0x65, + (byte)0x31, + (byte)0x2E, + (byte)0x30, + (byte)0x00, + (byte)0x02, + (byte)0x01, + (byte)0xED, + (byte)0x00, + (byte)0x02, + (byte)0x00, + (byte)0x02, + (byte)0x00, + (byte)0x80, + (byte)0xF8, + (byte)0x81, + (byte)0x00, + (byte)0x20, + (byte)0x00, + (byte)0x40, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x03, + (byte)0x02, + (byte)0xFF, + (byte)0x00, + (byte)0x00, + (byte)0x80, + (byte)0x01, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x08, + (byte)0xFA, + (byte)0xEA, + (byte)0x50, + (byte)0x7C, + (byte)0x00, + (byte)0x00, + (byte)0x31, + (byte)0xC0, + (byte)0x8E, + (byte)0xD8, + (byte)0x8E, + (byte)0xD0, + (byte)0xBC, + (byte)0x00, + (byte)0x20, + (byte)0xFB, + (byte)0xA0, + (byte)0x40, + (byte)0x7C, + (byte)0x3C, + (byte)0xFF, + (byte)0x74, + (byte)0x02, + (byte)0x88, + (byte)0xC2, + (byte)0x52, + (byte)0xBE, + (byte)0x76, + (byte)0x7D, + (byte)0xE8, + (byte)0x34, + (byte)0x01, + (byte)0xF6, + (byte)0xC2, + (byte)0x80, + (byte)0x74, + (byte)0x54, + (byte)0xB4, + (byte)0x41, + (byte)0xBB, + (byte)0xAA, + (byte)0x55, + (byte)0xCD, + (byte)0x13, + (byte)0x5A, + (byte)0x52, + (byte)0x72, + (byte)0x49, + (byte)0x81, + (byte)0xFB, + (byte)0x55, + (byte)0xAA, + (byte)0x75, + (byte)0x43, + (byte)0xA0, + (byte)0x41, + (byte)0x7C, + (byte)0x84, + (byte)0xC0, + (byte)0x75, + (byte)0x05, + (byte)0x83, + (byte)0xE1, + (byte)0x01, + (byte)0x74, + (byte)0x37, + (byte)0x66, + (byte)0x8B, + (byte)0x4C, + (byte)0x10, + (byte)0xBE, + (byte)0x05, + (byte)0x7C, + (byte)0xC6, + (byte)0x44, + (byte)0xFF, + (byte)0x01, + (byte)0x66, + (byte)0x8B, + (byte)0x1E, + (byte)0x44, + (byte)0x7C, + (byte)0xC7, + (byte)0x04, + (byte)0x10, + (byte)0x00, + (byte)0xC7, + (byte)0x44, + (byte)0x02, + (byte)0x01, + (byte)0x00, + (byte)0x66, + (byte)0x89, + (byte)0x5C, + (byte)0x08, + (byte)0xC7, + (byte)0x44, + (byte)0x06, + (byte)0x00, + (byte)0x70, + (byte)0x66, + (byte)0x31, + (byte)0xC0, + (byte)0x89, + (byte)0x44, + (byte)0x04, + (byte)0x66, + (byte)0x89, + (byte)0x44, + (byte)0x0C, + (byte)0xB4, + (byte)0x42, + (byte)0xCD, + (byte)0x13, + (byte)0x72, + (byte)0x05, + (byte)0xBB, + (byte)0x00, + (byte)0x70, + (byte)0xEB, + (byte)0x7D, + (byte)0xB4, + (byte)0x08, + (byte)0xCD, + (byte)0x13, + (byte)0x73, + (byte)0x0A, + (byte)0xF6, + (byte)0xC2, + (byte)0x80, + (byte)0x0F, + (byte)0x84, + (byte)0xF3, + (byte)0x00, + (byte)0xE9, + (byte)0x8D, + (byte)0x00, + (byte)0xBE, + (byte)0x05, + (byte)0x7C, + (byte)0xC6, + (byte)0x44, + (byte)0xFF, + (byte)0x00, + (byte)0x66, + (byte)0x31, + (byte)0xC0, + (byte)0x88, + (byte)0xF0, + (byte)0x40, + (byte)0x66, + (byte)0x89, + (byte)0x44, + (byte)0x04, + (byte)0x31, + (byte)0xD2, + (byte)0x88, + (byte)0xCA, + (byte)0xC1, + (byte)0xE2, + (byte)0x02, + (byte)0x88, + (byte)0xE8, + (byte)0x88, + (byte)0xF4, + (byte)0x40, + (byte)0x89, + (byte)0x44, + (byte)0x08, + (byte)0x31, + (byte)0xC0, + (byte)0x88, + (byte)0xD0, + (byte)0xC0, + (byte)0xE8, + (byte)0x02, + (byte)0x66, + (byte)0x89, + (byte)0x04, + (byte)0x66, + (byte)0xA1, + (byte)0x44, + (byte)0x7C, + (byte)0x66, + (byte)0x31, + (byte)0xD2, + (byte)0x66, + (byte)0xF7, + (byte)0x34, + (byte)0x88, + (byte)0x54, + (byte)0x0A, + (byte)0x66, + (byte)0x31, + (byte)0xD2, + (byte)0x66, + (byte)0xF7, + (byte)0x74, + (byte)0x04, + (byte)0x88, + (byte)0x54, + (byte)0x0B, + (byte)0x89, + (byte)0x44, + (byte)0x0C, + (byte)0x3B, + (byte)0x44, + (byte)0x08, + (byte)0x7D, + (byte)0x3C, + (byte)0x8A, + (byte)0x54, + (byte)0x0D, + (byte)0xC0, + (byte)0xE2, + (byte)0x06, + (byte)0x8A, + (byte)0x4C, + (byte)0x0A, + (byte)0xFE, + (byte)0xC1, + (byte)0x08, + (byte)0xD1, + (byte)0x8A, + (byte)0x6C, + (byte)0x0C, + (byte)0x5A, + (byte)0x8A, + (byte)0x74, + (byte)0x0B, + (byte)0xBB, + (byte)0x00, + (byte)0x70, + (byte)0x8E, + (byte)0xC3, + (byte)0x31, + (byte)0xDB, + (byte)0xB8, + (byte)0x01, + (byte)0x02, + (byte)0xCD, + (byte)0x13, + (byte)0x72, + (byte)0x2A, + (byte)0x8C, + (byte)0xC3, + (byte)0x8E, + (byte)0x06, + (byte)0x48, + (byte)0x7C, + (byte)0x60, + (byte)0x1E, + (byte)0xB9, + (byte)0x00, + (byte)0x01, + (byte)0x8E, + (byte)0xDB, + (byte)0x31, + (byte)0xF6, + (byte)0x31, + (byte)0xFF, + (byte)0xFC, + (byte)0xF3, + (byte)0xA5, + (byte)0x1F, + (byte)0x61, + (byte)0xFF, + (byte)0x26, + (byte)0x42, + (byte)0x7C, + (byte)0xBE, + (byte)0x7C, + (byte)0x7D, + (byte)0xE8, + (byte)0x40, + (byte)0x00, + (byte)0xEB, + (byte)0x0E, + (byte)0xBE, + (byte)0x81, + (byte)0x7D, + (byte)0xE8, + (byte)0x38, + (byte)0x00, + (byte)0xEB, + (byte)0x06, + (byte)0xBE, + (byte)0x8B, + (byte)0x7D, + (byte)0xE8, + (byte)0x30, + (byte)0x00, + (byte)0xBE, + (byte)0x90, + (byte)0x7D, + (byte)0xE8, + (byte)0x2A, + (byte)0x00, + (byte)0xEB, + (byte)0xFE, + (byte)0x47, + (byte)0x52, + (byte)0x55, + (byte)0x42, + (byte)0x20, + (byte)0x00, + (byte)0x47, + (byte)0x65, + (byte)0x6F, + (byte)0x6D, + (byte)0x00, + (byte)0x48, + (byte)0x61, + (byte)0x72, + (byte)0x64, + (byte)0x20, + (byte)0x44, + (byte)0x69, + (byte)0x73, + (byte)0x6B, + (byte)0x00, + (byte)0x52, + (byte)0x65, + (byte)0x61, + (byte)0x64, + (byte)0x00, + (byte)0x20, + (byte)0x45, + (byte)0x72, + (byte)0x72, + (byte)0x6F, + (byte)0x72, + (byte)0x00, + (byte)0xBB, + (byte)0x01, + (byte)0x00, + (byte)0xB4, + (byte)0x0E, + (byte)0xCD, + (byte)0x10, + (byte)0xAC, + (byte)0x3C, + (byte)0x00, + (byte)0x75, + (byte)0xF4, + (byte)0xC3, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x24, + (byte)0x12, + (byte)0x0F, + (byte)0x09, + (byte)0x00, + (byte)0xBE, + (byte)0xBD, + (byte)0x7D, + (byte)0x31, + (byte)0xC0, + (byte)0xCD, + (byte)0x13, + (byte)0x46, + (byte)0x8A, + (byte)0x0C, + (byte)0x80, + (byte)0xF9, + (byte)0x00, + (byte)0x75, + (byte)0x0F, + (byte)0xBE, + (byte)0xDA, + (byte)0x7D, + (byte)0xE8, + (byte)0xC6, + (byte)0xFF, + (byte)0xEB, + (byte)0x94, + (byte)0x46, + (byte)0x6C, + (byte)0x6F, + (byte)0x70, + (byte)0x70, + (byte)0x79, + (byte)0x00, + (byte)0xBB, + (byte)0x00, + (byte)0x70, + (byte)0xB8, + (byte)0x01, + (byte)0x02, + (byte)0xB5, + (byte)0x00, + (byte)0xB6, + (byte)0x00, + (byte)0xCD, + (byte)0x13, + (byte)0x72, + (byte)0xD7, + (byte)0xB6, + (byte)0x01, + (byte)0xB5, + (byte)0x4F, + (byte)0xE9, + (byte)0xDD, + (byte)0xFE, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x55, + (byte)0xAA }); +} Modified: trunk/fs/src/fs/org/jnode/fs/fat/FatFileSystemType.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/fat/FatFileSystemType.java 2007-12-30 21:55:52 UTC (rev 3667) +++ trunk/fs/src/fs/org/jnode/fs/fat/FatFileSystemType.java 2007-12-30 22:20:07 UTC (rev 3668) @@ -9,25 +9,20 @@ * 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 + * 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 + * 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., + * 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.fs.fat; -import java.io.IOException; - -import org.jnode.driver.ApiNotFoundException; import org.jnode.driver.Device; -import org.jnode.driver.block.BlockDeviceAPI; import org.jnode.driver.block.FSBlockDeviceAPI; -import org.jnode.fs.FileSystem; import org.jnode.fs.FileSystemException; import org.jnode.fs.FileSystemType; import org.jnode.partitions.PartitionTableEntry; @@ -41,8 +36,6 @@ /** Name of this filesystem type */ public static final String NAME = "FAT"; - private static final int NB_HEADS = 255; - private static final int SECTOR_PER_TRACK = 63; /** * Gets the unique name of this file system type. @@ -54,7 +47,7 @@ /** * Can this file system type be used on the given first sector of a * blockdevice? - * + * * @param pte * The partition table entry, if any. If null, there is no * partition table entry. @@ -92,575 +85,11 @@ /** * Create a filesystem for a given device. - * + * * @param device * @param readOnly */ public FatFileSystem create(Device device, boolean readOnly) throws FileSystemException { return new FatFileSystem(device, readOnly); } - - /** - * @param specificOptions - * Integer representing the FatSize - * - * @see org.jnode.fs.FileSystemType#format(org.jnode.driver.Device, - * java.lang.Object) - */ - public FatFileSystem format(Device device, Object specificOptions) throws FileSystemException { - try { - long numberOfSectors; - long offset; - int fatSize = ((Integer)specificOptions).intValue(); - - FSBlockDeviceAPI api = (FSBlockDeviceAPI)device.getAPI(BlockDeviceAPI.class); - int sectorSize = api.getSectorSize(); - - PartitionTableEntry entry = api.getPartitionTableEntry(); - - // if we can deduce partitiontable/fat dependencies do it otherwise - // guess it. - if (entry != null && entry instanceof IBMPartitionTableEntry) { - numberOfSectors = ((IBMPartitionTableEntry)entry).getNrSectors(); - offset = ((IBMPartitionTableEntry)entry).getStartLba(); - } else { - numberOfSectors = api.getLength() / sectorSize; - offset = 0; - } - - FatFormatter ff = - FatFormatter.HDFormatter( - sectorSize, - (int)numberOfSectors, - SECTOR_PER_TRACK, - NB_HEADS, - fatSize, - (int)offset, - 1, - FAT_STANDARD_BS); - ff.format(api); - - return new FatFileSystem(device, false); // not readOnly ! - } catch (IOException ioe) { - throw new FileSystemException("Formating problem", ioe); - } catch (ApiNotFoundException e) { - throw new FileSystemException("Formating problem", e); - } - } - - private static final BootSector FAT_STANDARD_BS = - new BootSector( - new byte[] { - (byte)0xEB, - (byte)0x48, - (byte)0x90, - (byte)0x4A, - (byte)0x4E, - (byte)0x6F, - (byte)0x64, - (byte)0x65, - (byte)0x31, - (byte)0x2E, - (byte)0x30, - (byte)0x00, - (byte)0x02, - (byte)0x01, - (byte)0xED, - (byte)0x00, - (byte)0x02, - (byte)0x00, - (byte)0x02, - (byte)0x00, - (byte)0x80, - (byte)0xF8, - (byte)0x81, - (byte)0x00, - (byte)0x20, - (byte)0x00, - (byte)0x40, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x03, - (byte)0x02, - (byte)0xFF, - (byte)0x00, - (byte)0x00, - (byte)0x80, - (byte)0x01, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x08, - (byte)0xFA, - (byte)0xEA, - (byte)0x50, - (byte)0x7C, - (byte)0x00, - (byte)0x00, - (byte)0x31, - (byte)0xC0, - (byte)0x8E, - (byte)0xD8, - (byte)0x8E, - (byte)0xD0, - (byte)0xBC, - (byte)0x00, - (byte)0x20, - (byte)0xFB, - (byte)0xA0, - (byte)0x40, - (byte)0x7C, - (byte)0x3C, - (byte)0xFF, - (byte)0x74, - (byte)0x02, - (byte)0x88, - (byte)0xC2, - (byte)0x52, - (byte)0xBE, - (byte)0x76, - (byte)0x7D, - (byte)0xE8, - (byte)0x34, - (byte)0x01, - (byte)0xF6, - (byte)0xC2, - (byte)0x80, - (byte)0x74, - (byte)0x54, - (byte)0xB4, - (byte)0x41, - (byte)0xBB, - (byte)0xAA, - (byte)0x55, - (byte)0xCD, - (byte)0x13, - (byte)0x5A, - (byte)0x52, - (byte)0x72, - (byte)0x49, - (byte)0x81, - (byte)0xFB, - (byte)0x55, - (byte)0xAA, - (byte)0x75, - (byte)0x43, - (byte)0xA0, - (byte)0x41, - (byte)0x7C, - (byte)0x84, - (byte)0xC0, - (byte)0x75, - (byte)0x05, - (byte)0x83, - (byte)0xE1, - (byte)0x01, - (byte)0x74, - (byte)0x37, - (byte)0x66, - (byte)0x8B, - (byte)0x4C, - (byte)0x10, - (byte)0xBE, - (byte)0x05, - (byte)0x7C, - (byte)0xC6, - (byte)0x44, - (byte)0xFF, - (byte)0x01, - (byte)0x66, - (byte)0x8B, - (byte)0x1E, - (byte)0x44, - (byte)0x7C, - (byte)0xC7, - (byte)0x04, - (byte)0x10, - (byte)0x00, - (byte)0xC7, - (byte)0x44, - (byte)0x02, - (byte)0x01, - (byte)0x00, - (byte)0x66, - (byte)0x89, - (byte)0x5C, - (byte)0x08, - (byte)0xC7, - (byte)0x44, - (byte)0x06, - (byte)0x00, - (byte)0x70, - (byte)0x66, - (byte)0x31, - (byte)0xC0, - (byte)0x89, - (byte)0x44, - (byte)0x04, - (byte)0x66, - (byte)0x89, - (byte)0x44, - (byte)0x0C, - (byte)0xB4, - (byte)0x42, - (byte)0xCD, - (byte)0x13, - (byte)0x72, - (byte)0x05, - (byte)0xBB, - (byte)0x00, - (byte)0x70, - (byte)0xEB, - (byte)0x7D, - (byte)0xB4, - (byte)0x08, - (byte)0xCD, - (byte)0x13, - (byte)0x73, - (byte)0x0A, - (byte)0xF6, - (byte)0xC2, - (byte)0x80, - (byte)0x0F, - (byte)0x84, - (byte)0xF3, - (byte)0x00, - (byte)0xE9, - (byte)0x8D, - (byte)0x00, - (byte)0xBE, - (byte)0x05, - (byte)0x7C, - (byte)0xC6, - (byte)0x44, - (byte)0xFF, - (byte)0x00, - (byte)0x66, - (byte)0x31, - (byte)0xC0, - (byte)0x88, - (byte)0xF0, - (byte)0x40, - (byte)0x66, - (byte)0x89, - (byte)0x44, - (byte)0x04, - (byte)0x31, - (byte)0xD2, - (byte)0x88, - (byte)0xCA, - (byte)0xC1, - (byte)0xE2, - (byte)0x02, - (byte)0x88, - (byte)0xE8, - (byte)0x88, - (byte)0xF4, - (byte)0x40, - (byte)0x89, - (byte)0x44, - (byte)0x08, - (byte)0x31, - (byte)0xC0, - (byte)0x88, - (byte)0xD0, - (byte)0xC0, - (byte)0xE8, - (byte)0x02, - (byte)0x66, - (byte)0x89, - (byte)0x04, - (byte)0x66, - (byte)0xA1, - (byte)0x44, - (byte)0x7C, - (byte)0x66, - (byte)0x31, - (byte)0xD2, - (byte)0x66, - (byte)0xF7, - (byte)0x34, - (byte)0x88, - (byte)0x54, - (byte)0x0A, - (byte)0x66, - (byte)0x31, - (byte)0xD2, - (byte)0x66, - (byte)0xF7, - (byte)0x74, - (byte)0x04, - (byte)0x88, - (byte)0x54, - (byte)0x0B, - (byte)0x89, - (byte)0x44, - (byte)0x0C, - (byte)0x3B, - (byte)0x44, - (byte)0x08, - (byte)0x7D, - (byte)0x3C, - (byte)0x8A, - (byte)0x54, - (byte)0x0D, - (byte)0xC0, - (byte)0xE2, - (byte)0x06, - (byte)0x8A, - (byte)0x4C, - (byte)0x0A, - (byte)0xFE, - (byte)0xC1, - (byte)0x08, - (byte)0xD1, - (byte)0x8A, - (byte)0x6C, - (byte)0x0C, - (byte)0x5A, - (byte)0x8A, - (byte)0x74, - (byte)0x0B, - (byte)0xBB, - (byte)0x00, - (byte)0x70, - (byte)0x8E, - (byte)0xC3, - (byte)0x31, - (byte)0xDB, - (byte)0xB8, - (byte)0x01, - (byte)0x02, - (byte)0xCD, - (byte)0x13, - (byte)0x72, - (byte)0x2A, - (byte)0x8C, - (byte)0xC3, - (byte)0x8E, - (byte)0x06, - (byte)0x48, - (byte)0x7C, - (byte)0x60, - (byte)0x1E, - (byte)0xB9, - (byte)0x00, - (byte)0x01, - (byte)0x8E, - (byte)0xDB, - (byte)0x31, - (byte)0xF6, - (byte)0x31, - (byte)0xFF, - (byte)0xFC, - (byte)0xF3, - (byte)0xA5, - (byte)0x1F, - (byte)0x61, - (byte)0xFF, - (byte)0x26, - (byte)0x42, - (byte)0x7C, - (byte)0xBE, - (byte)0x7C, - (byte)0x7D, - (byte)0xE8, - (byte)0x40, - (byte)0x00, - (byte)0xEB, - (byte)0x0E, - (byte)0xBE, - (byte)0x81, - (byte)0x7D, - (byte)0xE8, - (byte)0x38, - (byte)0x00, - (byte)0xEB, - (byte)0x06, - (byte)0xBE, - (byte)0x8B, - (byte)0x7D, - (byte)0xE8, - (byte)0x30, - (byte)0x00, - (byte)0xBE, - (byte)0x90, - (byte)0x7D, - (byte)0xE8, - (byte)0x2A, - (byte)0x00, - (byte)0xEB, - (byte)0xFE, - (byte)0x47, - (byte)0x52, - (byte)0x55, - (byte)0x42, - (byte)0x20, - (byte)0x00, - (byte)0x47, - (byte)0x65, - (byte)0x6F, - (byte)0x6D, - (byte)0x00, - (byte)0x48, - (byte)0x61, - (byte)0x72, - (byte)0x64, - (byte)0x20, - (byte)0x44, - (byte)0x69, - (byte)0x73, - (byte)0x6B, - (byte)0x00, - (byte)0x52, - (byte)0x65, - (byte)0x61, - (byte)0x64, - (byte)0x00, - (byte)0x20, - (byte)0x45, - (byte)0x72, - (byte)0x72, - (byte)0x6F, - (byte)0x72, - (byte)0x00, - (byte)0xBB, - (byte)0x01, - (byte)0x00, - (byte)0xB4, - (byte)0x0E, - (byte)0xCD, - (byte)0x10, - (byte)0xAC, - (byte)0x3C, - (byte)0x00, - (byte)0x75, - (byte)0xF4, - (byte)0xC3, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x24, - (byte)0x12, - (byte)0x0F, - (byte)0x09, - (byte)0x00, - (byte)0xBE, - (byte)0xBD, - (byte)0x7D, - (byte)0x31, - (byte)0xC0, - (byte)0xCD, - (byte)0x13, - (byte)0x46, - (byte)0x8A, - (byte)0x0C, - (byte)0x80, - (byte)0xF9, - (byte)0x00, - (byte)0x75, - (byte)0x0F, - (byte)0xBE, - (byte)0xDA, - (byte)0x7D, - (byte)0xE8, - (byte)0xC6, - (byte)0xFF, - (byte)0xEB, - (byte)0x94, - (byte)0x46, - (byte)0x6C, - (byte)0x6F, - (byte)0x70, - (byte)0x70, - (byte)0x79, - (byte)0x00, - (byte)0xBB, - (byte)0x00, - (byte)0x70, - (byte)0xB8, - (byte)0x01, - (byte)0x02, - (byte)0xB5, - (byte)0x00, - (byte)0xB6, - (byte)0x00, - (byte)0xCD, - (byte)0x13, - (byte)0x72, - (byte)0xD7, - (byte)0xB6, - (byte)0x01, - (byte)0xB5, - (byte)0x4F, - (byte)0xE9, - (byte)0xDD, - (byte)0xFE, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x55, - (byte)0xAA }); } Added: trunk/fs/src/fs/org/jnode/fs/fat/command/FormatFatCommand.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/fat/command/FormatFatCommand.java (rev 0) +++ trunk/fs/src/fs/org/jnode/fs/fat/command/FormatFatCommand.java 2007-12-30 22:20:07 UTC (rev 3668) @@ -0,0 +1,78 @@ +/* + * $Id: FormatCommand.java 3585 2007-11-13 13:31:18Z galatnm $ + * + * JNode.org + * Copyright (C) 2003-2006 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.fs.fat.command; + +import org.jnode.fs.command.AbstractFormatCommand; +import org.jnode.fs.fat.Fat; +import org.jnode.fs.fat.FatFileSystem; +import org.jnode.fs.fat.FatFileSystemFormatter; +import org.jnode.shell.CommandLine; +import org.jnode.shell.help.Help; +import org.jnode.shell.help.Parameter; +import org.jnode.shell.help.ParsedArguments; +import org.jnode.shell.help.Syntax; +import org.jnode.shell.help.SyntaxErrorException; +import org.jnode.shell.help.argument.OptionArgument; + +/** + * @author gbin + */ +public class FormatFatCommand extends AbstractFormatCommand<FatFileSystem> { + + static final OptionArgument FS = new OptionArgument("fstype", + "FAT type", new OptionArgument.Option[] { + new OptionArgument.Option("fat16", "FAT 16 filesystem"), + new OptionArgument.Option("fat12", "FAT 12 filesystem")}); + + static final Parameter PARAM_FS = new Parameter(FS, Parameter.MANDATORY); + + public static Help.Info HELP_INFO = new Help.Info("format", + new Syntax[] { new Syntax( + "Format a block device with fat filesystem", + new Parameter[] { PARAM_DEVICE, PARAM_FS}) }); + + public static void main(String[] args) throws Exception { + new FormatFatCommand().execute(args); + } + + @Override + protected FatFileSystemFormatter getFormatter(ParsedArguments cmdLine) { + String FSType = FS.getValue(cmdLine).intern(); + + FatFileSystemFormatter formatter = null; + if (FSType == "fat16") { + formatter = new FatFileSystemFormatter(Fat.FAT16); + } else if (FSType == "fat12") { + formatter = new FatFileSystemFormatter(Fat.FAT32); + } else + throw new IllegalArgumentException( + "invalid... [truncated message content] |
From: <fd...@us...> - 2008-01-01 00:06:54
|
Revision: 3672 http://jnode.svn.sourceforge.net/jnode/?rev=3672&view=rev Author: fduminy Date: 2007-12-31 16:06:53 -0800 (Mon, 31 Dec 2007) Log Message: ----------- - replaced set of int values by Enums in ext2/fat/jfat Formatter implementations - use of new EnumOptionArgument for Formatter commands Modified Paths: -------------- trunk/builder/src/builder/org/jnode/build/BootDiskBuilder.java trunk/fs/src/fs/org/jnode/fs/Formatter.java trunk/fs/src/fs/org/jnode/fs/ext2/Ext2FileSystem.java trunk/fs/src/fs/org/jnode/fs/ext2/Ext2FileSystemFormatter.java trunk/fs/src/fs/org/jnode/fs/ext2/Superblock.java trunk/fs/src/fs/org/jnode/fs/ext2/command/FormatExt2Command.java trunk/fs/src/fs/org/jnode/fs/fat/Fat.java trunk/fs/src/fs/org/jnode/fs/fat/FatFileSystem.java trunk/fs/src/fs/org/jnode/fs/fat/FatFileSystemFormatter.java trunk/fs/src/fs/org/jnode/fs/fat/FatFormatter.java trunk/fs/src/fs/org/jnode/fs/fat/GrubFatFormatter.java trunk/fs/src/fs/org/jnode/fs/fat/command/FormatFatCommand.java trunk/fs/src/fs/org/jnode/fs/initrd/InitRamdisk.java trunk/fs/src/fs/org/jnode/fs/jfat/FatFileSystemFormatter.java trunk/fs/src/fs/org/jnode/fs/jfat/FatFormatter.java trunk/fs/src/fs/org/jnode/fs/jfat/command/FatFormatCommand.java trunk/fs/src/test/org/jnode/test/fs/filesystem/FSConfigurations.java Added Paths: ----------- trunk/fs/src/fs/org/jnode/fs/ext2/BlockSize.java trunk/fs/src/fs/org/jnode/fs/fat/FatType.java trunk/fs/src/fs/org/jnode/fs/jfat/ClusterSize.java Modified: trunk/builder/src/builder/org/jnode/build/BootDiskBuilder.java =================================================================== --- trunk/builder/src/builder/org/jnode/build/BootDiskBuilder.java 2008-01-01 00:03:48 UTC (rev 3671) +++ trunk/builder/src/builder/org/jnode/build/BootDiskBuilder.java 2008-01-01 00:06:53 UTC (rev 3672) @@ -35,6 +35,7 @@ import org.jnode.driver.block.MappedFSBlockDeviceSupport; import org.jnode.fs.FileSystemException; import org.jnode.fs.fat.Fat; +import org.jnode.fs.fat.FatType; import org.jnode.fs.fat.GrubBootSector; import org.jnode.fs.fat.GrubFatFormatter; import org.jnode.partitions.ibm.IBMPartitionTableEntry; @@ -141,7 +142,7 @@ * @throws IOException */ protected GrubFatFormatter createFormatter() throws IOException { - return new GrubFatFormatter(bytesPerSector, spc, geom, Fat.FAT16, 1, + return new GrubFatFormatter(bytesPerSector, spc, geom, FatType.FAT16, 1, getStage1ResourceName(), getStage2ResourceName()); } Modified: trunk/fs/src/fs/org/jnode/fs/Formatter.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/Formatter.java 2008-01-01 00:03:48 UTC (rev 3671) +++ trunk/fs/src/fs/org/jnode/fs/Formatter.java 2008-01-01 00:06:53 UTC (rev 3672) @@ -1,6 +1,7 @@ package org.jnode.fs; import org.jnode.driver.Device; +import org.jnode.fs.ext2.Ext2FileSystemType; /** * @@ -8,7 +9,14 @@ * * @param <T> */ -public interface Formatter<T extends FileSystem> { +abstract public class Formatter<T extends FileSystem> { + private final FileSystemType<T> type; + + protected Formatter(FileSystemType<T> type) + { + this.type = type; + } + /** * Format the given device * @@ -16,5 +24,10 @@ * @return the newly created FileSystem * @throws FileSystemException */ - public T format(Device device) throws FileSystemException; + abstract public T format(Device device) throws FileSystemException; + + final public FileSystemType<T> getFileSystemType() + { + return type; + } } Added: trunk/fs/src/fs/org/jnode/fs/ext2/BlockSize.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/ext2/BlockSize.java (rev 0) +++ trunk/fs/src/fs/org/jnode/fs/ext2/BlockSize.java 2008-01-01 00:06:53 UTC (rev 3672) @@ -0,0 +1,21 @@ +package org.jnode.fs.ext2; + +import org.jnode.util.BinaryPrefix; + + +public enum BlockSize { + _1Kb(1), + _2Kb(2), + _4Kb(4); + + private final int size; + + private BlockSize(int blockSizeKb) + { + this.size = (int) (blockSizeKb * BinaryPrefix.K.getMultiplier()); //Converted into KB + } + + final public int getSize() { + return size; + } +} Modified: trunk/fs/src/fs/org/jnode/fs/ext2/Ext2FileSystem.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/ext2/Ext2FileSystem.java 2008-01-01 00:03:48 UTC (rev 3671) +++ trunk/fs/src/fs/org/jnode/fs/ext2/Ext2FileSystem.java 2008-01-01 00:06:53 UTC (rev 3672) @@ -9,16 +9,16 @@ * 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 + * 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 + * 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., + * 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.fs.ext2; import java.io.IOException; @@ -39,7 +39,7 @@ /** * @author Andras Nagy - * + * */ public class Ext2FileSystem extends AbstractFileSystem { private Superblock superblock; @@ -67,7 +67,7 @@ /** * Constructor for Ext2FileSystem in specified readOnly mode - * + * * @throws FileSystemException */ public Ext2FileSystem(Device device, boolean readOnly) @@ -170,10 +170,10 @@ + "\n" + " #block groups: " + groupCount + "\n" + " block size: " + superblock.getBlockSize() + "\n" + " #inodes: " + superblock.getINodesCount() + "\n" - + " #inodes/group: " + superblock.getINodesPerGroup()); + + " #inodes/group: " + superblock.getINodesPerGroup()); } - - public void create(int blockSize) throws FileSystemException { + + public void create(BlockSize blockSize) throws FileSystemException { try { //create the superblock superblock = new Superblock(); @@ -197,8 +197,8 @@ for (int i = 0; i < groupCount; i++) { log.debug("creating group " + i); - byte[] blockBitmap = new byte[blockSize]; - byte[] inodeBitmap = new byte[blockSize]; + byte[] blockBitmap = new byte[blockSize.getSize()]; + byte[] inodeBitmap = new byte[blockSize.getSize()]; //update the block bitmap: mark the metadata blocks allocated long iNodeTableBlock = groupDescriptors[i].getInodeTable(); @@ -225,7 +225,7 @@ INodeBitmap.setBit(inodeBitmap, j); //create an empty inode table - byte[] emptyBlock = new byte[blockSize]; + byte[] emptyBlock = new byte[blockSize.getSize()]; for (long j = iNodeTableBlock; j < firstNonMetadataBlock; j++) writeBlock(j, emptyBlock, false); @@ -252,7 +252,7 @@ /** * Flush all changed structures to the device. - * + * * @throws IOException */ public void flush() throws IOException { @@ -323,12 +323,12 @@ /** * Read a data block and put it in the cache if it is not yet cached, * otherwise get it from the cache. - * + * * Synchronized access to the blockCache is important as the bitmap * operations are synchronized to the blocks (actually, to Block.getData()), * so at any point in time it has to be sure that no two copies of the same * block are stored in the cache. - * + * * @return data block nr */ protected byte[] getBlock(long nr) throws IOException { @@ -381,7 +381,7 @@ /** * Update the block in cache, or write the block to disk - * + * * @param nr: * block number * @param data: @@ -434,14 +434,14 @@ /** * Helper class for timedWrite - * + * * @author blind */ /* * class TimeoutWatcher extends TimerTask { Thread mainThread; public * TimeoutWatcher(Thread mainThread) { this.mainThread = mainThread; } * public void run() { mainThread.interrupt(); } } - * + * * private static final long TIMEOUT = 100; */ /* @@ -461,7 +461,7 @@ * interrupted if(ioe.getCause() instanceof InterruptedException) { * writeTimer.cancel(); log.debug("IDE driver interrupted during write * operation: probably timeout"); finished = false; } } } } - * + * * private void timedRead(long nr, byte[] data) throws IOException{ boolean * finished = false; Timer readTimer; while(!finished) { finished = true; * readTimer = new Timer(); readTimer.schedule(new @@ -480,7 +480,7 @@ /** * Return the inode numbered inodeNr (the first inode is #1) - * + * * Synchronized access to the inodeCache is important as the file/directory * operations are synchronized to the inodes, so at any point in time it has * to be sure that only one instance of any inode is present in the @@ -526,7 +526,7 @@ /** * Checks whether block <code>blockNr</code> is free, and if it is, then * allocates it with preallocation. - * + * * @param blockNr * @return @throws * IOException @@ -577,7 +577,7 @@ /** * Create a new INode - * + * * @param preferredBlockBroup: * first try to allocate the inode in this block group * @return @@ -637,7 +637,7 @@ /** * Find a free INode in the inode bitmap and allocate it - * + * * @param blockGroup * @return @throws * IOException @@ -681,7 +681,7 @@ /** * Modify the number of free blocks in the block group - * + * * @param group * @param diff * can be positive or negative @@ -695,7 +695,7 @@ /** * Modify the number of free inodes in the block group - * + * * @param group * @param diff * can be positive or negative @@ -709,7 +709,7 @@ /** * Modify the number of used directories in a block group - * + * * @param group * @param diff */ @@ -720,7 +720,7 @@ /** * Free up a block in the block bitmap. - * + * * @param blockNr * @throws FileSystemException * @throws IOException @@ -773,7 +773,7 @@ * Find free blocks in the block group <code>group</code>'s block bitmap. * First check for a whole byte of free blocks (0x00) in the bitmap, then * check for any free bit. If blocks are found, mark them as allocated. - * + * * @return the index of the block (from the beginning of the partition) * @param group * the block group to check @@ -845,7 +845,7 @@ /** * Returns the number of groups. - * + * * @return int */ protected int getGroupCount() { @@ -855,7 +855,7 @@ /** * Check whether the filesystem uses the given RO feature * (S_FEATURE_RO_COMPAT) - * + * * @param mask * @return */ @@ -866,7 +866,7 @@ /** * Check whether the filesystem uses the given COMPAT feature * (S_FEATURE_INCOMPAT) - * + * * @param mask * @return */ @@ -877,7 +877,7 @@ /** * utility function for determining if a given block group has superblock * and group descriptor copies - * + * * @param a * positive integer * @param b @@ -901,7 +901,7 @@ /** * With the sparse_super option set, a filesystem does not have a superblock * and group descriptor copy in every block group. - * + * * @param groupNr * @return true if the block group <code>groupNr</code> has a superblock * and a group descriptor copy, otherwise false @@ -915,7 +915,7 @@ } /** - * + * */ protected FSFile createFile(FSEntry entry) throws IOException { Ext2Entry e = (Ext2Entry) entry; @@ -923,7 +923,7 @@ } /** - * + * */ protected FSDirectory createDirectory(FSEntry entry) throws IOException { Ext2Entry e = (Ext2Entry) entry; @@ -993,12 +993,12 @@ } public long getTotalSpace() { - // TODO implement me + // TODO implement me return 0; } public long getUsableSpace() { - // TODO implement me + // TODO implement me return 0; } } Modified: trunk/fs/src/fs/org/jnode/fs/ext2/Ext2FileSystemFormatter.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/ext2/Ext2FileSystemFormatter.java 2008-01-01 00:03:48 UTC (rev 3671) +++ trunk/fs/src/fs/org/jnode/fs/ext2/Ext2FileSystemFormatter.java 2008-01-01 00:06:53 UTC (rev 3672) @@ -29,17 +29,17 @@ /** * @author Andras Nagy */ -public class Ext2FileSystemFormatter implements Formatter<Ext2FileSystem> { +public class Ext2FileSystemFormatter extends Formatter<Ext2FileSystem> { + private BlockSize blockSize; - private int blockSize; - /** * * @param blockSizeKb size of blocks in KB */ - public Ext2FileSystemFormatter(int blockSizeKb) + public Ext2FileSystemFormatter(BlockSize blockSize) { - this.blockSize = (int) (blockSizeKb * BinaryPrefix.K.getMultiplier()); //Converted into KB + super(new Ext2FileSystemType()); + this.blockSize = blockSize; } /** Modified: trunk/fs/src/fs/org/jnode/fs/ext2/Superblock.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/ext2/Superblock.java 2008-01-01 00:03:48 UTC (rev 3671) +++ trunk/fs/src/fs/org/jnode/fs/ext2/Superblock.java 2008-01-01 00:06:53 UTC (rev 3672) @@ -9,16 +9,16 @@ * 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 + * 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 + * 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., + * 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.fs.ext2; import java.io.IOException; @@ -29,12 +29,12 @@ /** * Ext2fs superblock - * + * * @author Andras Nagy */ public class Superblock { public static final int SUPERBLOCK_LENGTH = 1024; - + //some constants for the fs creation private static final long BYTES_PER_INODE = 4096; //one inode for 4KBs of data private static final double RESERVED_BLOCKS_RATIO = 0.05; //5% reserved for the superuser @@ -42,40 +42,40 @@ private static final int MAX_MOUNT_COUNT = 256; //number of times to mount before check (check not yet implemented) private static final int CHECK_INTERVAL = 365*24*60*60; //check every year (check not yet implemented) private static final long JNODE = 42; //whatever - + private byte data[]; private boolean dirty; private Ext2FileSystem fs; private final Logger log = Logger.getLogger(getClass()); - public Superblock() { + public Superblock() { data = new byte[SUPERBLOCK_LENGTH]; - log.setLevel(Level.INFO); + log.setLevel(Level.INFO); } - + public void read(byte src[], Ext2FileSystem fs) throws FileSystemException { System.arraycopy(src, 0, data, 0, SUPERBLOCK_LENGTH); - + this.fs = fs; - + //check the magic :) if(getMagic() != 0xEF53) throw new FileSystemException("Not ext2 superblock ("+getMagic()+": bad magic)"); - + setDirty(false); } - - public void create(int blockSize, Ext2FileSystem fs) throws IOException { + + public void create(BlockSize blockSize, Ext2FileSystem fs) throws IOException { this.fs = fs; setRevLevel(Ext2Constants.EXT2_DYNAMIC_REV); setMinorRevLevel(0); setMagic(0xEF53); setCreatorOS(JNODE); - + //the number of inodes has to be <= than the number of blocks - long bytesPerInode = BYTES_PER_INODE>=blockSize ? BYTES_PER_INODE : blockSize; + long bytesPerInode = (BYTES_PER_INODE>=blockSize.getSize()) ? BYTES_PER_INODE : blockSize.getSize(); long size = fs.getApi().getLength(); - long blocks = size / blockSize; + long blocks = size / blockSize.getSize(); long inodes = size / bytesPerInode; setINodesCount(inodes); setBlocksCount(blocks); @@ -84,67 +84,67 @@ setDefResuid(0); setBlockSize(blockSize); //actually sets the S_LOG_BLOCK_SIZE setFragSize(blockSize); //set S_LOG_FRAG_SIZE - setFirstDataBlock(blockSize==1024 ? 1 : 0); + setFirstDataBlock(blockSize.getSize()==1024 ? 1 : 0); - //a block bitmap is 1 block long, so blockSize*8 blocks can be indexed by a bitmap + //a block bitmap is 1 block long, so blockSize*8 blocks can be indexed by a bitmap //and thus be in a group - long blocksPerGroup = blockSize << 3; + long blocksPerGroup = blockSize.getSize() << 3; setBlocksPerGroup(blocksPerGroup); setFragsPerGroup(blocksPerGroup); long groupCount = Ext2Utils.ceilDiv(blocks, blocksPerGroup); long inodesPerGroup = Ext2Utils.ceilDiv(inodes, groupCount); - setINodesPerGroup(inodesPerGroup); - + setINodesPerGroup(inodesPerGroup); + //calculate the number of blocks reserved for metadata //first, set the sparse_super option (it affects this value) if(CREATE_WITH_SPARSE_SUPER) setFeatureROCompat(getFeatureROCompat() | Ext2Constants.EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER); - long sbSize = 1; //superblock is 1 block fixed - long gdtSize = Ext2Utils.ceilDiv(groupCount*GroupDescriptor.GROUPDESCRIPTOR_LENGTH, blockSize); + long sbSize = 1; //superblock is 1 block fixed + long gdtSize = Ext2Utils.ceilDiv(groupCount*GroupDescriptor.GROUPDESCRIPTOR_LENGTH, blockSize.getSize()); long bbSize = 1; //block bitmap is 1 block fixed long ibSize = 1; //inode bitmap is 1 block fixed - long inodeTableSize = Ext2Utils.ceilDiv( inodesPerGroup*INode.INODE_LENGTH, blockSize); + long inodeTableSize = Ext2Utils.ceilDiv( inodesPerGroup*INode.INODE_LENGTH, blockSize.getSize()); int groupsWithMetadata = 0; for(int i=0; i<groupCount; i++) if(fs.groupHasDescriptors(i)) groupsWithMetadata++; - long metadataSize = (bbSize + ibSize + inodeTableSize) * groupCount + + long metadataSize = (bbSize + ibSize + inodeTableSize) * groupCount + (sbSize + gdtSize) * groupsWithMetadata; setFreeBlocksCount(blocks - metadataSize); setFirstInode(11); setFreeInodesCount(inodes - getFirstInode() + 1); - + setMTime(0); setWTime(0); setLastCheck(0); setCheckInterval(CHECK_INTERVAL); setMntCount(0); setMaxMntCount(MAX_MOUNT_COUNT); - + setState(Ext2Constants.EXT2_VALID_FS); setErrors(Ext2Constants.EXT2_ERRORS_DEFAULT); - + setINodeSize(INode.INODE_LENGTH); - + setBlockGroupNr(0); - + //set the options SPARSE_SUPER and FILETYPE setFeatureCompat(0); setFeatureROCompat( Ext2Constants.EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER ); setFeatureIncompat( Ext2Constants.EXT2_FEATURE_INCOMPAT_FILETYPE ); - + byte[] uuid = new byte[16]; for(int i=0; i<uuid.length; i++) uuid[i]=(byte)(Math.random()*255); setUUID(uuid); - + setPreallocBlocks(8); setPreallocDirBlocks(0); log.debug("Superblock.create(): getBlockSize(): "+getBlockSize()); } - + /** * Update the superblock copies on the disk */ @@ -152,7 +152,7 @@ if(isDirty()) { log.debug("Updating superblock copies"); byte[] oldData; - + //update the main copy if(getFirstDataBlock()==0) { oldData=fs.getBlock(0); @@ -161,10 +161,10 @@ System.arraycopy(data, 0, oldData, 1024, SUPERBLOCK_LENGTH); } else { oldData=fs.getBlock(getFirstDataBlock()); - System.arraycopy(data, 0, oldData, 0, SUPERBLOCK_LENGTH); + System.arraycopy(data, 0, oldData, 0, SUPERBLOCK_LENGTH); } fs.writeBlock(getFirstDataBlock(), oldData, true); - + //update the other copies for(int i=1; i<fs.getGroupCount(); i++) { //check if there is a superblock copy in the block group @@ -178,11 +178,11 @@ System.arraycopy(data, 0, oldData, 0, SUPERBLOCK_LENGTH); fs.writeBlock(blockNr, oldData, true); } - + setBlockGroupNr(0); setDirty(false); } - + } //this field is only written during format (so no synchronization issues here) @@ -193,7 +193,7 @@ Ext2Utils.set32(data, 0, count); setDirty(true); } - + //this field is only written during format (so no synchronization issues here) public long getBlocksCount() { return Ext2Utils.get32(data, 4); @@ -202,7 +202,7 @@ Ext2Utils.set32(data, 4, count); setDirty(true); } - + //this field is only written during format (so no synchronization issues here) public long getRBlocksCount() { return Ext2Utils.get32(data, 8); @@ -245,18 +245,19 @@ Ext2Utils.set32(data, 24, i); setDirty(true); } - + //this field is only written during format (so no synchronization issues here) public int getBlockSize() { return 1024 << getLogBlockSize(); } - public void setBlockSize(long size) { + public void setBlockSize(BlockSize size) { //setLogBlockSize( (long)(Math.log(size)/Math.log(2) - 10) ); //Math.log() is buggy - if(size==1024) setLogBlockSize(0); - if(size==2048) setLogBlockSize(1); - if(size==4096) setLogFragSize(2); - if(size==8192) setLogFragSize(3); + //TODO should we handle all these values for size or not ? from mke2fs man page, it seems NO. + if(size.getSize()==1024) setLogBlockSize(0); + if(size.getSize()==2048) setLogBlockSize(1); + if(size.getSize()==4096) setLogFragSize(2); + if(size.getSize()==8192) setLogFragSize(3); setDirty(true); } @@ -268,7 +269,7 @@ Ext2Utils.set32(data, 28, i); setDirty(true); } - + //this field is only written during format (so no synchronization issues here) public int getFragSize() { if(getLogFragSize()>0) @@ -276,17 +277,18 @@ else return 1024 >> -getLogFragSize(); } - public void setFragSize(long size) { + public void setFragSize(BlockSize size) { //setLogFragSize( (long)(Math.log(size)/Math.log(2)) - 10 ); //Math.log() is buggy - if(size==64) setLogFragSize(-4); - if(size==128) setLogFragSize(-3); - if(size==256) setLogBlockSize(-2); - if(size==512) setLogBlockSize(-1); - if(size==1024) setLogFragSize(0); - if(size==2048) setLogFragSize(1); - if(size==4096) setLogBlockSize(2); - if(size==8192) setLogBlockSize(3); + //TODO should we handle all these values for size or not ? from mke2fs man page, it seems NO. + if(size.getSize()==64) setLogFragSize(-4); + if(size.getSize()==128) setLogFragSize(-3); + if(size.getSize()==256) setLogBlockSize(-2); + if(size.getSize()==512) setLogBlockSize(-1); + if(size.getSize()==1024) setLogFragSize(0); + if(size.getSize()==2048) setLogFragSize(1); + if(size.getSize()==4096) setLogBlockSize(2); + if(size.getSize()==8192) setLogBlockSize(3); setDirty(true); } @@ -307,7 +309,7 @@ Ext2Utils.set32(data, 36, i); setDirty(true); } - + //this field is only written during format (so no synchronization issues here) public long getINodesPerGroup() { return Ext2Utils.get32(data, 40); @@ -333,7 +335,7 @@ Ext2Utils.set32(data, 48, time); setDirty(true); } - + //this field is only written during mounting (so no synchronization issues here) public int getMntCount() { return Ext2Utils.get16(data, 52); @@ -342,7 +344,7 @@ Ext2Utils.set16(data, 52, i); setDirty(true); } - + //this field is only written during format (so no synchronization issues here) public int getMaxMntCount() { return Ext2Utils.get16(data, 54); @@ -360,7 +362,7 @@ Ext2Utils.set16(data, 56, i); setDirty(true); } - + public synchronized int getState() { return Ext2Utils.get16(data, 58); } @@ -385,8 +387,8 @@ public void setMinorRevLevel(int i) { Ext2Utils.set16(data, 62, i); setDirty(true); - } - + } + //this field is only written during filesystem check (so no synchronization issues here) public long getLastCheck() { return Ext2Utils.get32(data, 64); @@ -395,7 +397,7 @@ Ext2Utils.set32(data, 64, i); setDirty(true); } - + //this field is only written during format (so no synchronization issues here) public long getCheckInterval() { return Ext2Utils.get32(data, 68); @@ -404,7 +406,7 @@ Ext2Utils.set32(data, 68, i); setDirty(true); } - + //this field is only written during format (so no synchronization issues here) public long getCreatorOS() { return Ext2Utils.get32(data, 72); @@ -413,7 +415,7 @@ Ext2Utils.set32(data, 72, i); setDirty(true); } - + //this field is only written during format (so no synchronization issues here) public long getRevLevel() { return Ext2Utils.get32(data, 76); @@ -422,7 +424,7 @@ Ext2Utils.set32(data, 76, i); setDirty(true); } - + //this field is only written during format (so no synchronization issues here) public int getDefResuid() { return Ext2Utils.get16(data, 80); @@ -431,7 +433,7 @@ Ext2Utils.set16(data, 80, i); setDirty(true); } - + //this field is only written during format (so no synchronization issues here) public int getDefResgid() { return Ext2Utils.get16(data, 82); @@ -445,19 +447,19 @@ public long getFirstInode() { if(getRevLevel()==Ext2Constants.EXT2_DYNAMIC_REV) return Ext2Utils.get32(data, 84); - else + else return 11; } public void setFirstInode(long i) { Ext2Utils.set32(data, 84, i); setDirty(true); } - + //this field is only written during format (so no synchronization issues here) public long getINodeSize() { if(getRevLevel()==Ext2Constants.EXT2_DYNAMIC_REV) return Ext2Utils.get16(data, 88); - else + else return INode.INODE_LENGTH; } public void setINodeSize(int i) { @@ -469,19 +471,19 @@ public synchronized long getBlockGroupNr() { if(getRevLevel()==Ext2Constants.EXT2_DYNAMIC_REV) return Ext2Utils.get16(data, 90); - else + else return 0; } public synchronized void setBlockGroupNr(int i) { Ext2Utils.set16(data, 90, i); setDirty(true); } - + //this field is only written during format (so no synchronization issues here) public long getFeatureCompat() { if(getRevLevel()==Ext2Constants.EXT2_DYNAMIC_REV) return Ext2Utils.get32(data, 92); - else + else return 0; } public void setFeatureCompat(long i) { @@ -493,19 +495,19 @@ public long getFeatureIncompat() { if(getRevLevel()==Ext2Constants.EXT2_DYNAMIC_REV) return Ext2Utils.get32(data, 96); - else + else return 0; } public void setFeatureIncompat(long i) { Ext2Utils.set32(data, 96, i); setDirty(true); } - + //this field is only written during format (so no synchronization issues here) public long getFeatureROCompat() { if(getRevLevel()==Ext2Constants.EXT2_DYNAMIC_REV) return Ext2Utils.get32(data, 100); - else + else return 0; } public void setFeatureROCompat(long i) { @@ -515,14 +517,14 @@ //this field is only written during format (so no synchronization issues here) public byte[] getUUID() { - byte[] result=new byte[16]; + byte[] result=new byte[16]; if(getRevLevel()==Ext2Constants.EXT2_DYNAMIC_REV) System.arraycopy(data, 104, result, 0, 16); return result; } public void setUUID(byte[] uuid) { if(getRevLevel()==Ext2Constants.EXT2_DYNAMIC_REV) - System.arraycopy(uuid, 0, data, 104, 16); + System.arraycopy(uuid, 0, data, 104, 16); setDirty(true); } @@ -536,7 +538,7 @@ result.append(c); else break; - } + } return result.toString(); } @@ -549,7 +551,7 @@ result.append(c); else break; - } + } return result.toString(); } @@ -557,10 +559,10 @@ public long getAlgoBitmap() { if(getRevLevel()==Ext2Constants.EXT2_DYNAMIC_REV) return Ext2Utils.get32(data, 200); - else + else return 11; } - + //this field is only written during format (so no synchronization issues here) public int getPreallocBlocks() { return Ext2Utils.get8(data, 204); @@ -580,11 +582,11 @@ } public byte[] getJournalUUID() { - byte[] result=new byte[16]; + byte[] result=new byte[16]; System.arraycopy(data, 208, result, 0, 16); return result; } - + public long getJournalINum() { return Ext2Utils.get32(data, 224); } Modified: trunk/fs/src/fs/org/jnode/fs/ext2/command/FormatExt2Command.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/ext2/command/FormatExt2Command.java 2008-01-01 00:03:48 UTC (rev 3671) +++ trunk/fs/src/fs/org/jnode/fs/ext2/command/FormatExt2Command.java 2008-01-01 00:06:53 UTC (rev 3672) @@ -22,25 +22,29 @@ package org.jnode.fs.ext2.command; import org.jnode.fs.command.AbstractFormatCommand; +import org.jnode.fs.ext2.BlockSize; import org.jnode.fs.ext2.Ext2FileSystem; import org.jnode.fs.ext2.Ext2FileSystemFormatter; +import org.jnode.fs.fat.FatType; import org.jnode.shell.CommandLine; import org.jnode.shell.help.Help; import org.jnode.shell.help.Parameter; import org.jnode.shell.help.ParsedArguments; import org.jnode.shell.help.Syntax; import org.jnode.shell.help.SyntaxErrorException; +import org.jnode.shell.help.argument.EnumOptionArgument; import org.jnode.shell.help.argument.OptionArgument; /** * @author gbin */ +@SuppressWarnings("unchecked") public class FormatExt2Command extends AbstractFormatCommand<Ext2FileSystem> { - static final OptionArgument BS_VAL = new OptionArgument("blocksize", - "block size for ext2 filesystem", new OptionArgument.Option[] { - new OptionArgument.Option("1", "1Kb"), - new OptionArgument.Option("2", "2Kb"), - new OptionArgument.Option("4", "4Kb"), }); + static final EnumOptionArgument<BlockSize> BS_VAL = new EnumOptionArgument<BlockSize>("blocksize", + "block size for ext2 filesystem", + new EnumOptionArgument.EnumOption<BlockSize>("1", "1Kb", BlockSize._1Kb), + new EnumOptionArgument.EnumOption<BlockSize>("2", "2Kb", BlockSize._2Kb), + new EnumOptionArgument.EnumOption<BlockSize>("4", "4Kb", BlockSize._4Kb)); static final Parameter PARAM_BS_VAL = new Parameter(BS_VAL, Parameter.OPTIONAL); @@ -56,13 +60,7 @@ @Override protected Ext2FileSystemFormatter getFormatter(ParsedArguments cmdLine) { - int bsize; - try { - bsize = Integer.parseInt(BS_VAL.getValue(cmdLine)); - } catch (NumberFormatException nfe) { - bsize = 4; - } - + BlockSize bsize = BS_VAL.getEnum(cmdLine, BlockSize.class); return new Ext2FileSystemFormatter(bsize); } Modified: trunk/fs/src/fs/org/jnode/fs/fat/Fat.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/fat/Fat.java 2008-01-01 00:03:48 UTC (rev 3671) +++ trunk/fs/src/fs/org/jnode/fs/fat/Fat.java 2008-01-01 00:06:53 UTC (rev 3672) @@ -9,16 +9,16 @@ * 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 + * 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 + * 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., + * 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.fs.fat; import java.io.IOException; @@ -31,38 +31,33 @@ /** * <description> - * + * * @author epr */ public class Fat { - public static final int FAT12 = 12; - public static final int FAT16 = 16; - public static final int FAT32 = 32; - private long[] entries; - /** The type of FAT, legal values are: 12, 16, 32 */ - private int bitSize; + /** The type of FAT */ + private FatType fatType; /** The number of sectors this fat takes */ private int nrSectors; /** The number of bytes/sector */ private int sectorSize; - private final long eofMarker; private boolean dirty; - + /** entry index for find next free entry*/ private int lastFreeCluster = 2; /** * Create a new instance - * + * * @param bitSize * @param nrSectors * @param sectorSize */ - public Fat(int bitSize, int mediumDescriptor, int nrSectors, int sectorSize) { - this.bitSize = bitSize; + public Fat(FatType bitSize, int mediumDescriptor, int nrSectors, int sectorSize) { + this.fatType = bitSize; this.nrSectors = nrSectors; this.sectorSize = sectorSize; this.dirty = false; @@ -70,19 +65,16 @@ case FAT12 : { entries = new long[(int) ((nrSectors * sectorSize) / 1.5)]; - eofMarker = 0xFFF; } break; case FAT16 : { entries = new long[(nrSectors * sectorSize) / 2]; - eofMarker = 0xFFFF; } break; case FAT32 : { entries = new long[(nrSectors * sectorSize) / 4]; - eofMarker = 0xFFFFFFFF; } break; default : @@ -93,15 +85,15 @@ /** * Read the contents of this FAT from the given device at the given offset. - * + * * @param device */ public synchronized void read(BlockDeviceAPI device, long offset) throws IOException { byte[] data = new byte[nrSectors * sectorSize]; device.read(offset, ByteBuffer.wrap(data)); for (int i = 0; i < entries.length; i++) { - switch (bitSize) { - case 12 : + switch (fatType) { + case FAT12 : { int idx = (int) (i * 1.5); int b1 = data[idx] & 0xFF; @@ -119,7 +111,7 @@ // Long.toHexString(entries[i])); } break; - case 16 : + case FAT16 : { int idx = i * 2; int b1 = data[idx] & 0xFF; @@ -127,7 +119,7 @@ entries[i] = (b2 << 8) | b1; } break; - case 32 : + case FAT32 : { int idx = i * 4; long b1 = data[idx] & 0xFF; @@ -144,15 +136,15 @@ /** * Write the contents of this FAT to the given device at the given offset. - * + * * @param device */ public synchronized void write(BlockDeviceAPI device, long offset) throws IOException { byte[] data = new byte[nrSectors * sectorSize]; for (int i = 0; i < entries.length; i++) { long v = entries[i]; - switch (bitSize) { - case 12 : + switch (fatType) { + case FAT12 : { int idx = (int) (i * 1.5); if ((i % 2) == 0) { @@ -164,14 +156,14 @@ } } break; - case 16 : + case FAT16 : { int idx = i << 1; data[idx] = (byte) (v & 0xFF); data[idx + 1] = (byte) ((v >> 8) & 0xFF); } break; - case 32 : + case FAT32 : { int idx = i << 2; data[idx] = (byte) (v & 0xFF); @@ -189,7 +181,7 @@ /** * Gets the medium descriptor byte - * + * * @return int */ public int getMediumDescriptor() { @@ -205,7 +197,7 @@ /** * Gets the number of entries of this fat - * + * * @return int */ public int getNrEntries() { @@ -214,7 +206,7 @@ /** * Gets the entry at a given offset - * + * * @param index * @return long */ @@ -245,7 +237,7 @@ /** * Gets the cluster after the given cluster - * + * * @param cluster * @return long The next cluster number or -1 which means eof. */ @@ -261,42 +253,42 @@ /** * Allocate a cluster for a new file - * + * * @return long */ public synchronized long allocNew() throws IOException { int i; int entryIndex = -1; - + for (i = lastFreeCluster; i < entries.length; i++) { if (isFreeCluster(entries[i])) { entryIndex=i; break; - } + } } - if(entryIndex<0){ + if(entryIndex<0){ for(i = 2; i < lastFreeCluster;i++){ if (isFreeCluster(entries[i])) { entryIndex=i; break; - } + } } } if(entryIndex < 0){ throw new FileSystemFullException("FAT Full (" + entries.length + ", " + i + ")"); } - entries[entryIndex] = eofMarker; + entries[entryIndex] = fatType.getEofMarker(); lastFreeCluster = entryIndex+1; this.dirty = true; return entryIndex; - + } /** * Allocate a series of clusters for a new file - * + * * @return long */ public synchronized long[] allocNew(int nrClusters) throws IOException { @@ -313,7 +305,7 @@ /** * Allocate a cluster to append to a new file - * + * * @return long */ public synchronized long allocAppend(long cluster) throws IOException { @@ -332,7 +324,7 @@ public synchronized void setEof(long cluster) { testCluster(cluster); - entries[(int)cluster] = eofMarker; + entries[(int)cluster] = fatType.getEofMarker(); } public synchronized void setFree(long cluster) { @@ -343,7 +335,7 @@ /** * Print the contents of this FAT to the given writer. Used for debugging * purposes. - * + * * @param out */ public void printTo(PrintWriter out) { @@ -381,7 +373,7 @@ /** * Is the given entry a free cluster? - * + * * @param entry * @return boolean */ @@ -391,40 +383,22 @@ /** * Is the given entry a reserved cluster? - * + * * @param entry * @return boolean */ protected boolean isReservedCluster(long entry) { - switch (bitSize) { - case 12 : - return ((entry >= 0xFF0) && (entry <= 0xFF6)); - case 16 : - return ((entry >= 0xFFF0) && (entry <= 0xFFF6)); - case 32 : - return ((entry >= 0xFFFFFFF0) && (entry <= 0xFFFFFFF6)); - default : - throw new IllegalArgumentException("Invalid bitSize " + bitSize); - } + return fatType.isReservedCluster(entry); } /** * Is the given entry an EOF marker - * + * * @param entry * @return boolean */ protected boolean isEofCluster(long entry) { - switch (bitSize) { - case 12 : - return (entry >=0xFF8); - case 16 : - return ((entry >= 0xFFF8)); - case 32 : - return (entry >= 0xFFFFFFF8); - default : - throw new IllegalArgumentException("Invalid bitSize " + bitSize); - } + return fatType.isEofCluster(entry); } protected void testCluster(long cluster) throws IllegalArgumentException { @@ -435,7 +409,7 @@ /** * Returns the dirty. - * + * * @return boolean */ public boolean isDirty() { Modified: trunk/fs/src/fs/org/jnode/fs/fat/FatFileSystem.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/fat/FatFileSystem.java 2008-01-01 00:03:48 UTC (rev 3671) +++ trunk/fs/src/fs/org/jnode/fs/fat/FatFileSystem.java 2008-01-01 00:06:53 UTC (rev 3672) @@ -9,16 +9,16 @@ * 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 + * 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 + * 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., + * 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.fs.fat; import java.io.IOException; @@ -48,7 +48,7 @@ */ public FatFileSystem(Device device, boolean readOnly) throws FileSystemException { super(device, readOnly); // false = read/write mode - + try { bs = new BootSector(512); bs.read(getApi()); @@ -59,12 +59,12 @@ Fat[] fats = new Fat[bs.getNrFats()]; rootDir = new FatLfnDirectory(this, bs.getNrRootDirEntries()); - int bitSize; + FatType bitSize; if (bs.getMediumDescriptor() == 0xf8) { - bitSize = 16; + bitSize = FatType.FAT16; } else { - bitSize = 12; + bitSize = FatType.FAT12; } for (int i = 0; i < fats.length; i++) { @@ -92,7 +92,7 @@ /** * Flush all changed structures to the device. - * + * * @throws IOException */ public void flush() throws IOException { @@ -129,7 +129,7 @@ /** * Gets the file for the given entry. - * + * * @param entry */ public synchronized FatFile getFile(FatDirEntry entry) { @@ -148,7 +148,7 @@ /** * Returns the fat. - * + * * @return Fat */ public Fat getFat() { @@ -157,7 +157,7 @@ /** * Returns the bootsector. - * + * * @return BootSector */ public BootSector getBootSector() { @@ -165,7 +165,7 @@ } /** * Returns the rootDir. - * + * * @return RootDirectory */ public FatDirectory getRootDir() { @@ -173,26 +173,26 @@ } /** - * + * */ protected FSFile createFile(FSEntry entry) throws IOException { - + // TODO Auto-generated method stub return null; } /** - * + * */ - protected FSDirectory createDirectory(FSEntry entry) throws IOException { + protected FSDirectory createDirectory(FSEntry entry) throws IOException { // TODO Auto-generated method stub return null; } /** - * + * */ - protected FSEntry createRootEntry() throws IOException { + protected FSEntry createRootEntry() throws IOException { // TODO Auto-generated method stub return null; } @@ -204,12 +204,12 @@ } public long getTotalSpace() { - // TODO implement me + // TODO implement me return 0; } public long getUsableSpace() { - // TODO implement me + // TODO implement me return 0; } } Modified: trunk/fs/src/fs/org/jnode/fs/fat/FatFileSystemFormatter.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/fat/FatFileSystemFormatter.java 2008-01-01 00:03:48 UTC (rev 3671) +++ trunk/fs/src/fs/org/jnode/fs/fat/FatFileSystemFormatter.java 2008-01-01 00:06:53 UTC (rev 3672) @@ -31,6 +31,7 @@ import org.jnode.fs.FileSystemException; import org.jnode.fs.FileSystemType; import org.jnode.fs.Formatter; +import org.jnode.fs.ext2.Ext2FileSystemType; import org.jnode.partitions.PartitionTableEntry; import org.jnode.partitions.ibm.IBMPartitionTableEntry; import org.jnode.partitions.ibm.IBMPartitionTypes; @@ -40,14 +41,15 @@ /** * @author epr */ -public class FatFileSystemFormatter implements Formatter<FatFileSystem> { +public class FatFileSystemFormatter extends Formatter<FatFileSystem> { private static final int NB_HEADS = 255; private static final int SECTOR_PER_TRACK = 63; - private int fatSize; + private FatType fatSize; - public FatFileSystemFormatter(int fatSize) + public FatFileSystemFormatter(FatType fatSize) { + super(new FatFileSystemType()); this.fatSize = fatSize; } Modified: trunk/fs/src/fs/org/jnode/fs/fat/FatFormatter.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/fat/FatFormatter.java 2008-01-01 00:03:48 UTC (rev 3671) +++ trunk/fs/src/fs/org/jnode/fs/fat/FatFormatter.java 2008-01-01 00:06:53 UTC (rev 3672) @@ -9,16 +9,16 @@ * 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 + * 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 + * 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., + * 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.fs.fat; import java.io.IOException; @@ -28,7 +28,7 @@ /** * <description> - * + * * @author epr */ public class FatFormatter { @@ -43,7 +43,7 @@ private FatDirectory rootDir; public static FatFormatter fat144FloppyFormatter(int reservedSectors, BootSector bs) { - return new FatFormatter(FLOPPY_DESC, 512, 1, 2880, 18, 2, Fat.FAT12, 2, 0, reservedSectors, bs); + return new FatFormatter(FLOPPY_DESC, 512, 1, 2880, 18, 2, FatType.FAT32, 2, 0, reservedSectors, bs); } public static FatFormatter HDFormatter( @@ -51,7 +51,7 @@ int nbTotalSectors, int sectorsPerTrack, int nbHeads, - int fatSize, + FatType fatSize, int hiddenSectors, int reservedSectors, BootSector bs) { @@ -76,24 +76,13 @@ int nbTotalSectors, int sectorsPerTrack, int nbHeads, - int fatSize, + FatType fatSize, int nbFats, int hiddenSectors, int reservedSectors, BootSector bs) { this.bs = bs; - float fatEntrySize; - switch (fatSize) { - case Fat.FAT12 : - fatEntrySize = 1.5f; - break; - case Fat.FAT16 : - fatEntrySize = 2.0f; - break; - default : - fatEntrySize = 4.0f; - break; - } + final float fatEntrySize = fatSize.getEntrySize(); bs.setMediumDescriptor(mediumDescriptor); bs.setOemName("JNode1.0"); @@ -176,7 +165,7 @@ /** * Set the label - * + * * @param label */ public void setLabel(String label) throws IOException { @@ -185,7 +174,7 @@ /** * Format the given device, according to my settings - * + * * @param api * @throws IOException */ @@ -204,7 +193,7 @@ /** * Returns the bs. - * + * * @return BootSector */ public BootSector getBootSector() { Added: trunk/fs/src/fs/org/jnode/fs/fat/FatType.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/fat/FatType.java (rev 0) +++ trunk/fs/src/fs/org/jnode/fs/fat/FatType.java 2008-01-01 00:06:53 UTC (rev 3672) @@ -0,0 +1,38 @@ +package org.jnode.fs.fat; + +public enum FatType { + FAT12(0xFFF, 1.5f), + FAT16(0xFFFF, 2.0f), + FAT32(0xFFFFFFFF, 4.0f); + + private final long minReservedEntry; + private final long maxReservedEntry; + private final long eofCluster; + private final long eofMarker; + private final float entrySize; + + private FatType(long bitMask, float entrySize) + { + this.minReservedEntry = (0xFFFFFFF0 & bitMask); + this.maxReservedEntry = (0xFFFFFFF6 & bitMask); + this.eofCluster = (0xFFFFFFF8 & bitMask); + this.eofMarker = (0xFFFFFFFF & bitMask); + this.entrySize = entrySize; + } + + final public boolean isReservedCluster(long entry) { + return ((entry >= minReservedEntry) && (entry <= maxReservedEntry)); + } + + final public boolean isEofCluster(long entry) { + return (entry >= eofCluster); + } + + final public long getEofMarker() { + return eofMarker; + } + + final public float getEntrySize() { + return entrySize; + } +} Modified: trunk/fs/src/fs/org/jnode/fs/fat/GrubFatFormatter.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/fat/GrubFatFormatter.java 2008-01-01 00:03:48 UTC (rev 3671) +++ trunk/fs/src/fs/org/jnode/fs/fat/GrubFatFormatter.java 2008-01-01 00:06:53 UTC (rev 3672) @@ -9,16 +9,16 @@ * 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 + * 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 + * 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., + * 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.fs.fat; import java.io.IOException; @@ -54,7 +54,7 @@ int bps, int spc, Geometry geom, - int fatSize, + FatType fatSize, int bootSectorOffset, String stage1ResourceName, String stage2ResourceName) { @@ -81,7 +81,7 @@ /** * Constructor for GrubFatFormatter. - * + * * @param bootSectorOffset * @param stage1ResourceName * @param stage2ResourceName @@ -182,7 +182,7 @@ /** * Sets the configFile. - * + * * @param configFile * The configFile to set */ @@ -203,7 +203,7 @@ /** * Sets the installPartition. - * + * * @param installPartition * The installPartition to set */ Modified: trunk/fs/src/fs/org/jnode/fs/fat/command/FormatFatCommand.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/fat/command/FormatFatCommand.java 2008-01-01 00:03:48 UTC (rev 3671) +++ trunk/fs/src/fs/org/jnode/fs/fat/command/FormatFatCommand.java 2008-01-01 00:06:53 UTC (rev 3672) @@ -25,6 +25,7 @@ import org.jnode.fs.fat.Fat; import org.jnode.fs.fat.FatFileSystem; import org.jnode.fs.fat.FatFileSystemFormatter; +import org.jnode.fs.fat.FatType; import org.jnode.shell.CommandLine; import org.jnode.shell.help.Help; import org.jnode.shell.help.Parameter; @@ -60,9 +61,9 @@ FatFileSystemFormatter formatter = null; if (FSType == "fat16") { - formatter = new FatFileSystemFormatter(Fat.FAT16); + formatter = new FatFileSystemFormatter(FatType.FAT16); } else if (FSType == "fat12") { - formatter = new FatFileSystemFormatter(Fat.FAT32); + formatter = new FatFileSystemFormatter(FatType.FAT32); } else throw new IllegalArgumentException( "invalid fat type"); Modified: trunk/fs/src/fs/org/jnode/fs/initrd/InitRamdisk.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/initrd/InitRamdisk.java 2008-01-01 00:03:48 UTC (rev 3671) +++ trunk/fs/src/fs/org/jnode/fs/initrd/InitRamdisk.java 2008-01-01 00:06:53 UTC (rev 3672) @@ -39,6 +39,7 @@ import org.jnode.fs.fat.Fat; import org.jnode.fs.fat.FatFileSystemFormatter; import org.jnode.fs.fat.FatFileSystemType; +import org.jnode.fs.fat.FatType; import org.jnode.fs.service.FileSystemService; import org.jnode.naming.InitialNaming; import org.jnode.plugin.Plugin; @@ -76,7 +77,7 @@ log.info("Format initrd ramdisk"); - final FatFileSystemFormatter formatter = new FatFileSystemFormatter(Fat.FAT16); + final FatFileSystemFormatter formatter = new FatFileSystemFormatter(FatType.FAT16); final FileSystem fs = formatter.format(dev); try { fs.getRootEntry().getDirectory().addDirectory("tmp"); Added: trunk/fs/src/fs/org/jnode/fs/jfat/ClusterSize.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/jfat/ClusterSize.java (rev 0) +++ trunk/fs/src/fs/org/jnode/fs/jfat/ClusterSize.java 2008-01-01 00:06:53 UTC (rev 3672) @@ -0,0 +1,26 @@ +package org.jnode.fs.jfat; + +import org.jnode.util.BinaryPrefix; + + +public enum ClusterSize { + _1Kb(1), + _2Kb(2), + _4Kb(4), + _8Kb(8), + _16Kb(16), + _32Kb(32), + _64Kb(64); + + private final int size; + + private ClusterSize(int sizeInKb) + { + size = (int) (sizeInKb * BinaryPrefix.K.getMultiplier()); //Converted into KB + } + + final public int getSize() + { + return size; + } +} Modified: trunk/fs/src/fs/org/jnode/fs/jfat/FatFileSystemFormatter.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/jfat/FatFileSystemFormatter.java 2008-01-01 00:03:48 UTC (rev 3671) +++ trunk/fs/src/fs/org/jnode/fs/jfat/FatFileSystemFormatter.java 2008-01-01 00:06:53 UTC (rev 3672) @@ -28,6 +28,7 @@ import org.jnode.driver.Device; import org.jnode.driver.block.BlockDeviceAPI; import org.jnode.driver.block.FSBlockDeviceAPI; +import org.jnode.driver.bus.ide.IDEConstants; import org.jnode.fs.FileSystem; import org.jnode.fs.FileSystemException; import org.jnode.fs.Formatter; @@ -43,15 +44,16 @@ * @author gvt * @author Tango */ -public class FatFileSystemFormatter implements Formatter<FatFileSystem> { +public class FatFileSystemFormatter extends Formatter<FatFileSystem> { private static final Logger log = Logger.getLogger ( FatFileSystemFormatter.class ); - private int clusterSize; + private ClusterSize clusterSize; - public FatFileSystemFormatter(int clusterSizeKb) + public FatFileSystemFormatter(ClusterSize clusterSize) { - this.clusterSize = (int) (clusterSizeKb * BinaryPrefix.K.getMultiplier()); //Converted into KB + super(new FatFileSystemType()); + this.clusterSize = clusterSize; } public FatFileSystem format ( Device device) @@ -64,8 +66,8 @@ FSBlockDeviceAPI api = (FSBlockDeviceAPI)device.getAPI(BlockDeviceAPI.class); int sectorSize = api.getSectorSize(); - if(sectorSize!=512){ - log.error("This mkjfat1.0 support only the Hard Disk.Sector Size must 512 bytes.\n"); + if(sectorSize != IDEConstants.SECTOR_SIZE){ + log.error("This mkjfat1.0 support only the Hard Disk.Sector Size must "+IDEConstants.SECTOR_SIZE+" bytes.\n"); } Modified: trunk/fs/src/fs/org/jnode/fs/jfat/FatFormatter.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/jfat/FatFormatter.java 2008-01-01 00:03:48 UTC (rev 3671) +++ trunk/fs/src/fs/org/jnode/fs/jfat/FatFormatter.java 2008-01-01 00:06:53 UTC (rev 3672) @@ -10,13 +10,13 @@ * 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 + * 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 + * 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., + * along with this library; If not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ @@ -31,7 +31,7 @@ import static java.lang.Integer.toHexString; /** - * + * * @author tango * <p> * <ul>According to the FAT32 Documents.</ul> @@ -49,7 +49,7 @@ * <li>Reserved sectors upto the FAT at sector 32</li> * */ -public class FatFormatter { +public class FatFormatter { private static final Logger log = Logger.getLogger ( FatFormatter.class ); @@ -58,7 +58,7 @@ /** The Device Identifier for Hard Disk Device*/ public static final int HD_DESC = 0xf8; /** The Device Identifier for RAM Disk Device */ - public static final int RAMDISK_DESC = 0xfa; + public static final int RAMDISK_DESC = 0xfa; /** The Size of Fat.*/ private int FatSize; /** The Number of the Fat in system.*/ @@ -74,12 +74,12 @@ /** The volume label.*/ private static final String VOL_LABEL="NO NAME "; /** The FAT version label.*/ - private static final String FAT_LABEL="FAT32 "; + private static final String FAT_LABEL="FAT32 "; /** The Identifier of the Boot Sector */ public final byte[] BS_Identifier={(byte)0x55,(byte)0xAA}; /** The First 3 Bytes of the BootSector */ - public final byte[] BS_jmpBoot={(byte)0xEB,(byte)0x5A,(byte)0x90}; - /** This lead signature is used to validate that this is in fact an FSInfo sector.*/ + public final byte[] BS_jmpBoot={(byte)0xEB,(byte)0x5A,(byte)0x90}; + /** This lead signature is used to validate that this is in fact an FSInfo sector.*/ private final int FSI_LeadSig =0x41615252; /** The signature that is more localized in the sector to the location of the fields that are used.*/ private final int FSI_StrucSig =0x61417272; @@ -88,7 +88,7 @@ /** This is a hint for the FAT driver. It indicates the cluster number at which the driver should start looking for free clusters.*/ private final int FSI_Nxt_Free =3;//A confusion here but OK now for setting the Info at 3rd sec /** This trail signature is used to validate that this is in fact an FSInfo sector*/ - private final int FSI_TrailSig =0xaa550000; + private final int FSI_TrailSig =0xaa550000; /** The media ID at the reserved cluster one.*/ private final int ReservedSector_0=0x0ffffff8; /** The End Of Chain ID at the reserved sector second.*/ @@ -97,62 +97,62 @@ private final int ReservedSector_2=0x0fffffff; /** The array for the reserved sector.*/ private byte[] reservedSector; - + /** * The Hard Disk's formatting logic implementation by JFAT. * This Version only support to the Hard Disks. - * - * @throws IOException - */ - public static FatFormatter HDDFormatter(int bps, + * + * @throws IOException + */ + public static FatFormatter HDDFormatter(int sectorSize, int nbTotalSectors, - int fatSize, + ClusterSize clusterSize, int hiddenSectors, BlockDeviceAPI api - ) throws IOException{ - + ) throws IOException{ + return new FatFormatter( HD_DESC, - bps, + sectorSize, nbTotalSectors, SECTOR_PER_TRACK, NB_HEADS, - fatSize, - hiddenSectors, + clusterSize, + hiddenSectors, api ); - } - + } + /** * The Constructor for the HDD devices in the JNode system. - * @throws IOException + * @throws IOException * */ public FatFormatter( int mediumDescriptor, - int bps, + int sectorSize, int nbTotalSectors, int sectorsPerTrack, int nbHeads, - int ClusterSize, + ClusterSize ClusterSize, int hiddenSectors, BlockDeviceAPI api ) throws IOException{ - - FatFsInfo fsInfo=new FatFsInfo(bps); - BootSector bs=new BootSector(bps); - api.flush(); - int DiskSize=getDiskSize(nbTotalSectors, bps); - int SectorPerCluster=get_spc(ClusterSize,bps); + + FatFsInfo fsInfo=new FatFsInfo(sectorSize); + BootSector bs=new BootSector(sectorSize); + api.flush(); + int DiskSize=getDiskSize(nbTotalSectors, sectorSize); + int SectorPerCluster=get_spc(ClusterSize,s... [truncated message content] |
From: <fd...@us...> - 2008-01-04 17:38:08
|
Revision: 3683 http://jnode.svn.sourceforge.net/jnode/?rev=3683&view=rev Author: fduminy Date: 2008-01-04 09:38:02 -0800 (Fri, 04 Jan 2008) Log Message: ----------- - JPartition : work in progress - moved tests from distr/src/apps to distr/src/test Modified Paths: -------------- trunk/all/conf/full-plugin-list.xml trunk/all/lib/jnode.xml trunk/distr/.classpath trunk/distr/build.xml trunk/distr/src/apps/org/jnode/apps/jpartition/JPartition.java trunk/distr/src/apps/org/jnode/apps/jpartition/ViewFactory.java trunk/distr/src/apps/org/jnode/apps/jpartition/commands/BaseDeviceCommand.java trunk/distr/src/apps/org/jnode/apps/jpartition/commands/framework/BaseCommand.java trunk/distr/src/apps/org/jnode/apps/jpartition/commands/framework/CommandProcessor.java trunk/distr/src/apps/org/jnode/apps/jpartition/swingview/CommandProcessorView.java trunk/distr/src/apps/org/jnode/apps/jpartition/swingview/DiskAreaView.java trunk/distr/src/apps/org/jnode/apps/jpartition/swingview/PartitionView.java trunk/distr/src/apps/org/jnode/apps/jpartition/swingview/SwingViewFactory.java trunk/distr/src/apps/org/jnode/apps/jpartition/swingview/actions/InitMbrAction.java trunk/distr/src/apps/org/jnode/apps/vmware/disk/handler/sparse/AllocationTable.java trunk/distr/src/apps/org/jnode/apps/vmware/disk/tools/DiskCopier.java trunk/distr/src/test/org/jnode/apps/jpartition/utils/device/AbstractIDEDevice.java trunk/distr/src/test/org/jnode/apps/jpartition/utils/device/DeviceUtils.java trunk/distr/src/test/org/jnode/apps/jpartition/utils/device/FakeIDEDevice.java trunk/distr/src/test/org/jnode/apps/vmware/disk/test/readwrite/TestVMWareDisk.java trunk/fs/src/fs/org/jnode/fs/Formatter.java Added Paths: ----------- trunk/distr/descriptors/org.jnode.apps.jpartition.xml trunk/distr/descriptors/org.jnode.apps.vmware.disk.xml trunk/distr/lib/jedit.jar trunk/distr/src/apps/org/jnode/apps/jpartition/ErrorReporter.java trunk/distr/src/apps/org/jnode/apps/jpartition/commands/BasePartitionCommand.java trunk/distr/src/apps/org/jnode/apps/jpartition/commands/CreatePartitionCommand.java trunk/distr/src/apps/org/jnode/apps/jpartition/commands/FormatPartitionCommand.java trunk/distr/src/apps/org/jnode/apps/jpartition/commands/RemovePartitionCommand.java trunk/distr/src/apps/org/jnode/apps/jpartition/model/Bounded.java trunk/distr/src/apps/org/jnode/apps/jpartition/model/Device.java trunk/distr/src/apps/org/jnode/apps/jpartition/model/DeviceException.java trunk/distr/src/apps/org/jnode/apps/jpartition/model/OSFacade.java trunk/distr/src/apps/org/jnode/apps/jpartition/model/OSListener.java trunk/distr/src/apps/org/jnode/apps/jpartition/model/Partition.java trunk/distr/src/apps/org/jnode/apps/jpartition/model/UserFacade.java trunk/distr/src/apps/org/jnode/apps/jpartition/model/UserListener.java trunk/distr/src/apps/org/jnode/apps/jpartition/swingview/SwingErrorReporter.java trunk/distr/src/apps/org/jnode/apps/jpartition/swingview/actions/AddPartitionAction.java trunk/distr/src/apps/org/jnode/apps/jpartition/swingview/actions/FormatPartitionAction.java trunk/distr/src/test/ trunk/distr/src/test/org/ trunk/distr/src/test/org/jnode/ trunk/distr/src/test/org/jnode/apps/ trunk/distr/src/test/org/jnode/apps/jpartition/ trunk/distr/src/test/org/jnode/apps/jpartition/JPartitionTest.java trunk/distr/src/test/org/jnode/apps/jpartition/model/ trunk/distr/src/test/org/jnode/apps/jpartition/model/AbstractTest.java trunk/distr/src/test/org/jnode/apps/jpartition/model/AbstractTestDevice.java trunk/distr/src/test/org/jnode/apps/jpartition/model/DummyErrorReporter.java trunk/distr/src/test/org/jnode/apps/jpartition/model/TestEmptyDevice.java trunk/distr/src/test/org/jnode/apps/jpartition/model/TestNonEmptyDevice.java trunk/distr/src/test/org/jnode/apps/jpartition/model/TestOSFacade.java trunk/distr/src/test/org/jnode/apps/jpartition/model/TestRemovePartitionFromDevice.java trunk/distr/src/test/org/jnode/apps/jpartition/swingview/ trunk/distr/src/test/org/jnode/apps/jpartition/swingview/FileDeviceView.java trunk/distr/src/test/org/jnode/apps/jpartition/utils/ trunk/distr/src/test/org/jnode/apps/jpartition/utils/BasicNameSpace.java trunk/distr/src/test/org/jnode/apps/jpartition/utils/device/ trunk/distr/src/test/org/jnode/apps/vmware/ trunk/distr/src/test/org/jnode/apps/vmware/disk/ trunk/distr/src/test/org/jnode/apps/vmware/disk/test/ trunk/distr/src/test/org/jnode/apps/vmware/disk/test/BaseTest.java trunk/distr/src/test/org/jnode/apps/vmware/disk/test/TestCreation.java trunk/distr/src/test/org/jnode/apps/vmware/disk/test/Utils.java trunk/distr/src/test/org/jnode/apps/vmware/disk/test/disks/ trunk/distr/src/test/org/jnode/apps/vmware/disk/test/disks/Menuet32-0.vmdk trunk/distr/src/test/org/jnode/apps/vmware/disk/test/disks/Menuet32-1-flat.vmdk trunk/distr/src/test/org/jnode/apps/vmware/disk/test/disks/Menuet32-1.vmdk trunk/distr/src/test/org/jnode/apps/vmware/disk/test/disks/Menuet32-2-s001.vmdk trunk/distr/src/test/org/jnode/apps/vmware/disk/test/disks/Menuet32-2.vmdk trunk/distr/src/test/org/jnode/apps/vmware/disk/test/disks/Menuet32-3-f001.vmdk trunk/distr/src/test/org/jnode/apps/vmware/disk/test/disks/Menuet32-3.vmdk trunk/distr/src/test/org/jnode/apps/vmware/disk/test/disks/others/ trunk/distr/src/test/org/jnode/apps/vmware/disk/test/disks/others/JNode-0.vmdk trunk/distr/src/test/org/jnode/apps/vmware/disk/test/disks/others/JNode-1-s001.vmdk trunk/distr/src/test/org/jnode/apps/vmware/disk/test/disks/others/JNode-1-s002.vmdk trunk/distr/src/test/org/jnode/apps/vmware/disk/test/disks/others/JNode-1-s003.vmdk trunk/distr/src/test/org/jnode/apps/vmware/disk/test/disks/others/JNode-1-s004.vmdk trunk/distr/src/test/org/jnode/apps/vmware/disk/test/disks/others/JNode-1-s005.vmdk trunk/distr/src/test/org/jnode/apps/vmware/disk/test/disks/others/JNode-1.vmdk trunk/distr/src/test/org/jnode/apps/vmware/disk/test/disks/others/JNode.vmdk trunk/distr/src/test/org/jnode/apps/vmware/disk/test/disks/readme.txt trunk/distr/src/test/org/jnode/apps/vmware/disk/test/readwrite/ Removed Paths: ------------- trunk/distr/lib/commons-logging.jar trunk/distr/lib/stamps_framework.jar trunk/distr/src/apps/org/jnode/apps/jpartition/model/AbstractModel.java trunk/distr/src/apps/org/jnode/apps/jpartition/model/CommandProcessorModel.java trunk/distr/src/apps/org/jnode/apps/jpartition/model/DeviceModel.java trunk/distr/src/apps/org/jnode/apps/jpartition/model/FileDeviceModel.java trunk/distr/src/apps/org/jnode/apps/jpartition/model/PartitionModel.java trunk/distr/src/apps/org/jnode/apps/jpartition/swingview/FileDeviceView.java trunk/distr/src/apps/org/jnode/apps/jpartition/swingview/actions/BaseDeviceAction.java trunk/distr/src/apps/org/jnode/apps/jpartition/utils/ trunk/distr/src/apps/org/jnode/apps/vmware/disk/test/BaseTest.java trunk/distr/src/apps/org/jnode/apps/vmware/disk/test/TestCreation.java trunk/distr/src/apps/org/jnode/apps/vmware/disk/test/Utils.java trunk/distr/src/apps/org/jnode/apps/vmware/disk/test/disks/ trunk/distr/src/apps/org/jnode/apps/vmware/disk/test/readwrite/ Modified: trunk/all/conf/full-plugin-list.xml =================================================================== --- trunk/all/conf/full-plugin-list.xml 2008-01-03 14:57:22 UTC (rev 3682) +++ trunk/all/conf/full-plugin-list.xml 2008-01-04 17:38:02 UTC (rev 3683) @@ -32,4 +32,7 @@ <plugin id="org.jnode.shell.bjorne"/> <plugin id="org.jnode.shell.command.unix"/> + + <plugin id="org.jnode.apps.vmware.disk"/> + <plugin id="org.jnode.apps.jpartition"/> </plugin-list> Modified: trunk/all/lib/jnode.xml =================================================================== --- trunk/all/lib/jnode.xml 2008-01-03 14:57:22 UTC (rev 3682) +++ trunk/all/lib/jnode.xml 2008-01-04 17:38:02 UTC (rev 3683) @@ -7,11 +7,14 @@ <javac destdir="${my-classes.dir}" debug="on" optimize="on" - fork="on" - memoryMaximumSize="512m" + + fork="off" + memoryInitialSize="515m" + memoryMaximumSize="1024m" + compiler="modern" includeJavaRuntime="false" - target="${java.target}" + target="${java.target}" source="${java.source}" encoding="${java.encoding}" excludes="**/*-template.java,**/package-info.java"> @@ -24,14 +27,14 @@ <macrodef name="jnode.javadoc"> <attribute name="destdir"/> <element name="parameters" implicit="true"/> - + <sequential> <mkdir dir="@{destdir}"/> - <javadoc + <javadoc destdir="@{destdir}" - author="true" - version="true" - use="true" + author="true" + version="true" + use="true" windowtitle="JNode" maxmemory="256M"> @@ -52,7 +55,7 @@ <filterset refid="descriptors-filter"/> </copy> </presetdef> - + <!-- Perform a default clean --> <presetdef name="jnode.clean"> <delete dir="${my-build.dir}" quiet="true"/> Modified: trunk/distr/.classpath =================================================================== --- trunk/distr/.classpath 2008-01-03 14:57:22 UTC (rev 3682) +++ trunk/distr/.classpath 2008-01-04 17:38:02 UTC (rev 3683) @@ -1,15 +1,15 @@ <?xml version="1.0" encoding="UTF-8"?> <classpath> <classpathentry kind="src" path="src/install"/> + <classpathentry kind="src" path="src/emu"/> + <classpathentry kind="src" path="src/test"/> <classpathentry kind="src" path="/JNode-Core"/> <classpathentry kind="src" path="src/apps"/> <classpathentry kind="src" path="/JNode-GUI"/> - <classpathentry kind="lib" path="/JNode-Shell/lib/bsh-2.0b4.jar"/> - <classpathentry kind="lib" path="lib/stamps_framework.jar"/> - <classpathentry kind="lib" path="lib/commons-logging.jar"/> <classpathentry kind="src" path="/JNode-Shell"/> <classpathentry kind="src" path="/JNode-TextUI"/> <classpathentry combineaccessrules="false" kind="src" path="/JNode-FS"/> + <classpathentry kind="lib" path="/JNode-Shell/lib/bsh-2.0b5.jar"/> <classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/4"/> <classpathentry kind="output" path="build/classes"/> </classpath> Modified: trunk/distr/build.xml =================================================================== --- trunk/distr/build.xml 2008-01-03 14:57:22 UTC (rev 3682) +++ trunk/distr/build.xml 2008-01-04 17:38:02 UTC (rev 3683) @@ -8,8 +8,6 @@ <property name="my.jar" value="${jnode-distr.jar}"/> <property name="junit4.jar" value="${basedir}/lib/junit-4.1.jar"/> - <property name="commons-logging.jar" value="${basedir}/lib/commons-logging.jar"/> - <property name="stamps-mvc.jar" value="${basedir}/lib/stamps_framework.jar"/> <!-- Subproject specific classpath --> <path id="my-cp"> @@ -20,8 +18,6 @@ <pathelement location="${jnode-fs.jar}"/> <pathelement location="${junit4.jar}"/> - <pathelement location="${commons-logging.jar}"/> - <pathelement location="${stamps-mvc.jar}"/> <path refid="cp"/> </path> Added: trunk/distr/descriptors/org.jnode.apps.jpartition.xml =================================================================== --- trunk/distr/descriptors/org.jnode.apps.jpartition.xml (rev 0) +++ trunk/distr/descriptors/org.jnode.apps.jpartition.xml 2008-01-04 17:38:02 UTC (rev 3683) @@ -0,0 +1,23 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plugin SYSTEM "jnode.dtd"> + +<plugin id="org.jnode.apps.jpartition" + name="JPartition" + version="@VERSION@" + license-name="lgpl" + provider-name="JNode.org"> + + <requires> + <import plugin="org.jnode.apps.vmware.disk"/> + </requires> + + <runtime> + <library name="jnode-distr.jar"> + <export name="org.jnode.apps.jpartition.*"/> + </library> + </runtime> + + <extension point="org.jnode.shell.aliases"> + <alias name="jpartition" class="org.jnode.apps.jpartition.JPartition"/> + </extension> +</plugin> Property changes on: trunk/distr/descriptors/org.jnode.apps.jpartition.xml ___________________________________________________________________ Name: svn:executable + * Added: trunk/distr/descriptors/org.jnode.apps.vmware.disk.xml =================================================================== --- trunk/distr/descriptors/org.jnode.apps.vmware.disk.xml (rev 0) +++ trunk/distr/descriptors/org.jnode.apps.vmware.disk.xml 2008-01-04 17:38:02 UTC (rev 3683) @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plugin SYSTEM "jnode.dtd"> + +<plugin id="org.jnode.apps.vmware.disk" + name="VMWareDisk" + version="@VERSION@" + license-name="lgpl" + provider-name="JNode.org"> + + <runtime> + <library name="jnode-distr.jar"> + <export name="org.jnode.apps.vmware.disk.*"/> + </library> + </runtime> +</plugin> Property changes on: trunk/distr/descriptors/org.jnode.apps.vmware.disk.xml ___________________________________________________________________ Name: svn:executable + * Deleted: trunk/distr/lib/commons-logging.jar =================================================================== (Binary files differ) Added: trunk/distr/lib/jedit.jar =================================================================== (Binary files differ) Property changes on: trunk/distr/lib/jedit.jar ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Deleted: trunk/distr/lib/stamps_framework.jar =================================================================== (Binary files differ) Added: trunk/distr/src/apps/org/jnode/apps/jpartition/ErrorReporter.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/jpartition/ErrorReporter.java (rev 0) +++ trunk/distr/src/apps/org/jnode/apps/jpartition/ErrorReporter.java 2008-01-04 17:38:02 UTC (rev 3683) @@ -0,0 +1,9 @@ +package org.jnode.apps.jpartition; + +import org.apache.log4j.Logger; + +public interface ErrorReporter { + void reportError(Logger log, Object source, Throwable t); + + void reportError(Logger log, Object source, String message); +} Modified: trunk/distr/src/apps/org/jnode/apps/jpartition/JPartition.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/jpartition/JPartition.java 2008-01-03 14:57:22 UTC (rev 3682) +++ trunk/distr/src/apps/org/jnode/apps/jpartition/JPartition.java 2008-01-04 17:38:02 UTC (rev 3683) @@ -3,37 +3,19 @@ import org.apache.log4j.Logger; import org.jnode.apps.jpartition.controller.MainController; import org.jnode.apps.jpartition.swingview.SwingViewFactory; -import org.jnode.apps.jpartition.utils.BasicNameSpace; -import org.jnode.driver.DeviceManager; -import org.jnode.emu.Emu; -import org.jnode.naming.InitialNaming; -import org.jnode.naming.NameSpace; -import org.jnode.test.fs.driver.stubs.StubDeviceManager; -import org.jnode.util.OsUtils; -public class JPartition extends Emu { +public class JPartition { private static final Logger log = Logger.getLogger(JPartition.class); - - public static void main(String[] args) throws Throwable + + public static void main(String[] args) throws Throwable { // testCharva(); - - if(!OsUtils.isJNode()) - { - initJNodeCore(); - } - + ViewFactory viewFactory = new SwingViewFactory(); MainController controller = new MainController(viewFactory); } - - private static void initJNodeCore() throws Exception { - NameSpace namespace = new BasicNameSpace(); - InitialNaming.setNameSpace(namespace); - namespace.bind(DeviceManager.NAME, StubDeviceManager.INSTANCE); - } - -/* + +/* private static void testCharva() throws Throwable { initEnv(); @@ -45,14 +27,14 @@ final ShellManager sm = InitialNaming.lookup(ShellManager.NAME); sm.registerShell(cs); new Thread(cs).start(); - + charvax.swing.JFrame frm = new charvax.swing.JFrame("test"); JLabel label = new JLabel("test"); frm.add(label); frm.setFocus(label); frm.setSize(300, 300); frm.setVisible(true); - frm.setDefaultCloseOperation(charvax.swing.JFrame.EXIT_ON_CLOSE); + frm.setDefaultCloseOperation(charvax.swing.JFrame.EXIT_ON_CLOSE); } -*/ +*/ } Modified: trunk/distr/src/apps/org/jnode/apps/jpartition/ViewFactory.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/jpartition/ViewFactory.java 2008-01-03 14:57:22 UTC (rev 3682) +++ trunk/distr/src/apps/org/jnode/apps/jpartition/ViewFactory.java 2008-01-04 17:38:02 UTC (rev 3683) @@ -1,12 +1,11 @@ package org.jnode.apps.jpartition; -import org.jnode.apps.jpartition.controller.MainController; public interface ViewFactory { - Object createDeviceView(MainController controller, Object fileDeviceView, - Object cmdProcessorView) throws Exception; - - Object createFileDeviceView(MainController controller) throws Exception; + Object createDeviceView(Object cmdProcessorView) + throws Exception; - Object createCommandProcessorView(MainController mainController); + Object createCommandProcessorView(); + + ErrorReporter createErrorReporter(); } Modified: trunk/distr/src/apps/org/jnode/apps/jpartition/commands/BaseDeviceCommand.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/jpartition/commands/BaseDeviceCommand.java 2008-01-03 14:57:22 UTC (rev 3682) +++ trunk/distr/src/apps/org/jnode/apps/jpartition/commands/BaseDeviceCommand.java 2008-01-04 17:38:02 UTC (rev 3683) @@ -5,17 +5,24 @@ import org.jnode.driver.bus.ide.IDEDevice; import org.jnode.partitions.command.FdiskCommand; +import sun.java2d.pipe.NullPipe; + abstract public class BaseDeviceCommand extends BaseCommand { protected final IDEDevice device; - - public BaseDeviceCommand(String name, IDEDevice device) + + public BaseDeviceCommand(String name, IDEDevice device) { super(name); + if(device == null) + { + throw new NullPointerException("device is null"); + } + this.device = device; } abstract protected void doExecute() throws CommandException; - + @Override public String toString() { return super.toString() + " - " + device.getId(); Added: trunk/distr/src/apps/org/jnode/apps/jpartition/commands/BasePartitionCommand.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/jpartition/commands/BasePartitionCommand.java (rev 0) +++ trunk/distr/src/apps/org/jnode/apps/jpartition/commands/BasePartitionCommand.java 2008-01-04 17:38:02 UTC (rev 3683) @@ -0,0 +1,21 @@ +package org.jnode.apps.jpartition.commands; + +import org.jnode.apps.jpartition.commands.framework.CommandException; +import org.jnode.driver.bus.ide.IDEDevice; + +abstract public class BasePartitionCommand extends BaseDeviceCommand { + private final int partitionNumber; + + public BasePartitionCommand(String name, IDEDevice device, int partitionNumber) + { + super(name, device); + this.partitionNumber = partitionNumber; + } + + abstract protected void doExecute() throws CommandException; + + @Override + public String toString() { + return super.toString() + " - partition " + partitionNumber; + } +} Added: trunk/distr/src/apps/org/jnode/apps/jpartition/commands/CreatePartitionCommand.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/jpartition/commands/CreatePartitionCommand.java (rev 0) +++ trunk/distr/src/apps/org/jnode/apps/jpartition/commands/CreatePartitionCommand.java 2008-01-04 17:38:02 UTC (rev 3683) @@ -0,0 +1,17 @@ +package org.jnode.apps.jpartition.commands; + +import org.jnode.apps.jpartition.commands.framework.CommandException; +import org.jnode.driver.bus.ide.IDEDevice; + +public class CreatePartitionCommand extends BasePartitionCommand { + + public CreatePartitionCommand(IDEDevice device, int partitionNumber) { + super("create partition", device, partitionNumber); + } + + @Override + final protected void doExecute() throws CommandException { + // TODO Auto-generated method stub + + } +} Added: trunk/distr/src/apps/org/jnode/apps/jpartition/commands/FormatPartitionCommand.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/jpartition/commands/FormatPartitionCommand.java (rev 0) +++ trunk/distr/src/apps/org/jnode/apps/jpartition/commands/FormatPartitionCommand.java 2008-01-04 17:38:02 UTC (rev 3683) @@ -0,0 +1,17 @@ +package org.jnode.apps.jpartition.commands; + +import org.jnode.apps.jpartition.commands.framework.CommandException; +import org.jnode.driver.bus.ide.IDEDevice; + +public class FormatPartitionCommand extends BasePartitionCommand { + + public FormatPartitionCommand(IDEDevice device, int partitionNumber) { + super("format partition", device, partitionNumber); + } + + @Override + final protected void doExecute() throws CommandException { + // TODO Auto-generated method stub + + } +} Added: trunk/distr/src/apps/org/jnode/apps/jpartition/commands/RemovePartitionCommand.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/jpartition/commands/RemovePartitionCommand.java (rev 0) +++ trunk/distr/src/apps/org/jnode/apps/jpartition/commands/RemovePartitionCommand.java 2008-01-04 17:38:02 UTC (rev 3683) @@ -0,0 +1,17 @@ +package org.jnode.apps.jpartition.commands; + +import org.jnode.apps.jpartition.commands.framework.CommandException; +import org.jnode.driver.bus.ide.IDEDevice; + +public class RemovePartitionCommand extends BasePartitionCommand { + + public RemovePartitionCommand(IDEDevice device, int partitionNumber) { + super("remove partition", device, partitionNumber); + } + + @Override + final protected void doExecute() throws CommandException { + // TODO Auto-generated method stub + + } +} Modified: trunk/distr/src/apps/org/jnode/apps/jpartition/commands/framework/BaseCommand.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/jpartition/commands/framework/BaseCommand.java 2008-01-03 14:57:22 UTC (rev 3682) +++ trunk/distr/src/apps/org/jnode/apps/jpartition/commands/framework/BaseCommand.java 2008-01-04 17:38:02 UTC (rev 3683) @@ -2,27 +2,27 @@ import org.apache.log4j.Logger; -abstract public class BaseCommand implements Command +abstract public class BaseCommand implements Command { private static final Logger log = Logger.getLogger(BaseCommand.class); - + private CommandStatus status = CommandStatus.NOT_RUNNING; - protected String name; - + final private String name; + protected BaseCommand(String name) { this.name = name; } - + final public void execute(CommandProcessor processor) throws CommandException { try { status = CommandStatus.RUNNING; processor.commandStarted(this); - + doExecute(); - status = CommandStatus.SUCCESS; + status = CommandStatus.SUCCESS; } catch(CommandException e) { @@ -37,14 +37,14 @@ throw new CommandException("command failed", t); } } - - public CommandStatus getStatus() + + final public CommandStatus getStatus() { return status; } - + abstract protected void doExecute() throws CommandException; - + @Override public String toString() { return status + " - " + name; Modified: trunk/distr/src/apps/org/jnode/apps/jpartition/commands/framework/CommandProcessor.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/jpartition/commands/framework/CommandProcessor.java 2008-01-03 14:57:22 UTC (rev 3682) +++ trunk/distr/src/apps/org/jnode/apps/jpartition/commands/framework/CommandProcessor.java 2008-01-04 17:38:02 UTC (rev 3683) @@ -4,82 +4,99 @@ import java.util.List; import java.util.Stack; import org.apache.log4j.Logger; +import org.jnode.apps.jpartition.ErrorReporter; +import org.jnode.apps.jpartition.swingview.SwingErrorReporter; -public class CommandProcessor { +public class CommandProcessor implements ErrorReporter +{ private static final Logger log = Logger.getLogger(CommandProcessor.class); - + + private final ErrorReporter errorReporter; + private Stack<Command> commands = new Stack<Command>(); private List<CommandProcessorListener> listeners = new ArrayList<CommandProcessorListener>(); - + private boolean running = false; - + + public CommandProcessor(ErrorReporter errorReporter) + { + this.errorReporter = errorReporter; + } + public synchronized void process() { - if(!running) + try { - running = true; - - while(!commands.isEmpty()) + if(!running) { - Command command = null; - try + running = true; + + while(!commands.isEmpty()) { - command = peekCommand(); - - command.execute(this); - } - catch(CommandException e) - { - log.error("error in command processing", e); - break; - } - catch(Throwable t) - { - log.error("unexpected error in command processing", t); - break; - } - finally - { - if(command != null) + Command command = null; + try { - for(CommandProcessorListener l : listeners) + command = peekCommand(); + + command.execute(this); + } + catch(CommandException e) + { + log.error("error in command processing", e); + break; + } + catch(Throwable t) + { + log.error("unexpected error in command processing", t); + break; + } + finally + { + if(command != null) { - l.commandFinished(this, command); + for(CommandProcessorListener l : listeners) + { + l.commandFinished(this, command); + } + + try { + removeCommand(); + } + catch(Throwable t) + { + log.error("error in removeCommand", t); + } } - - try { - removeCommand(); - } - catch(Throwable t) - { - log.error("error in removeCommand", t); - } } } + + running = false; } - - running = false; } + catch(Throwable t) + { + errorReporter.reportError(log, this, t); + } } - + public void addCommand(Command command) { if(command.getStatus() != CommandStatus.NOT_RUNNING) { throw new IllegalArgumentException("command must be in status NOT_RUNNING"); } - + commands.push(command); - + for(CommandProcessorListener l : listeners) { l.commandAdded(this, command); - } + } } - + protected Command peekCommand() throws Exception { - Command command = commands.peek(); + Command command = commands.peek(); if(command.getStatus() != CommandStatus.NOT_RUNNING) { throw new Exception("command already started : "+command); @@ -90,7 +107,7 @@ protected void removeCommand() { Command command = commands.pop(); - + for(CommandProcessorListener l : listeners) { l.commandRemoved(this, command); @@ -102,16 +119,24 @@ for(CommandProcessorListener l : listeners) { l.commandStarted(this, command); - } + } } - + public void addListener(CommandProcessorListener listener) { listeners.add(listener); } - + public void removeListener(CommandProcessorListener listener) { listeners.remove(listener); } + + public void reportError(Logger log, Object source, Throwable t) { + errorReporter.reportError(log, source, t); + } + + public void reportError(Logger log, Object source, String message) { + errorReporter.reportError(log, source, message); + } } Deleted: trunk/distr/src/apps/org/jnode/apps/jpartition/model/AbstractModel.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/jpartition/model/AbstractModel.java 2008-01-03 14:57:22 UTC (rev 3682) +++ trunk/distr/src/apps/org/jnode/apps/jpartition/model/AbstractModel.java 2008-01-04 17:38:02 UTC (rev 3683) @@ -1,31 +0,0 @@ -package org.jnode.apps.jpartition.model; - -import it.battlehorse.stamps.Model; -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; - -abstract public class AbstractModel implements Model -{ - final protected PropertyChangeSupport propSupport; - - /** - * Creates a new instance of the class - */ - public AbstractModel() { - propSupport = new PropertyChangeSupport(this); - } - - // - // This method will be invoked by the dispatcher on model registration - // - public void addPropertyChangeListener(PropertyChangeListener listener) { - propSupport.addPropertyChangeListener(listener); - } - - // - // This method will be invoked by the dispatcher on model deregistration - // - public void removePropertyChangeListener(PropertyChangeListener listener) { - propSupport.removePropertyChangeListener(listener); - } -} Added: trunk/distr/src/apps/org/jnode/apps/jpartition/model/Bounded.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/jpartition/model/Bounded.java (rev 0) +++ trunk/distr/src/apps/org/jnode/apps/jpartition/model/Bounded.java 2008-01-04 17:38:02 UTC (rev 3683) @@ -0,0 +1,9 @@ +package org.jnode.apps.jpartition.model; + +public interface Bounded { + + long getStart(); + + long getEnd(); + +} Deleted: trunk/distr/src/apps/org/jnode/apps/jpartition/model/CommandProcessorModel.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/jpartition/model/CommandProcessorModel.java 2008-01-03 14:57:22 UTC (rev 3682) +++ trunk/distr/src/apps/org/jnode/apps/jpartition/model/CommandProcessorModel.java 2008-01-04 17:38:02 UTC (rev 3683) @@ -1,53 +0,0 @@ -package org.jnode.apps.jpartition.model; - -import org.apache.log4j.Logger; -import org.jnode.apps.jpartition.commands.framework.Command; -import org.jnode.apps.jpartition.commands.framework.CommandProcessor; -import org.jnode.apps.jpartition.commands.framework.CommandProcessorListener; -import org.jnode.apps.jpartition.swingview.ErrorReporter; - -public class CommandProcessorModel extends AbstractModel - implements CommandProcessorListener -{ - private static final Logger log = Logger.getLogger(CommandProcessorModel.class); - - private final CommandProcessor commandProcessor; - - public CommandProcessorModel() - { - commandProcessor = new CommandProcessor(); - commandProcessor.addListener(this); - } - - public void processCommands() - { - try - { - commandProcessor.process(); - } - catch(Throwable t) - { - ErrorReporter.reportError(log, this, t); - } - finally - { - propSupport.firePropertyChange("commandsProcessed", null, this); - } - } - - public void commandAdded(CommandProcessor processor, Command command) { - propSupport.firePropertyChange("commandAdded", null, command); - } - - public void commandStarted(CommandProcessor processor, Command command) { - propSupport.firePropertyChange("commandStarted", command, command); - } - - public void commandFinished(CommandProcessor processor, Command command) { - propSupport.firePropertyChange("commandFinished", command, command); - } - - public void commandRemoved(CommandProcessor processor, Command command) { - propSupport.firePropertyChange("commandRemoved", command, command); - } -} Added: trunk/distr/src/apps/org/jnode/apps/jpartition/model/Device.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/jpartition/model/Device.java (rev 0) +++ trunk/distr/src/apps/org/jnode/apps/jpartition/model/Device.java 2008-01-04 17:38:02 UTC (rev 3683) @@ -0,0 +1,250 @@ +package org.jnode.apps.jpartition.model; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; + +import org.jnode.driver.ApiNotFoundException; +import org.jnode.driver.bus.ide.IDEDeviceAPI; +import org.jnode.fs.FileSystem; +import org.jnode.fs.Formatter; + + +public class Device implements Iterable<Partition>, Bounded { + final private String name; + final private long size; + final private List<Partition> partitions; + final private org.jnode.driver.Device device; + + Device(String name, long size) { + this(name, size, null); + } + + Device(org.jnode.driver.Device dev) throws ApiNotFoundException, IOException { + this(dev.getId(), dev.getAPI(IDEDeviceAPI.class).getLength(), dev); + } + + private Device(String name, long size, org.jnode.driver.Device device) { + this.name = name; + this.size = size; + partitions = new ArrayList<Partition>(); + partitions.add(new Partition(0L, size, false)); + this.device = device; + } + + final public String getName() { + return name; + } + + final public long getSize() { + return size; + } + + final public Iterator<Partition> iterator() { + return partitions.iterator(); + } + + final public List<Partition> getPartitions() { + return Collections.unmodifiableList(partitions); + } + + final public long getEnd() { + return size - 1; + } + + final public long getStart() { + return 0; + } + + final public boolean equals(Object o) + { + if(!(o instanceof Device)) + { + return false; + } + + Device other = (Device) o; + return name.equals(other.name); + } + + final org.jnode.driver.Device getDevice() + { + return device; + } + + final public int hashCode() + { + return name.hashCode(); + } + + final void addPartition(long start, long size) + { + final long end = (start + size - 1); + checkBounds(this, "start", start); + checkBounds(this, "end", end); + + Partition newPart = null; + int index = findPartition(start, false); + if(index < 0) + { + throw new DeviceException("can't add a partition in a used one"); + } + + Partition oldPart = partitions.get(index); + checkBounds(oldPart, "end", end); + + newPart = new Partition(start, size, true); + if(oldPart.getSize() == size) + { + // replace the unused partition + partitions.set(index, newPart); + } + else if(start == oldPart.getStart()) + { + // the new partition + partitions.add(index, newPart); + + // after the new partition + oldPart.setSize(oldPart.getSize() - size); + oldPart.setStart(newPart.getEnd() + 1); + partitions.set(index + 1, oldPart); + } + else if(end == oldPart.getEnd()) + { + // before the new partition + oldPart.setSize(oldPart.getSize() - size); + + // the new partition + partitions.add(index + 1, newPart); + } + else + { + long beginSize = start - oldPart.getStart(); + long endSize = oldPart.getSize() - size - beginSize; + + // before the new partition + oldPart.setSize(beginSize); + + // the new partition + partitions.add(index + 1, newPart); + + // after the new partition + partitions.add(index + 2, new Partition(end + 1, endSize, false)); + } + } + + final void removePartition(long offset) + { + int index = findPartition(offset, true); + if(index < 0) + { + throw new DeviceException("can't remove an empty partition"); + } + + Partition part = partitions.get(index); + long start = part.getStart(); + long size = part.getSize(); + if(index > 0) + { + Partition partBefore = partitions.get(index - 1); + if(!partBefore.isUsed() ) + { + // merge with previous empty partition + start = partBefore.getStart(); + size += partBefore.getSize(); + partitions.remove(index); + index--; + } + } + + if(index < (partitions.size() - 1)) + { + Partition partAfter = partitions.get(index + 1); + if(!partAfter.isUsed()) + { + // merge with following empty partition + size += partAfter.getSize(); + partitions.remove(index + 1); + } + } + + partitions.set(index, new Partition(start, size, false)); + } + + final void formatPartition(long offset, Formatter<? extends FileSystem> formatter) + { + int index = findPartition(offset, true); + if(index < 0) + { + throw new DeviceException("can't format an empty partition"); + } + + Partition part = partitions.get(index); + part.format(formatter); + } + +/* + public void moveStart(DevicePart part, long delta) + { + if(part.isUsed()) + { + ((Partition) part).moveStart(delta); + } + } + + public void moveEnd(DevicePart part, long delta) + { + if(part.isUsed()) + { + //TODO + //((Partition) part).moveEnd(delta); + } + } + + public void move(DevicePart part, long delta) + { + moveStart(part, delta); + moveEnd(part, delta); + } +*/ + + final private int findPartition(long offset, boolean used) + { + checkOffset(offset); + + int result = -1; + int index = 0; + for(Partition currentPart : this) + { + if(currentPart.contains(offset) && (currentPart.isUsed() == used)) + { + result = index; + break; + } + index++; + } + return result; + } + + final private void checkOffset(long offset) + { + if((offset < 0) || (offset >= size)) + { + throw new DeviceException("offset("+offset+") out of bounds. should be >=0 and <"+size); + } + } + + + final private void checkBounds(Bounded bounded, String valueName, long value) { + if(value < bounded.getStart()) + { + throw new DeviceException(valueName + " must be >= "+ bounded.getStart()); + } + if(value > bounded.getEnd()) + { + throw new DeviceException(valueName + " must be <= "+ bounded.getEnd()); + } + } +} Added: trunk/distr/src/apps/org/jnode/apps/jpartition/model/DeviceException.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/jpartition/model/DeviceException.java (rev 0) +++ trunk/distr/src/apps/org/jnode/apps/jpartition/model/DeviceException.java 2008-01-04 17:38:02 UTC (rev 3683) @@ -0,0 +1,22 @@ +package org.jnode.apps.jpartition.model; + + +public class DeviceException extends RuntimeException { + + public DeviceException() { + super(); + } + + public DeviceException(String message, Throwable cause) { + super(message, cause); + } + + public DeviceException(String message) { + super(message); + } + + public DeviceException(Throwable cause) { + super(cause); + } + +} Deleted: trunk/distr/src/apps/org/jnode/apps/jpartition/model/DeviceModel.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/jpartition/model/DeviceModel.java 2008-01-03 14:57:22 UTC (rev 3682) +++ trunk/distr/src/apps/org/jnode/apps/jpartition/model/DeviceModel.java 2008-01-04 17:38:02 UTC (rev 3683) @@ -1,104 +0,0 @@ -package org.jnode.apps.jpartition.model; - -import java.util.ArrayList; -import java.util.List; -import javax.naming.NameNotFoundException; -import org.apache.log4j.Logger; -import org.jnode.driver.Device; -import org.jnode.driver.DeviceListener; -import org.jnode.driver.DeviceUtils; -import org.jnode.driver.block.PartitionableBlockDeviceAPI; -import org.jnode.driver.bus.ide.IDEDevice; -import org.jnode.partitions.PartitionTableEntry; -import org.jnode.partitions.command.PartitionHelper; -import org.jnode.partitions.ibm.IBMPartitionTableEntry; - -public class DeviceModel extends AbstractModel - implements DeviceListener -{ - private static final Logger log = Logger.getLogger(DeviceModel.class); - - private final List<PartitionModel> partitions = new ArrayList<PartitionModel>(); - - public DeviceModel() - { - try { - DeviceUtils.getDeviceManager().addListener(this); - } catch (NameNotFoundException e) { - log.error(e); - } - } - - public void setDevice(Object device) { - propSupport.firePropertyChange("deviceSelected", null, device); - try { - addPartitions((IDEDevice) device); - } catch (Exception e) { - log.error(e); - } - } - - protected void addPartitions(IDEDevice device) throws Exception - { - PartitionHelper helper = new PartitionHelper(device); - - log.debug("addPartitions"); - if(device.implementsAPI(PartitionableBlockDeviceAPI.class)) - { - log.debug("implementsAPI"); - partitions.clear(); - PartitionableBlockDeviceAPI<?> api = device.getAPI(PartitionableBlockDeviceAPI.class); - for(PartitionTableEntry e : api.getPartitionTable()) - { - log.debug("PartitionTableEntry"); - addPartition(e); - } - } - } - - public void addPartition(PartitionTableEntry e) - { - if(e instanceof IBMPartitionTableEntry) - { - IBMPartitionTableEntry pte = (IBMPartitionTableEntry) e; - addPartition(new PartitionModel(pte)); - } - else - { - log.warn("found non-IBMPartitionTableEntry"); - } - } - - public void addPartition(PartitionModel partition) - { - propSupport.fireIndexedPropertyChange("partitionAdded", partitions.size(), null, partition); - partitions.add(partition); - } - - public void removePartition(PartitionModel partition) - { - int index = partitions.indexOf(partition); - propSupport.fireIndexedPropertyChange("partitionRemoved", index, null, partition); - partitions.remove(partition); - } - - // - // DeviceListener interface - // - public void deviceStarted(Device device) { - if(device instanceof IDEDevice) - { - log.debug("deviceStarted..."); - propSupport.firePropertyChange("deviceStarted", null, device); - } - } - - public void deviceStop(Device device) { - log.debug("deviceStop..."); - propSupport.firePropertyChange("deviceStop", null, device); - } - - // - // - // -} Deleted: trunk/distr/src/apps/org/jnode/apps/jpartition/model/FileDeviceModel.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/jpartition/model/FileDeviceModel.java 2008-01-03 14:57:22 UTC (rev 3682) +++ trunk/distr/src/apps/org/jnode/apps/jpartition/model/FileDeviceModel.java 2008-01-04 17:38:02 UTC (rev 3683) @@ -1,35 +0,0 @@ -package org.jnode.apps.jpartition.model; - -import java.util.ArrayList; -import java.util.List; -import org.jnode.apps.jpartition.utils.device.DeviceUtils; -import org.jnode.driver.bus.ide.IDEDevice; - -public class FileDeviceModel extends AbstractModel { - private List<IDEDevice> fileDevices = new ArrayList<IDEDevice>(); - - public void addFakeDisk() { - addDevice(DeviceUtils.createFakeDevice()); - } - - public void addVMWareDisk() { - addDevice(DeviceUtils.createVMWareDevice()); - } - - public void addDevice(IDEDevice device) - { - if(device != null) - { - fileDevices.add(device); - propSupport.firePropertyChange("deviceAdded", null, device); - } - } - - public void removeFileDevice(Object device) { - if(device != null) - { - fileDevices.remove(device); - propSupport.firePropertyChange("deviceRemoved", null, device); - } - } -} Added: trunk/distr/src/apps/org/jnode/apps/jpartition/model/OSFacade.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/jpartition/model/OSFacade.java (rev 0) +++ trunk/distr/src/apps/org/jnode/apps/jpartition/model/OSFacade.java 2008-01-04 17:38:02 UTC (rev 3683) @@ -0,0 +1,126 @@ +package org.jnode.apps.jpartition.model; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import javax.naming.NameNotFoundException; + +import org.jnode.driver.ApiNotFoundException; +import org.jnode.driver.DeviceListener; +import org.jnode.driver.DeviceManager; +import org.jnode.driver.DeviceNotFoundException; +import org.jnode.driver.DeviceUtils; +import org.jnode.driver.block.PartitionableBlockDeviceAPI; +import org.jnode.driver.bus.ide.IDEConstants; +import org.jnode.driver.bus.ide.IDEDevice; +import org.jnode.driver.bus.ide.IDEDeviceAPI; +import org.jnode.partitions.PartitionTableEntry; +import org.jnode.partitions.ibm.IBMPartitionTableEntry; + +public class OSFacade { + private static final OSFacade INSTANCE; + static + { + INSTANCE = new OSFacade(); + } + + private OSListener osListener; + + private OSFacade() + { + } + + final static OSFacade getInstance() + { + return INSTANCE; + } + + final void setOSListener(final OSListener listener) + { + if(this.osListener != null) + { + throw new IllegalStateException("listener already set"); + } + + try { + DeviceUtils.getDeviceManager().addListener(new DeviceListener(){ + public void deviceStarted(org.jnode.driver.Device device) { + if(device instanceof IDEDevice) + { + Device dev = createDevice(device); + if(dev != null) + { + listener.deviceAdded(dev); + } + } + } + + public void deviceStop(org.jnode.driver.Device device) { + if(device instanceof IDEDevice) + { + Device dev = createDevice(device); + if(dev != null) + { + listener.deviceRemoved(dev); + } + } + }}); + } catch (NameNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + final List<Device> getDevices() throws NameNotFoundException, ApiNotFoundException, IOException + { + List<Device> devices = new ArrayList<Device>(); + DeviceManager devMan = org.jnode.driver.DeviceUtils.getDeviceManager(); + for(org.jnode.driver.Device dev : devMan.getDevicesByAPI(IDEDeviceAPI.class)) + { + Device device = createDevice(dev); + if(device != null) + { + devices.add(device); + } + } + return devices; + } + + private Device createDevice(org.jnode.driver.Device dev) + { + Device device = null; + try { + if(dev.implementsAPI(IDEDeviceAPI.class)) + { + Device tmpDevice = new Device(dev); + + if(dev.implementsAPI(PartitionableBlockDeviceAPI.class)) + { + PartitionableBlockDeviceAPI<?> api = dev.getAPI(PartitionableBlockDeviceAPI.class); + for(PartitionTableEntry e : api.getPartitionTable()) + { + if(e instanceof IBMPartitionTableEntry) + { + IBMPartitionTableEntry pte = (IBMPartitionTableEntry) e; + if(!pte.isEmpty()) + { + long size = pte.getNrSectors() * IDEConstants.SECTOR_SIZE; + tmpDevice.addPartition(pte.getStartLba(), size); + } + } + } + } + + device = tmpDevice; + } + } catch (ApiNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return device; + } +} Added: trunk/distr/src/apps/org/jnode/apps/jpartition/model/OSListener.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/jpartition/model/OSListener.java (rev 0) +++ trunk/distr/src/apps/org/jnode/apps/jpartition/model/OSListener.java 2008-01-04 17:38:02 UTC (rev 3683) @@ -0,0 +1,9 @@ +package org.jnode.apps.jpartition.model; + +interface OSListener { + + void deviceAdded(Device addedDevice); + + void deviceRemoved(Device removedDevice); + +} Added: trunk/distr/src/apps/org/jnode/apps/jpartition/model/Partition.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/jpartition/model/Partition.java (rev 0) +++ trunk/distr/src/apps/org/jnode/apps/jpartition/model/Partition.java 2008-01-04 17:38:02 UTC (rev 3683) @@ -0,0 +1,84 @@ +package org.jnode.apps.jpartition.model; + +import org.jnode.fs.FileSystem; +import org.jnode.fs.Formatter; + + +public class Partition implements Bounded { + private static final long MIN_SIZE = 1; + + private long start; + private long size; + private boolean used; + private Formatter<? extends FileSystem> formatter; + + Partition(long start, long size, boolean used) { + this.start = start; + this.size = size; + this.used = used; + + if(size < MIN_SIZE) + { + throw new IllegalArgumentException("size must be > "+MIN_SIZE); + } + } + + final public long getStart() { + return start; + } + + final public long getEnd() + { + return getStart() + size - 1; + } + + final public long getSize() { + return size; + } + + final public boolean isUsed() + { + return used; + } + + final public String toString() + { + return "["+getStart()+","+getEnd()+"]"; + } + + final public String getFormat() + { + return isUsed() ? formatter.getFileSystemType().getName() : ""; + } + + final boolean contains(long offset) { + long start = getStart(); + return (offset >= start) && ((offset - start) < size); + } + + final void moveStart(long delta) { +// if((delta < 0) && (previous != null)) +// { +// previous.resize(delta); +// } +// else if(delta > 0) +// { +// if(previous != null) +// { +// previous.resize(delta); +// } +// } + } + + final void setStart(long start) { + this.start = start; + } + + final void setSize(long size) { + this.size = size; + } + + final void format(Formatter<? extends FileSystem> formatter) { + this.formatter = formatter; + } +} Deleted: trunk/distr/src/apps/org/jnode/apps/jpartition/model/PartitionModel.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/jpartition/model/PartitionModel.java 2008-01-03 14:57:22 UTC (rev 3682) +++ trunk/distr/src/apps/org/jnode/apps/jpartition/model/PartitionModel.java 2008-01-04 17:38:02 UTC (rev 3683) @@ -1,109 +0,0 @@ -package org.jnode.apps.jpartition.model; - -import it.battlehorse.stamps.annotations.Refreshable; -import org.jnode.partitions.ibm.IBMPartitionTableEntry; -import org.jnode.partitions.ibm.IBMPartitionTypes; - - -public class PartitionModel extends AbstractModel -{ - private boolean empty; - private boolean bootable; - private IBMPartitionTypes type; - private long start; - private long size; - - private IBMPartitionTableEntry pte; - - public PartitionModel(IBMPartitionTableEntry pte) - { - this.pte = pte; - - //TODO remove these fake values - this.empty = false; - this.bootable = true; - this.type = IBMPartitionTypes.PARTTYPE_WIN95_FAT32; - this.start = 0; - this.size = 1024; - } - - @Refreshable - public boolean isEmpty() { - return empty; - } - public void setEmpty(boolean empty) { - propSupport.firePropertyChange("empty", this.empty, empty); - this.empty = empty; - } - - @Refreshable - public boolean isBootable() { - return bootable; - } - public void setBootable(boolean bootable) { - propSupport.firePropertyChange("bootable", this.bootable, bootable); - this.bootable = bootable; - } - - @Refreshable - public IBMPartitionTypes getType() { - return type; - } - public void setType(IBMPartitionTypes type) { - propSupport.firePropertyChange("type", this.type, type); - this.type = type; - } - - @Refreshable - public long getStart() { - return start; - } - public void setStart(long start) { - propSupport.firePropertyChange("start", this.start, start); - this.start = start; - } - - @Refreshable - public long getSize() { - return size; - } - public void setSize(long size) { - propSupport.firePropertyChange("size", this.size, size); - this.size = size; - } - - -/* - private final IBMPartitionTableEntry pte; - - public PartitionModel(IBMPartitionTableEntry pte) - { - this.pte = pte; - } - - public boolean isEmpty() - { - return pte.isEmpty(); - } - - public boolean isBootable() - { - return pte.getBootIndicator(); - } - - public IBMPartitionTypes getType() - { - return pte.getSystemIndicator(); - } - - public long getStart() - { - return pte.getStartLba(); - } - - public long getSize() - { - return pte.getNrSectors() * IDEConstants.SECTOR_SIZE; - } -*/ -} Added: trunk/distr/src/apps/org/jnode/apps/jpartition/model/UserFacade.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/jpartition/model/UserFacade.java (rev 0) +++ trunk/distr/src/apps/org/jnode/apps/jpartition/model/UserFacade.java 2008-01-04 17:38:02 UTC (rev 3683) @@ -0,0 +1,206 @@ +package org.jnode.apps.jpartition.model; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Arrays; + +import javax.naming.NameNotFoundException; + +import org.apache.log4j.Logger; +import org.jnode.apps.jpartition.ErrorReporter; +import org.jnode.apps.jpartition.commands.CreatePartitionCommand; +import org.jnode.apps.jpartition.commands.FormatPartitionCommand; +import org.jnode.apps.jpartition.commands.RemovePartitionCommand; +import org.jnode.apps.jpartition.commands.framework.CommandProcessor; +import org.jnode.apps.jpartition.commands.framework.CommandProcessorListener; +import org.jnode.driver.ApiNotFoundException; +import org.jnode.driver.bus.ide.IDEDevice; +import org.jnode.fs.FileSystem; +import org.jnode.fs.Formatter; +import org.jnode.fs.ext2.BlockSize; +import org.jnode.fs.ext2.Ext2FileSystemFormatter; +import org.jnode.fs.fat.FatFileSystemFormatter; +import org.jnode.fs.fat.FatType; +import org.jnode.fs.jfat.ClusterSize; + +public class UserFacade { + private static final UserFacade INSTANCE = new UserFacade(); + + final private Map<String, Device> devices = new HashMap<String, Device>(); + private Device selectedDevice; + private UserListener userListener; + + final private Map<String, Formatter<? extends FileSystem>> formatters = new HashMap<String, Formatter<? extends FileSystem>>(); + private Formatter<? extends FileSystem> selectedFormatter; + + private CommandProcessor cmdProcessor; + + public static UserFacade getInstance() { + return INSTANCE; + } + + private UserFacade() + { + refreshDevicesFromOS(); + + addFormatter(new FatFileSystemFormatter(FatType.FAT32)); + addFormatter(new org.jnode.fs.jfat.FatFileSystemFormatter(ClusterSize._16Kb)); + addFormatter(new Ext2FileSystemFormatter(BlockSize._4Kb)); + + //TODO remove that direct creation of ErrorReporter : + cmdProcessor = new CommandProcessor(new ErrorReporter(){ + public void reportError(Logger log, Object source, Throwable t) { + // TODO Auto-generated method stub + log.error(source, t); + } + + public void reportError(Logger log, Object source, String message) { + // TODO Auto-generated method stub + log.error(source+" : "+message); + }}); + } + + public void selectFormatter(String name) + { + selectedFormatter = formatters.get(name); + } + + public void selectDevice(String name) + { + selectDevice(name, false); // called by the user => no need to notify + } + + public Device getSelectedDevice() + { + return selectedDevice; + } + + private void selectDevice(String name, boolean notify) + { + selectedDevice = devices.get(name); + if(notify && (userListener != null)) + { + userListener.selectionChanged(selectedDevice); + } + } + + public void setUserListener(UserListener listener) + { + this.userListener = listener; + + OSFacade.getInstance().setOSListener(new OSListener(){ + public void deviceAdded(Device addedDevice) { + devices.put(addedDevice.getName(), addedDevice); + userListener.deviceAdded(addedDevice.getName()); + } + + public void deviceRemoved(Device removedDevice) { + devices.remove(removedDevice.getName()); + userListener.deviceRemoved(removedDevice.getName()); + + if((selectedDevice != null) && selectedDevice.equals(removedDevice)) + { + selectDevice(null, true); // not called by user => need to notify + } + }}); + } + + public void addCommandProcessorListener(CommandProcessorListener listener) + { + cmdProcessor.addListener(listener); + } + + public String[] getFormatters() { + String[] names = formatters.keySet().toArray(new String[formatters.size()]); + Arrays.sort(names); + return names; + } + + public String[] getDevices() { + String[] names = devices.keySet().toArray(new String[devices.size()]); + Arrays.sort(names); + return names; + } + + public List<Partition> getPartitions() throws Exception { + checkSelectedDevice(); + return selectedDevice.getPartitions(); + } + + public void createPartition(long start, long size) throws Exception { + checkSelectedDevice(); + + selectedDevice.addPartition(start, size); + cmdProcessor.addCommand(new CreatePartitionCommand((IDEDevice) selectedDevice.getDevice(), 0)); //TODO set parameters + } + + public void removePartition(long offset) throws Exception { + checkSelectedDevice(); + + selectedDevice.removePartition(offset); + cmdProcessor.addCommand(new RemovePartitionCommand((IDEDevice) selectedDevice.getDevice(), 0)); //TODO set parameters + } + + public void formatPartition(long offset) throws Exception { + checkSelectedDevice(); + checkSelectedFormatter(); + + selectedDevice.formatPartition(offset, selectedFormatter.clone()); + cmdProcessor.addCommand(new FormatPartitionCommand((IDEDevice) selectedDevice.getDevice(), 0)); //TODO set parameters + } + + public void applyChanges() + { + cmdProcessor.process(); + refreshDevicesFromOS(); + } + + private void refreshDevicesFromOS() + { + devices.clear(); + String selectedDev = (selectedDevice == null) ? null : selectedDevice.getName(); + + try { + for(Device device : OSFacade.getInstance().getDevices()) + { + devices.put(device.getName(), device); + } + + selectDevice(selectedDev, true); // not called by user => need to notify + } catch (NameNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (ApiNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + private void checkSelectedDevice() throws Exception + { + if(selectedDevice == null) + { + throw new Exception("no device selected"); + } + } + + private void checkSelectedFormatter() throws Exception + { + if(selectedFormatter == null) + { + throw new Exception("no formatter selected"); + } + } + + private void addFormatter(Formatter<? extends FileSystem> formatter) + { + formatters.put(formatter.getFileSystemType().getName(), formatter); + } +} Added: trunk/distr/src/apps/org/jnode/apps/jpartition/model/UserListener.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/jpartition/model/UserListener.java (rev 0) +++ trunk/distr/src/apps/org/jnode/apps/jpartition/model/UserListener.java 2008-01-04 17:38:02 UTC (rev 3683) @@ -0,0 +1,11 @@ +package org.jnode.apps.jpartition.model; + +public interface UserListener { + + void selectionChanged(Device selectedDevice); + + void deviceAdded(String name); + + void deviceRemoved(String name); + +} Modified: trunk/distr/src/apps/org/jnode/apps/jpartition/swingview/CommandProcessorView.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/jpartition/swingview/CommandProcessorView.java 2008-01-03 14:57:22 UTC (rev 3682) +++ trunk/distr/src/apps/org/jnode/apps/jpartition/swingview/CommandProcessorView.java 2008-01-04 17:38:02 UTC (rev 3683) @@ -1,74 +1,73 @@ package org.jnode.apps.jpartition.swingview; -import it.battlehorse.stamps.annotations.ModelDependent; -import java.awt.*; +import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -import javax.swing.*; + +import javax.swing.BorderFactory; +import javax.swing.DefaultListModel; +import javax.swing.JButton; +import javax.swing.JList; +import javax.swing.JPanel; +import javax.swing.JScrollPane; + import org.apache.log4j.Logger; -import org.jnode.apps.jpartition.controller.MainController; +import org.jnode.apps.jpartition.commands.framework.Command; +import org.jnode.apps.jpartition.commands.framework.CommandProcessor; +import org.jnode.apps.jpartition.commands.framework.CommandProcessorListener; +import org.jnode.apps.jpartition.model.UserFacade; public class CommandProcessorView extends JPanel + implements CommandProcessorListener { private static final Logger log = Logger.getLogger(CommandProcessorView.class); - - private MainController controller; - + private DefaultListModel commands = new DefaultListModel(); private JList commandsUI = new JList(commands); private JButton btnApply = new JButton("Apply"); - - public CommandProcessorView(MainController controller) + + public CommandProcessorView() { - this.controller = controller; - setBorder(BorderFacto... [truncated message content] |
From: <fd...@us...> - 2008-01-06 18:08:02
|
Revision: 3687 http://jnode.svn.sourceforge.net/jnode/?rev=3687&view=rev Author: fduminy Date: 2008-01-06 10:07:36 -0800 (Sun, 06 Jan 2008) Log Message: ----------- integration of a telnet server in jnode (base on telnetd library) Modified Paths: -------------- trunk/all/build.xml trunk/all/conf/full-plugin-list.xml trunk/core/src/driver/org/jnode/driver/textscreen/x86/PcBufferTextScreen.java trunk/distr/.classpath trunk/distr/build.xml trunk/shell/src/shell/org/jnode/shell/CommandShell.java Added Paths: ----------- trunk/core/src/driver/org/jnode/driver/textscreen/x86/AbstractPcBufferTextScreen.java trunk/distr/descriptors/net.wimpi.telnetd.xml trunk/distr/descriptors/org.apache.jakarta.commons.logging.xml trunk/distr/lib/commons-logging.jar trunk/distr/lib/telnetd.jar trunk/distr/src/apps/org/jnode/apps/telnetd/ trunk/distr/src/apps/org/jnode/apps/telnetd/JNodeCommandShell.java trunk/distr/src/apps/org/jnode/apps/telnetd/JNodeShell.java trunk/distr/src/apps/org/jnode/apps/telnetd/RemoteConsoleInputStream.java trunk/distr/src/apps/org/jnode/apps/telnetd/RemoteConsoleManager.java trunk/distr/src/apps/org/jnode/apps/telnetd/RemoteConsoleOutputStream.java trunk/distr/src/apps/org/jnode/apps/telnetd/RemoteTextScreen.java trunk/distr/src/apps/org/jnode/apps/telnetd/TelnetServerCommand.java trunk/distr/src/apps/org/jnode/apps/telnetd/telnetd.properties Modified: trunk/all/build.xml =================================================================== --- trunk/all/build.xml 2008-01-06 11:17:48 UTC (rev 3686) +++ trunk/all/build.xml 2008-01-06 18:07:36 UTC (rev 3687) @@ -51,6 +51,8 @@ <property name="jcifs.jar" value="${root.dir}/fs/lib/jcifs-1.2.6.jar"/> <property name="ejc.jar" value="${root.dir}/core/lib/ejc-3.1.1.jar"/> <property name="oncrpc.jar" value="${root.dir}/net/lib/oncrpc.jar"/> + <property name="telnetd.jar" value="${root.dir}/distr/lib/telnetd.jar" /> + <property name="commons-logging.jar" value="${root.dir}/distr/lib/commons-logging.jar" /> <!-- libraries needed to run tests --> <property name="jmock-cglib.jar" value="${root.dir}/core/lib/jmock-cglib-1.0.1.jar"/> @@ -219,7 +221,9 @@ <libalias name="jcifs.jar" alias="${jcifs.jar}"/> <libalias name="ejc.jar" alias="${ejc.jar}"/> <libalias name="oncrpc.jar" alias="${oncrpc.jar}"/> - + <libalias name="telnetd.jar" alias="${telnetd.jar}"/> + <libalias name="commons-logging.jar" alias="${commons-logging.jar}"/> + <descriptors dir="${descriptors.dir}/"> <include name="*.xml"/> <exclude name="*plugin-list.xml"/> Modified: trunk/all/conf/full-plugin-list.xml =================================================================== --- trunk/all/conf/full-plugin-list.xml 2008-01-06 11:17:48 UTC (rev 3686) +++ trunk/all/conf/full-plugin-list.xml 2008-01-06 18:07:36 UTC (rev 3687) @@ -35,4 +35,7 @@ <plugin id="org.jnode.apps.vmware.disk"/> <plugin id="org.jnode.apps.jpartition"/> + + <plugin id="org.apache.jakarta.commons.logging"/> + <plugin id="net.wimpi.telnetd"/> </plugin-list> Added: trunk/core/src/driver/org/jnode/driver/textscreen/x86/AbstractPcBufferTextScreen.java =================================================================== --- trunk/core/src/driver/org/jnode/driver/textscreen/x86/AbstractPcBufferTextScreen.java (rev 0) +++ trunk/core/src/driver/org/jnode/driver/textscreen/x86/AbstractPcBufferTextScreen.java 2008-01-06 18:07:36 UTC (rev 3687) @@ -0,0 +1,173 @@ +/* + * $Id: PcBufferTextScreen.java 2764 2006-09-23 17:56:19Z lsantha $ + * + * JNode.org + * Copyright (C) 2003-2006 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.driver.textscreen.x86; + +import org.jnode.driver.textscreen.TextScreen; +import org.jnode.vm.Unsafe; + +/** + * @author Ewout Prangsma (ep...@us...) + * @author Fabien DUMINY (fduminy at jnode.org) + */ +public abstract class AbstractPcBufferTextScreen extends AbstractPcTextScreen implements TextScreen { + + /** Actual content buffer */ + private final char[] buffer; + + /** Temporary buffer that includes the cursor. This goes to the video device. + * Slower, but more likely to be correct than a temporary pointer to the last character + * the cursor was over, as in previous versions.*/ + private final char[]screenBuffer; + private int cursorIndex=0; + private boolean cursorVisible=true; + + /** + * Initialize this instance. + * @param width + * @param height + */ + public AbstractPcBufferTextScreen(int width, int height) { + super(width, height); + this.buffer = new char[width * height]; + this.screenBuffer=new char[buffer.length]; + } + + /** + * @see org.jnode.driver.textscreen.TextScreen#copyContent(int, int, int) + */ + public void copyContent(int srcOffset, int destOffset, int length) { + System.arraycopy(buffer, srcOffset, buffer, destOffset, length); + } + + /** + * @see org.jnode.driver.textscreen.TextScreen#getChar(int) + */ + public char getChar(int offset) { + return (char)(buffer[offset] & 0xFF); + } + + /** + * @see org.jnode.driver.textscreen.TextScreen#getColor(int) + */ + public int getColor(int offset) { + return (char)((buffer[offset] >> 8) & 0xFF); + } + + /** + * @see org.jnode.driver.textscreen.TextScreen#set(int, char, int, int) + */ + public void set(int offset, char ch, int count, int color) { + final char v = (char)((ch & 0xFF) | ((color & 0xFF) << 8)); + count = Math.min(count, buffer.length - offset); + for (int i = 0; i < count; i++) { + buffer[offset+i] = v; + } + } + + /** + * @see org.jnode.driver.textscreen.TextScreen#set(int, char[], int, int, int) + */ + public void set(int offset, char[] ch, int chOfs, int length, int color) { + color = (color & 0xFF) << 8; + length = Math.min(length, buffer.length - offset); + for (int i = 0; i < length; i++) { + buffer[offset+i] = (char)((ch[chOfs+i] & 0xFF) | color); + } + } + + /** + * @see org.jnode.driver.textscreen.TextScreen#set(int, char[], int, int, int[], int) + */ + public void set(int offset, char[] ch, int chOfs, int length, int[] colors, + int colorsOfs) { + length = Math.min(length, buffer.length - offset); + for (int i = 0; i < length; i++) { + buffer[offset+i] = (char)((ch[chOfs+i] & 0xFF) | (colors[colorsOfs+i] & 0xFF) << 8); + } + } + + /** + * Copies the entire screen to the given destination. + * For this operation to succeed, the screens involved must be + * compatible. + * @param dst + */ + public void copyTo( TextScreen dst ) { + if( dst instanceof AbstractPcTextScreen ) { + char[] toScreen = buffer; + if( cursorVisible&&cursorIndex<buffer.length&&cursorIndex>=0 ) { + System.arraycopy( buffer, 0, screenBuffer, 0, buffer.length ); + char origValue = buffer[cursorIndex]; + //origValue |= 0x7000;//from december 2003 jnode code. + + //exchange the background with the foreground + int color = (origValue >>8) & 0xFF; + color = ((color >> 4) & 0xF) | ((color << 4) & 0xF0); + origValue &= 0x00FF; + origValue |= (color << 8) & 0xFF00; + + screenBuffer[cursorIndex] = origValue; + toScreen = screenBuffer; + } + ( (AbstractPcTextScreen)dst ).copyFrom( toScreen, getTopOffset() ); + } + else { + throw new IllegalArgumentException( "Unknown destination type " + dst.getClass().getName() ); + } + } + + /** + * Return the offset in the buffer of the first visible row. + * @return the offset + */ + protected int getTopOffset() { + return 0; + } + + /** + * Copy the content of the given rawData into this screen. + * @param rawData + * @param rawDataOffset + */ + public final void copyFrom(char[] rawData, int rawDataOffset) { + if (rawDataOffset < 0) { + Unsafe.die("Buffer:rawDataOffset = " + rawDataOffset); + } + System.arraycopy(rawData, rawDataOffset, buffer, getTopOffset(), getWidth() * getHeight()); + } + + /** + * Synchronize the state with the actual device. + */ + abstract public void sync(); + + public void setCursor( int x, int y ) { + this.cursorIndex=getOffset( x,y); + setParentCursor(x, y); + } + + abstract protected void setParentCursor( int x, int y ); + + public void setCursorVisible( boolean visible ) { + this.cursorVisible=visible; + } +} Modified: trunk/core/src/driver/org/jnode/driver/textscreen/x86/PcBufferTextScreen.java =================================================================== --- trunk/core/src/driver/org/jnode/driver/textscreen/x86/PcBufferTextScreen.java 2008-01-06 11:17:48 UTC (rev 3686) +++ trunk/core/src/driver/org/jnode/driver/textscreen/x86/PcBufferTextScreen.java 2008-01-06 18:07:36 UTC (rev 3687) @@ -27,21 +27,11 @@ /** * @author Ewout Prangsma (ep...@us...) */ -public class PcBufferTextScreen extends AbstractPcTextScreen implements TextScreen { +public class PcBufferTextScreen extends AbstractPcBufferTextScreen implements TextScreen { /** My parent */ private final AbstractPcTextScreen parent; - /** Actual content buffer */ - private final char[] buffer; - - /** Temporary buffer that includes the cursor. This goes to the video device. - * Slower, but more likely to be correct than a temporary pointer to the last character - * the cursor was over, as in previous versions.*/ - private final char[]screenBuffer; - private int cursorIndex=0; - private boolean cursorVisible=true; - /** * Initialize this instance. * @param width @@ -49,131 +39,20 @@ */ public PcBufferTextScreen(int width, int height, AbstractPcTextScreen parent) { super(width, height); - this.buffer = new char[width * height]; - this.screenBuffer=new char[buffer.length]; this.parent = parent; } /** - * @see org.jnode.driver.textscreen.TextScreen#copyContent(int, int, int) - */ - public void copyContent(int srcOffset, int destOffset, int length) { - System.arraycopy(buffer, srcOffset, buffer, destOffset, length); - } - - /** - * @see org.jnode.driver.textscreen.TextScreen#getChar(int) - */ - public char getChar(int offset) { - return (char)(buffer[offset] & 0xFF); - } - - /** - * @see org.jnode.driver.textscreen.TextScreen#getColor(int) - */ - public int getColor(int offset) { - return (char)((buffer[offset] >> 8) & 0xFF); - } - - /** - * @see org.jnode.driver.textscreen.TextScreen#set(int, char, int, int) - */ - public void set(int offset, char ch, int count, int color) { - final char v = (char)((ch & 0xFF) | ((color & 0xFF) << 8)); - count = Math.min(count, buffer.length - offset); - for (int i = 0; i < count; i++) { - buffer[offset+i] = v; - } - } - - /** - * @see org.jnode.driver.textscreen.TextScreen#set(int, char[], int, int, int) - */ - public void set(int offset, char[] ch, int chOfs, int length, int color) { - color = (color & 0xFF) << 8; - length = Math.min(length, buffer.length - offset); - for (int i = 0; i < length; i++) { - buffer[offset+i] = (char)((ch[chOfs+i] & 0xFF) | color); - } - } - - /** - * @see org.jnode.driver.textscreen.TextScreen#set(int, char[], int, int, int[], int) - */ - public void set(int offset, char[] ch, int chOfs, int length, int[] colors, - int colorsOfs) { - length = Math.min(length, buffer.length - offset); - for (int i = 0; i < length; i++) { - buffer[offset+i] = (char)((ch[chOfs+i] & 0xFF) | (colors[colorsOfs+i] & 0xFF) << 8); - } - } - - /** - * Copies the entire screen to the given destination. - * For this operation to succeed, the screens involved must be - * compatible. - * @param dst - */ - public void copyTo( TextScreen dst ) { - if( dst instanceof AbstractPcTextScreen ) { - char[] toScreen = buffer; - if( cursorVisible&&cursorIndex<buffer.length&&cursorIndex>=0 ) { - System.arraycopy( buffer, 0, screenBuffer, 0, buffer.length ); - char origValue = buffer[cursorIndex]; - //origValue |= 0x7000;//from december 2003 jnode code. - - //exchange the background with the foreground - int color = (origValue >>8) & 0xFF; - color = ((color >> 4) & 0xF) | ((color << 4) & 0xF0); - origValue &= 0x00FF; - origValue |= (color << 8) & 0xFF00; - - screenBuffer[cursorIndex] = origValue; - toScreen = screenBuffer; - } - ( (AbstractPcTextScreen)dst ).copyFrom( toScreen, getTopOffset() ); - } - else { - throw new IllegalArgumentException( "Unknown destination type " + dst.getClass().getName() ); - } - } - - /** - * Return the offset in the buffer of the first visible row. - * @return the offset - */ - protected int getTopOffset() { - return 0; - } - - /** - * Copy the content of the given rawData into this screen. - * @param rawData - * @param rawDataOffset - */ - public final void copyFrom(char[] rawData, int rawDataOffset) { - if (rawDataOffset < 0) { - Unsafe.die("Buffer:rawDataOffset = " + rawDataOffset); - } - System.arraycopy(rawData, rawDataOffset, buffer, getTopOffset(), getWidth() * getHeight()); - } - - /** * Synchronize the state with the actual device. */ public void sync() { copyTo(parent); } - public void setCursor( int x, int y ) { - this.cursorIndex=getOffset( x,y); + protected void setParentCursor( int x, int y ) { parent.setCursor(x, y); } - public void setCursorVisible( boolean visible ) { - this.cursorVisible=visible; - } - /** * @return Returns the parent. */ Modified: trunk/distr/.classpath =================================================================== --- trunk/distr/.classpath 2008-01-06 11:17:48 UTC (rev 3686) +++ trunk/distr/.classpath 2008-01-06 18:07:36 UTC (rev 3687) @@ -6,10 +6,12 @@ <classpathentry kind="src" path="/JNode-Core"/> <classpathentry kind="src" path="src/apps"/> <classpathentry kind="src" path="/JNode-GUI"/> + <classpathentry kind="lib" path="lib/telnetd.jar"/> <classpathentry kind="src" path="/JNode-Shell"/> <classpathentry kind="src" path="/JNode-TextUI"/> <classpathentry combineaccessrules="false" kind="src" path="/JNode-FS"/> <classpathentry kind="lib" path="/JNode-Shell/lib/bsh-2.0b5.jar"/> <classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/4"/> + <classpathentry kind="lib" path="lib/commons-logging.jar"/> <classpathentry kind="output" path="build/classes"/> </classpath> Modified: trunk/distr/build.xml =================================================================== --- trunk/distr/build.xml 2008-01-06 11:17:48 UTC (rev 3686) +++ trunk/distr/build.xml 2008-01-06 18:07:36 UTC (rev 3687) @@ -18,7 +18,8 @@ <pathelement location="${jnode-fs.jar}"/> <pathelement location="${junit4.jar}"/> - + <pathelement location="${telnetd.jar}"/> + <path refid="cp"/> </path> @@ -36,6 +37,13 @@ <src path="${my-src.dir}/install"/> <classpath refid="my-cp"/> </jnode.compile> + + <!-- copy properties files --> + <copy todir="${my-classes.dir}/org/jnode/apps/telnetd"> + <fileset dir="${my-src.dir}/apps/org/jnode/apps/telnetd"> + <include name="**/*.properties" /> + </fileset> + </copy> </target> <!-- Assemble the jarfile --> Added: trunk/distr/descriptors/net.wimpi.telnetd.xml =================================================================== --- trunk/distr/descriptors/net.wimpi.telnetd.xml (rev 0) +++ trunk/distr/descriptors/net.wimpi.telnetd.xml 2008-01-06 18:07:36 UTC (rev 3687) @@ -0,0 +1,36 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plugin SYSTEM "jnode.dtd"> + +<plugin id="net.wimpi.telnetd" + name="telnetd" + version="2" + license-name="bsd" + provider-name="wimpi.net" + provider-url="http://telnetd.sourceforge.net/"> + + <runtime> + <library name="telnetd.jar"> + <export name="*"/> + </library> + + <library name="jnode-distr.jar"> + <export name="org.jnode.apps.telnetd.*"/> + </library> + </runtime> + + <requires> + <import plugin="org.apache.jakarta.commons.logging"/> + <import plugin="org.apache.jakarta.log4j"/> + <import plugin="org.jnode.shell"/> + </requires> + + <extension point="org.jnode.security.permissions"> + <permission class="java.lang.RuntimePermission" name="modifyThreadGroup"/> + + <permission class="java.lang.RuntimePermission" name="exitVM"/> + </extension> + + <extension point="org.jnode.shell.aliases"> + <alias name="telnetd" class="org.jnode.apps.telnetd.TelnetServerCommand"/> + </extension> +</plugin> Property changes on: trunk/distr/descriptors/net.wimpi.telnetd.xml ___________________________________________________________________ Name: svn:executable + * Added: trunk/distr/descriptors/org.apache.jakarta.commons.logging.xml =================================================================== --- trunk/distr/descriptors/org.apache.jakarta.commons.logging.xml (rev 0) +++ trunk/distr/descriptors/org.apache.jakarta.commons.logging.xml 2008-01-06 18:07:36 UTC (rev 3687) @@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plugin SYSTEM "jnode.dtd"> + +<plugin id="org.apache.jakarta.commons.logging" + name="commons-logging" + version="1.1.1" + license-name="apache2.0" + provider-name="apache commons" + provider-url="http://commons.apache.org/logging/"> + + <runtime> + <library name="commons-logging.jar"> + <export name="*"/> + </library> + </runtime> +</plugin> Property changes on: trunk/distr/descriptors/org.apache.jakarta.commons.logging.xml ___________________________________________________________________ Name: svn:executable + * Added: trunk/distr/lib/commons-logging.jar =================================================================== (Binary files differ) Property changes on: trunk/distr/lib/commons-logging.jar ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/distr/lib/telnetd.jar =================================================================== (Binary files differ) Property changes on: trunk/distr/lib/telnetd.jar ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/distr/src/apps/org/jnode/apps/telnetd/JNodeCommandShell.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/telnetd/JNodeCommandShell.java (rev 0) +++ trunk/distr/src/apps/org/jnode/apps/telnetd/JNodeCommandShell.java 2008-01-06 18:07:36 UTC (rev 3687) @@ -0,0 +1,24 @@ +package org.jnode.apps.telnetd; + +import java.io.InputStream; +import java.io.PrintStream; + +import org.jnode.driver.console.TextConsole; +import org.jnode.shell.CommandShell; +import org.jnode.shell.ShellException; + +public class JNodeCommandShell extends CommandShell { + private final JNodeShell shell; + + public JNodeCommandShell(JNodeShell shell, TextConsole console, InputStream in, PrintStream out, PrintStream err) + throws ShellException { + super(console, in, out, err); + this.shell = shell; + } + + @Override + public void exit(){ + shell.close(); + super.exit(); + } +} Added: trunk/distr/src/apps/org/jnode/apps/telnetd/JNodeShell.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/telnetd/JNodeShell.java (rev 0) +++ trunk/distr/src/apps/org/jnode/apps/telnetd/JNodeShell.java 2008-01-06 18:07:36 UTC (rev 3687) @@ -0,0 +1,343 @@ +package org.jnode.apps.telnetd; + +import java.io.InputStream; +import java.io.PrintStream; + +import net.wimpi.telnetd.io.BasicTerminalIO; +import net.wimpi.telnetd.net.Connection; +import net.wimpi.telnetd.net.ConnectionEvent; +import net.wimpi.telnetd.shell.Shell; + +import org.apache.log4j.Logger; +import org.jnode.driver.console.ConsoleException; +import org.jnode.driver.console.ConsoleManager; +import org.jnode.driver.console.TextConsole; +import org.jnode.driver.console.textscreen.ScrollableTextScreenConsole; +import org.jnode.driver.textscreen.ScrollableTextScreen; +import org.jnode.shell.CommandShell; + +/** + * + * @author Fabien DUMINY (fduminy at jnode.org) + * + */ +public class JNodeShell implements Shell { + private static final RemoteConsoleManager CONSOLE_MANAGER; + + static + { + try { + CONSOLE_MANAGER = new RemoteConsoleManager(); + } catch (ConsoleException e) { + throw new RuntimeException("can't create RemoteConsoleManager", e); + } + } + + private static final Logger log = Logger.getLogger(JNodeShell.class); + + private CommandShell commandShell; + private Connection connection; + private BasicTerminalIO terminalIO; + private TextConsole console; + +// private Editfield m_EF; + + /** + * Method that runs a shell + * + * @param con Connection that runs the shell. + */ + public void run(Connection con) { + try { + connection = con; + //mycon.setNextShell("nothing"); + terminalIO = connection.getTerminalIO(); + //dont forget to register listener + connection.addConnectionListener(this); + + //clear the screen and start from zero + terminalIO.eraseScreen(); + terminalIO.homeCursor(); + + //We just read any key + terminalIO.write("Welcome to JNode telnet server. Thanks for connecting.\r\n" + + "You can type any jnode command and press enter **2 times**(it's a bug!!!) to execute it.\r\n" + + "Use the exit command to logout!\r\n"); // some output + terminalIO.flush(); + + final RemoteTextScreen screen = new RemoteTextScreen(terminalIO); + final ScrollableTextScreen scrollScreen = screen.createCompatibleScrollableBufferScreen(terminalIO.getRows()*10); + final String name = connection.getConnectionData().getHostName(); + console = new ScrollableTextScreenConsole(CONSOLE_MANAGER, name, + scrollScreen, ConsoleManager.CreateOptions.TEXT + | ConsoleManager.CreateOptions.SCROLLABLE); + CONSOLE_MANAGER.registerConsole(console); + + InputStream in = new RemoteConsoleInputStream(terminalIO); + PrintStream out = new PrintStream(new RemoteConsoleOutputStream(terminalIO)); + PrintStream err = out; + commandShell = new JNodeCommandShell(this, console, in, out, err); + + commandShell.run(); +/* + boolean done = false; + while (!done) { + int i = m_IO.read(); + if (i == -1 || i == -2) { + log.debug("Input(Code):" + i); + done = true; + } + if (i == 10) { + done = true; + + } else if (i == 117) { + + ConnectionData cd = m_Connection.getConnectionData(); + //output header + m_IO.write(BasicTerminalIO.CRLF + + "DEBUG: Active Connection" + + BasicTerminalIO.CRLF); + m_IO.write("------------------------" + BasicTerminalIO.CRLF); + + //output connection data + m_IO.write("Connected from: " + cd.getHostName() + + "[" + cd.getHostAddress() + ":" + cd.getPort() + "]" + + BasicTerminalIO.CRLF); + m_IO.write("Guessed Locale: " + cd.getLocale() + + BasicTerminalIO.CRLF); + m_IO.write(BasicTerminalIO.CRLF); + //output negotiated terminal properties + m_IO.write("Negotiated Terminal Type: " + + cd.getNegotiatedTerminalType() + BasicTerminalIO.CRLF); + m_IO.write("Negotiated Columns: " + cd.getTerminalColumns() + + BasicTerminalIO.CRLF); + m_IO.write("Negotiated Rows: " + cd.getTerminalRows() + + BasicTerminalIO.CRLF); + + //output of assigned terminal instance (the cast is a hack, please + //do not copy for other TCommands, because it would break the + //decoupling of interface and implementation! + m_IO.write(BasicTerminalIO.CRLF); + m_IO.write("Assigned Terminal instance: " + + ((TerminalIO) m_IO).getTerminal()); + m_IO.write(BasicTerminalIO.CRLF); + m_IO.write("Environment: " + cd.getEnvironment().toString()); + m_IO.write(BasicTerminalIO.CRLF); + //output footer + m_IO.write("-----------------------------------------------" + + BasicTerminalIO.CRLF + BasicTerminalIO.CRLF); + + m_IO.flush(); + + + } else if (i == 'e') { + //run editfield test + Label l = new Label(m_IO, "testedit", "TestEdit: "); + m_EF = new Editfield(m_IO, "edit", 50); + m_EF.registerInputFilter(new InputFilter() { + + public int filterInput(int key) throws java.io.IOException { + if (key == 't') { + try { + m_EF.setValue("Test"); + } catch (BufferOverflowException e) { + + } + return InputFilter.INPUT_HANDLED; + } else if (key == 'c') { + m_EF.clear(); + return InputFilter.INPUT_HANDLED; + } else { + + return key; + } + } + }); + l.draw(); + m_EF.run(); + } else if (i == 116) { + //run test sequence + + Pager pg = new Pager(m_IO); + pg.setShowPosition(true); + pg.page(logo + logo + logo + logo + logo + logo + logo + logo + logo + logo + logo); + + Label l = new Label(m_IO, "label1"); + l.setText("Hello World!"); + l.setLocation(new Point(1, 5)); + l.draw(); + m_IO.flush(); + + m_IO.homeCursor(); + m_IO.eraseScreen(); + Titlebar tb = new Titlebar(m_IO, "title 1"); + tb.setTitleText("MyTitle"); + tb.setAlignment(Titlebar.ALIGN_CENTER); + tb.setBackgroundColor(ColorHelper.BLUE); + tb.setForegroundColor(ColorHelper.YELLOW); + tb.draw(); + + + Statusbar sb = new Statusbar(m_IO, "status 1"); + sb.setStatusText("MyStatus"); + sb.setAlignment(Statusbar.ALIGN_LEFT); + sb.setBackgroundColor(ColorHelper.BLUE); + sb.setForegroundColor(ColorHelper.YELLOW); + sb.draw(); + + m_IO.flush(); + + m_IO.setCursor(2, 1); + + Selection sel = new Selection(m_IO, "selection 1"); + String[] tn = TerminalManager.getReference().getAvailableTerminals(); + + for (int n = 0; n < tn.length; n++) { + sel.addOption(tn[n]); + } + + sel.setLocation(1, 10); + sel.run(); + + Checkbox cb = new Checkbox(m_IO, "checkbox 1"); + cb.setText("Check me !"); + cb.setLocation(1, 12); + cb.run(); + + Editfield ef = new Editfield(m_IO, "editfield 1", 20); + ef.setLocation(1, 13); + ef.run(); + try { + ef.setValue("SETVALUE!"); + } catch (Exception ex) { + + } + Editfield ef2 = new Editfield(m_IO, "editfield 2", 8); + ef2.setLocation(1, 14); + ef2.setPasswordField(true); + ef2.run(); + + log.debug("Your secret password was:" + ef2.getValue()); + m_IO.flush(); + + //clear the screen and start from zero + m_IO.eraseScreen(); + m_IO.homeCursor(); + //myio.flush(); + Titlebar tb2 = new Titlebar(m_IO, "title 1"); + tb2.setTitleText("jEditor v0.1"); + tb2.setAlignment(Titlebar.ALIGN_LEFT); + tb2.setBackgroundColor(ColorHelper.BLUE); + tb2.setForegroundColor(ColorHelper.YELLOW); + tb2.draw(); + + Statusbar sb2 = new Statusbar(m_IO, "status 1"); + sb2.setStatusText("Status"); + sb2.setAlignment(Statusbar.ALIGN_LEFT); + sb2.setBackgroundColor(ColorHelper.BLUE); + sb2.setForegroundColor(ColorHelper.YELLOW); + sb2.draw(); + + m_IO.setCursor(2, 1); + + Editarea ea = new Editarea(m_IO, "area", m_IO.getRows() - 2, 100); + m_IO.flush(); + ea.run(); + log.debug(ea.getValue()); + + m_IO.eraseScreen(); + m_IO.homeCursor(); + m_IO.write("Dummy Shell. Please press enter to logout!\r\n"); + m_IO.flush(); + + + } + //the next line is for debug reasons + else + log.debug("Input(Code):" + i); + } + m_IO.homeCursor(); + m_IO.eraseScreen(); + m_IO.write("Goodbye!.\r\n\r\n"); + m_IO.flush(); +*/ + + } catch (Exception ex) { + log.error("run()", ex); + } + }//run + + void close() + { + try { + CONSOLE_MANAGER.unregisterConsole(console); + + terminalIO.homeCursor(); + terminalIO.eraseScreen(); + terminalIO.write("Goodbye!.\r\n\r\n"); + terminalIO.flush(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + //this implements the ConnectionListener! + public void connectionTimedOut(ConnectionEvent ce) { + try { + terminalIO.write("CONNECTION_TIMEDOUT"); + terminalIO.flush(); + //close connection + connection.close(); + console.close(); + } catch (Exception ex) { + log.error("connectionTimedOut()", ex); + } + }//connectionTimedOut + + public void connectionIdle(ConnectionEvent ce) { + try { + terminalIO.write("CONNECTION_IDLE"); + terminalIO.flush(); + } catch (java.io.IOException e) { + log.error("connectionIdle()", e); + } + + }//connectionIdle + + public void connectionLogoutRequest(ConnectionEvent ce) { + try { + terminalIO.write("CONNECTION_LOGOUTREQUEST"); + terminalIO.flush(); + console.close(); + } catch (Exception ex) { + log.error("connectionLogoutRequest()", ex); + } + }//connectionLogout + + public void connectionSentBreak(ConnectionEvent ce) { + try { + terminalIO.write("CONNECTION_BREAK"); + terminalIO.flush(); + console.close(); + } catch (Exception ex) { + log.error("connectionSentBreak()", ex); + } + }//connectionSentBreak + + + public static Shell createShell() { + return new JNodeShell(); + }//createShell + + //Constants +// private static final String logo = +// "/***\n" + +// "* \n" + +// "* TelnetD library (embeddable telnet daemon)\n" + +// "* Copyright (C) 2000-2005 Dieter Wimberger\n" + +// "***/\n" + +// "A looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo" + +// "oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo" + +// "oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo" + +// "ng line!"; +} Added: trunk/distr/src/apps/org/jnode/apps/telnetd/RemoteConsoleInputStream.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/telnetd/RemoteConsoleInputStream.java (rev 0) +++ trunk/distr/src/apps/org/jnode/apps/telnetd/RemoteConsoleInputStream.java 2008-01-06 18:07:36 UTC (rev 3687) @@ -0,0 +1,67 @@ +/* + * $Id: ConsoleInputStream.java 2224 2006-01-01 12:49:03Z epr $ + * + * JNode.org + * Copyright (C) 2003-2006 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.apps.telnetd; + +import java.io.IOException; +import java.io.InputStream; + +import net.wimpi.telnetd.io.BasicTerminalIO; + +/** + * + * @author Fabien DUMINY (fduminy at jnode.org) + * + */ +public class RemoteConsoleInputStream extends InputStream { + + private final BasicTerminalIO terminalIO; + private boolean echo = true; + + public RemoteConsoleInputStream(BasicTerminalIO terminalIO) { + this.terminalIO = terminalIO; + } + + /** + * @see java.io.InputStream#read() + * @return int + * @throws IOException + */ + @Override + public int read() throws IOException { + while (true) { + int ch = terminalIO.read(); + if (ch != 0) { + if (echo) { + terminalIO.write((char) ch); + } + + if(ch == 10) + { + //TODO it seems we need that to be able to launch JNode commands + ch = -1; + } + + return ch; + } + } + } +} Added: trunk/distr/src/apps/org/jnode/apps/telnetd/RemoteConsoleManager.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/telnetd/RemoteConsoleManager.java (rev 0) +++ trunk/distr/src/apps/org/jnode/apps/telnetd/RemoteConsoleManager.java 2008-01-06 18:07:36 UTC (rev 3687) @@ -0,0 +1,21 @@ +package org.jnode.apps.telnetd; + +import org.jnode.driver.console.Console; +import org.jnode.driver.console.ConsoleException; +import org.jnode.driver.console.spi.AbstractConsoleManager; + +/** + * + * @author Fabien DUMINY (fduminy at jnode.org) + * + */ +public class RemoteConsoleManager extends AbstractConsoleManager { + public RemoteConsoleManager() throws ConsoleException { + super(); + } + + public Console createConsole(String name, int options) { + // not used for now + throw new UnsupportedOperationException("shouldn't be used"); + } +} Added: trunk/distr/src/apps/org/jnode/apps/telnetd/RemoteConsoleOutputStream.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/telnetd/RemoteConsoleOutputStream.java (rev 0) +++ trunk/distr/src/apps/org/jnode/apps/telnetd/RemoteConsoleOutputStream.java 2008-01-06 18:07:36 UTC (rev 3687) @@ -0,0 +1,46 @@ +/* + * $Id: ConsoleInputStream.java 2224 2006-01-01 12:49:03Z epr $ + * + * JNode.org + * Copyright (C) 2003-2006 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.apps.telnetd; + +import java.io.IOException; +import java.io.OutputStream; + +import net.wimpi.telnetd.io.BasicTerminalIO; + +/** + * + * @author Fabien DUMINY (fduminy at jnode.org) + * + */ +public class RemoteConsoleOutputStream extends OutputStream { + + private final BasicTerminalIO terminalIO; + + public RemoteConsoleOutputStream(BasicTerminalIO terminalIO) { + this.terminalIO = terminalIO; + } + + @Override + public void write(int b) throws IOException { + terminalIO.write((byte) b); + } +} Added: trunk/distr/src/apps/org/jnode/apps/telnetd/RemoteTextScreen.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/telnetd/RemoteTextScreen.java (rev 0) +++ trunk/distr/src/apps/org/jnode/apps/telnetd/RemoteTextScreen.java 2008-01-06 18:07:36 UTC (rev 3687) @@ -0,0 +1,36 @@ +package org.jnode.apps.telnetd; + +import java.io.IOException; + +import net.wimpi.telnetd.io.BasicTerminalIO; + +import org.jnode.driver.textscreen.TextScreen; +import org.jnode.driver.textscreen.x86.AbstractPcBufferTextScreen; + +/** + * + * @author Fabien DUMINY (fduminy at jnode.org) + * + */ +public class RemoteTextScreen extends AbstractPcBufferTextScreen implements TextScreen { + private final BasicTerminalIO terminalIO; + public RemoteTextScreen(BasicTerminalIO terminalIO) + { + super(terminalIO.getColumns(), terminalIO.getRows()); + this.terminalIO = terminalIO; + } + + @Override + protected void setParentCursor(int x, int y) { + try { + terminalIO.setCursor(x, y); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Override + public void sync() { + + } +} Added: trunk/distr/src/apps/org/jnode/apps/telnetd/TelnetServerCommand.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/telnetd/TelnetServerCommand.java (rev 0) +++ trunk/distr/src/apps/org/jnode/apps/telnetd/TelnetServerCommand.java 2008-01-06 18:07:36 UTC (rev 3687) @@ -0,0 +1,32 @@ +package org.jnode.apps.telnetd; + +import java.io.InputStream; +import java.util.Properties; + +import net.wimpi.telnetd.TelnetD; + + +/** + * + * @author Fabien DUMINY (fduminy at jnode.org) + * + */ +public class TelnetServerCommand +{ + public static void main(String[] args) throws Exception { + try { + //1. prepare daemon + Properties props = new Properties(); + InputStream is = TelnetServerCommand.class.getResourceAsStream("telnetd.properties"); + props.load(is); + + TelnetD daemon = TelnetD.createTelnetD(props); + + //2.start serving/accepting connections + daemon.start(); + } catch (Exception ex) { + ex.printStackTrace(); + System.exit(1); + } + } +} Added: trunk/distr/src/apps/org/jnode/apps/telnetd/telnetd.properties =================================================================== --- trunk/distr/src/apps/org/jnode/apps/telnetd/telnetd.properties (rev 0) +++ trunk/distr/src/apps/org/jnode/apps/telnetd/telnetd.properties 2008-01-06 18:07:36 UTC (rev 3687) @@ -0,0 +1,71 @@ +#Unified telnet proxy properties +#Daemon configuration example. +#Created: 15/11/2004 wimpi + + +############################ +# Telnet daemon properties # +############################ + +##################### +# Terminals Section # +##################### + +# List of terminals available and defined below +terminals=vt100,ansi,windoof,xterm + +# vt100 implementation and aliases +term.vt100.class=net.wimpi.telnetd.io.terminal.vt100 +term.vt100.aliases=default,vt100-am,vt102,dec-vt100 + +# ansi implementation and aliases +term.ansi.class=net.wimpi.telnetd.io.terminal.ansi +term.ansi.aliases=color-xterm,xterm-color,vt320,vt220,linux,screen + +# windoof implementation and aliases +term.windoof.class=net.wimpi.telnetd.io.terminal.Windoof +term.windoof.aliases= + +# xterm implementation and aliases +term.xterm.class=net.wimpi.telnetd.io.terminal.xterm +term.xterm.aliases= + +################## +# Shells Section # +################## + +# List of shells available and defined below +shells=jnode,dummy + +# shell implementations +shell.dummy.class=net.wimpi.telnetd.shell.DummyShell +shell.jnode.class=org.jnode.apps.telnetd.JNodeShell + +##################### +# Listeners Section # +##################### +listeners=std + + +# std listener specific properties + +#Basic listener and connection management settings +std.port=6666 +std.floodprotection=5 +std.maxcon=25 + + +# Timeout Settings for connections (ms) +std.time_to_warning=3600000 +std.time_to_timedout=60000 + +# Housekeeping thread active every 1 secs +std.housekeepinginterval=1000 + +std.inputmode=character + +# Login shell +std.loginshell=jnode + +# Connection filter class +std.connectionfilter=none \ No newline at end of file Modified: trunk/shell/src/shell/org/jnode/shell/CommandShell.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/CommandShell.java 2008-01-06 11:17:48 UTC (rev 3686) +++ trunk/shell/src/shell/org/jnode/shell/CommandShell.java 2008-01-06 18:07:36 UTC (rev 3687) @@ -42,6 +42,7 @@ import javax.naming.NameNotFoundException; import org.apache.log4j.Logger; +import org.jnode.driver.console.Console; import org.jnode.driver.console.InputHistory; import org.jnode.driver.console.CompletionInfo; import org.jnode.driver.console.ConsoleManager; @@ -185,6 +186,27 @@ } } + protected CommandShell(TextConsole console, InputStream in, PrintStream out, PrintStream err) throws ShellException { + try { + this.console = console; + this.out = out; + this.err = err; + this.in = in; + SystemInputStream.getInstance().initialize(this.in); + //cons.setCompleter(this); + + //console.addConsoleListener(this); + aliasMgr = ((AliasManager) InitialNaming.lookup(AliasManager.NAME)) + .createAliasManager(); + System.setProperty(PROMPT_PROPERTY_NAME, DEFAULT_PROMPT); + } catch (NameNotFoundException ex) { + throw new ShellException("Cannot find required resource", ex); + } + catch (Exception ex) { + ex.printStackTrace(); + } + } + /** * Run this shell until exit. * This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fd...@us...> - 2008-01-08 22:43:35
|
Revision: 3688 http://jnode.svn.sourceforge.net/jnode/?rev=3688&view=rev Author: fduminy Date: 2008-01-08 14:43:33 -0800 (Tue, 08 Jan 2008) Log Message: ----------- new AnnotateTask features : - support for multiple annotations per class - support for MagicPermission annotation Modified Paths: -------------- trunk/all/conf/openjdk-annotations.properties trunk/builder/src/builder/org/jnode/ant/taskdefs/AnnotateTask.java Modified: trunk/all/conf/openjdk-annotations.properties =================================================================== --- trunk/all/conf/openjdk-annotations.properties 2008-01-06 18:07:36 UTC (rev 3687) +++ trunk/all/conf/openjdk-annotations.properties 2008-01-08 22:43:33 UTC (rev 3688) @@ -1,2 +1,9 @@ -sun.misc.SharedSecrets=SharedStatics -java.util.Currency=SharedStatics \ No newline at end of file +# +# Annotations to add to openjdk classes +# +# format of a line : +# package/className.class=<annotations list separated by a ','> +# supported annotations : SharedStatics, MagicPermission + +sun/misc/SharedSecrets.class=SharedStatics,MagicPermission +java/util/Currency.class=SharedStatics,MagicPermission \ No newline at end of file Modified: trunk/builder/src/builder/org/jnode/ant/taskdefs/AnnotateTask.java =================================================================== --- trunk/builder/src/builder/org/jnode/ant/taskdefs/AnnotateTask.java 2008-01-06 18:07:36 UTC (rev 3687) +++ trunk/builder/src/builder/org/jnode/ant/taskdefs/AnnotateTask.java 2008-01-08 22:43:33 UTC (rev 3688) @@ -30,8 +30,13 @@ import java.util.Arrays; import java.util.Collections; import java.util.Properties; +import java.util.List; +import java.util.ArrayList; import org.apache.tools.ant.BuildException; +import java.util.StringTokenizer; + +import org.jnode.vm.annotation.MagicPermission; import org.jnode.vm.annotation.SharedStatics; import org.objectweb.asm.Attribute; import org.objectweb.asm.ClassAdapter; @@ -54,13 +59,18 @@ * */ public class AnnotateTask extends FileSetTask { + private static final String SHAREDSTATICS_TYPE_DESC = Type.getDescriptor(SharedStatics.class); + private static final String MAGICPERMISSION_TYPE_DESC = Type.getDescriptor(MagicPermission.class); private File annotationFile; private String[] classesFiles; - + private Properties properties; + protected void doExecute() throws BuildException { - classesFiles = readProperties(annotationFile); - processFiles(); + if(readProperties(annotationFile)) + { + processFiles(); + } } public final File getAnnotationFile() { @@ -72,25 +82,25 @@ } /** - * Read the properties file. For now, it simply contains a list of + * Read the properties file. For now, it simply contains a list of * classes that need the SharedStatics annotation. - * + * * @return * @throws BuildException */ - private static String[] readProperties(File file) throws BuildException + private boolean readProperties(File file) throws BuildException { if(file == null) { throw new BuildException("annotationFile is mandatory"); } - - Properties props = new Properties(); + + properties = new Properties(); FileInputStream fis = null; try { fis = new FileInputStream(file); - props.load(fis); + properties.load(fis); } catch (IOException e) { throw new BuildException(e); } @@ -104,67 +114,56 @@ throw new BuildException(e); } } - } - if(props.isEmpty()) + } + if(properties.isEmpty()) { System.err.println("WARNING: annotationFile is empty"); - return new String[0]; + return false; } - - String[] classesFiles = new String[props.size()]; - int i = 0; - for(Object name : props.keySet()) - { - String className = String.valueOf(name); - String annotations = props.getProperty(className); - if("SharedStatics".equals(annotations)) - { - className = className.replace('.', File.separatorChar); - className += ".class"; - classesFiles[i++] = className; - } - } - - // we must sort the classes in reverse order so that + + classesFiles = (String[]) properties.keySet().toArray(new String[properties.size()]); + + // we must sort the classes in reverse order so that // classes with longest package name will be used first // (that is only necessary for classes whose name is the same // but package is different ; typical such class name : "Constants") Arrays.sort(classesFiles, Collections.reverseOrder()); - - return classesFiles; + + return true; } - - private static boolean hasFile(String[] files, File file) + + private String getAnnotations(File file) { - boolean found = false; + String annotations = null; String filePath = file.getAbsolutePath(); - for(String f : files) + for(String f : classesFiles) { if(filePath.endsWith(f)) { - found = true; + annotations = properties.getProperty(f); break; } } - - return found; + + return annotations; } - + @Override protected void processFile(File file) throws IOException { - if(!hasFile(classesFiles, file)) + String annotations = getAnnotations(file); + if(annotations == null) { return; } - + File tmpFile = new File(file.getParentFile(), file.getName()+".tmp"); FileInputStream fis = null; boolean classIsModified = false; - + try { fis = new FileInputStream(file); - classIsModified = addAnnotation(file.getName(), fis, tmpFile); + classIsModified = addAnnotation(file.getName(), fis, tmpFile, annotations); } finally { @@ -173,33 +172,33 @@ fis.close(); } } - + if(classIsModified) { if(trace) { traceClass(file, "before"); - + traceClass(tmpFile, "after"); - } - + } + if(!file.delete()) { throw new IOException("can't delete "+file.getAbsolutePath()); } - + if(!tmpFile.renameTo(file)) { throw new IOException("can't rename "+tmpFile.getAbsolutePath()); } } } - + /** * Simple debug method that trace a class file. - * It can be used to visually check that the annotations has been + * It can be used to visually check that the annotations has been * properly added - * + * * @param file * @throws IOException */ @@ -210,39 +209,50 @@ try { fis = new FileInputStream(file); - + ClassReader cr = new ClassReader(fis); - TraceClassVisitor tcv = new TraceClassVisitor(null, new PrintWriter(System.out)); - cr.accept(tcv, Attributes.getDefaultAttributes(), true); + TraceClassVisitor tcv = new TraceClassVisitor(null, new PrintWriter(System.out)); + cr.accept(tcv, Attributes.getDefaultAttributes(), true); } finally { if(fis != null) { fis.close(); - } + } } System.out.println("----- end trace -----"); } - private boolean addAnnotation(String fileName, InputStream inputClass, File tmpFile) throws BuildException { + private boolean addAnnotation(String fileName, InputStream inputClass, File tmpFile, String annotations) throws BuildException { boolean classIsModified = false; FileOutputStream outputClass = null; - + ClassWriter cw = new ClassWriter(false); try { ClassReader cr = new ClassReader(inputClass); - MarkerClassVisitor mcv = new MarkerClassVisitor(cw); + + List<String> annotationTypeDescs = new ArrayList<String>(2); + if(annotations.contains("SharedStatics")) + { + annotationTypeDescs.add(SHAREDSTATICS_TYPE_DESC); + } + if(annotations.contains("MagicPermission")) + { + annotationTypeDescs.add(MAGICPERMISSION_TYPE_DESC); + } + + MarkerClassVisitor mcv = new MarkerClassVisitor(cw, annotationTypeDescs); cr.accept(mcv, Attributes.getDefaultAttributes(), true); - + if(mcv.classIsModified()) { - System.out.println("adding annotation to file "+fileName); + System.out.println("adding annotations "+annotations+" to file "+fileName); classIsModified = true; - + outputClass = new FileOutputStream(tmpFile); - byte[] b = cw.toByteArray(); + byte[] b = cw.toByteArray(); outputClass.write(b); } } catch (Exception ex) { @@ -250,7 +260,7 @@ throw new BuildException("Unable to add annotations to file "+fileName, ex); } finally - { + { if(outputClass != null) { try { @@ -258,28 +268,30 @@ } catch (IOException e) { System.err.println("Can't close stream for file "+fileName); } - } + } } - + return classIsModified; } private static class MarkerClassVisitor extends ClassAdapter { - private static final String ANNOTATION_TYPE_DESC = Type.getDescriptor(SharedStatics.class); + final private List<String> annotationTypeDescs; + private boolean classIsModified = false; - private boolean foundAnnotation = false; - - public MarkerClassVisitor(ClassVisitor cv) { + + public MarkerClassVisitor(ClassVisitor cv, List<String> annotationTypeDescs) { super(cv); + + this.annotationTypeDescs = annotationTypeDescs; } @Override public void visit(int version, int access, String name, String superName, String[] interfaces, String sourceFile) { - super.visit(org.objectweb.asm.Constants.V1_5, access, + super.visit(org.objectweb.asm.Constants.V1_5, access, name, superName, interfaces, sourceFile); } - + @Override public void visitAttribute(Attribute attr) { if(attr instanceof RuntimeVisibleAnnotations) @@ -290,36 +302,45 @@ if(annotation instanceof Annotation) { Annotation ann = (Annotation) annotation; - if(ann.type.equals(ANNOTATION_TYPE_DESC)) + for(String annTypeDesc : annotationTypeDescs) { - // we have found the annotation -> we won't need to add it again ! - foundAnnotation = true; + if(ann.type.equals(annTypeDesc)) + { + // we have found one of the annotations -> we won't need to add it again ! + annotationTypeDescs.remove(annTypeDesc); + break; + } } } - } + } } - + super.visitAttribute(attr); } @SuppressWarnings("unchecked") public void visitEnd() { - if(!foundAnnotation) - { + if(!annotationTypeDescs.isEmpty()) + { // we have not found the annotation -> we will add it and so modify the class classIsModified = true; - - Annotation ann = new Annotation(ANNOTATION_TYPE_DESC); - ann.add("name", ""); - RuntimeVisibleAnnotations attr = new RuntimeVisibleAnnotations(); - attr.annotations.add(ann); + + for(String annTypeDesc : annotationTypeDescs) + { + + Annotation ann = new Annotation(annTypeDesc); + ann.add("name", ""); + + attr.annotations.add(ann); + } + cv.visitAttribute(attr); } - + super.visitEnd(); } - + public boolean classIsModified() { return classIsModified; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <hag...@us...> - 2008-02-01 15:55:49
|
Revision: 3744 http://jnode.svn.sourceforge.net/jnode/?rev=3744&view=rev Author: hagar-wize Date: 2008-02-01 07:55:46 -0800 (Fri, 01 Feb 2008) Log Message: ----------- started add of apache.db.Derby Modified Paths: -------------- trunk/all/build.xml trunk/all/conf/full-plugin-list.xml Added Paths: ----------- trunk/distr/descriptors/derby.xml trunk/distr/lib/derby.jar trunk/distr/lib/derbynet.jar trunk/distr/src/apps/org/jnode/apps/derby/ trunk/distr/src/apps/org/jnode/apps/derby/DerbyCommand.java Modified: trunk/all/build.xml =================================================================== --- trunk/all/build.xml 2008-02-01 08:47:04 UTC (rev 3743) +++ trunk/all/build.xml 2008-02-01 15:55:46 UTC (rev 3744) @@ -58,6 +58,8 @@ <property name="jsp.jar" value="${root.dir}/distr/lib/jsp-2.1.jar" /> <property name="jsp-api.jar" value="${root.dir}/distr/lib/jsp-api-2.1.jar" /> <property name="servlet.jar" value="${root.dir}/distr/lib/servlet-api-2.5-6.1.5.jar" /> + <property name="derby.jar" value="${root.dir}/distr/lib/derby.jar" /> + <property name="derbynet.jar" value="${root.dir}/distr/lib/derbynet.jar" /> <!-- libraries needed to run tests --> <property name="jmock-cglib.jar" value="${root.dir}/core/lib/jmock-cglib-1.0.1.jar"/> @@ -119,6 +121,8 @@ <pathelement location="${commons-net.jar}"/> <pathelement location="${dnsjava.jar}"/> <pathelement location="${mauve.jar}"/> + <pathelement location="${derby.jar}"/> + <pathelement location="${derbynet.jar}"/> </path> <path id="cp-jnode"> @@ -244,6 +248,8 @@ <libalias name="jsp.jar" alias="${jsp.jar}"/> <libalias name="jsp-api.jar" alias="${jsp-api.jar}"/> <libalias name="servlet.jar" alias="${servlet.jar}"/> + <libalias name="derby.jar" alias="${derby.jar}"/> + <libalias name="derbynet.jar" alias="${derbynet.jar}"/> <descriptors dir="${descriptors.dir}/"> <include name="*.xml"/> Modified: trunk/all/conf/full-plugin-list.xml =================================================================== --- trunk/all/conf/full-plugin-list.xml 2008-02-01 08:47:04 UTC (rev 3743) +++ trunk/all/conf/full-plugin-list.xml 2008-02-01 15:55:46 UTC (rev 3744) @@ -39,4 +39,5 @@ <plugin id="net.wimpi.telnetd"/> <plugin id="jetty"/> + <plugin id="derby"/> </plugin-list> Added: trunk/distr/descriptors/derby.xml =================================================================== --- trunk/distr/descriptors/derby.xml (rev 0) +++ trunk/distr/descriptors/derby.xml 2008-02-01 15:55:46 UTC (rev 3744) @@ -0,0 +1,36 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plugin SYSTEM "jnode.dtd"> + +<plugin id="derby" + name="Derby" + version="10.3.2.1" + license-name="apache2.0" + provider-name="apache DB" + provider-url="http://db.apache.org/derby/"> + + + <requires> + <import plugin="org.jnode.shell"/> + </requires> + + <runtime> + <library name="derby.jar"> + <export name="*"/> + </library> + <library name="derbynet.jar"> + <export name="*"/> + </library> + <library name="jnode-distr.jar"> + <export name="org.jnode.apps.derby.*"/> + </library> + </runtime> + + <extension point="org.jnode.shell.aliases"> + <alias name="derby" class="org.jnode.apps.derby.DerbyCommand"/> + </extension> + + <extension point="org.jnode.security.permissions"> + <permission class="java.lang.RuntimePermission" name="exitVM" actions="*" /> + </extension> + +</plugin> Added: trunk/distr/lib/derby.jar =================================================================== (Binary files differ) Property changes on: trunk/distr/lib/derby.jar ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/distr/lib/derbynet.jar =================================================================== (Binary files differ) Property changes on: trunk/distr/lib/derbynet.jar ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/distr/src/apps/org/jnode/apps/derby/DerbyCommand.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/derby/DerbyCommand.java (rev 0) +++ trunk/distr/src/apps/org/jnode/apps/derby/DerbyCommand.java 2008-02-01 15:55:46 UTC (rev 3744) @@ -0,0 +1,57 @@ +/* + * $Id$ + */ +package org.jnode.apps.derby; + + +import org.apache.derby.drda.NetworkServerControl; + +import org.jnode.shell.AbstractCommand; +import org.jnode.shell.CommandLine; +import org.jnode.shell.help.ParsedArguments; +import org.jnode.shell.help.Help; +import org.jnode.shell.help.Parameter; +import org.jnode.shell.help.Argument; +import org.jnode.shell.help.argument.FileArgument; +import org.jnode.shell.help.argument.IntegerArgument; +import org.jnode.shell.help.argument.StringArgument; + +import java.io.InputStream; +import java.io.PrintStream; +import java.io.File; + +/** + * Command for handling Derby server. + * + * @author Martin Husted Hartvig (ha...@jn...) + */ +public class DerbyCommand extends AbstractCommand { + static final FileArgument ARG_HOME = new FileArgument("derbyhome", "home directory for derby"); + static final Argument ARG_COMMAND = new StringArgument("command","start/stop command for derby"); + static final IntegerArgument ARG_PORT = new IntegerArgument("port", "jdbc port"); + + private static Parameter PARAM_HOME = new Parameter(ARG_HOME, Parameter.OPTIONAL); + private static Parameter PARAM_PORT = new Parameter(ARG_PORT, Parameter.OPTIONAL); + + public static Help.Info HELP_INFO = new Help.Info("derby", "start or stop the derby db server on a given port (default 1527)", + new Parameter(ARG_COMMAND, Parameter.MANDATORY), + PARAM_HOME, + PARAM_PORT); + + public static void main(String[] args) throws Exception { + new DerbyCommand().execute(args); + } + + public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) throws Exception { + ParsedArguments arguments = HELP_INFO.parse(commandLine); + File home_dir = ARG_HOME.getFile(arguments); + String command = ARG_COMMAND.getValue(arguments); + + int port; + if (PARAM_PORT.isSet(arguments)) { + port = ARG_PORT.getInteger(arguments); + } + + NetworkServerControl.main(new String[]{command}); + } +} \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fd...@us...> - 2008-02-04 20:04:23
|
Revision: 3758 http://jnode.svn.sourceforge.net/jnode/?rev=3758&view=rev Author: fduminy Date: 2008-02-04 12:04:19 -0800 (Mon, 04 Feb 2008) Log Message: ----------- - added class MasterBootRecord to encapsulate the byte[] used for mbr related stuff - jgrub : separation of stage 1, stage 1.5 and stage 2 + use of class MasterBootRecord - jgrub : extraction of the actual job from the command + update of jnode installer - jgrub : simplification of the command - factorised code that check for existence of an mbr - added api to FileSystemService to get mounted filesystems Modified Paths: -------------- trunk/builder/src/builder/org/jnode/build/BootDiskBuilder.java trunk/core/src/core/org/jnode/util/FileUtils.java trunk/distr/src/install/org/jnode/install/action/GrubInstallerAction.java trunk/fs/descriptors/org.jnode.fs.jfat.command.xml trunk/fs/src/driver/org/jnode/driver/block/FileDevice.java trunk/fs/src/driver/org/jnode/driver/block/PartitionableBlockDeviceAPI.java trunk/fs/src/fs/org/jnode/fs/command/MountCommand.java trunk/fs/src/fs/org/jnode/fs/fat/BootSector.java trunk/fs/src/fs/org/jnode/fs/jfat/BootSector.java trunk/fs/src/fs/org/jnode/fs/jfat/command/JGrubInstallCommand.java trunk/fs/src/fs/org/jnode/fs/jfat/command/MBRFormatter.java trunk/fs/src/fs/org/jnode/fs/service/FileSystemService.java trunk/fs/src/fs/org/jnode/fs/service/def/FileSystemAPIImpl.java trunk/fs/src/fs/org/jnode/fs/service/def/FileSystemPlugin.java trunk/fs/src/fs/org/jnode/fs/service/def/VirtualDirEntry.java trunk/fs/src/fs/org/jnode/partitions/command/PartitionHelper.java trunk/fs/src/fs/org/jnode/partitions/ibm/IBMPartitionTable.java Added Paths: ----------- trunk/fs/src/fs/org/jnode/fs/jfat/command/GrubException.java trunk/fs/src/fs/org/jnode/fs/jfat/command/JGrub.java trunk/fs/src/fs/org/jnode/fs/jfat/command/Stage1_5.java trunk/fs/src/fs/org/jnode/fs/jfat/command/Stage2.java trunk/fs/src/fs/org/jnode/partitions/ibm/MasterBootRecord.java Removed Paths: ------------- trunk/fs/src/fs/org/jnode/fs/jfat/command/GrubJFatFormatter.java Modified: trunk/builder/src/builder/org/jnode/build/BootDiskBuilder.java =================================================================== --- trunk/builder/src/builder/org/jnode/build/BootDiskBuilder.java 2008-02-04 19:54:36 UTC (rev 3757) +++ trunk/builder/src/builder/org/jnode/build/BootDiskBuilder.java 2008-02-04 20:04:19 UTC (rev 3758) @@ -9,16 +9,16 @@ * 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 + * 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 + * 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., + * 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.build; import java.io.File; @@ -61,7 +61,7 @@ /** * Create the actual bootfloppy - * + * * @throws IOException * @throws DriverException * @throws FileSystemException @@ -88,7 +88,7 @@ /** * Format the given device - * + * * @param device * @throws IOException */ @@ -98,19 +98,8 @@ GrubBootSector mbr = (GrubBootSector) (createFormatter() .getBootSector()); - mbr.getPartition(0).clear(); - mbr.getPartition(1).clear(); - mbr.getPartition(2).clear(); - mbr.getPartition(3).clear(); + IBMPartitionTableEntry pte = mbr.initPartitions(geom,IBMPartitionTypes.PARTTYPE_DOS_FAT16_LT32M); - IBMPartitionTableEntry pte = mbr.getPartition(0); - pte.setBootIndicator(true); - pte.setStartLba(1); - pte.setNrSectors(geom.getTotalSectors() - 1); - pte.setSystemIndicator(IBMPartitionTypes.PARTTYPE_DOS_FAT16_LT32M); - pte.setStartCHS(geom.getCHS(pte.getStartLba())); - pte.setEndCHS(geom.getCHS(pte.getStartLba() + pte.getNrSectors() - 1)); - /* * System.out.println("partition table:"); for (int i = 0; i < 4; i++) { * System.out.println("" + i + " " + mbr.getPartition(i)); } @@ -163,7 +152,7 @@ /** * Sets the plnFile. - * + * * @param plnFile * The plnFile to set */ @@ -182,7 +171,7 @@ /** * Used by ant to set the geometry property. - * + * * @param geometryString String in the format ' <cylinder>/ <heads>/ <sectors>', e.\u00f6g. * '64/16/32'. */ Modified: trunk/core/src/core/org/jnode/util/FileUtils.java =================================================================== --- trunk/core/src/core/org/jnode/util/FileUtils.java 2008-02-04 19:54:36 UTC (rev 3757) +++ trunk/core/src/core/org/jnode/util/FileUtils.java 2008-02-04 20:04:19 UTC (rev 3758) @@ -9,19 +9,23 @@ * 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 + * 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 + * 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., + * 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.util; import java.io.ByteArrayOutputStream; +import java.io.Closeable; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -29,7 +33,7 @@ /** * <description> - * + * * @author epr */ public class FileUtils { @@ -48,7 +52,7 @@ int size = is.read(dest, ofs, len); ofs += size; len -= size; - } + } } /** @@ -100,4 +104,69 @@ public static final ByteBuffer loadToBuffer(InputStream is, boolean close) throws IOException { return ByteBuffer.wrap(load(is, close)); } + + /** + * close quietly a stream (no IOException thrown), which might be null + * + * @param closeable the stream to close, might be null + * + * @return true if the stream was null or was closed properly + */ + public static final boolean close(Closeable closeable) + { + boolean ok = false; + + try { + if(closeable != null) + { + closeable.close(); + } + + ok = true; + } catch (IOException e) { + e.printStackTrace(); + } + + return ok; + } + + public static final void copyFile(File srcFile, File destFile) throws IOException { + InputStream in = null; + OutputStream out = null; + + try + { + in = new FileInputStream(srcFile); + out = new FileOutputStream(destFile); + + byte[] buffer = new byte[1024]; + int bytesRead; + while ((bytesRead = in.read(buffer)) >= 0) { + out.write(buffer, 0, bytesRead); + } + } + finally + { + FileUtils.close(out); + FileUtils.close(in); + } + } + + public static final void copyFile(String srcFileCopy, String destFileCopy, String destFileName) throws IOException { + + // make sure the source file is indeed a readable file + File srcFile = new File(srcFileCopy); + if (!srcFile.isFile() || !srcFile.canRead()) { + throw new IllegalArgumentException("Not a readable file: " + srcFile.getName()); + } + + // make sure the second argument is a directory + File destDir = new File(destFileCopy); + + // create File object for destination file + File destFile = new File(destDir, destFileName); + + // copy file, optionally creating a checksum + copyFile(srcFile, destFile); + } } Modified: trunk/distr/src/install/org/jnode/install/action/GrubInstallerAction.java =================================================================== --- trunk/distr/src/install/org/jnode/install/action/GrubInstallerAction.java 2008-02-04 19:54:36 UTC (rev 3757) +++ trunk/distr/src/install/org/jnode/install/action/GrubInstallerAction.java 2008-02-04 20:04:19 UTC (rev 3758) @@ -3,24 +3,31 @@ */ package org.jnode.install.action; -import org.jnode.fs.jfat.command.JGrubInstallCommand; -import org.jnode.install.*; +import org.jnode.driver.Device; +import org.jnode.driver.DeviceUtils; +import org.jnode.fs.jfat.command.JGrub; +import org.jnode.install.AbstractInstaller; +import org.jnode.install.ActionInput; +import org.jnode.install.ActionOutput; +import org.jnode.install.InputContext; +import org.jnode.install.InstallerAction; +import org.jnode.install.OutputContext; /** * @author Levente S\u00e1ntha */ public class GrubInstallerAction implements InstallerAction { - private String disk; - private String partition; - private String targetDirectory; + private JGrub jgrub; public ActionInput getInput(final InputContext inContext) { return new ActionInput() { public AbstractInstaller.Step collect() { try { - disk = inContext.getStringInput("Enter the installation disk device name: "); - partition = inContext.getStringInput("Enter the partition number: "); - targetDirectory = "/devices/" + disk + partition + "/"; - inContext.setStringValue(ActionConstants.INSTALL_ROOT_DIR, targetDirectory); + String deviceID = inContext.getStringInput("Enter the installation disk device name (example: hda0) : "); + + Device disk = DeviceUtils.getDevice(deviceID); + JGrub jgrub = new JGrub(System.out, System.err, disk); + + inContext.setStringValue(ActionConstants.INSTALL_ROOT_DIR, jgrub.getMountPoint()); return AbstractInstaller.Step.forth; } catch(Exception e){ return AbstractInstaller.Step.back; @@ -30,7 +37,7 @@ } public void execute() throws Exception { - JGrubInstallCommand.main(disk,"-p", partition, targetDirectory); + jgrub.install(); } public ActionOutput getOutput(OutputContext outContext) { Modified: trunk/fs/descriptors/org.jnode.fs.jfat.command.xml =================================================================== --- trunk/fs/descriptors/org.jnode.fs.jfat.command.xml 2008-02-04 19:54:36 UTC (rev 3757) +++ trunk/fs/descriptors/org.jnode.fs.jfat.command.xml 2008-02-04 20:04:19 UTC (rev 3758) @@ -11,6 +11,7 @@ <import plugin="org.jnode.fs.jfat"/> <import plugin="org.jnode.fs.command"/> <import plugin="org.jnode.shell.help"/> + <import plugin="org.jnode.partitions.ibm"/> </requires> <runtime> Modified: trunk/fs/src/driver/org/jnode/driver/block/FileDevice.java =================================================================== --- trunk/fs/src/driver/org/jnode/driver/block/FileDevice.java 2008-02-04 19:54:36 UTC (rev 3757) +++ trunk/fs/src/driver/org/jnode/driver/block/FileDevice.java 2008-02-04 20:04:19 UTC (rev 3758) @@ -9,16 +9,16 @@ * 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 + * 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 + * 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., + * 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.driver.block; import java.io.File; @@ -33,7 +33,7 @@ /** * This class is a device wrapping a simple file - * + * * @author epr */ public class FileDevice extends Device implements FSBlockDeviceAPI { @@ -70,8 +70,8 @@ public void read(long devOffset, ByteBuffer destBuf) throws IOException { BlockDeviceAPIHelper.checkBounds(this, devOffset, destBuf.remaining()); raf.seek(devOffset); - - //TODO optimize it also to use ByteBuffer at lower level + + //TODO optimize it also to use ByteBuffer at lower level ByteBufferUtils.ByteArray destBA = ByteBufferUtils.toByteArray(destBuf); byte[] dest = destBA.toArray(); raf.read(dest, 0, dest.length); @@ -86,8 +86,8 @@ // log.debug("fd.write devOffset=" + devOffset + ", length=" + length); BlockDeviceAPIHelper.checkBounds(this, devOffset, srcBuf.remaining()); raf.seek(devOffset); - - //TODO optimize it also to use ByteBuffer at lower level + + //TODO optimize it also to use ByteBuffer at lower level byte[] src = ByteBufferUtils.toArray(srcBuf); raf.write(src, 0, src.length); } @@ -114,14 +114,14 @@ public void close() throws IOException { raf.close(); } - + /** * @see org.jnode.driver.block.FSBlockDeviceAPI#getPartitionTableEntry() */ public PartitionTableEntry getPartitionTableEntry() { return null; } - + /** * @see org.jnode.driver.block.FSBlockDeviceAPI#getSectorSize() */ Modified: trunk/fs/src/driver/org/jnode/driver/block/PartitionableBlockDeviceAPI.java =================================================================== --- trunk/fs/src/driver/org/jnode/driver/block/PartitionableBlockDeviceAPI.java 2008-02-04 19:54:36 UTC (rev 3757) +++ trunk/fs/src/driver/org/jnode/driver/block/PartitionableBlockDeviceAPI.java 2008-02-04 20:04:19 UTC (rev 3758) @@ -9,16 +9,16 @@ * 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 + * 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 + * 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., + * 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.driver.block; import java.io.IOException; @@ -29,26 +29,24 @@ /** * This device API is implemented by block devices that * support partition tables. - * + * * @author Ewout Prangsma (ep...@us...) */ -public interface PartitionableBlockDeviceAPI - <PTE extends PartitionTableEntry> +public interface PartitionableBlockDeviceAPI + <PTE extends PartitionTableEntry> extends BlockDeviceAPI { /** * Gets the sector size for this device. * @return The sector size in bytes - * @throws IOException + * @throws IOException */ public int getSectorSize() throws IOException; - + /** * Gets the partition table that this block device contains. * @return Null if no partition table is found. * @throws IOException */ public PartitionTable<PTE> getPartitionTable() throws IOException; - - public String toString(); } Modified: trunk/fs/src/fs/org/jnode/fs/command/MountCommand.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/command/MountCommand.java 2008-02-04 19:54:36 UTC (rev 3757) +++ trunk/fs/src/fs/org/jnode/fs/command/MountCommand.java 2008-02-04 20:04:19 UTC (rev 3758) @@ -9,16 +9,16 @@ * 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 + * 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 + * 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., + * 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.fs.command; import java.io.InputStream; @@ -70,13 +70,13 @@ // Find the filesystem service final FileSystemService fss = InitialNaming.lookup(FileSystemService.NAME); - + // Find the filesystem final FileSystem fs = fss.getFileSystem(dev); if (fs == null) { err.println("No filesystem found on " + dev.getId()); exit(1); - } else { + } else { // Mount it fss.mount(mountPoint, fs, fsPath); } Modified: trunk/fs/src/fs/org/jnode/fs/fat/BootSector.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/fat/BootSector.java 2008-02-04 19:54:36 UTC (rev 3757) +++ trunk/fs/src/fs/org/jnode/fs/fat/BootSector.java 2008-02-04 20:04:19 UTC (rev 3758) @@ -9,29 +9,33 @@ * 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 + * 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 + * 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., + * 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.fs.fat; import java.io.IOException; import java.nio.ByteBuffer; import org.jnode.driver.block.BlockDeviceAPI; +import org.jnode.driver.block.Geometry; +import org.jnode.driver.block.Geometry.GeometryException; +import org.jnode.partitions.ibm.IBMPartitionTable; import org.jnode.partitions.ibm.IBMPartitionTableEntry; +import org.jnode.partitions.ibm.IBMPartitionTypes; import org.jnode.util.LittleEndian; import org.jnode.util.NumberUtils; /** * <description> - * + * * @author epr */ public class BootSector { @@ -54,27 +58,23 @@ } public boolean isaValidBootSector() { - if (data.length >= 512) { - return (data[510] & 0xFF) == 0x55 && (data[511] & 0xFF) == 0xAA; - } else { - return false; - } + return IBMPartitionTable.containsPartitionTable(data); } /** * Read the contents of this bootsector from the given device. - * + * * @param device */ public synchronized void read(BlockDeviceAPI device) throws IOException { device.read(0, ByteBuffer.wrap(data)); - + dirty = false; } /** * Write the contents of this bootsector to the given device. - * + * * @param device */ public synchronized void write(BlockDeviceAPI device) throws IOException { @@ -84,7 +84,7 @@ /** * Gets the OEM name - * + * * @return String */ public String getOemName() { @@ -113,7 +113,7 @@ /** * Gets the number of bytes/sector - * + * * @return int */ public int getBytesPerSector() { @@ -129,7 +129,7 @@ /** * Gets the number of sectors/cluster - * + * * @return int */ public int getSectorsPerCluster() { @@ -145,7 +145,7 @@ /** * Gets the number of reserved (for bootrecord) sectors - * + * * @return int */ public int getNrReservedSectors() { @@ -161,7 +161,7 @@ /** * Gets the number of fats - * + * * @return int */ public int getNrFats() { @@ -177,7 +177,7 @@ /** * Gets the number of entries in the root directory - * + * * @return int */ public int getNrRootDirEntries() { @@ -193,7 +193,7 @@ /** * Gets the number of logical sectors - * + * * @return int */ public int getNrLogicalSectors() { @@ -209,7 +209,7 @@ /** * Gets the medium descriptor byte - * + * * @return int */ public int getMediumDescriptor() { @@ -225,7 +225,7 @@ /** * Gets the number of sectors/fat - * + * * @return int */ public int getSectorsPerFat() { @@ -241,7 +241,7 @@ /** * Gets the number of sectors/track - * + * * @return int */ public int getSectorsPerTrack() { @@ -257,7 +257,7 @@ /** * Gets the number of heads - * + * * @return int */ public int getNrHeads() { @@ -273,7 +273,7 @@ /** * Gets the number of hidden sectors - * + * * @return int */ public int getNrHiddenSectors() { @@ -289,7 +289,7 @@ /** * Gets an unsigned 8-bit byte from a given offset - * + * * @param offset * @return int */ @@ -299,7 +299,7 @@ /** * Sets an unsigned 8-bit byte at a given offset - * + * * @param offset */ protected void set8(int offset, int value) { @@ -309,7 +309,7 @@ /** * Gets an unsigned 16-bit word from a given offset - * + * * @param offset * @return int */ @@ -319,7 +319,7 @@ /** * Sets an unsigned 16-bit word at a given offset - * + * * @param offset */ protected void set16(int offset, int value) { @@ -329,7 +329,7 @@ /** * Gets an unsigned 32-bit word from a given offset - * + * * @param offset * @return int */ @@ -339,7 +339,7 @@ /** * Sets an unsigned 32-bit word at a given offset - * + * * @param offset */ protected void set32(int offset, long value) { @@ -349,7 +349,7 @@ /** * Returns the dirty. - * + * * @return boolean */ public boolean isDirty() { @@ -358,9 +358,26 @@ public int getNbPartitions() { - return partitions.length; + return partitions.length; } - + + public IBMPartitionTableEntry initPartitions(Geometry geom, IBMPartitionTypes firstPartitionType) throws GeometryException { + getPartition(0).clear(); + getPartition(1).clear(); + getPartition(2).clear(); + getPartition(3).clear(); + + IBMPartitionTableEntry entry = getPartition(0); + entry.setBootIndicator(true); + entry.setStartLba(1); + entry.setNrSectors(geom.getTotalSectors() - 1); + entry.setSystemIndicator(firstPartitionType); + entry.setStartCHS(geom.getCHS(entry.getStartLba())); + entry.setEndCHS(geom.getCHS(entry.getStartLba() + entry.getNrSectors() - 1)); + + return entry; + } + public synchronized IBMPartitionTableEntry getPartition(int partNr) { if (partitions[partNr] == null) { partitions[partNr] = new IBMPartitionTableEntry(null, data, partNr); @@ -407,7 +424,7 @@ res.append("Nr Root Dir Entries = "); res.append(getNrRootDirEntries()); res.append('\n'); - + for(int i=0; i<data.length /16 ; i++) { res.append(Integer.toHexString(i)); @@ -415,7 +432,7 @@ res.append(NumberUtils.hex(data,i*16,16)); res.append('\n'); } - + return res.toString(); } } Modified: trunk/fs/src/fs/org/jnode/fs/jfat/BootSector.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/jfat/BootSector.java 2008-02-04 19:54:36 UTC (rev 3757) +++ trunk/fs/src/fs/org/jnode/fs/jfat/BootSector.java 2008-02-04 20:04:19 UTC (rev 3758) @@ -30,6 +30,7 @@ import org.jnode.fs.FileSystemException; import org.jnode.fs.jfat.StrWriter; import org.jnode.driver.block.BlockDeviceAPI; +import org.jnode.partitions.ibm.IBMPartitionTable; import org.jnode.util.LittleEndian; import org.jnode.util.NumberUtils; @@ -126,13 +127,7 @@ public boolean isaValidBootSector() { - if ( sector.length >= 512 ) - return - ( sector[510] & 0xFF ) == 0x55 && - ( sector[511] & 0xFF ) == 0xAA; - else - return - false; + return IBMPartitionTable.containsPartitionTable(sector); } Added: trunk/fs/src/fs/org/jnode/fs/jfat/command/GrubException.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/jfat/command/GrubException.java (rev 0) +++ trunk/fs/src/fs/org/jnode/fs/jfat/command/GrubException.java 2008-02-04 20:04:19 UTC (rev 3758) @@ -0,0 +1,11 @@ +package org.jnode.fs.jfat.command; + +public class GrubException extends Exception { + public GrubException(String message) { + super(message); + } + + public GrubException(String message, Throwable cause) { + super(message, cause); + } +} Deleted: trunk/fs/src/fs/org/jnode/fs/jfat/command/GrubJFatFormatter.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/jfat/command/GrubJFatFormatter.java 2008-02-04 19:54:36 UTC (rev 3757) +++ trunk/fs/src/fs/org/jnode/fs/jfat/command/GrubJFatFormatter.java 2008-02-04 20:04:19 UTC (rev 3758) @@ -1,107 +0,0 @@ -/* - * $Id: GrubJFatFormatter.java Tanmoy $ - * - * JNode.org - * Copyright (C) 2007 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.fs.jfat.command; - -import java.io.*; -import org.apache.log4j.Logger; -import org.jnode.fs.FileSystemException; - - -/** - * File :GrubFatFormatter.java - * <p/> - * The very important file for the Grub Installation. Here the - * methods for setting the Stage2 to the partition is kept. - * - * @author Tango Devian - */ -public class GrubJFatFormatter { - private static final Logger log = Logger.getLogger(GrubJFatFormatter.class); - private static final String GRUB_STAGE_2 = "/devices/sg0/boot/grub/grub.s2"; - private static final String GRUB_MENU_LST = "/devices/sg0/boot/grub/menu.lst"; - - /** - * @throws org.jnode.fs.FileSystemException - * - * @throws org.jnode.fs.FileSystemException - * - * @throws org.jnode.fs.FileSystemException - * - * @throws java.io.IOException - * @throws java.io.IOException - * @see org.jnode.fs.fat.FatFormatter#format(org.jnode.driver.block.BlockDeviceAPI) - */ - public void format(String path) throws FileSystemException, IOException { - // writting of the stage2 and menu.LST - try { - File destDir = new File(path + "/boot/grub/"); - if(!destDir.exists()){ - System.out.print("Creating directory: " + destDir.getAbsolutePath() + " ... "); - destDir.mkdirs(); - System.out.println("done."); - } - - System.out.print("Writing stage 2 ... "); - copyFAT(GRUB_STAGE_2, destDir.getAbsolutePath(), "stage2"); - System.out.println("done."); - - System.out.print("Writing menu.lst ... "); - copyFAT(GRUB_MENU_LST, destDir.getAbsolutePath(), "menu.lst"); - System.out.println("done."); - - } catch (IOException e) { - e.printStackTrace(); - } - } - - private static void copyFile(File srcFile, File destFile) throws IOException { - - InputStream in = new FileInputStream(srcFile); - OutputStream out = new FileOutputStream(destFile); - - byte[] buffer = new byte[1024]; - int bytesRead; - while ((bytesRead = in.read(buffer)) >= 0) { - out.write(buffer, 0, bytesRead); - } - out.close(); - in.close(); - - } - - private static void copyFAT(String srcFileCopy, String destFileCopy, String destFileName) throws IOException { - - // make sure the source file is indeed a readable file - File srcFile = new File(srcFileCopy); - if (!srcFile.isFile() || !srcFile.canRead()) { - throw new IllegalArgumentException("Not a readable file: " + srcFile.getName()); - } - - // make sure the second argument is a directory - File destDir = new File(destFileCopy); - - // create File object for destination file - File destFile = new File(destDir, destFileName); - - // copy file, optionally creating a checksum - copyFile(srcFile, destFile); - } -} Added: trunk/fs/src/fs/org/jnode/fs/jfat/command/JGrub.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/jfat/command/JGrub.java (rev 0) +++ trunk/fs/src/fs/org/jnode/fs/jfat/command/JGrub.java 2008-02-04 20:04:19 UTC (rev 3758) @@ -0,0 +1,190 @@ +/* + * $Id: FatConstants.java 2224 Tanmoy $ + * + * JNode.org + * Copyright (C) 2003-2006 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.fs.jfat.command; + +import java.io.File; +import java.io.PrintStream; +import java.util.Map; + +import javax.naming.NameNotFoundException; + +import org.jnode.driver.ApiNotFoundException; +import org.jnode.driver.Device; +import org.jnode.driver.DeviceManager; +import org.jnode.driver.DeviceNotFoundException; +import org.jnode.driver.DeviceUtils; +import org.jnode.driver.DriverException; +import org.jnode.driver.block.BlockDeviceAPI; +import org.jnode.fs.FileSystem; +import org.jnode.fs.service.FileSystemService; +import org.jnode.naming.InitialNaming; + +/** + * The Grub Installer for JNode. + * + * TODO: Adding more options for supporting JGRUB with user specified File + * System wise. + * Adding more command support for grub installation. + * + * @author Tango Devian + */ +public class JGrub { + private final PrintStream out; + private final PrintStream err; + private final MBRFormatter stage1; + private final Stage1_5 stage1_5; + private final Stage2 stage2; + private final Device device; + private final String mountPoint; + + public JGrub(PrintStream out, PrintStream err, Device device) throws GrubException + { + this(out, err, device, new MBRFormatter(), new Stage1_5(), new Stage2()); + } + + protected JGrub(PrintStream out, PrintStream err, Device device, MBRFormatter stage1, Stage1_5 stage1_5, Stage2 stage2) throws GrubException + { + this.out = out; + this.err = err; + this.stage1 = stage1; + this.stage1_5 = stage1_5; + this.stage2 = stage2; + this.device = device; + + mountPoint = getMountPoint(device); + } + + public String getMountPoint() + { + return mountPoint; + } + + public void install() throws GrubException + { + final String deviceName = device.getId(); + out.println("Installing GRUB to " + deviceName); + + DeviceManager dm; + try { + dm = DeviceUtils.getDeviceManager(); + } catch (NameNotFoundException e1) { + throw new GrubException("can't find device manager", e1); + } + + // workaround. TODO add a new interface to FileSystemService to find parent device ? + int i = deviceName.length() - 1; + while((i >= 0) && Character.isDigit(deviceName.charAt(i))) + { + i--; + } + final String parentDeviceName = deviceName.substring(0, i + 1); + final int partitionNumber = Integer.parseInt(deviceName.substring(i + 1)); + // + + final Device parentDevice = getDevice(dm, parentDeviceName); + final BlockDeviceAPI parentDeviceApi = getBlockDeviceAPI(parentDevice); + + stage1.format(parentDeviceApi); + stage1_5.format(parentDeviceApi, partitionNumber); + + stage2.format(mountPoint); + + restart(dm, parentDevice); + out.println("GRUB has been successfully installed to " + deviceName + "."); + } + + private String getMountPoint(Device device) throws GrubException { + FileSystemService fss = null; + try { + fss = InitialNaming.lookup(FileSystemService.NAME); + } catch (NameNotFoundException e) { + throw new GrubException("filesystem not found", e); + } + + FileSystem<?> filesystem = fss.getFileSystem(device); + if(filesystem == null) + { + throw new GrubException("can't find filesystem for device "+device.getId()); + } + + Map<String, FileSystem<?>> mountPoints = fss.getMountPoints(); + String mountPoint = null; + for(String fullPath : mountPoints.keySet()) + { + FileSystem<?> fs = mountPoints.get(fullPath); + if(fs == filesystem) + { + mountPoint = fullPath; + break; + } + } + + if(mountPoint == null) + { + throw new GrubException("can't find mount point for filesystem "+filesystem); + } + + if(!mountPoint.endsWith(File.separator)) + { + mountPoint += File.separatorChar; + } + + return mountPoint; + } + + private void restart(DeviceManager dm, Device device) throws GrubException { + out.println("Restarting device " + device.getId()); + try { + dm.stop(device); + dm.start(device); + } catch (DeviceNotFoundException e) { + throw new GrubException("device not found : "+device.getId(), e); + } catch (DriverException e) { + throw new GrubException("device must be a partition device", e); + } + } + + private Device getDevice(DeviceManager dm, String deviceName) throws GrubException + { + Device parentDevice = null; + try { + parentDevice = dm.getDevice(deviceName); + } catch (DeviceNotFoundException e1) { + throw new GrubException("can't find device with name "+deviceName, e1); + } + return parentDevice; + } + + private BlockDeviceAPI getBlockDeviceAPI(Device device) throws GrubException + { + BlockDeviceAPI deviceApi = null; + try + { + deviceApi = device.getAPI(BlockDeviceAPI.class); + } catch (ApiNotFoundException e) { + throw new GrubException("device must be a partition device", e); + } + + return deviceApi; + } +} Modified: trunk/fs/src/fs/org/jnode/fs/jfat/command/JGrubInstallCommand.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/jfat/command/JGrubInstallCommand.java 2008-02-04 19:54:36 UTC (rev 3757) +++ trunk/fs/src/fs/org/jnode/fs/jfat/command/JGrubInstallCommand.java 2008-02-04 20:04:19 UTC (rev 3758) @@ -9,68 +9,46 @@ * 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 + * 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 + * 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., + * 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.fs.jfat.command; -import java.io.*; -import javax.naming.NameNotFoundException; +import java.io.InputStream; +import java.io.PrintStream; + import org.jnode.driver.Device; -import org.jnode.driver.DeviceManager; -import org.jnode.driver.DeviceNotFoundException; -import org.jnode.driver.DriverException; -import org.jnode.naming.InitialNaming; +import org.jnode.driver.block.BlockDeviceAPI; import org.jnode.shell.AbstractCommand; import org.jnode.shell.CommandLine; import org.jnode.shell.help.Help; import org.jnode.shell.help.Parameter; import org.jnode.shell.help.ParsedArguments; import org.jnode.shell.help.argument.DeviceArgument; -import org.jnode.shell.help.argument.FileArgument; -import org.jnode.shell.help.argument.OptionArgument; /** - * <p/> - * The Grub Installer command for the JNODE. - * jnode/>grub hdb /devices/hdb0 + * Grub Installer command for JNode. + * example of usage : grub hdb0 * - * @HDA_TARGET /dev/hda0 or /dev/fd0 - * <p/> - * TODO: Adding more options for supporting JGRUB with user specified File - * System wise. - * Adding more command support for grub insallation. + * TODO: Add more options for supporting Grub with user specified file + * TODO: Add more command support for grub installation. * @author Tango Devian */ public class JGrubInstallCommand extends AbstractCommand { - static final DeviceArgument ARG_DEVICE = new DeviceArgument("device", "device where grub will be installed"); - static final FileArgument ARG_DIR = new FileArgument("directory", "the directory for stage2 and menu.lst"); - static final OptionArgument TYPE = new OptionArgument("action","Type parameter", - new OptionArgument.Option("-p","Set the partition point for installing Stage2,menu.lst")); - static final OptionArgument PS_VAL = new OptionArgument("Partition Value", - "Setting The Partition value like (-p 1) for the hdx1", - new OptionArgument.Option("0", "hdX0"), - new OptionArgument.Option("1", "hdX1"), - new OptionArgument.Option("2", "hdX2"), - new OptionArgument.Option("3", "hdX3")); + static final DeviceArgument ARG_DEVICE = new DeviceArgument("device partition", "device where grub stage 2 will be installed", BlockDeviceAPI.class); - - static final Help.Info HELP_INFO = new Help.Info("grub", "Install the grub to the specified location.", - new Parameter(ARG_DEVICE, Parameter.MANDATORY), - new Parameter(TYPE,Parameter.MANDATORY), - new Parameter(PS_VAL,Parameter.MANDATORY), - new Parameter(ARG_DIR,Parameter.MANDATORY)); + new Parameter(ARG_DEVICE, Parameter.MANDATORY)); /** * @param args * @throws Exception @@ -83,39 +61,10 @@ * */ public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) throws Exception { - try { - ParsedArguments cmdLine = HELP_INFO.parse(commandLine); - String device = ARG_DEVICE.getValue(cmdLine); - File destDir = ARG_DIR.getFile(cmdLine); + ParsedArguments cmdLine = HELP_INFO.parse(commandLine); + Device device = ARG_DEVICE.getDevice(cmdLine); - Integer bsize=null; - try { - bsize = Integer.valueOf(PS_VAL.getValue(cmdLine)); - } catch (NumberFormatException nfe) { - System.out.println("ERROR: give the partition value as the 0 ,1,2,3"+"\n" +"This grub installer not support the Extended partition."); - } - DeviceManager dm = InitialNaming.lookup(DeviceManager.NAME); - Device dev = dm.getDevice(device); - String destDirName = destDir.getAbsolutePath(); - out.println("Installing GRUB to: " + device + ", " + destDirName); - try { - new MBRFormatter().format(dev,bsize); - new GrubJFatFormatter().format(destDirName); - out.println("Restarting device: " + device); - dm.stop(dev); - dm.start(dev); - out.println("GRUB has been successflly installed to " + device + "."); - } catch (FileNotFoundException e) { - err.println("File not found: " + e.getMessage()); - } catch (IOException e) { - err.println("I/O exception: " + e.getMessage()); - } - } catch (NameNotFoundException e) { - err.println("Name not found: " + e.getMessage()); - } catch (DeviceNotFoundException e) { - err.println("Device not found: " + e.getMessage()); - } catch (DriverException e) { - err.println("The DriverException Occuered ..." + e.getMessage()); - } + JGrub jgrub = new JGrub(out, err, device); + jgrub.install(); } } Modified: trunk/fs/src/fs/org/jnode/fs/jfat/command/MBRFormatter.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/jfat/command/MBRFormatter.java 2008-02-04 19:54:36 UTC (rev 3757) +++ trunk/fs/src/fs/org/jnode/fs/jfat/command/MBRFormatter.java 2008-02-04 20:04:19 UTC (rev 3758) @@ -9,476 +9,176 @@ * 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 + * 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 + * 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., + * 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.fs.jfat.command; -/** - * The MBRFormatter is the main class for writing the stage1 and stage1.5 - * to the MBR. - */ import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; -import java.nio.ByteBuffer; import org.apache.log4j.Logger; -import org.jnode.driver.ApiNotFoundException; -import org.jnode.driver.Device; import org.jnode.driver.block.BlockDeviceAPI; -import org.jnode.driver.bus.ide.IDEConstants; import org.jnode.fs.FileSystemException; -import org.jnode.partitions.ibm.IBMPartitionTable; -import org.jnode.partitions.ibm.IBMPartitionTableEntry; +import org.jnode.partitions.ibm.MasterBootRecord; import org.jnode.util.FileUtils; -import org.jnode.util.LittleEndian; /** + * The MBRFormatter is the main class for writing the stage1 and stage1.5 + * to the MBR. + * * @author tango */ - -public class MBRFormatter { +class MBRFormatter { private static final Logger log = Logger.getLogger(MBRFormatter.class); - IBMPartitionTableEntry oldEntry; - byte[] stage1; - byte[] stage1_5; + private MasterBootRecord stage1; + + final static String GRUB_HOME = "/devices/sg0/boot/grub/"; /** * The Source path for the Grub in CD://devices/sg0/boot/grub/STAGE1. - * Because the grub can installed from the Live Boot CD. + * Because the grub can installed from the Live Boot CD. */ - final String stageResourceName1 = "/devices/sg0/boot/grub/grub.s1"; - final String stageResourceName2 = "/devices/sg0/boot/grub/fat.s15"; - private static int INSTALL_PARTITION = 0xFFFFFF; - private String configFile; - //The Embedded Variables values in Jnode - final int SAVED_ENTRY_NUMBER=0xe; - final String CONFIG_FILE_NAME="/boot/grub/menu.lst"; + final private String stageResourceName1 = GRUB_HOME + "grub.s1"; /** - * - * The reading of the OLD MBR - * @throws java.io.IOException - * - */ - private void checkMBR(ByteBuffer MBR) throws IOException - { - if (!IBMPartitionTable.containsPartitionTable(MBR.array())) - throw new IOException("This device doesn't contain a valid MBR."); - } - - /** * Reading the Grub stages from the Rescue Device. * * @param stage1ResourceName * @return * @throws java.io.IOException */ - public byte[] getStage1(String stage1ResourceName) throws IOException { + private MasterBootRecord getStage1(String stage1ResourceName) throws GrubException { if (stage1 == null) { - File file = new File(stage1ResourceName); - InputStream is = new FileInputStream(file); - byte[] buf = new byte[512]; - FileUtils.copy(is, buf); - is.close(); - stage1 = buf; + try { + File file = new File(stage1ResourceName); + InputStream is = new FileInputStream(file); + byte[] buf = new byte[512]; + FileUtils.copy(is, buf); + is.close(); + stage1 = new MasterBootRecord(buf); + } catch (IOException e) { + throw new GrubException("error while reading stage1", e); + } } return stage1; } - + /** - * The Method for reading the stage1.5 from the Rescue Disk. - * @param stage2ResourceName - * @return - * @throws java.io.IOException + * + * @param device + * @param bsize + * @throws FileSystemException + * @throws IOException */ - public byte[] getStage1_5(String stage2ResourceName) throws IOException { - if (stage1_5 == null) { - File file = new File(stage2ResourceName); - InputStream is = new FileInputStream(file); - byte[] buf = new byte[(int)file.length()]; - FileUtils.copy(is, buf); - is.close(); - stage1_5 = buf; - } - return stage1_5; - - } - - /** - * The method that will write the stage1.5 for the File System - * specific to the Boot-sector to the block device. - * - * - */ - public final static void writeStage1_5(long stage1_5_start, - ByteBuffer stage1_5, - BlockDeviceAPI devApi) { - try { - devApi.write(stage1_5_start,(stage1_5)); - }catch (IOException e) { - e.printStackTrace(); - - } - } - - /** - * @throws org.jnode.fs.FileSystemException - * @throws org.jnode.fs.FileSystemException - * @throws org.jnode.fs.FileSystemException - * @throws java.io.IOException - * @throws java.io.IOException - * @see org.jnode.fs.fat.FatFormatter#format(org.jnode.driver.block.BlockDeviceAPI) - */ - public void format(Device device,int bsize) throws FileSystemException, IOException { - BlockDeviceAPI devApi; - try { - devApi = device.getAPI(BlockDeviceAPI.class); - } catch (ApiNotFoundException e) { - throw new FileSystemException("Device is not a partition!", e); - } + public void format(BlockDeviceAPI devApi) throws GrubException { log.info("Checking the old MBR..."); - ByteBuffer MBR=ByteBuffer.allocate(IDEConstants.SECTOR_SIZE); - devApi.read(0, MBR); - checkMBR(MBR); - log.info("done."); - + MasterBootRecord oldMbr; + try { + oldMbr = new MasterBootRecord(devApi); + } catch (IOException e) { + throw new GrubException("error while reading MBR", e); + } + + if (!oldMbr.containsPartitionTable()) { + throw new GrubException( + "This device doesn't contain a valid MBR."); + } + log.info("done."); + /*int add=LittleEndian.getInt32(MBR.array(),0x44); System.out.println("The value at the position 0x44 is-> " +Integer.toHexString(add));*/ - byte[] partition=getPartitionTable(0x1be,64,MBR); - - if(!isaValidBootSector(MBR.array())){ - log.error("The OLD Boot Sector is not valid."); - } - try{ + stage1=getStage1(stageResourceName1); - }catch(FileNotFoundException e){ - log.error("The stage1 is not available."); - } /** - * The BPB stands for the Bios Parameter Block.As the BPB of - * a disk is fixed and it is written to the disk during the - * partitioning of the disk. The BPB is present between the + * The BPB stands for the Bios Parameter Block.As the BPB of + * a disk is fixed and it is written to the disk during the + * partitioning of the disk. The BPB is present between the * position of 0x3 to 0x48 position. - * + * * NOTE: - * 1) Here need to make the BPB more independently(ie without + * 1) Here need to make the BPB more independently(ie without * array of the BPB using it in MBR) - * + * * 2)The next Important matter is here that in the MBR's - * <b> 0x44 th</b> position we setting the position of the - * stage1.5 or Stage2.here as i used the Stage1.5 at the Sector + * <b> 0x44 th</b> position we setting the position of the + * stage1.5 or Stage2.here as i used the Stage1.5 at the Sector * 1(second sector) so The Value is set here as 01 00 00 00 - * - * 3)In the Position of the 0x40: + * + * 3)In the Position of the 0x40: * The boot drive. If it is 0xFF, use a drive passed by BIOS. * The value is 0x80 for HDD.I kept it default here. - * + * * 4)0x42: The starting address of Stage 2 or Stage1.5. * As here i used the Stage1.5;hence the value i set here 0x2000 - * If it is Stage2 then it will be 0x8000. - * + * If it is Stage2 then it will be 0x8000. + * * 5)0x48: The starting segment of Stage 2 or Stage1.5. * Here for stage1.5 i used the value 0x20 * For stage2 it will be 0x80. - * + * * TODO: In this portion we need to use dynamically the BPB values. - * And, that time at the stage1 buffer the EMBEDDED variables need to + * And, that time at the stage1 buffer the EMBEDDED variables need to * set here individually. - * + * * BUGs REPORT: Using statically the value of the BPB.and setted - * the EMBEDDED variables in that array statically.It is not good. - * ;-) - * + * the EMBEDDED variables in that array statically.It is not good. + * ;-) + * */ - setBPB(BPB,stage1); + stage1.setBPB(BPB); + /** * The Partition table is the cruisal part of the HDD formatted with - * different FS.For the grub disk the Stage1 is kept upto the first + * different FS.For the grub disk the Stage1 is kept upto the first * 446bytes to the MBR.Then after the 64 bytes are kept for Setting * the PArtition table. - * - * N.B. : The grub will be written actually always after the + * + * N.B. : The grub will be written actually always after the * Partition Table written to the HDD.IT is very IMPORTANT. - * - */ - setPartitionTable(0x1be,64,partition,stage1); - + * + */ + stage1.copyPartitionTableFrom(oldMbr); + /** * Checking the BootSector is Valid or not. * Actually here need to check the Sector Signature. - * 0x55AA ---> - * + * 0x55AA ---> + * */ - if(!isaValidBootSector(stage1)){ - log.error("The New Boot Sector Is Not Valid."); + if(!stage1.containsPartitionTable()){ + throw new GrubException("The new boot sector is not valid"); } - - try { + + try { /** - * write the GRUB's stage1 to the MBR - */ + * write the GRUB's stage1 to the MBR + */ System.out.print("Writing stage 1 ... "); - devApi.write(0,ByteBuffer.wrap(stage1)); - devApi.flush(); + stage1.write(devApi); System.out.println("done."); - - - - System.out.println("The Stage1.5 is now embedding."); - try{ - stage1_5 = getStage1_5(stageResourceName2); - }catch(FileNotFoundException ex){ - log.error("The Stage1.5 is not available."); - } - int size=stage1_5.length/IDEConstants.SECTOR_SIZE; - log.info("The Size of the stage1_5 is : "+size); - - - - /** - * The most important stage of the GRUB BOOTING. THE stage1.5. - * - * The Embedded variables for the grub setting into - * the JNode's grub stage1.5 - */ - - - /** - * The Blocklists for JNode grub installer is setting to - * the (512-4)th position of the Sector1 of the Stage1.5. - * Blocklists is the size of the stage1.5 in the sectors unit. - * - **/ - setLittleEnd_BlockLists(stage1_5,size); - - - - /** Fixup the install partition */ - setLittleEnd_InstallPartition(stage1_5,INSTALL_PARTITION); - - - - setConfigFile(CONFIG_FILE_NAME); - - /** The Saved Entry Number **/ - setLittleEnd_EntryNumber(stage1_5,SAVED_ENTRY_NUMBER); - - - /** - * The most important section of the Grub - * The path of the stage2 in the stage1.5 - * - * NOTE: Here at the ox19 offset of the second - * Sector of the stage1.5. the value of the Drive Path - * is kept where the stage2 is kept. - * Ex: as here the /dev/hd0 is used (ie the partition where - * the FATfs is kept and where the stage2 will keep. - * So here the value set as 0x00. - * - * The path of the stage2 is very important.Otherwise it will can - * create ERROR 17. - * - * Suppose (hd0,1)/boot/grub/stage2-- - * (hd0,1) corresponds to linux partition /dev/hda2 - * (or /dev/sda2, depending on bios).So hd0 is the first hard disk found by bios. - * The "1" stands for partition number starting from "0". - * Under linux partition numbers start with 1. Therefore, - * the number differs.When this path - * is patched into stage1.5 at position 512+0x12+5, then the device specification - * (hd0,1) is converted to binary, e.g. 0x8001ffff - * (0x80 first hard disk, 0x01 first partition, 0xffff - * only for BSD partition).The directory /boot/grub/stage2 is relative to the - * partition, so if you have a /boot partition, then the path would be just /grub/stage2. - * Normally grub should detect the mapping of unix partition to its own - * partition numbering scheme automatically. In some cases this does - * not work, e.g. if you have multiple hard disks, the numbering of your - * BIOS is hard to predict. Grub uses a file device.map where you can change - * the numbering manually. - * - * - * <b>BUGS:</b>1) As currently it is only statically written here the - * value of the 0x00; so the stage2 is need to only kept at - * the /devices/hdb0.For supporting it in the any partition - * here need to change once little bit logic. - * - * 2)Need to support the Device.map for MUltiple Disk supporting in - * the JNODE. - * - **/ - setLittleEnd_DrivePath(stage1_5,bsize); - - - /** - * Fixup the config file - * TODO: here to be change that the Config File - * will write after skipping the /boot/grub/stage2 - * - */ - if (configFile != null) { - int ofs = 512 + 0x27; - while (stage1_5[ofs] != 0) { - ofs++; - } - ofs++; /* Skip '\0' */ - for (int i = 0; i < configFile.length(); i++) { - stage1_5[ofs++] = (byte) configFile.charAt(i); - } - stage1_5[ofs] = 0; - } - - - /** - * The Method for writing the Stage1.5 to - * the Sector 1 actually to the second sector. - * - * - */ - writeStage1_5(IDEConstants.SECTOR_SIZE, ByteBuffer.wrap(stage1_5), devApi); - - } catch (IOException e) { - System.out.println("The Bootsector Failed...."); + throw new GrubException("Failed writing boot sector"); } - - System.out.println("Writing stage 1 and stage 1.5 has been completed."); - - -} - /** - * The Install Partition setting - * @arch i386 - * @param stage1_5 - * @param installPartition2 - */ - private void setLittleEnd_InstallPartition(byte[] stage1_5, int installPartition) { - LittleEndian.setInt32(stage1_5, 512 + 0x08, installPartition); + System.out.println("Writing stage 1 has been completed."); + } - } /** - * The saved Entry Number setting. - * @arch i386 - * @param stage1_5 - * @param i - */ - private void setLittleEnd_EntryNumber(byte[] stage1_5, int i) { - LittleEndian.setInt32(stage1_5,512+0xc,i); - - } - /** ... [truncated message content] |
From: <hag...@us...> - 2008-02-13 15:40:21
|
Revision: 3788 http://jnode.svn.sourceforge.net/jnode/?rev=3788&view=rev Author: hagar-wize Date: 2008-02-13 07:40:20 -0800 (Wed, 13 Feb 2008) Log Message: ----------- a little step on the way to have derby running Modified Paths: -------------- trunk/all/build.xml trunk/distr/descriptors/derby.xml trunk/distr/src/apps/org/jnode/apps/derby/DerbyCommand.java Added Paths: ----------- trunk/distr/lib/derbytools.jar Modified: trunk/all/build.xml =================================================================== --- trunk/all/build.xml 2008-02-13 14:54:42 UTC (rev 3787) +++ trunk/all/build.xml 2008-02-13 15:40:20 UTC (rev 3788) @@ -60,6 +60,7 @@ <property name="servlet.jar" value="${root.dir}/distr/lib/servlet-api-2.5-6.1.5.jar" /> <property name="derby.jar" value="${root.dir}/distr/lib/derby.jar" /> <property name="derbynet.jar" value="${root.dir}/distr/lib/derbynet.jar" /> + <property name="derbytools.jar" value="${root.dir}/distr/lib/derbytools.jar" /> <!-- libraries needed to run tests --> <property name="jmock-cglib.jar" value="${root.dir}/core/lib/jmock-cglib-1.0.1.jar"/> @@ -123,6 +124,7 @@ <pathelement location="${mauve.jar}"/> <pathelement location="${derby.jar}"/> <pathelement location="${derbynet.jar}"/> + <pathelement location="${derbytools.jar}"/> </path> <path id="cp-jnode"> @@ -250,6 +252,7 @@ <libalias name="servlet.jar" alias="${servlet.jar}"/> <libalias name="derby.jar" alias="${derby.jar}"/> <libalias name="derbynet.jar" alias="${derbynet.jar}"/> + <libalias name="derbytools.jar" alias="${derbytools.jar}"/> <descriptors dir="${descriptors.dir}/"> <include name="*.xml"/> Modified: trunk/distr/descriptors/derby.xml =================================================================== --- trunk/distr/descriptors/derby.xml 2008-02-13 14:54:42 UTC (rev 3787) +++ trunk/distr/descriptors/derby.xml 2008-02-13 15:40:20 UTC (rev 3788) @@ -20,9 +20,16 @@ <library name="derbynet.jar"> <export name="org.apache.derby.drda.*"/> <export name="org.apache.derby.impl.drda.*"/> - <export name="org.apache.derby.impl.info.net.prpperties"/> + <export name="org.apache.derby.info.net*"/> <export name="org.apache.derby.loc.drda.*"/> </library> + <library name="derbytools.jar"> + <export name="org.apache.derby.tools.*"/> + <export name="org.apache.derby.impl.tools.*"/> + <export name="org.apache.derby.iapi.reference.*"/> + <export name="org.apache.derby.info.tools*"/> + <export name="org.apache.derby.loc.toolsmessages*"/> + </library> <library name="jnode-distr.jar"> <export name="org.jnode.apps.derby.*"/> </library> @@ -34,6 +41,8 @@ <extension point="org.jnode.security.permissions"> <permission class="java.lang.RuntimePermission" name="exitVM" actions="*" /> + <permission class="java.net.SocketPermission" name="*:1527" actions="accept,connect,listen"/> + <permission class="java.io.FilePermission" name="<<ALL FILES>>" actions="read,write"/> </extension> </plugin> Added: trunk/distr/lib/derbytools.jar =================================================================== (Binary files differ) Property changes on: trunk/distr/lib/derbytools.jar ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Modified: trunk/distr/src/apps/org/jnode/apps/derby/DerbyCommand.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/derby/DerbyCommand.java 2008-02-13 14:54:42 UTC (rev 3787) +++ trunk/distr/src/apps/org/jnode/apps/derby/DerbyCommand.java 2008-02-13 15:40:20 UTC (rev 3788) @@ -5,6 +5,7 @@ import org.apache.derby.drda.NetworkServerControl; +import org.apache.derby.impl.drda.NetworkServerControlImpl; import org.jnode.shell.AbstractCommand; import org.jnode.shell.CommandLine; @@ -19,6 +20,8 @@ import java.io.InputStream; import java.io.PrintStream; import java.io.File; +import java.io.PrintWriter; +import java.util.Date; /** * Command for handling Derby server. @@ -42,6 +45,30 @@ new DerbyCommand().execute(args); } + final void find(long fixedDate) + { + long d0; + int d1, d2, d3, d4; + int n400, n100, n4, n1; + int year; + + if (fixedDate > 0) { + d0 = fixedDate - 1; + + n400 = (int)(d0 / 146097); + + d1 = (int)(d0 % 146097); + n100 = d1 / 36524; + d2 = d1 % 36524; + n4 = d2 / 1461; + d3 = d2 % 1461; + n1 = d3 / 365; + d4 = (d3 % 365) + 1; + + System.out.println(n400); + } + } + public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) throws Exception { ParsedArguments arguments = HELP_INFO.parse(commandLine); File home_dir = ARG_HOME.getFile(arguments); @@ -52,6 +79,19 @@ port = ARG_PORT.getInteger(arguments); } - NetworkServerControl.main(new String[]{command}); + NetworkServerControlImpl server = new NetworkServerControlImpl(); + + try { + int server_command = server.parseArgs( new String[]{command} ); + PrintWriter printWriter = new PrintWriter(out); + server.setLogWriter(printWriter); + server.start(printWriter); + } catch (Exception e) { + e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. + } + +// server.executeWork(server_command); + +// NetworkServerControl.main(new String[]{command}); } } \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <hag...@us...> - 2008-02-21 09:58:38
|
Revision: 3813 http://jnode.svn.sourceforge.net/jnode/?rev=3813&view=rev Author: hagar-wize Date: 2008-02-21 01:58:33 -0800 (Thu, 21 Feb 2008) Log Message: ----------- increased heap Modified Paths: -------------- trunk/build.bat trunk/build.sh Modified: trunk/build.bat =================================================================== --- trunk/build.bat 2008-02-21 08:07:12 UTC (rev 3812) +++ trunk/build.bat 2008-02-21 09:58:33 UTC (rev 3813) @@ -1,3 +1,3 @@ @echo off setlocal -"%JAVA_HOME%\bin\java" -Xmx512M -Xms128M -jar core\lib\ant-launcher.jar -lib "%JAVA_HOME%\lib" -lib core\lib -f all\build.xml %* +"%JAVA_HOME%\bin\java" -Xmx768M -Xms256M -jar core\lib\ant-launcher.jar -lib "%JAVA_HOME%\lib" -lib core\lib -f all\build.xml %* Modified: trunk/build.sh =================================================================== --- trunk/build.sh 2008-02-21 08:07:12 UTC (rev 3812) +++ trunk/build.sh 2008-02-21 09:58:33 UTC (rev 3813) @@ -1,6 +1,6 @@ #!/bin/sh dir=`dirname $0` -java -Xmx512M -Xms128M -jar $dir/core/lib/ant-launcher.jar -lib $JAVA_HOME/lib -lib $dir/core/lib -f $dir/all/build.xml $* +java -Xmx768M -Xms256M -jar $dir/core/lib/ant-launcher.jar -lib $JAVA_HOME/lib -lib $dir/core/lib -f $dir/all/build.xml $* This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <hag...@us...> - 2008-02-22 09:17:04
|
Revision: 3816 http://jnode.svn.sourceforge.net/jnode/?rev=3816&view=rev Author: hagar-wize Date: 2008-02-22 01:17:03 -0800 (Fri, 22 Feb 2008) Log Message: ----------- Modified Paths: -------------- trunk/JNode.ipr trunk/JNode.iws trunk/all/all.iml trunk/builder/builder.iml trunk/core/core.iml trunk/distr/distr.iml trunk/fs/fs.iml trunk/gui/gui.iml trunk/jnode.iml trunk/net/net.iml trunk/shell/shell.iml trunk/textui/textui.iml Modified: trunk/JNode.ipr =================================================================== --- trunk/JNode.ipr 2008-02-22 04:11:37 UTC (rev 3815) +++ trunk/JNode.ipr 2008-02-22 09:17:03 UTC (rev 3816) @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8"?> -<project version="4" relativePaths="true"> +<project relativePaths="true" version="4"> <component name="AntConfiguration"> <defaultAnt bundledAnt="true" /> <buildFile url="file://$PROJECT_DIR$/all/build.xml"> @@ -10,13 +10,19 @@ <properties /> </buildFile> </component> + <component name="BuildJarProjectSettings"> + <option name="BUILD_JARS_ON_MAKE" value="false" /> + </component> + <component name="CodeStyleProjectProfileManger"> + <option name="PROJECT_PROFILE" /> + <option name="USE_PROJECT_LEVEL_SETTINGS" value="false" /> + </component> <component name="CodeStyleSettingsManager"> <option name="PER_PROJECT_SETTINGS" /> <option name="USE_PER_PROJECT_SETTINGS" value="false" /> </component> <component name="CompilerConfiguration"> <option name="DEFAULT_COMPILER" value="Javac" /> - <option name="CLEAR_OUTPUT_DIRECTORY" value="false" /> <option name="DEPLOY_AFTER_MAKE" value="0" /> <resourceExtensions> <entry name=".+\.(properties|xml|html|dtd|tld)" /> @@ -34,20 +40,47 @@ <entry name="?*.jpg" /> </wildcardResourcePatterns> </component> - <component name="DataSourceManagerImpl" /> <component name="DependenciesAnalyzeManager"> <option name="myForwardDirection" value="false" /> </component> - <component name="DependencyValidationManager" /> + <component name="DependencyValidationManager"> + <option name="SKIP_IMPORT_STATEMENTS" value="false" /> + </component> + <component name="EclipseCompilerSettings"> + <option name="DEBUGGING_INFO" value="true" /> + <option name="GENERATE_NO_WARNINGS" value="true" /> + <option name="DEPRECATION" value="false" /> + <option name="ADDITIONAL_OPTIONS_STRING" value="" /> + <option name="MAXIMUM_HEAP_SIZE" value="128" /> + </component> + <component name="EclipseEmbeddedCompilerSettings"> + <option name="DEBUGGING_INFO" value="true" /> + <option name="GENERATE_NO_WARNINGS" value="true" /> + <option name="DEPRECATION" value="false" /> + <option name="ADDITIONAL_OPTIONS_STRING" value="" /> + <option name="MAXIMUM_HEAP_SIZE" value="128" /> + </component> <component name="EntryPointsManager"> - <entry_points /> + <entry_points version="2.0" /> </component> <component name="ExportToHTMLSettings"> <option name="PRINT_LINE_NUMBERS" value="false" /> <option name="OPEN_IN_BROWSER" value="false" /> <option name="OUTPUT_DIRECTORY" /> </component> - <component name="GUI Designer component loader factory" /> + <component name="IdProvider" IDEtalkID="435AAC2234C36B0F2257FA7F02C447FB" /> + <component name="InspectionProjectProfileManager"> + <option name="PROJECT_PROFILE" value="Project Default" /> + <option name="USE_PROJECT_LEVEL_SETTINGS" value="false" /> + <scopes /> + <profiles> + <profile version="1.0" is_locked="false"> + <option name="myName" value="Project Default" /> + <option name="myLocal" value="false" /> + </profile> + </profiles> + <list size="0" /> + </component> <component name="JavacSettings"> <option name="DEBUGGING_INFO" value="true" /> <option name="GENERATE_NO_WARNINGS" value="false" /> @@ -69,6 +102,7 @@ <option name="OPTION_DEPRECATED_LIST" value="true" /> <option name="OTHER_OPTIONS" value="" /> <option name="HEAP_SIZE" /> + <option name="LOCALE" /> <option name="OPEN_IN_BROWSER" value="true" /> </component> <component name="JikesSettings"> @@ -81,108 +115,126 @@ </component> <component name="Palette2"> <group name="Swing"> - <item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.png" removable="false"> + <item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.png" removable="false" auto-create-binding="false" can-attach-label="false"> <default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" /> </item> - <item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.png" removable="false"> + <item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.png" removable="false" auto-create-binding="false" can-attach-label="false"> <default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" /> </item> - <item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.png" removable="false"> + <item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.png" removable="false" auto-create-binding="false" can-attach-label="false"> <default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" /> </item> - <item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.png" removable="false"> + <item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.png" removable="false" auto-create-binding="false" can-attach-label="true"> <default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" /> </item> - <item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.png" removable="false"> + <item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.png" removable="false" auto-create-binding="true" can-attach-label="false"> <default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" /> <initial-values> <property name="text" value="Button" /> </initial-values> </item> - <item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.png" removable="false"> + <item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.png" removable="false" auto-create-binding="true" can-attach-label="false"> <default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" /> <initial-values> <property name="text" value="RadioButton" /> </initial-values> </item> - <item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.png" removable="false"> + <item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.png" removable="false" auto-create-binding="true" can-attach-label="false"> <default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" /> <initial-values> <property name="text" value="CheckBox" /> </initial-values> </item> - <item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.png" removable="false"> + <item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.png" removable="false" auto-create-binding="false" can-attach-label="false"> <default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" /> <initial-values> <property name="text" value="Label" /> </initial-values> </item> - <item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.png" removable="false"> + <item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.png" removable="false" auto-create-binding="true" can-attach-label="true"> <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1"> <preferred-size width="150" height="-1" /> </default-constraints> </item> - <item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.png" removable="false"> + <item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.png" removable="false" auto-create-binding="true" can-attach-label="true"> <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1"> <preferred-size width="150" height="-1" /> </default-constraints> </item> - <item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.png" removable="false"> + <item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.png" removable="false" auto-create-binding="true" can-attach-label="true"> <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1"> <preferred-size width="150" height="-1" /> </default-constraints> </item> - <item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.png" removable="false"> + <item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.png" removable="false" auto-create-binding="true" can-attach-label="true"> <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3"> <preferred-size width="150" height="50" /> </default-constraints> </item> - <item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.png" removable="false"> + <item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.png" removable="false" auto-create-binding="true" can-attach-label="true"> <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3"> <preferred-size width="150" height="50" /> </default-constraints> </item> - <item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.png" removable="false"> + <item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.png" removable="false" auto-create-binding="true" can-attach-label="true"> <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3"> <preferred-size width="150" height="50" /> </default-constraints> </item> - <item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.png" removable="false"> + <item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.png" removable="false" auto-create-binding="true" can-attach-label="true"> <default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" /> </item> - <item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.png" removable="false"> + <item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.png" removable="false" auto-create-binding="true" can-attach-label="false"> <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3"> <preferred-size width="150" height="50" /> </default-constraints> </item> - <item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.png" removable="false"> + <item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.png" removable="false" auto-create-binding="true" can-attach-label="false"> <default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3"> <preferred-size width="150" height="50" /> </default-constraints> </item> - <item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.png" removable="false"> + <item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.png" removable="false" auto-create-binding="true" can-attach-label="false"> <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3"> <preferred-size width="150" height="50" /> </default-constraints> </item> - <item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.png" removable="false"> + <item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.png" removable="false" auto-create-binding="true" can-attach-label="false"> <default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3"> <preferred-size width="200" height="200" /> </default-constraints> </item> - <item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.png" removable="false"> + <item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.png" removable="false" auto-create-binding="false" can-attach-label="false"> <default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3"> <preferred-size width="200" height="200" /> </default-constraints> </item> - <item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.png" removable="false"> + <item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.png" removable="false" auto-create-binding="true" can-attach-label="true"> <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" /> </item> - <item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.png" removable="false"> + <item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.png" removable="false" auto-create-binding="true" can-attach-label="false"> <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" /> </item> + <item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.png" removable="false" auto-create-binding="false" can-attach-label="false"> + <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" /> + </item> + <item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.png" removable="false" auto-create-binding="true" can-attach-label="false"> + <default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" /> + </item> + <item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.png" removable="false" auto-create-binding="false" can-attach-label="false"> + <default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1"> + <preferred-size width="-1" height="20" /> + </default-constraints> + </item> + <item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.png" removable="false" auto-create-binding="false" can-attach-label="false"> + <default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" /> + </item> + <item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.png" removable="false" auto-create-binding="true" can-attach-label="false"> + <default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" /> + </item> </group> </component> + <component name="ProjectFileVersion" converted="true" /> <component name="ProjectModuleManager"> <modules> <module fileurl="file://$PROJECT_DIR$/all/all.iml" filepath="$PROJECT_DIR$/all/all.iml" /> @@ -197,7 +249,14 @@ <module fileurl="file://$PROJECT_DIR$/textui/textui.iml" filepath="$PROJECT_DIR$/textui/textui.iml" /> </modules> </component> - <component name="ProjectRootManager" version="2" assert-keyword="true" jdk-15="true" project-jdk-name="java version "1.5.0_02"" /> + <component name="ProjectRootManager" version="2" assert-keyword="true" jdk-15="true" project-jdk-name="1.6" project-jdk-type="JavaSDK" /> + <component name="ResourceManagerContainer"> + <option name="myResourceBundles"> + <value> + <list size="0" /> + </value> + </option> + </component> <component name="RmicSettings"> <option name="IS_EANABLED" value="false" /> <option name="DEBUGGING_INFO" value="true" /> @@ -205,7 +264,10 @@ <option name="GENERATE_IIOP_STUBS" value="false" /> <option name="ADDITIONAL_OPTIONS_STRING" value="" /> </component> - <component name="WebServicesPlugin" /> + <component name="VcsDirectoryMappings"> + <mapping directory="" vcs="svn" /> + </component> + <component name="WebServicesPlugin" addRequiredLibraries="true" /> <component name="libraryTable"> <library name="core"> <CLASSES> @@ -236,11 +298,23 @@ <JAVADOC /> <SOURCES /> </library> + <library name="distr"> + <CLASSES> + <root url="file://$PROJECT_DIR$/distr/lib" /> + <root url="file://$PROJECT_DIR$/distr/lib" /> + <root url="file://$PROJECT_DIR$/distr/lib" /> + </CLASSES> + <JAVADOC /> + <SOURCES> + <root url="file://$PROJECT_DIR$/decompiled" /> + <root url="file://$PROJECT_DIR$/distr/decompiled" /> + </SOURCES> + <jarDirectory url="file://$PROJECT_DIR$/distr/lib" recursive="false" /> + </library> </component> <component name="uidesigner-configuration"> <option name="INSTRUMENT_CLASSES" value="true" /> <option name="COPY_FORMS_RUNTIME_TO_OUTPUT" value="true" /> </component> - <UsedPathMacros /> </project> Modified: trunk/JNode.iws =================================================================== --- trunk/JNode.iws 2008-02-22 04:11:37 UTC (rev 3815) +++ trunk/JNode.iws 2008-02-22 09:17:03 UTC (rev 3816) @@ -1,7 +1,19 @@ <?xml version="1.0" encoding="UTF-8"?> -<project version="4" relativePaths="true"> - <component name="AspectsView" /> - <component name="BookmarkManager" /> +<project relativePaths="true" version="4"> + <component name="CCaseConfig"> + <option name="checkoutReserved" value="false" /> + <option name="markExternalChangeAsUpToDate" value="true" /> + <option name="checkInUseHijack" value="true" /> + <option name="useUcmModel" value="true" /> + <option name="isOffline" value="false" /> + <option name="synchOutside" value="false" /> + <option name="isHistoryResticted" value="true" /> + <option name="useIdenticalSwitch" value="true" /> + <option name="synchActivitiesOnRefresh" value="true" /> + <option name="lastScr" value="" /> + <option name="scrTextFileName" value="" /> + <option name="historyRevisionsNumber" value="4" /> + </component> <component name="ChangeBrowserSettings"> <option name="MAIN_SPLITTER_PROPORTION" value="0.3" /> <option name="MESSAGES_SPLITTER_PROPORTION" value="0.8" /> @@ -16,7 +28,25 @@ <option name="USE_USER_FILTER" value="false" /> <option name="USER" value="" /> </component> - <component name="CheckinPanelState" /> + <component name="ChangeListManager"> + <list default="true" name="Default" comment=""> + <change type="MODIFICATION" beforePath="$PROJECT_DIR$/core/core.iml" afterPath="$PROJECT_DIR$/core/core.iml" /> + <change type="MODIFICATION" beforePath="$PROJECT_DIR$/distr/distr.iml" afterPath="$PROJECT_DIR$/distr/distr.iml" /> + <change type="MODIFICATION" beforePath="$PROJECT_DIR$/all/all.iml" afterPath="$PROJECT_DIR$/all/all.iml" /> + <change type="MODIFICATION" beforePath="$PROJECT_DIR$/fs/fs.iml" afterPath="$PROJECT_DIR$/fs/fs.iml" /> + <change type="MODIFICATION" beforePath="$PROJECT_DIR$/JNode.iws" afterPath="$PROJECT_DIR$/JNode.iws" /> + <change type="MODIFICATION" beforePath="$PROJECT_DIR$/net/net.iml" afterPath="$PROJECT_DIR$/net/net.iml" /> + <change type="MODIFICATION" beforePath="$PROJECT_DIR$/jnode.iml" afterPath="$PROJECT_DIR$/jnode.iml" /> + <change type="MODIFICATION" beforePath="$PROJECT_DIR$/JNode.ipr" afterPath="$PROJECT_DIR$/JNode.ipr" /> + <change type="MODIFICATION" beforePath="$PROJECT_DIR$/gui/gui.iml" afterPath="$PROJECT_DIR$/gui/gui.iml" /> + <change type="MODIFICATION" beforePath="$PROJECT_DIR$/textui/textui.iml" afterPath="$PROJECT_DIR$/textui/textui.iml" /> + <change type="MODIFICATION" beforePath="$PROJECT_DIR$/builder/builder.iml" afterPath="$PROJECT_DIR$/builder/builder.iml" /> + <change type="MODIFICATION" beforePath="$PROJECT_DIR$/shell/shell.iml" afterPath="$PROJECT_DIR$/shell/shell.iml" /> + </list> + <ignored path="JNode.iws" /> + <ignored path=".idea/workspace.xml" /> + </component> + <component name="ChangesViewManager" flattened_view="true" show_ignored="false" /> <component name="Commander"> <leftPanel /> <rightPanel /> @@ -28,6 +58,10 @@ <option name="CLOSE_MESSAGE_VIEW_IF_SUCCESS" value="true" /> <option name="COMPILE_DEPENDENT_FILES" value="false" /> </component> + <component name="CreatePatchCommitExecutor"> + <option name="PATCH_PATH" value="" /> + <option name="REVERSE_PATCH" value="false" /> + </component> <component name="Cvs2Configuration"> <option name="PRUNE_EMPTY_DIRECTORIES" value="true" /> <option name="MERGING_MODE" value="0" /> @@ -75,7 +109,6 @@ <option name="TAG_AFTER_PROJECT_COMMIT_NAME" value="" /> <option name="CLEAN_COPY" value="false" /> </component> - <component name="CvsTabbedWindow" /> <component name="DaemonCodeAnalyzer"> <disable_hints /> </component> @@ -85,9 +118,9 @@ <option name="NOTIFY_CAUGHT" value="true" /> <option name="NOTIFY_UNCAUGHT" value="true" /> <option name="ENABLED" value="false" /> - <option name="SUSPEND_POLICY" value="SuspendAll" /> <option name="LOG_ENABLED" value="false" /> <option name="LOG_EXPRESSION_ENABLED" value="false" /> + <option name="SUSPEND_POLICY" value="SuspendAll" /> <option name="COUNT_FILTER_ENABLED" value="false" /> <option name="COUNT_FILTER" value="0" /> <option name="CONDITION_ENABLED" value="false" /> @@ -100,9 +133,9 @@ <option name="NOTIFY_CAUGHT" value="true" /> <option name="NOTIFY_UNCAUGHT" value="true" /> <option name="ENABLED" value="false" /> - <option name="SUSPEND_POLICY" value="SuspendAll" /> <option name="LOG_ENABLED" value="false" /> <option name="LOG_EXPRESSION_ENABLED" value="false" /> + <option name="SUSPEND_POLICY" value="SuspendAll" /> <option name="COUNT_FILTER_ENABLED" value="false" /> <option name="COUNT_FILTER" value="0" /> <option name="CONDITION_ENABLED" value="false" /> @@ -119,6 +152,9 @@ <option name="IS_AUTOSCROLL_TO_SOURCE" value="false" /> <option name="HIDE_WARNINGS" value="false" /> </component> + <component name="FavoritesManager"> + <favorites_list name="JNode" /> + </component> <component name="FavoritesViewImpl"> <favorites_list name="JNode"> <option name="IS_AUTOSCROLL_TO_SOURCE" value="false" /> @@ -132,7 +168,19 @@ </favorites_list> <option name="myCurrentFavoritesList" value="JNode" /> </component> - <component name="FileEditorManager" /> + <component name="FileEditorManager"> + <leaf> + <file leaf-file-name="build.xml" pinned="false" current="true" current-in-tab="true"> + <entry file="file://$PROJECT_DIR$/all/build.xml"> + <provider selected="true" editor-type-id="text-editor"> + <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0"> + <folding /> + </state> + </provider> + </entry> + </file> + </leaf> + </component> <component name="FindManager"> <FindUsagesManager> <setting name="OPEN_NEW_TAB" value="false" /> @@ -143,24 +191,6 @@ <option name="SORT_ALPHABETICALLY" value="false" /> <option name="HIDE_CLASSES_WHERE_METHOD_NOT_IMPLEMENTED" value="false" /> </component> - <component name="InspectionManager"> - <option name="AUTOSCROLL_TO_SOURCE" value="false" /> - <option name="SPLITTER_PROPORTION" value="0.5" /> - <option name="GROUP_BY_SEVERITY" value="false" /> - <option name="ANALYZE_TEST_SOURCES" value="true" /> - <option name="SCOPE_TYPE" value="1" /> - <option name="CUSTOM_SCOPE_NAME" value="" /> - <profile name="Default" /> - </component> - <component name="J2EEProjectPane"> - <PATH> - <PATH_ELEMENT> - <option name="myItemId" value="JNode.ipr" /> - <option name="myItemType" value="com.intellij.j2ee.module.view.nodes.J2EEProjectNodeDescriptor" /> - </PATH_ELEMENT> - </PATH> - <setting name="SHOW_AS_DEPLOYMENT_VIEW" value="false" /> - </component> <component name="KiwiScrap"> <confirmations /> <scraps /> @@ -169,44 +199,86 @@ <option name="LAST_EDITED_MODULE_NAME" value="jnode" /> <option name="LAST_EDITED_TAB_NAME" value="Paths" /> </component> - <component name="NamedScopeManager" /> <component name="PackagesPane"> - <PATH> - <PATH_ELEMENT> - <option name="myItemId" value="JNode.ipr" /> - <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PackageViewProjectNode" /> - </PATH_ELEMENT> - </PATH> + <subPane> + <PATH> + <PATH_ELEMENT> + <option name="myItemId" value="JNode" /> + <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PackageViewProjectNode" /> + </PATH_ELEMENT> + </PATH> + <PATH> + <PATH_ELEMENT> + <option name="myItemId" value="JNode" /> + <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PackageViewProjectNode" /> + </PATH_ELEMENT> + <PATH_ELEMENT> + <option name="myItemId" value="core" /> + <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PackageViewModuleNode" /> + </PATH_ELEMENT> + </PATH> + <PATH> + <PATH_ELEMENT> + <option name="myItemId" value="JNode" /> + <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PackageViewProjectNode" /> + </PATH_ELEMENT> + <PATH_ELEMENT> + <option name="myItemId" value="core" /> + <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PackageViewModuleNode" /> + </PATH_ELEMENT> + <PATH_ELEMENT> + <option name="myItemId" value="org" /> + <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PackageElementNode" /> + </PATH_ELEMENT> + </PATH> + <PATH> + <PATH_ELEMENT> + <option name="myItemId" value="JNode" /> + <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PackageViewProjectNode" /> + </PATH_ELEMENT> + <PATH_ELEMENT> + <option name="myItemId" value="core" /> + <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PackageViewModuleNode" /> + </PATH_ELEMENT> + <PATH_ELEMENT> + <option name="myItemId" value="org" /> + <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PackageElementNode" /> + </PATH_ELEMENT> + <PATH_ELEMENT> + <option name="myItemId" value="jnode" /> + <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PackageElementNode" /> + </PATH_ELEMENT> + <PATH_ELEMENT> + <option name="myItemId" value="work" /> + <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PackageElementNode" /> + </PATH_ELEMENT> + </PATH> + <PATH> + <PATH_ELEMENT> + <option name="myItemId" value="JNode" /> + <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PackageViewProjectNode" /> + </PATH_ELEMENT> + <PATH_ELEMENT> + <option name="myItemId" value="core" /> + <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PackageViewModuleNode" /> + </PATH_ELEMENT> + <PATH_ELEMENT> + <option name="myItemId" value="org" /> + <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PackageElementNode" /> + </PATH_ELEMENT> + <PATH_ELEMENT> + <option name="myItemId" value="jnode" /> + <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PackageElementNode" /> + </PATH_ELEMENT> + </PATH> + </subPane> </component> <component name="PerforceChangeBrowserSettings"> <option name="USE_CLIENT_FILTER" value="true" /> <option name="CLIENT" value="" /> </component> <component name="PerforceDirect.Settings"> - <option name="useP4CONFIG" value="true" /> - <option name="port" value="<perforce_server>:1666" /> - <option name="client" value="" /> - <option name="user" value="" /> - <option name="passwd" value="" /> - <option name="showCmds" value="false" /> <option name="useNativeApi" value="true" /> - <option name="pathToExec" value="p4" /> - <option name="useCustomPathToExec" value="false" /> - <option name="SYNC_FORCE" value="false" /> - <option name="SYNC_RUN_RESOLVE" value="true" /> - <option name="REVERT_UNCHANGED_FILES" value="true" /> - <option name="CHARSET" value="none" /> - <option name="SHOW_BRANCHES_HISTORY" value="true" /> - <option name="ENABLED" value="true" /> - <option name="USE_LOGIN" value="false" /> - <option name="LOGIN_SILENTLY" value="false" /> - <option name="INTEGRATE_BRANCH_NAME" /> - <option name="INTEGRATE_CHANGELIST_NUM" value="-1" /> - <option name="INTEGRATE_RUN_RESOLVE" value="true" /> - <option name="INTEGRATE_REVERT_UNCHANGED" value="true" /> - <option name="INTEGRATE_CHANGE_LIST_NUMBER" value="" /> - <option name="INTEGRATE_CHANGE_LIST" value="false" /> - <option name="INTEGRATE_REVERSE" value="false" /> </component> <component name="ProjectLevelVcsManager"> <OptionsSetting value="true" id="Add" /> @@ -223,42 +295,20 @@ <ConfirmationsSetting value="0" id="Remove" /> </component> <component name="ProjectPane"> - <PATH> - <PATH_ELEMENT> - <option name="myItemId" value="JNode.ipr" /> - <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> - </PATH_ELEMENT> - </PATH> - <PATH> - <PATH_ELEMENT> - <option name="myItemId" value="JNode.ipr" /> - <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> - </PATH_ELEMENT> - <PATH_ELEMENT> - <option name="myItemId" value="jnode" /> - <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewModuleNode" /> - </PATH_ELEMENT> - </PATH> - <PATH> - <PATH_ELEMENT> - <option name="myItemId" value="JNode.ipr" /> - <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> - </PATH_ELEMENT> - <PATH_ELEMENT> - <option name="myItemId" value="jnode" /> - <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewModuleNode" /> - </PATH_ELEMENT> - <PATH_ELEMENT> - <option name="myItemId" value="PsiDirectory:C:\opensource\jnode" /> - <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> - </PATH_ELEMENT> - </PATH> + <subPane> + <PATH> + <PATH_ELEMENT> + <option name="myItemId" value="JNode" /> + <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> + </PATH_ELEMENT> + </PATH> + </subPane> </component> <component name="ProjectReloadState"> <option name="STATE" value="0" /> </component> <component name="ProjectView"> - <navigator currentView="ProjectPane" splitterProportion="0.5"> + <navigator currentView="ProjectPane" proportions="0.5" version="1" splitterProportion="0.5"> <flattenPackages /> <showMembers /> <showModules /> @@ -272,87 +322,120 @@ </navigator> </component> <component name="PropertiesComponent"> - <property name="vcs_file_view_treeWidth2" value="77" /> + <property name="cvs_file_history_treeOrder6" value="6" /> + <property name="vcs_file_view_flatOrder5" value="5" /> + <property name="cvs_file_history_treeOrder5" value="5" /> + <property name="cvs_file_history_treeOrder2" value="2" /> + <property name="cvs_file_history_treeOrder1" value="1" /> + <property name="cvs_file_history_treeOrder4" value="4" /> + <property name="cvs_file_history_treeOrder3" value="3" /> + <property name="FileHistory.org.jetbrains.idea.svn.history.SvnHistoryProvider_treeWidth2" value="96" /> + <property name="vcs_file_view_treeOrder2" value="2" /> + <property name="MemberChooser.sorted" value="false" /> + <property name="FileHistory.org.jetbrains.idea.svn.history.SvnHistoryProvider_treeWidth1" value="102" /> + <property name="vcs_file_view_treeOrder3" value="3" /> + <property name="FileHistory.org.jetbrains.idea.svn.history.SvnHistoryProvider_treeWidth0" value="102" /> + <property name="vcs_file_view_treeOrder0" value="0" /> + <property name="vcs_file_view_treeOrder1" value="1" /> + <property name="FileHistory.org.jetbrains.idea.svn.history.SvnHistoryProvider_treeWidth4" value="754" /> <property name="vcs_file_view_treeOrder4" value="4" /> - <property name="cvs_file_history_treeWidth0" value="171" /> - <property name="cvs_file_history_treeOrder4" value="4" /> - <property name="cvs_file_history_flatWidth2" value="171" /> - <property name="cvs_file_history_flatOrder4" value="4" /> - <property name="cvs_file_history_flatOrder1" value="1" /> - <property name="vcs_file_view_flatWidth2" value="47" /> - <property name="cvs_file_history_flatWidth1" value="171" /> + <property name="FileHistory.org.jetbrains.idea.svn.history.SvnHistoryProvider_treeWidth3" value="101" /> <property name="vcs_file_view_flatWidth5" value="50" /> - <property name="vcs_file_view_flatOrder3" value="3" /> - <property name="cvs_file_history_flatOrder2" value="2" /> - <property name="MemberChooser.showClasses" value="true" /> + <property name="cvs_file_history_flatWidth6" value="170" /> <property name="cvs_file_history_flatWidth4" value="170" /> - <property name="vcs_file_view_treeWidth0" value="77" /> - <property name="vcs_file_view_treeOrder0" value="0" /> - <property name="cvs_file_history_treeOrder5" value="5" /> - <property name="vcs_file_view_flatOrder4" value="4" /> - <property name="MemberChooser.sorted" value="false" /> - <property name="cvs_file_history_flatOrder0" value="0" /> - <property name="cvs_file_history_treeWidth4" value="170" /> - <property name="cvs_file_history_treeOrder3" value="3" /> - <property name="vcs_file_view_flatWidth4" value="51" /> - <property name="cvs_file_history_treeWidth6" value="170" /> - <property name="vcs_file_view_flatOrder2" value="2" /> - <property name="cvs_file_history_treeWidth3" value="171" /> - <property name="vcs_file_view_treeWidth4" value="77" /> - <property name="cvs_file_history_flatOrder6" value="6" /> - <property name="vcs_file_view_treeWidth3" value="78" /> + <property name="cvs_file_history_flatWidth5" value="171" /> + <property name="cvs_file_history_flatWidth2" value="171" /> + <property name="vcs_file_view_flatOrder0" value="0" /> + <property name="cvs_file_history_treeOrder0" value="0" /> <property name="cvs_file_history_flatWidth3" value="171" /> - <property name="vcs_file_view_flatOrder0" value="0" /> <property name="vcs_file_view_flatWidth0" value="147" /> + <property name="cvs_file_history_flatWidth0" value="171" /> + <property name="vcs_file_view_flatOrder2" value="2" /> <property name="vcs_file_view_flatWidth1" value="45" /> - <property name="MemberChooser.copyJavadoc" value="false" /> + <property name="GoToClass.includeLibraries" value="false" /> + <property name="cvs_file_history_flatWidth1" value="171" /> + <property name="vcs_file_view_flatWidth2" value="47" /> <property name="vcs_file_view_flatOrder1" value="1" /> - <property name="cvs_file_history_treeOrder1" value="1" /> + <property name="vcs_file_view_flatWidth3" value="47" /> + <property name="vcs_file_view_flatOrder4" value="4" /> + <property name="vcs_file_view_flatOrder3" value="3" /> + <property name="vcs_file_view_flatWidth4" value="51" /> <property name="GoToFile.includeJavaFiles" value="false" /> + <property name="MemberChooser.copyJavadoc" value="false" /> + <property name="FileHistory.org.jetbrains.idea.svn.history.SvnHistoryProvider_flatWidth1" value="125" /> + <property name="FileHistory.org.jetbrains.idea.svn.history.SvnHistoryProvider_flatWidth0" value="98" /> + <property name="vcs_file_view_treeWidth4" value="77" /> + <property name="FileHistory.org.jetbrains.idea.svn.history.SvnHistoryProvider_flatWidth3" value="31" /> + <property name="FileHistory.org.jetbrains.idea.svn.history.SvnHistoryProvider_flatWidth2" value="122" /> + <property name="FileHistory.org.jetbrains.idea.svn.history.SvnHistoryProvider_flatOrder1" value="1" /> + <property name="vcs_file_view_treeWidth1" value="78" /> + <property name="FileHistory.org.jetbrains.idea.svn.history.SvnHistoryProvider_flatOrder0" value="0" /> + <property name="vcs_file_view_treeWidth0" value="77" /> + <property name="FileHistory.org.jetbrains.idea.svn.history.SvnHistoryProvider_flatOrder3" value="3" /> + <property name="vcs_file_view_treeWidth3" value="78" /> + <property name="FileHistory.org.jetbrains.idea.svn.history.SvnHistoryProvider_flatOrder2" value="2" /> + <property name="vcs_file_view_treeWidth2" value="77" /> + <property name="FileHistory.org.jetbrains.idea.svn.history.SvnHistoryProvider_flatOrder4" value="4" /> + <property name="GoToClass.includeJavaFiles" value="false" /> + <property name="GoToClass.toSaveIncludeLibraries" value="false" /> + <property name="cvs_file_history_treeWidth0" value="171" /> <property name="cvs_file_history_treeWidth1" value="171" /> - <property name="cvs_file_history_treeOrder6" value="6" /> - <property name="GoToClass.includeLibraries" value="false" /> <property name="cvs_file_history_treeWidth2" value="171" /> - <property name="GoToClass.toSaveIncludeLibraries" value="false" /> + <property name="cvs_file_history_treeWidth3" value="171" /> + <property name="cvs_file_history_treeWidth4" value="170" /> + <property name="MemberChooser.showClasses" value="true" /> + <property name="FileHistory.org.jetbrains.idea.svn.history.SvnHistoryProvider_flatWidth4" value="779" /> + <property name="cvs_file_history_treeWidth5" value="171" /> + <property name="cvs_file_history_treeWidth6" value="170" /> + <property name="cvs_file_history_flatOrder4" value="4" /> + <property name="cvs_file_history_flatOrder5" value="5" /> + <property name="FileHistory.org.jetbrains.idea.svn.history.SvnHistoryProvider_treeOrder3" value="3" /> + <property name="cvs_file_history_flatOrder2" value="2" /> + <property name="FileHistory.org.jetbrains.idea.svn.history.SvnHistoryProvider_treeOrder4" value="4" /> <property name="cvs_file_history_flatOrder3" value="3" /> - <property name="cvs_file_history_flatWidth6" value="170" /> - <property name="vcs_file_view_flatOrder5" value="5" /> - <property name="vcs_file_view_treeOrder3" value="3" /> - <property name="vcs_file_view_treeWidth1" value="78" /> - <property name="cvs_file_history_flatOrder5" value="5" /> - <property name="cvs_file_history_flatWidth5" value="171" /> - <property name="cvs_file_history_treeOrder2" value="2" /> - <property name="vcs_file_view_treeOrder2" value="2" /> - <property name="cvs_file_history_treeWidth5" value="171" /> - <property name="vcs_file_view_flatWidth3" value="47" /> - <property name="cvs_file_history_flatWidth0" value="171" /> - <property name="vcs_file_view_treeOrder1" value="1" /> - <property name="cvs_file_history_treeOrder0" value="0" /> + <property name="FileHistory.org.jetbrains.idea.svn.history.SvnHistoryProvider_treeOrder1" value="1" /> + <property name="cvs_file_history_flatOrder0" value="0" /> + <property name="FileHistory.org.jetbrains.idea.svn.history.SvnHistoryProvider_treeOrder2" value="2" /> + <property name="cvs_file_history_flatOrder1" value="1" /> + <property name="FileHistory.org.jetbrains.idea.svn.history.SvnHistoryProvider_treeOrder0" value="0" /> + <property name="cvs_file_history_flatOrder6" value="6" /> </component> - <component name="ReadonlyStatusHandler"> - <option name="SHOW_DIALOG" value="true" /> + <component name="RecentsManager"> + <key name="CopyClassDialog.RECENTS_KEY"> + <recent name="org.jnode.apps.derby" /> + </key> </component> - <component name="RecentsManager" /> - <component name="RestoreUpdateTree" /> <component name="RunManager"> - <activeType name="Application" /> - <configuration selected="false" default="true" type="Remote" factoryName="Remote"> - <option name="USE_SOCKET_TRANSPORT" value="true" /> - <option name="SERVER_MODE" value="false" /> - <option name="SHMEM_ADDRESS" value="javadebug" /> - <option name="HOST" value="localhost" /> - <option name="PORT" value="5005" /> - </configuration> - <configuration selected="false" default="true" type="Application" factoryName="Application"> + <configuration default="true" type="TestNG" factoryName="TestNG" enabled="false" merge="false"> + <module name="" /> + <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> + <option name="ALTERNATIVE_JRE_PATH" /> + <option name="SUITE_NAME" /> + <option name="PACKAGE_NAME" /> <option name="MAIN_CLASS_NAME" /> + <option name="METHOD_NAME" /> + <option name="GROUP_NAME" /> + <option name="TEST_OBJECT" value="CLASS" /> <option name="VM_PARAMETERS" /> - <option name="PROGRAM_PARAMETERS" /> - <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" /> - <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> - <option name="ALTERNATIVE_JRE_PATH" /> - <module name="" /> + <option name="PARAMETERS" /> + <option name="WORKING_DIRECTORY" /> + <option name="OUTPUT_DIRECTORY" /> + <option name="ANNOTATION_TYPE" /> + <option name="ENV_VARIABLES" /> + <option name="PASS_PARENT_ENVS" value="true" /> + <option name="ADDITIONAL_CLASS_PATH" /> + <option name="TEST_SEARCH_SCOPE"> + <value defaultName="wholeProject" /> + </option> + <option name="PROPERTIES_FILE" /> + <envs /> + <properties /> + <listeners /> + <method> + <option name="Make" value="true" /> + </method> </configuration> - <configuration selected="false" default="true" type="Applet" factoryName="Applet"> + <configuration default="true" type="Applet" factoryName="Applet"> <module name="" /> <option name="MAIN_CLASS_NAME" /> <option name="HTML_FILE_NAME" /> @@ -364,21 +447,7 @@ <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> <option name="ALTERNATIVE_JRE_PATH" /> </configuration> - <configuration selected="false" default="true" type="WebLogic Instance" factoryName="Local"> - <option name="WORKING_DIRECTORY" /> - <option name="HOST" value="localhost" /> - <option name="PORT" value="7001" /> - <option name="LOCAL" value="true" /> - <option name="OPEN_IN_BROWSER" value="true" /> - <option name="OPEN_IN_BROWSER_URL" value="/" /> - <option name="COMMON_VM_ARGUMENTS" value="" /> - <option name="DOMAIN_PATH" value="" /> - <option name="USER" value="weblogic" /> - <option name="PASSWORD" value="weblogic" /> - <option name="SERVER_NAME" value="myserver" /> - <option name="DOMAIN_NAME" value="mydomain" /> - </configuration> - <configuration selected="false" default="true" type="JUnit" factoryName="JUnit"> + <configuration default="true" type="JUnit" factoryName="JUnit" enabled="false" merge="false"> <module name="" /> <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> <option name="ALTERNATIVE_JRE_PATH" /> @@ -389,11 +458,57 @@ <option name="VM_PARAMETERS" /> <option name="PARAMETERS" /> <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" /> + <option name="ENV_VARIABLES" /> + <option name="PASS_PARENT_ENVS" value="true" /> <option name="ADDITIONAL_CLASS_PATH" /> <option name="TEST_SEARCH_SCOPE"> <value defaultName="wholeProject" /> </option> + <envs /> + <method> + <option name="Make" value="true" /> + </method> </configuration> + <configuration default="true" type="Remote" factoryName="Remote"> + <option name="USE_SOCKET_TRANSPORT" value="true" /> + <option name="SERVER_MODE" value="false" /> + <option name="SHMEM_ADDRESS" value="javadebug" /> + <option name="HOST" value="localhost" /> + <option name="PORT" value="5005" /> + </configuration> + <configuration default="true" type="Application" factoryName="Application" enabled="false" merge="false"> + <option name="MAIN_CLASS_NAME" /> + <option name="VM_PARAMETERS" /> + <option name="PROGRAM_PARAMETERS" /> + <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" /> + <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> + <option name="ALTERNATIVE_JRE_PATH" /> + <option name="ENABLE_SWING_INSPECTOR" value="false" /> + <option name="ENV_VARIABLES" /> + <option name="PASS_PARENT_ENVS" value="true" /> + <module name="" /> + <envs /> + <method> + <option name="Make" value="true" /> + </method> + </configuration> + <configuration default="true" type="WebLogic Instance" factoryName="Local"> + <option name="WORKING_DIRECTORY" /> + <option name="HOST" value="localhost" /> + <option name="PORT" value="7001" /> + <option name="LOCAL" value="true" /> + <option name="OPEN_IN_BROWSER" value="true" /> + <option name="OPEN_IN_BROWSER_URL" value="/" /> + <option name="COMMON_VM_ARGUMENTS" value="" /> + <option name="DOMAIN_PATH" value="" /> + <option name="USER" value="weblogic" /> + <option name="PASSWORD" value="weblogic" /> + <option name="SERVER_NAME" value="myserver" /> + <option name="DOMAIN_NAME" value="mydomain" /> + <predefined_log_file id="WEBLOGIC_DOMAIN_LOG_FILE" enabled="true" /> + <predefined_log_file id="WEBLOGIC_SERVER_LOG_FILE" enabled="true" /> + </configuration> + <list size="0" /> </component> <component name="SQL"> <general /> @@ -404,7 +519,6 @@ <resizeColumns toHeader="true" toContent="true" /> </results> </component> - <component name="SelectInManager" /> <component name="StarteamConfiguration"> <option name="SERVER" value="" /> <option name="PORT" value="49201" /> @@ -413,8 +527,9 @@ <option name="PROJECT" value="" /> <option name="VIEW" value="" /> <option name="ALTERNATIVE_WORKING_PATH" value="" /> + <option name="LOCK_ON_CHECKOUT" value="false" /> + <option name="UNLOCK_ON_CHECKIN" value="false" /> </component> - <component name="StructuralSearchPlugin" /> <component name="StructureViewFactory"> <option name="AUTOSCROLL_MODE" value="true" /> <option name="AUTOSCROLL_FROM_SOURCE" value="false" /> @@ -430,7 +545,10 @@ <component name="SvnConfiguration"> <option name="USER" value="" /> <option name="PASSWORD" value="" /> - <option name="PROCESS_UNRESOLVED" value="false" /> + <option name="LAST_MERGED_REVISION" /> + <option name="UPDATE_RUN_STATUS" value="false" /> + <option name="UPDATE_RECURSIVELY" value="true" /> + <option name="MERGE_DRY_RUN" value="false" /> <configuration useDefault="false">C:\Documents and Settings\mh\Application Data\Subversion</configuration> </component> <component name="TodoView" selected-index="0"> @@ -446,37 +564,50 @@ <flatten-packages value="false" /> <is-autoscroll-to-source value="true" /> </todo-panel> + <todo-panel id="default-changelist"> + <are-packages-shown value="false" /> + <are-modules-shown value="false" /> + <flatten-packages value="false" /> + <is-autoscroll-to-source value="false" /> + </todo-panel> </component> <component name="ToolWindowManager"> - <frame x="1280" y="95" width="1278" height="764" extended-state="0" /> + <frame x="4" y="5" width="1260" height="989" extended-state="0" /> <editor active="false" /> <layout> - <window_info id="CVS" active="false" anchor="bottom" auto_hide="false" internal_type="docked" type="docked" visible="false" weight="0.3291536" order="8" /> - <window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="docked" type="docked" visible="false" weight="0.33" order="7" /> - <window_info id="Project" active="true" anchor="left" auto_hide="false" internal_type="docked" type="docked" visible="true" weight="0.33523655" order="0" /> - <window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="docked" type="docked" visible="false" weight="0.33" order="1" /> - <window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="docked" type="docked" visible="false" weight="0.17752443" order="1" /> - <window_info id="Messages" active="false" anchor="bottom" auto_hide="false" internal_type="docked" type="docked" visible="false" weight="0.32970452" order="8" /> - <window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="docked" type="docked" visible="false" weight="0.4" order="6" /> - <window_info id="Module Dependencies" active="false" anchor="right" auto_hide="false" internal_type="docked" type="docked" visible="false" weight="0.33" order="-1" /> - <window_info id="Dependency Viewer" active="false" anchor="bottom" auto_hide="false" internal_type="docked" type="docked" visible="false" weight="0.33" order="8" /> - <window_info id="Favorites" active="false" anchor="right" auto_hide="false" internal_type="docked" type="docked" visible="false" weight="0.33" order="-1" /> - <window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="docked" type="docked" visible="true" weight="0.32952693" order="1" /> - <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="docked" type="docked" visible="false" weight="0.33" order="2" /> - <window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="docked" type="docked" visible="false" weight="0.25" order="2" /> - <window_info id="File View" active="false" anchor="right" auto_hide="false" internal_type="docked" type="docked" visible="false" weight="0.33" order="-1" /> - <window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="docked" type="docked" visible="false" weight="0.4" order="4" /> - <window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="sliding" type="sliding" visible="false" weight="0.4" order="0" /> - <window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="docked" type="docked" visible="false" weight="0.33" order="-1" /> - <window_info id="Web" active="false" anchor="left" auto_hide="false" internal_type="docked" type="docked" visible="false" weight="0.25" order="2" /> - <window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="docked" type="docked" visible="false" weight="0.33" order="0" /> - <window_info id="EJB" active="false" anchor="bottom" auto_hide="false" internal_type="docked" type="docked" visible="false" weight="0.25" order="3" /> - <window_info id="Sequence" active="false" anchor="bottom" auto_hide="false" internal_type="docked" type="docked" visible="false" weight="0.33" order="8" /> - <window_info id="IDE talk" active="false" anchor="right" auto_hide="false" internal_type="docked" type="docked" visible="false" weight="0.33" order="3" /> - <window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="docked" type="docked" visible="false" weight="0.25" order="5" /> - <window_info id="CVS File View" active="false" anchor="right" auto_hide="false" internal_type="docked" type="docked" visible="false" weight="0.32980457" order="3" /> - <window_info id="simpleUML" active="false" anchor="left" auto_hide="false" internal_type="docked" type="docked" visible="false" weight="0.32927817" order="3" /> - <window_info id="IDEtalk Messages" active="false" anchor="bottom" auto_hide="false" internal_type="docked" type="docked" visible="false" weight="0.33" order="8" /> + <window_info id="UI Designer" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" order="3" /> + <window_info id="Changes" active="true" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.31942788" order="8" /> + <window_info id="Palette" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" order="10" /> + <window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.21161826" order="1" /> + <window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32894737" order="1" /> + <window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" order="4" /> + <window_info id="IDEtalk Messages" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" order="16" /> + <window_info id="IDEtalk" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" order="3" /> + <window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32777116" order="9" /> + <window_info id="Messages" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32777116" order="10" /> + <window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" order="7" /> + <window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.17676349" order="1" /> + <window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" order="0" /> + <window_info id="Maven projects" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" order="4" /> + <window_info id="Module Dependencies" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" order="9" /> + <window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.19585063" order="0" /> + <window_info id="Dependency Viewer" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" order="13" /> + <window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" order="2" /> + <window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" order="6" /> + <window_info id="Duplicates" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" order="15" /> + <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" order="2" /> + <window_info id="IDE talk" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" order="5" /> + <window_info id="simpleUML" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32927817" order="3" /> + <window_info id="File View" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" order="6" /> + <window_info id="Sequence" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" order="11" /> + <window_info id="CVS File View" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32980457" order="7" /> + <window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" order="5" /> + <window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" order="0" /> + <window_info id="IntelliJad Console" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.32894737" order="12" /> + <window_info id="Favorites" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" order="8" /> + <window_info id="Web" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" order="2" /> + <window_info id="EJB" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" order="3" /> + <window_info id="CVS" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.3291536" order="14" /> </layout> </component> <component name="VCS.FileViewConfiguration"> @@ -487,30 +618,45 @@ <option name="SHOW_FILE_HISTORY_AS_TREE" value="false" /> </component> <component name="VcsManagerConfiguration"> + <option name="OFFER_MOVE_TO_ANOTHER_CHANGELIST_ON_PARTIAL_COMMIT" value="true" /> <option name="CHECK_CODE_SMELLS_BEFORE_PROJECT_COMMIT" value="true" /> - <option name="PUT_FOCUS_INTO_COMMENT" value="false" /> + <option name="PERFORM_UPDATE_IN_BACKGROUND" value="false" /> + <option name="PERFORM_COMMIT_IN_BACKGROUND" value="false" /> + <option name="PERFORM_EDIT_IN_BACKGROUND" value="true" /> + <option name="PERFORM_ADD_REMOVE_IN_BACKGROUND" value="true" /> <option name="FORCE_NON_EMPTY_COMMENT" value="false" /> - <option name="LAST_COMMIT_MESSAGE" /> - <option name="SAVE_LAST_COMMIT_MESSAGE" value="true" /> - <option name="CHECKIN_DIALOG_SPLITTER_PROPORTION" value="0.8" /> + <option name="LAST_COMMIT_MESSAGE" value="increased heap" /> <option name="OPTIMIZE_IMPORTS_BEFORE_PROJECT_COMMIT" value="false" /> - <option name="OPTIMIZE_IMPORTS_BEFORE_FILE_COMMIT" value="false" /> <option name="REFORMAT_BEFORE_PROJECT_COMMIT" value="false" /> <option name="REFORMAT_BEFORE_FILE_COMMIT" value="false" /> <option name="FILE_HISTORY_DIALOG_COMMENTS_SPLITTER_PROPORTION" value="0.8" /> <option name="FILE_HISTORY_DIALOG_SPLITTER_PROPORT... [truncated message content] |
From: <fd...@us...> - 2008-03-10 21:35:22
|
Revision: 3828 http://jnode.svn.sourceforge.net/jnode/?rev=3828&view=rev Author: fduminy Date: 2008-03-10 14:35:17 -0700 (Mon, 10 Mar 2008) Log Message: ----------- fixed wrong display of memory between JIFS & GcCommand : now display the same (truncated) value with 2 significant digits after the decimal separator. ex : 2.04 GB Modified Paths: -------------- trunk/core/src/core/org/jnode/util/BinaryPrefix.java trunk/core/src/core/org/jnode/util/DecimalPrefix.java trunk/core/src/core/org/jnode/util/NumberUtils.java trunk/fs/src/fs/org/jnode/fs/jifs/files/JIFSFmemory.java Modified: trunk/core/src/core/org/jnode/util/BinaryPrefix.java =================================================================== --- trunk/core/src/core/org/jnode/util/BinaryPrefix.java 2008-03-08 10:16:45 UTC (rev 3827) +++ trunk/core/src/core/org/jnode/util/BinaryPrefix.java 2008-03-10 21:35:17 UTC (rev 3828) @@ -46,17 +46,23 @@ /** * Convert the given value to a size string like 64K - * @param v the size to convert - * @return the text for of the size + * @param value the size to convert + * @param nbDecimals number of significant figures to display after dot. use Integer.MAX_VALUE for all. + * @return the text for the size */ - public static String apply(long v) { - for (BinaryPrefix unit : values()) { + public static String apply(final long value, final int nbDecimals) { + long v = value; + BinaryPrefix unit = null; + for (BinaryPrefix u : values()) { if ((v < 1024) && (v >= 0)) { - return String.valueOf(v) + unit.getUnit(); + unit = u; + break; } v = v >>> 10; } - return String.valueOf(v >>> 10) + MAX.getUnit(); + unit = (unit == null) ? MAX : unit; + float dv = ((float) value) / unit.getMultiplier(); + return NumberUtils.toString(dv, nbDecimals) + " " + unit.getUnit(); } } Modified: trunk/core/src/core/org/jnode/util/DecimalPrefix.java =================================================================== --- trunk/core/src/core/org/jnode/util/DecimalPrefix.java 2008-03-08 10:16:45 UTC (rev 3827) +++ trunk/core/src/core/org/jnode/util/DecimalPrefix.java 2008-03-10 21:35:17 UTC (rev 3828) @@ -16,8 +16,8 @@ E(1000l*1000l*1000l*1000l*1000l*1000l, "E"); //these units have too big multipliers to fit in a long // (aka they are greater than 2^64) : - //Z(1024l*1024l*1024l*1024l*1024l*1024l*1024l, "Z"), - //Y(1024l*1024l*1024l*1024l*1024l*1024l*1024l*1024l, "Y"); + //Z(1000l*1000l*1000l*1000l*1000l*1000l*1000l, "Z"), + //Y(1000l*1000l*1000l*1000l*1000l*1000l*1000l*1000l, "Y"); public static final DecimalPrefix MIN = B; public static final DecimalPrefix MAX = E; @@ -47,16 +47,22 @@ /** * Convert the given value to a size string like 64K * @param v the size to convert - * @return the text for of the size + * @param nbDecimals number of significant figures to display after dot. use Integer.MAX_VALUE for all. + * @return the text for the size */ - public static String apply(long v) { - for (DecimalPrefix unit : values()) { + public static String apply(final long value, final int nbDecimals) { + long v = value; + DecimalPrefix unit = null; + for (DecimalPrefix u : values()) { if ((v < 1000l) && (v >= 0l)) { - return String.valueOf(v) + unit.getUnit(); - } + unit = u; + break; + } v = v / 1000l; } - return String.valueOf(v / 1000l) + MAX.getUnit(); + unit = (unit == null) ? MAX : unit; + float dv = ((float) value) / unit.getMultiplier(); + return NumberUtils.toString(dv, nbDecimals) + " " + unit.getUnit(); } } Modified: trunk/core/src/core/org/jnode/util/NumberUtils.java =================================================================== --- trunk/core/src/core/org/jnode/util/NumberUtils.java 2008-03-08 10:16:45 UTC (rev 3827) +++ trunk/core/src/core/org/jnode/util/NumberUtils.java 2008-03-10 21:35:17 UTC (rev 3828) @@ -230,16 +230,36 @@ * @return the text for of the size */ public static String toDecimalByte(long v) { - return DecimalPrefix.apply(v) + "B"; + return toDecimalByte(v, 2); } /** * Convert the given value to a size string like 64K * @param v the size to convert + * @param nbDecimals number of significant figures to display after dot. use Integer.MAX_VALUE for all * @return the text for of the size */ + public static String toDecimalByte(long v, int nbDecimals) { + return DecimalPrefix.apply(v, nbDecimals) + "B"; + } + + /** + * Convert the given value to a size string like 64K + * @param v the size to convert + * @param nbDecimals number of significant figures to display after dot. use Integer.MAX_VALUE for all + * @return the text for of the size + */ + public static String toBinaryByte(long v, int nbDecimals) { + return BinaryPrefix.apply(v, nbDecimals) + "B"; + } + + /** + * Convert the given value to a size string like 64K + * @param v the size to convert + * @return the text for of the size + */ public static String toBinaryByte(long v) { - return BinaryPrefix.apply(v) + "B"; + return toBinaryByte(v, 2); } Modified: trunk/fs/src/fs/org/jnode/fs/jifs/files/JIFSFmemory.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/jifs/files/JIFSFmemory.java 2008-03-08 10:16:45 UTC (rev 3827) +++ trunk/fs/src/fs/org/jnode/fs/jifs/files/JIFSFmemory.java 2008-03-10 21:35:17 UTC (rev 3828) @@ -23,6 +23,7 @@ import org.jnode.fs.FSDirectory; import org.jnode.fs.jifs.JIFSFile; +import org.jnode.util.NumberUtils; /** * File, which contains information about memory usage. @@ -43,9 +44,9 @@ public void refresh(){ super.refresh(); final Runtime rt = Runtime.getRuntime(); - addStringln("Memory size: \n\t" + rt.totalMemory()); - addStringln("Used memory: \n\t" + (rt.totalMemory()-rt.freeMemory())); - addStringln("Free memory: \n\t" + rt.freeMemory()); + addStringln("Memory size: \n\t" + NumberUtils.toBinaryByte(rt.totalMemory())); + addStringln("Used memory: \n\t" + NumberUtils.toBinaryByte((rt.totalMemory()-rt.freeMemory()))); + addStringln("Free memory: \n\t" + NumberUtils.toBinaryByte(rt.freeMemory())); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cr...@us...> - 2008-03-16 13:55:06
|
Revision: 3844 http://jnode.svn.sourceforge.net/jnode/?rev=3844&view=rev Author: crawley Date: 2008-03-16 06:55:01 -0700 (Sun, 16 Mar 2008) Log Message: ----------- Changes to add / integrate the new-style command syntax system. Modified Paths: -------------- trunk/all/conf/default-plugin-list.xml trunk/all/conf/shell-plugin-list.xml trunk/shell/.classpath trunk/shell/descriptors/org.jnode.shell.command.xml trunk/shell/descriptors/org.jnode.shell.help.xml trunk/shell/descriptors/org.jnode.shell.xml trunk/shell/src/shell/org/jnode/shell/AbstractCommand.java trunk/shell/src/shell/org/jnode/shell/AsyncCommandInvoker.java trunk/shell/src/shell/org/jnode/shell/Command.java trunk/shell/src/shell/org/jnode/shell/CommandInfo.java trunk/shell/src/shell/org/jnode/shell/CommandInvoker.java trunk/shell/src/shell/org/jnode/shell/CommandLine.java trunk/shell/src/shell/org/jnode/shell/CommandShell.java trunk/shell/src/shell/org/jnode/shell/DefaultCommandInvoker.java trunk/shell/src/shell/org/jnode/shell/DefaultInterpreter.java trunk/shell/src/shell/org/jnode/shell/NoTokensAvailableException.java trunk/shell/src/shell/org/jnode/shell/ProcletCommandInvoker.java trunk/shell/src/shell/org/jnode/shell/RedirectingInterpreter.java trunk/shell/src/shell/org/jnode/shell/Shell.java trunk/shell/src/shell/org/jnode/shell/ShellUtils.java trunk/shell/src/shell/org/jnode/shell/ThreadCommandInvoker.java trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneContext.java trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneInterpreter.java trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneToken.java trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneTokenizer.java trunk/shell/src/shell/org/jnode/shell/command/HelpCommand.java trunk/shell/src/shell/org/jnode/shell/command/SetCommand.java trunk/shell/src/shell/org/jnode/shell/def/ShellPlugin.java trunk/shell/src/shell/org/jnode/shell/help/Argument.java trunk/shell/src/shell/org/jnode/shell/help/Help.java trunk/shell/src/shell/org/jnode/shell/help/def/DefaultHelp.java Added Paths: ----------- trunk/shell/descriptors/org.jnode.shell.syntax.xml trunk/shell/src/shell/org/jnode/shell/SymbolSource.java trunk/shell/src/shell/org/jnode/shell/syntax/ trunk/shell/src/shell/org/jnode/shell/syntax/AliasArgument.java trunk/shell/src/shell/org/jnode/shell/syntax/AlternativesSyntax.java trunk/shell/src/shell/org/jnode/shell/syntax/Argument.java trunk/shell/src/shell/org/jnode/shell/syntax/ArgumentBundle.java trunk/shell/src/shell/org/jnode/shell/syntax/ArgumentSyntax.java trunk/shell/src/shell/org/jnode/shell/syntax/CommandSyntaxException.java trunk/shell/src/shell/org/jnode/shell/syntax/DefaultSyntaxManager.java trunk/shell/src/shell/org/jnode/shell/syntax/EnumArgument.java trunk/shell/src/shell/org/jnode/shell/syntax/FileArgument.java trunk/shell/src/shell/org/jnode/shell/syntax/FlagArgument.java trunk/shell/src/shell/org/jnode/shell/syntax/GroupSyntax.java trunk/shell/src/shell/org/jnode/shell/syntax/IntegerArgument.java trunk/shell/src/shell/org/jnode/shell/syntax/MuAlternation.java trunk/shell/src/shell/org/jnode/shell/syntax/MuArgument.java trunk/shell/src/shell/org/jnode/shell/syntax/MuBackReference.java trunk/shell/src/shell/org/jnode/shell/syntax/MuParser.java trunk/shell/src/shell/org/jnode/shell/syntax/MuPreset.java trunk/shell/src/shell/org/jnode/shell/syntax/MuSequence.java trunk/shell/src/shell/org/jnode/shell/syntax/MuSymbol.java trunk/shell/src/shell/org/jnode/shell/syntax/MuSyntax.java trunk/shell/src/shell/org/jnode/shell/syntax/OptionSetSyntax.java trunk/shell/src/shell/org/jnode/shell/syntax/OptionSyntax.java trunk/shell/src/shell/org/jnode/shell/syntax/PowersetSyntax.java trunk/shell/src/shell/org/jnode/shell/syntax/PropertyNameArgument.java trunk/shell/src/shell/org/jnode/shell/syntax/RepeatSyntax.java trunk/shell/src/shell/org/jnode/shell/syntax/SequenceSyntax.java trunk/shell/src/shell/org/jnode/shell/syntax/SharedStack.java trunk/shell/src/shell/org/jnode/shell/syntax/StringArgument.java trunk/shell/src/shell/org/jnode/shell/syntax/Syntax.java trunk/shell/src/shell/org/jnode/shell/syntax/SyntaxArgumentMissingException.java trunk/shell/src/shell/org/jnode/shell/syntax/SyntaxFailureException.java trunk/shell/src/shell/org/jnode/shell/syntax/SyntaxManager.java trunk/shell/src/shell/org/jnode/shell/syntax/SyntaxMultiplicityException.java trunk/shell/src/shell/org/jnode/shell/syntax/SystemSyntaxPlugin.java trunk/shell/src/shell/org/jnode/shell/syntax/TokenSyntax.java trunk/shell/src/test/ trunk/shell/src/test/org/ trunk/shell/src/test/org/jnode/ trunk/shell/src/test/org/jnode/test/ trunk/shell/src/test/org/jnode/test/shell/ trunk/shell/src/test/org/jnode/test/shell/syntax/ trunk/shell/src/test/org/jnode/test/shell/syntax/AllTests.java trunk/shell/src/test/org/jnode/test/shell/syntax/AlternativesSyntaxTest.java trunk/shell/src/test/org/jnode/test/shell/syntax/ArgumentBundleTest.java trunk/shell/src/test/org/jnode/test/shell/syntax/ArgumentMultiplicityTest.java trunk/shell/src/test/org/jnode/test/shell/syntax/ArgumentTypesTest.java trunk/shell/src/test/org/jnode/test/shell/syntax/CommandLineTest.java trunk/shell/src/test/org/jnode/test/shell/syntax/DefaultTokenizerTest.java trunk/shell/src/test/org/jnode/test/shell/syntax/MuParserTest.java trunk/shell/src/test/org/jnode/test/shell/syntax/MuParserTest2.java trunk/shell/src/test/org/jnode/test/shell/syntax/MuSyntaxTest.java trunk/shell/src/test/org/jnode/test/shell/syntax/OptionSetSyntaxTest.java trunk/shell/src/test/org/jnode/test/shell/syntax/OptionSyntaxTest.java trunk/shell/src/test/org/jnode/test/shell/syntax/PowersetSyntaxTest.java trunk/shell/src/test/org/jnode/test/shell/syntax/RepeatedSyntaxTest.java trunk/shell/src/test/org/jnode/test/shell/syntax/SequenceSyntaxTest.java trunk/shell/src/test/org/jnode/test/shell/syntax/TestAliasManager.java trunk/shell/src/test/org/jnode/test/shell/syntax/TestShell.java trunk/shell/src/test/org/jnode/test/shell/syntax/TestSyntaxManager.java Modified: trunk/all/conf/default-plugin-list.xml =================================================================== --- trunk/all/conf/default-plugin-list.xml 2008-03-16 05:47:04 UTC (rev 3843) +++ trunk/all/conf/default-plugin-list.xml 2008-03-16 13:55:01 UTC (rev 3844) @@ -154,6 +154,7 @@ <plugin id="org.jnode.shell"/> <plugin id="org.jnode.shell.help"/> + <plugin id="org.jnode.shell.syntax"/> <plugin id="org.jnode.shell.command"/> <plugin id="org.jnode.shell.command.bsh"/> <plugin id="org.jnode.shell.command.debug"/> Modified: trunk/all/conf/shell-plugin-list.xml =================================================================== --- trunk/all/conf/shell-plugin-list.xml 2008-03-16 05:47:04 UTC (rev 3843) +++ trunk/all/conf/shell-plugin-list.xml 2008-03-16 13:55:01 UTC (rev 3844) @@ -28,4 +28,5 @@ <plugin id="org.jnode.shell"/> <plugin id="org.jnode.shell.command"/> <plugin id="org.jnode.shell.help"/> + <plugin id="org.jnode.shell.syntax"/> </plugin-list> Modified: trunk/shell/.classpath =================================================================== --- trunk/shell/.classpath 2008-03-16 05:47:04 UTC (rev 3843) +++ trunk/shell/.classpath 2008-03-16 13:55:01 UTC (rev 3844) @@ -1,6 +1,7 @@ <?xml version="1.0" encoding="UTF-8"?> <classpath> <classpathentry kind="src" path="src/shell"/> + <classpathentry kind="src" path="src/test"/> <classpathentry kind="src" path="/JNode-Core"/> <classpathentry kind="lib" path="/JNode-Core/lib/log4j-1.2.8.jar"/> <classpathentry kind="lib" path="/JNode-Core/lib/junit.jar"/> Modified: trunk/shell/descriptors/org.jnode.shell.command.xml =================================================================== --- trunk/shell/descriptors/org.jnode.shell.command.xml 2008-03-16 05:47:04 UTC (rev 3843) +++ trunk/shell/descriptors/org.jnode.shell.command.xml 2008-03-16 13:55:01 UTC (rev 3844) @@ -46,6 +46,15 @@ <alias name="onheap" class="org.jnode.shell.command.OnHeapCommand"/> <alias name="grep" class="org.jnode.shell.command.GrepCommand"/> </extension> + + <extension point="org.jnode.shell.syntaxes"> + <syntax alias="set"> + <sequence> + <argument argLabel="key"/> + <argument argLabel="value"/> + </sequence> + </syntax> + </extension> <extension point="org.jnode.security.permissions"> <permission class="java.util.PropertyPermission" name="*" actions="read,write"/> Modified: trunk/shell/descriptors/org.jnode.shell.help.xml =================================================================== --- trunk/shell/descriptors/org.jnode.shell.help.xml 2008-03-16 05:47:04 UTC (rev 3843) +++ trunk/shell/descriptors/org.jnode.shell.help.xml 2008-03-16 13:55:01 UTC (rev 3844) @@ -10,6 +10,7 @@ <requires> <import plugin="org.jnode.shell"/> + <import plugin="org.jnode.shell.syntax"/> </requires> <extension point="org.jnode.security.permissions"> Added: trunk/shell/descriptors/org.jnode.shell.syntax.xml =================================================================== --- trunk/shell/descriptors/org.jnode.shell.syntax.xml (rev 0) +++ trunk/shell/descriptors/org.jnode.shell.syntax.xml 2008-03-16 13:55:01 UTC (rev 3844) @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plugin SYSTEM "jnode.dtd"> + +<plugin id="org.jnode.shell.syntax" + name="JNode Command Syntax System" + version="@VERSION@" + provider-name="JNode.org" + license-name="lgpl" + class="org.jnode.shell.syntax.SystemSyntaxPlugin"> + + <requires> + <import plugin="org.jnode.shell"/> + </requires> + + <extension point="org.jnode.security.permissions"> + <permission class="java.io.FilePermission" name="<<ALL FILES>>" actions="read"/> + </extension> + +</plugin> Modified: trunk/shell/descriptors/org.jnode.shell.xml =================================================================== --- trunk/shell/descriptors/org.jnode.shell.xml 2008-03-16 05:47:04 UTC (rev 3843) +++ trunk/shell/descriptors/org.jnode.shell.xml 2008-03-16 13:55:01 UTC (rev 3844) @@ -24,10 +24,13 @@ <export name="org.jnode.shell.help.argument.*"/> <export name="org.jnode.shell.help.def.*"/> <export name="org.jnode.shell.proclet.*"/> + <export name="org.jnode.shell.syntax.*"/> </library> </runtime> <extension-point id="aliases" name="System shell aliases"/> + + <extension-point id="syntaxes" name="System command syntaxes"/> <extension point="org.jnode.security.permissions"> <permission class="java.io.FilePermission" name="<<ALL FILES>>" actions="read,write"/> Modified: trunk/shell/src/shell/org/jnode/shell/AbstractCommand.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/AbstractCommand.java 2008-03-16 05:47:04 UTC (rev 3843) +++ trunk/shell/src/shell/org/jnode/shell/AbstractCommand.java 2008-03-16 13:55:01 UTC (rev 3844) @@ -1,5 +1,28 @@ +/* + * $Id: Command.java 3772 2008-02-10 15:02:53Z lsantha $ + * + * JNode.org + * Copyright (C) 2007-2008 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.shell; +import org.jnode.shell.syntax.Argument; +import org.jnode.shell.syntax.ArgumentBundle; import org.jnode.vm.VmExit; /** @@ -9,7 +32,17 @@ * */ public abstract class AbstractCommand implements Command { + + private ArgumentBundle bundle; + + public AbstractCommand() { + this.bundle = null; + } + public AbstractCommand(String description) { + this.bundle = new ArgumentBundle(description); + } + @SuppressWarnings("deprecation") public final void execute(String[] args) throws Exception { execute(new CommandLine(args), System.in, System.out, System.err); @@ -23,4 +56,17 @@ protected void exit(int rc) { throw new VmExit(rc); } + + public final ArgumentBundle getArgumentBundle() { + return bundle; + } + + protected final void registerArguments(Argument<?> ... args) { + if (bundle == null) { + bundle = new ArgumentBundle(); + } + for (Argument<?> arg : args) { + bundle.addArgument(arg); + } + } } Modified: trunk/shell/src/shell/org/jnode/shell/AsyncCommandInvoker.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/AsyncCommandInvoker.java 2008-03-16 05:47:04 UTC (rev 3843) +++ trunk/shell/src/shell/org/jnode/shell/AsyncCommandInvoker.java 2008-03-16 13:55:01 UTC (rev 3844) @@ -77,22 +77,26 @@ // ctrl-c } - public int invoke(CommandLine cmdLine) throws ShellException { + public int invoke(CommandLine cmdLine, Command command) throws ShellException { + // FIXME -- we already did this ... CommandInfo cmdInfo = lookupCommand(cmdLine); if (cmdInfo == null) { return 0; } - CommandRunner cr = setup(cmdLine, cmdInfo); + CommandRunner cr = setup(cmdLine, command, cmdInfo); return runIt(cmdLine, cmdInfo, cr); } - public CommandThread invokeAsynchronous(CommandLine cmdLine) + public CommandThread invokeAsynchronous(CommandLine cmdLine, Command command) throws ShellException { - CommandInfo cmdInfo = lookupCommand(cmdLine); - if (cmdInfo == null) { - return null; + CommandInfo cmdInfo = null; + if (command == null) { + cmdInfo = lookupCommand(cmdLine); + if (cmdInfo == null) { + return null; + } } - CommandRunner cr = setup(cmdLine, cmdInfo); + CommandRunner cr = setup(cmdLine, command, cmdInfo); return forkIt(cmdLine, cmdInfo, cr); } @@ -110,7 +114,7 @@ } } - private CommandRunner setup(CommandLine cmdLine, CommandInfo cmdInfo) + private CommandRunner setup(CommandLine cmdLine, Command command, CommandInfo cmdInfo) throws ShellException { Method method; CommandRunner cr = null; @@ -125,17 +129,10 @@ } catch (ClassCastException ex) { throw new ShellFailureException("streams array broken", ex); } - try { - method = cmdInfo.getCommandClass().getMethod(EXECUTE_METHOD, - EXECUTE_ARG_TYPES); - if ((method.getModifiers() & Modifier.STATIC) == 0) { - cr = createRunner(cmdInfo.getCommandClass(), method, - new Object[] { cmdLine, in, out, err }, in, out, err); - } - } catch (NoSuchMethodException e) { - // continue; + if (command != null) { + cr = createRunner(command, cmdLine, in, out, err); } - if (cr == null) { + else { try { method = cmdInfo.getCommandClass().getMethod(MAIN_METHOD, MAIN_ARG_TYPES); @@ -149,19 +146,20 @@ + " does not allow redirection or pipelining"); } cr = createRunner(cmdInfo.getCommandClass(), method, - new Object[] { cmdLine.getArguments() }, in, out, - err); + new Object[] { cmdLine.getArguments() }, + in, out, err); } } catch (NoSuchMethodException e) { // continue; } + if (cr == null) { + throw new ShellInvocationException( + "No suitable entry point method for " + + cmdInfo.getCommandClass()); + } } - if (cr == null) { - throw new ShellInvocationException( - "No suitable entry point method for " - + cmdInfo.getCommandClass()); - } - // THese are now the real streams ... + + // These are now the real streams ... cmdLine.setStreams(new Closeable[] { in, out, err }); return cr; } @@ -178,11 +176,13 @@ throw new ShellInvocationException( "Exception while creating command thread", ex); } - + // FIXME this method for waiting for the command to finish is + // really lame ... and theoretically incorrect. We should + // wait / notify. this.blocking = true; this.blockingThread = Thread.currentThread(); this.cmdName = cmdLine.getCommandName(); - + threadProcess.start(); while (this.blocking) { @@ -274,8 +274,10 @@ public void keyReleased(KeyboardEvent event) { } + + abstract CommandRunner createRunner(Class<?> cx, Method method, Object[] args, + InputStream in, PrintStream out, PrintStream err); - abstract CommandRunner createRunner(Class<?> cx, Method method, - Object[] args, InputStream commandIn, PrintStream commandOut, - PrintStream commandErr); + abstract CommandRunner createRunner(Command command, CommandLine cmdLine, + InputStream in, PrintStream out, PrintStream err); } Modified: trunk/shell/src/shell/org/jnode/shell/Command.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/Command.java 2008-03-16 05:47:04 UTC (rev 3843) +++ trunk/shell/src/shell/org/jnode/shell/Command.java 2008-03-16 13:55:01 UTC (rev 3844) @@ -24,8 +24,11 @@ import java.io.InputStream; import java.io.PrintStream; +import org.jnode.shell.syntax.ArgumentBundle; + /** * @author Martin Husted Hartvig (ha...@jn...) + * @author cr...@jn... */ public interface Command { @@ -43,4 +46,6 @@ */ public void execute(CommandLine commandLine, InputStream in, PrintStream out, PrintStream err) throws Exception; + + public ArgumentBundle getArgumentBundle(); } Modified: trunk/shell/src/shell/org/jnode/shell/CommandInfo.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/CommandInfo.java 2008-03-16 05:47:04 UTC (rev 3843) +++ trunk/shell/src/shell/org/jnode/shell/CommandInfo.java 2008-03-16 13:55:01 UTC (rev 3844) @@ -42,4 +42,13 @@ public final boolean isInternal() { return internal; } + + public final Command createCommandInstance() throws InstantiationException, IllegalAccessException { + if (Command.class.isAssignableFrom(clazz)) { + return (Command) (clazz.newInstance()); + } + else { + return null; + } + } } Modified: trunk/shell/src/shell/org/jnode/shell/CommandInvoker.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/CommandInvoker.java 2008-03-16 05:47:04 UTC (rev 3843) +++ trunk/shell/src/shell/org/jnode/shell/CommandInvoker.java 2008-03-16 13:55:01 UTC (rev 3844) @@ -45,11 +45,13 @@ * * @param commandLine this provides the command name (alias), the command * arguments and (where relevant) the command's i/o stream context. + * @param command the command instance to which arguments have previously + * been bound, or <code>null</null> * @return an integer return code, with zero indicating command success, * non-zero indicating command failure. * @throws ShellException if there was some problem launching the command. */ - int invoke(CommandLine commandLine) throws ShellException; + int invoke(CommandLine commandLine, Command command) throws ShellException; /** * Create a thread for running a command asynchronously. This can be used @@ -57,12 +59,14 @@ * * @param commandLine this provides the command name (alias), the command * arguments and (where relevant) the command's i/o stream context. + * @param command the command object that we bound arguments to, or + * <code>null</code> * @return the thread for the command. Calling * {@link java.lang.Thread.start()} will cause the command to * execute. * @throws ShellException if there was some problem launching the command. */ - CommandThread invokeAsynchronous(CommandLine commandLine) + CommandThread invokeAsynchronous(CommandLine commandLine, Command command) throws ShellException; /** Modified: trunk/shell/src/shell/org/jnode/shell/CommandLine.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/CommandLine.java 2008-03-16 05:47:04 UTC (rev 3843) +++ trunk/shell/src/shell/org/jnode/shell/CommandLine.java 2008-03-16 13:55:01 UTC (rev 3844) @@ -22,24 +22,32 @@ package org.jnode.shell; import java.io.Closeable; -import java.util.Iterator; +import java.util.Collections; +import java.util.List; import java.util.NoSuchElementException; +import org.apache.log4j.Logger; import org.jnode.driver.console.CompletionInfo; -import org.jnode.shell.help.Argument; import org.jnode.shell.help.CompletionException; import org.jnode.shell.help.Help; import org.jnode.shell.help.HelpException; import org.jnode.shell.help.Parameter; -import org.jnode.shell.help.argument.AliasArgument; -import org.jnode.shell.help.argument.FileArgument; +import org.jnode.shell.syntax.CommandSyntaxException; +import org.jnode.shell.syntax.AliasArgument; +import org.jnode.shell.syntax.FileArgument; +import org.jnode.shell.syntax.ArgumentBundle; +import org.jnode.shell.syntax.ArgumentSyntax; +import org.jnode.shell.syntax.RepeatSyntax; +import org.jnode.shell.syntax.Syntax; + /** * This class represents the command line as command name and a sequence of * argument strings. It also can carry the i/o stream environment for launching * the command. * - * TODO This class needs to be "syntax agnostic". + * TODO This class needs to be fully "shell and command syntax agnostic". + * TODO Get rid of API methods using a String argument representation. * * @author cr...@jn... */ @@ -93,17 +101,22 @@ private static final Token[] NO_TOKENS = new Token[0]; private final Help.Info defaultParameter = new Help.Info("file", - "default parameter for command line completion", new Parameter( - new FileArgument("file", "a file", Argument.MULTI), - Parameter.OPTIONAL)); + "default parameter for command line completion", + new Parameter( + new org.jnode.shell.help.argument.FileArgument( + "file", "a file", org.jnode.shell.help.Argument.MULTI), + org.jnode.shell.help.Parameter.OPTIONAL)); - private final Argument defaultArg = new AliasArgument("command", + private final org.jnode.shell.help.Argument defaultArg = + new org.jnode.shell.help.argument.AliasArgument("command", "the command to be called"); + + private final Syntax defaultSyntax = new RepeatSyntax(new ArgumentSyntax("argument")); + private final ArgumentBundle defaultArguments = new ArgumentBundle( + new FileArgument("argument", org.jnode.shell.syntax.Argument.MULTIPLE)); - private final String commandName; private final Token commandToken; - private final String[] arguments; private final Token[] argumentTokens; private Closeable[] streams; @@ -120,10 +133,8 @@ public CommandLine(Token commandToken, Token[] argumentTokens, Closeable[] streams) { this.commandToken = commandToken; - this.commandName = (commandToken == null) ? null : commandToken.token; this.argumentTokens = (argumentTokens == null || argumentTokens.length == 0) ? NO_TOKENS : argumentTokens.clone(); - this.arguments = prepareArguments(this.argumentTokens); this.streams = setupStreams(streams); } @@ -140,11 +151,17 @@ */ public CommandLine(String commandName, String[] arguments, Closeable[] streams) { - this.commandName = commandName; - this.arguments = (arguments == null || arguments.length == 0) ? NO_ARGS - : arguments.clone(); - this.commandToken = null; - this.argumentTokens = null; + this.commandToken = commandName == null ? null : new Token(commandName); + if (arguments == null || arguments.length == 0) { + this.argumentTokens = NO_TOKENS; + } + else { + int len = arguments.length; + argumentTokens = new Token[len]; + for (int i = 0; i < len; i++) { + this.argumentTokens[i] = new Token(arguments[i]); + } + } this.streams = setupStreams(streams); } @@ -166,7 +183,7 @@ * @deprecated It is a bad idea to leave out the command name. */ public CommandLine(String[] arguments) { - this(null, arguments, null); + this(null, arguments, null /* FIXME */); } private Closeable[] setupStreams(Closeable[] streams) { @@ -180,48 +197,77 @@ } } - private String[] prepareArguments(Token[] argumentTokens) { - String[] arguments = new String[argumentTokens.length]; - for (int i = 0; i < arguments.length; i++) { - arguments[i] = argumentTokens[i].token; - } - return arguments; - } - /** * This method returns an Iterator for the arguments represented as Strings. + * @deprecated */ - public Iterator<String> iterator() { - return new Iterator<String>() { + public SymbolSource<String> iterator() { + final boolean whitespaceAfterLast = this.argumentAnticipated; + + return new SymbolSource<String>() { private int pos = 0; public boolean hasNext() { - return pos < arguments.length; + return pos < argumentTokens.length; } public String next() throws NoSuchElementException { if (!hasNext()) { throw new NoSuchElementException(); } - return arguments[pos++]; + return argumentTokens[pos++].token; } + public String peek() throws NoSuchElementException { + if (!hasNext()) { + throw new NoSuchElementException(); + } + return argumentTokens[pos].token; + } + + public String last() throws NoSuchElementException { + if (pos <= 0) { + throw new NoSuchElementException(); + } + return argumentTokens[pos - 1].token; + } + public void remove() { throw new UnsupportedOperationException(); } + public void seek(int pos) throws NoSuchElementException { + if (pos >= 0 && pos <= argumentTokens.length) { + this.pos = pos; + } + else { + throw new NoSuchElementException("pos out of range"); + } + } + + public int tell() { + return pos; + } + + public boolean whitespaceAfterLast() { + return whitespaceAfterLast; + } + }; } /** * This method returns an Iterator for the arguments represented as Tokens */ - public Iterator<Token> tokenIterator() throws NoTokensAvailableException { + public SymbolSource<Token> tokenIterator() throws NoTokensAvailableException { if (argumentTokens == null) { throw new NoTokensAvailableException( "No tokens available in the CommandLine"); } - return new Iterator<Token>() { + + final boolean whitespaceAfterLast = this.argumentAnticipated; + + return new SymbolSource<Token>() { private int pos = 0; public boolean hasNext() { @@ -235,10 +281,41 @@ return argumentTokens[pos++]; } - public void remove() { - throw new UnsupportedOperationException(); + public Token peek() throws NoSuchElementException { + if (!hasNext()) { + throw new NoSuchElementException(); + } + return argumentTokens[pos]; } + + public Token last() throws NoSuchElementException { + if (pos <= 0) { + throw new NoSuchElementException(); + } + return argumentTokens[pos - 1]; + } + + public void remove() { + throw new UnsupportedOperationException(); + } + + public void seek(int pos) throws NoSuchElementException { + if (pos >= 0 && pos <= argumentTokens.length) { + this.pos = pos; + } + else { + throw new NoSuchElementException("pos out of range"); + } + } + public int tell() { + return pos; + } + + public boolean whitespaceAfterLast() { + return whitespaceAfterLast; + } + }; } @@ -248,7 +325,7 @@ * @return the command name */ public String getCommandName() { - return commandName; + return commandToken == null ? null : commandToken.token; } /** @@ -266,7 +343,15 @@ * @return the arguments as String[] */ public String[] getArguments() { - return arguments.clone(); + int len = argumentTokens.length; + if (len == 0) { + return NO_ARGS; + } + String[] arguments = new String[len]; + for (int i = 0; i < len; i++) { + arguments[i] = argumentTokens[i].token; + } + return arguments; } /** @@ -276,7 +361,7 @@ * @deprecated this method name is wrong. */ public String[] toStringArray() { - return arguments.clone(); + return getArguments(); } /** @@ -285,10 +370,10 @@ * @return the entire command line */ public String toString() { - StringBuilder sb = new StringBuilder(escape(commandName)); - for (String argument : arguments) { + StringBuilder sb = new StringBuilder(escape(commandToken.token)); + for (Token arg : argumentTokens) { sb.append(' '); - sb.append(escape(argument)); + sb.append(escape(arg.token)); } return sb.toString(); } @@ -299,7 +384,7 @@ * @return the remaining number of parts */ public int getLength() { - return arguments.length; + return argumentTokens.length; } public boolean isArgumentAnticipated() { @@ -342,13 +427,60 @@ * interpreter. */ public final int end; + + /** + * This field is <code>true</code> if the token is the target for completion. + */ + public final boolean completionTarget; - public Token(String token, int type, int start, int end) { - this.token = token; + public Token(String value, int type, int start, int end, boolean completionTarget) { + this.token = value; this.tokenType = type; this.start = start; this.end = end; + this.completionTarget = completionTarget; } + + public Token(String token) { + this(token, 0, 0, 0, false); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (completionTarget ? 1231 : 1237); + result = prime * result + end; + result = prime * result + start; + result = prime * result + ((token == null) ? 0 : token.hashCode()); + result = prime * result + tokenType; + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final Token other = (Token) obj; + if (completionTarget != other.completionTarget) + return false; + if (end != other.end) + return false; + if (start != other.start) + return false; + if (token == null) { + if (other.token != null) + return false; + } else if (!token.equals(other.token)) + return false; + if (tokenType != other.tokenType) + return false; + return true; + } } // escape and unescape methods @@ -378,8 +510,8 @@ * @param forceQuote if <code>true</code>, forces the argument to be * returned in quotes even if not necessary * @return the escaped argument - * @deprecated This method does not belong here. Escaping is an interpretter - * concern, and this class needs to be interpretter specific. + * @deprecated This method does not belong here. Escaping is an interpreter + * concern, and this class needs to be interpreter specific. */ public static String doEscape(String arg, boolean forceQuote) { int length = arg.length(); @@ -443,11 +575,57 @@ this.streams = streams.clone(); } + /** + * Perform command line argument parsing in preparation to invoking a command. + * This locates the command's class and a suitable command line syntax, then + * parses against the Syntax, binding the command arguments to Argument objects + * in an ArgumentBundle object obtained from the Command object. + * + * @param shell the context for resolving command aliases and locating syntaxes + * @return the command instance to which the arguments have been bound + * @throws CommandSyntaxException if the chosen syntax doesn't match the command + * line arguments. + */ + public Command parseCommandLine(CommandShell shell) + throws ShellException { + String cmd = (commandToken == null) ? "" : commandToken.token.trim(); + if (cmd.equals("")) { + throw new ShellFailureException("no command name"); + } + try { + // Get command's argument bundle and syntax + CommandInfo cmdClass = shell.getCommandClass(cmd); + Command command = cmdClass.createCommandInstance(); + + // Get the command's argument bundle, or the default one. + ArgumentBundle bundle = (command == null) ? null : + command.getArgumentBundle(); + bundle = (bundle == null) ? defaultArguments : bundle; + + // Get a syntax for the alias, or a default one. + Syntax syntax = shell.getSyntaxManager().getSyntax(cmd); + syntax = syntax == null ? defaultSyntax : syntax; + + // Do a full parse to bind the command line argument tokens to corresponding + // command arguments + bundle.parse(this, syntax); + return command; + } catch (ClassNotFoundException ex) { + throw new ShellException("Command class not found", ex); + } catch (InstantiationException ex) { + throw new ShellException("Command class cannot be instantiated", ex); + } catch (IllegalAccessException ex) { + throw new ShellException("Command class cannot be instantiated", ex); + } + } + public void complete(CompletionInfo completion, CommandShell shell) throws CompletionException { - String cmd = (commandName == null) ? "" : commandName.trim(); + Logger log = Logger.getLogger(CommandLine.class); + String cmd = (commandToken == null) ? "" : commandToken.token.trim(); String result = null; - if (!cmd.equals("") && (arguments.length > 0 || argumentAnticipated)) { + if (!cmd.equals("") && (argumentTokens.length > 0 || argumentAnticipated)) { + log.debug("doing argument completion"); try { // get command's help info CommandInfo cmdClass = shell.getCommandClass(cmd); @@ -470,6 +648,7 @@ } } else { // do completion on the command name + log.debug("doing command name completion"); result = defaultArg.complete(cmd); } completion.setCompleted(result); Modified: trunk/shell/src/shell/org/jnode/shell/CommandShell.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/CommandShell.java 2008-03-16 05:47:04 UTC (rev 3843) +++ trunk/shell/src/shell/org/jnode/shell/CommandShell.java 2008-03-16 13:55:01 UTC (rev 3844) @@ -36,7 +36,10 @@ import java.security.AccessController; import java.security.PrivilegedAction; import java.text.DateFormat; +import java.util.ArrayList; +import java.util.Collections; import java.util.Date; +import java.util.List; import java.util.StringTokenizer; import javax.naming.NameNotFoundException; @@ -53,13 +56,15 @@ import org.jnode.shell.alias.AliasManager; import org.jnode.shell.alias.NoSuchAliasException; import org.jnode.shell.help.CompletionException; +import org.jnode.shell.syntax.ArgumentBundle; +import org.jnode.shell.syntax.SyntaxManager; import org.jnode.util.SystemInputStream; import org.jnode.vm.VmSystem; /** * @author epr * @author Fabien DUMINY - * @authod crawley + * @author cr...@jn... */ public class CommandShell implements Runnable, Shell, ConsoleListener { @@ -97,6 +102,8 @@ private AliasManager aliasMgr; + private SyntaxManager syntaxMgr; + /** * Keeps a reference to the console this CommandShell is using * */ @@ -176,8 +183,8 @@ cons.setCompleter(this); console.addConsoleListener(this); - aliasMgr = ((AliasManager) InitialNaming.lookup(AliasManager.NAME)) - .createAliasManager(); + aliasMgr = ShellUtils.getAliasManager().createAliasManager(); + syntaxMgr = ShellUtils.getSyntaxManager().createSyntaxManager(); System.setProperty(PROMPT_PROPERTY_NAME, DEFAULT_PROMPT); } catch (NameNotFoundException ex) { throw new ShellException("Cannot find required resource", ex); @@ -206,6 +213,17 @@ ex.printStackTrace(); } } + + /** + * This constructor builds a partial command shell for test purposes only. + * + * @param aliasMgr test framework supplies an alias manager + * @param syntaxMgr test framework supplies a syntax manager + */ + protected CommandShell(AliasManager aliasMgr, SyntaxManager syntaxMgr) { + this.aliasMgr = aliasMgr; + this.syntaxMgr = syntaxMgr; + } /** * Run this shell until exit. @@ -429,8 +447,8 @@ * @return the command's return code * @throws ShellException */ - public int invoke(CommandLine cmdLine) throws ShellException { - return this.invoker.invoke(cmdLine); + public int invoke(CommandLine cmdLine, Command command) throws ShellException { + return this.invoker.invoke(cmdLine, command); } /** @@ -442,9 +460,9 @@ * @return the command's return code * @throws ShellException */ - public CommandThread invokeAsynchronous(CommandLine cmdLine) + public CommandThread invokeAsynchronous(CommandLine cmdLine, Command command) throws ShellException { - return this.invoker.invokeAsynchronous(cmdLine); + return this.invoker.invokeAsynchronous(cmdLine, command); } protected CommandInfo getCommandClass(String cmd) @@ -458,6 +476,19 @@ return new CommandInfo(cl.loadClass(cmd), false); } } + + protected ArgumentBundle getCommandArgumentBundle(CommandInfo commandInfo) { + if (Command.class.isAssignableFrom(commandInfo.getCommandClass())) { + try { + Command cmd = (Command) (commandInfo.getCommandClass().newInstance()); + return cmd.getArgumentBundle(); + } + catch (Exception ex) { + // drop through + } + } + return null; + } boolean isDebugEnabled() { return debugEnabled; @@ -540,7 +571,11 @@ throws ShellSyntaxException { return interpreter.parsePartial(this, cmdLineStr); } - + + /** + * This method is called by the console input driver to perform command line + * completion in response to a TAB character. + */ public CompletionInfo complete(String partial) { if (!readingCommand) { // dummy completion behavior for application input. @@ -551,6 +586,7 @@ } // workaround to set the currentShell to this shell + // FIXME is this needed? try { ShellUtils.getShellManager().registerShell(this); } catch (NameNotFoundException ex) { @@ -572,16 +608,11 @@ } } catch (ShellSyntaxException ex) { out.println(); // next line - err.println("Cannot parse: " + ex.getMessage()); // print the - // error - // (optional) + err.println("Cannot parse: " + ex.getMessage()); } catch (CompletionException ex) { out.println(); // next line - err.println("Problem in completer: " + ex.getMessage()); // print - // the - // error - // (optional) + err.println("Problem in completer: " + ex.getMessage()); } if (!success) { @@ -641,7 +672,7 @@ } /** - * This class subtypes FilterInputStream to capture console input to an + * This subtype of FilterInputStream captures the console input for an * application in the application input history. */ private class HistoryInputStream extends FilterInputStream { @@ -809,4 +840,8 @@ return new PrintStream((OutputStream) tmp); } } + + public SyntaxManager getSyntaxManager() { + return syntaxMgr; + } } Modified: trunk/shell/src/shell/org/jnode/shell/DefaultCommandInvoker.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/DefaultCommandInvoker.java 2008-03-16 05:47:04 UTC (rev 3843) +++ trunk/shell/src/shell/org/jnode/shell/DefaultCommandInvoker.java 2008-03-16 13:55:01 UTC (rev 3844) @@ -33,6 +33,7 @@ import org.jnode.shell.help.Help; import org.jnode.shell.help.SyntaxErrorException; +import org.jnode.vm.VmExit; /* * User: Sam Reid Date: Dec 20, 2003 Time: 1:20:33 AM Copyright (c) Dec 20, 2003 @@ -52,7 +53,7 @@ private final PrintStream err; private final CommandShell commandShell; - private static final Class<?>[] MAIN_ARG_TYPES = new Class[] { String[].class }; + private static final Class<?>[] MAIN_ARG_TYPES = new Class[] { String[].class}; static final Factory FACTORY = new Factory() { public CommandInvoker create(CommandShell shell) { @@ -73,7 +74,10 @@ return "default"; } - public int invoke(CommandLine cmdLine) { + /** + * Invoke the command. The Command argument is not used by this method. + */ + public int invoke(CommandLine cmdLine, Command command) { String cmdName = cmdLine.getCommandName(); if (cmdName == null) { return 0; @@ -109,15 +113,11 @@ } catch (PrivilegedActionException ex) { throw ex.getException(); } - } catch (InvocationTargetException ex) { - Throwable tex = ex.getTargetException(); - if (tex instanceof SyntaxErrorException) { - Help.getInfo(cmdInfo.getCommandClass()).usage(); - err.println(tex.getMessage()); - } else { - err.println("Exception in command"); - stackTrace(tex); - } + } catch (SyntaxErrorException ex) { + Help.getInfo(cmdInfo.getCommandClass()).usage(); + err.println(ex.getMessage()); + } catch (VmExit ex) { + return ex.getStatus(); } catch (Exception ex) { err.println("Exception in command"); stackTrace(ex); @@ -138,7 +138,7 @@ return 1; } - public CommandThread invokeAsynchronous(CommandLine commandLine) { + public CommandThread invokeAsynchronous(CommandLine commandLine, Command command) { throw new UnsupportedOperationException(); } Modified: trunk/shell/src/shell/org/jnode/shell/DefaultInterpreter.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/DefaultInterpreter.java 2008-03-16 05:47:04 UTC (rev 3843) +++ trunk/shell/src/shell/org/jnode/shell/DefaultInterpreter.java 2008-03-16 13:55:01 UTC (rev 3844) @@ -21,10 +21,13 @@ package org.jnode.shell; -import java.util.Iterator; +import java.util.ArrayList; import java.util.LinkedList; import java.util.NoSuchElementException; +import org.jnode.shell.CommandLine.Token; +import org.jnode.shell.syntax.CommandSyntaxException; + /** * This interpreter simply parses the command line into a command name and * arguments, with simple quoting and escaping. @@ -78,7 +81,8 @@ } public int interpret(CommandShell shell, String line) throws ShellException { - LinkedList<CommandLine.Token> tokens = new LinkedList<CommandLine.Token>(); + LinkedList<CommandLine.Token> tokens = + new LinkedList<CommandLine.Token>(); Tokenizer tokenizer = new Tokenizer(line); while (tokenizer.hasNext()) { tokens.add(tokenizer.next()); @@ -87,17 +91,23 @@ if (nosTokens == 0) { return 0; } - CommandLine commandLine; + CommandLine cmd; if (nosTokens == 1) { - commandLine = new CommandLine(tokens.get(0), null, null); + cmd = new CommandLine(tokens.get(0), null, null); } else { CommandLine.Token commandToken = tokens.removeFirst(); - CommandLine.Token[] argTokens = new CommandLine.Token[nosTokens - 1]; - commandLine = new CommandLine(commandToken, tokens - .toArray(argTokens), null); + CommandLine.Token[] argTokens = + new CommandLine.Token[nosTokens - 1]; + cmd = new CommandLine( + commandToken, tokens.toArray(argTokens),null); } shell.addCommandToHistory(line); - return shell.invoke(commandLine); + try { + Command command = cmd.parseCommandLine(shell); + return shell.invoke(cmd, command); + } catch (CommandSyntaxException ex) { + throw new ShellException("Command arguments don't match syntax", ex); + } } public Completable parsePartial(CommandShell shell, String line) @@ -107,14 +117,15 @@ return new CommandLine("", null); } CommandLine.Token commandToken = tokenizer.next(); - LinkedList<CommandLine.Token> tokenList = new LinkedList<CommandLine.Token>(); + LinkedList<CommandLine.Token> tokenList = + new LinkedList<CommandLine.Token>(); while (tokenizer.hasNext()) { tokenList.add(tokenizer.next()); } - CommandLine.Token[] argTokens = tokenList - .toArray(new CommandLine.Token[tokenList.size()]); + CommandLine.Token[] argTokens = + tokenList.toArray(new CommandLine.Token[tokenList.size()]); CommandLine res = new CommandLine(commandToken, argTokens, null); - res.setArgumentAnticipated(tokenizer.whitespaceAfter(tokenizer.last())); + res.setArgumentAnticipated(tokenizer.whitespaceAfterLast()); return res; } @@ -123,26 +134,20 @@ * understands quoting, some '\' escapes, and (depending on constructor * flags) certain "special" symbols. */ - static class Tokenizer implements Iterator<CommandLine.Token> { - private final String s; - private final int flags; - + protected static class Tokenizer implements SymbolSource<CommandLine.Token> { private int pos = 0; - private boolean inFullEscape = false; - private boolean inQuote = false; + private final ArrayList<CommandLine.Token> tokens = + new ArrayList<Token>(8); + private boolean whiteSpaceAfterLast; - private CommandLine.Token lastToken; - /** - * Instantiate a commandline tokenizer for a given input String. + * Instantiate a command line tokenizer for a given input String. * * @param line the input String. * @param flags flags controlling the tokenization. */ public Tokenizer(String line, int flags) { - pos = 0; - s = line; - this.flags = flags; + tokenize(line, flags); } public Tokenizer(String line) { @@ -156,10 +161,7 @@ * <code>false</code> otherwise */ public boolean hasNext() { - while (pos < s.length() && s.charAt(pos) == SPACE_CHAR) { - pos++; - } - return pos < s.length() && s.charAt(pos) != COMMENT_CHAR; + return pos < tokens.size(); } /** @@ -171,110 +173,128 @@ if (!hasNext()) { throw new NoSuchElementException(); } + return tokens.get(pos++); + } - int type = LITERAL; - int start = pos; + private void tokenize(String s, int flags) + throws IllegalArgumentException { + int pos = 0; - StringBuilder token = new StringBuilder(5); - char currentChar; + while (true) { + // Skip spaces before start of token + whiteSpaceAfterLast = false; + while (pos < s.length() && s.charAt(pos) == SPACE_CHAR) { + pos++; + whiteSpaceAfterLast = true; + } + if (pos >= s.length()) { + break; + } - boolean finished = false; + // Parse a token + boolean inFullEscape = false; + boolean inQuote = false; + int type = LITERAL; + int start = pos; + StringBuilder token = new StringBuilder(5); + char currentChar; + boolean finished = false; - while (!finished && pos < s.length()) { - currentChar = s.charAt(pos++); + while (!finished && pos < s.length()) { + currentChar = s.charAt(pos++); - switch (currentChar) { - case ESCAPE_CHAR: - if (pos >= s.length()) { - throw new IllegalArgumentException( - "escape char ('\\') not followed by a character"); - } - char ch; - switch (ch = s.charAt(pos++)) { - case N: - token.append(ESCAPE_N); + switch (currentChar) { + case ESCAPE_CHAR: + if (pos >= s.length()) { + throw new IllegalArgumentException( + "escape char ('\\') not followed by a character"); + } + char ch; + switch (ch = s.charAt(pos++)) { + case N: + token.append(ESCAPE_N); + break; + case B: + token.append(ESCAPE_B); + break; + case R: + token.append(ESCAPE_R); + break; + case T: + token.append(ESCAPE_T); + break; + default: + token.append(ch); + } break; - case B: - token.append(ESCAPE_B); + + case FULL_ESCAPE_CHAR: + if (inQuote) { + token.append(currentChar); + } else { + inFullEscape = !inFullEscape; // just a toggle + type = STRING; + if (!inFullEscape) { + type |= CLOSED; + } + } break; - case R: - token.append(ESCAPE_R); + case QUOTE_CHAR: + if (inFullEscape) { + token.append(currentChar); + } else { + inQuote = !inQuote; + type = STRING; + if (!inQuote) { + type |= CLOSED; + } + } break; - case T: - token.append(ESCAPE_T); + case SPACE_CHAR: + if (inFullEscape || inQuote) { + token.append(currentChar); + } else { + if (token.length() != 0) { // don't return an empty + // token + finished = true; + pos--; // to return trailing space as empty + // last + // token + } + } break; - default: - token.append(ch); - } - break; - - case FULL_ESCAPE_CHAR: - if (inQuote) { - token.append(currentChar); - } else { - inFullEscape = !inFullEscape; // just a toggle - type = STRING; - if (!inFullEscape) { - type |= CLOSED; - } - } - break; - case QUOTE_CHAR: - if (inFullEscape) { - token.append(currentChar); - } else { - inQuote = !inQuote; - type = STRING; - if (!inQuote) { - type |= CLOSED; - } - } - break; - case SPACE_CHAR: - if (inFullEscape || inQuote) { - token.append(currentChar); - } else { - if (token.length() != 0) { // don't return an empty - // token + case COMMENT_CHAR: + if (inFullEscape || inQuote) { + token.append(currentChar); + } else { finished = true; - pos--; // to return trailing space as empty last - // token + pos = s.length(); // ignore EVERYTHING } - } - break; - case COMMENT_CHAR: - if (inFullEscape || inQuote) { - token.append(currentChar); - } else { - finished = true; - pos = s.length(); // ignore EVERYTHING - } - break; - case GET_INPUT_FROM_CHAR: - case SEND_OUTPUT_TO_CHAR: - case PIPE_CHAR: - if (inFullEscape || inQuote - || (flags & REDIRECTS_FLAG) == 0) { - token.append(currentChar); - } else { - finished = true; - if (token.length() == 0) { + break; + case GET_INPUT_FROM_CHAR: + case SEND_OUTPUT_TO_CHAR: + case PIPE_CHAR: + if (inFullEscape || inQuote || + (flags & REDIRECTS_FLAG) == 0) { token.append(currentChar); - type = SPECIAL; } else { - pos--; // the special character terminates the - // literal. + finished = true; + if (token.length() == 0) { + token.append(currentChar); + type = SPECIAL; + } else { + pos--; // the special character terminates the + // literal. + } } + break; + default: + token.append(currentChar); } - break; - default: - token.append(currentChar); } + tokens.add(new CommandLine.Token(token.toString(), type, start, + pos, pos < s.length())); } - - lastToken = new CommandLine.Token(token.toString(), type, start, - pos); - return lastToken; } /** @@ -290,15 +310,29 @@ * @return the last token. */ public CommandLine.Token last() { - return lastToken; + return tokens.get(pos - 1); } - /** - * Test if there is a whitespace character after a token. This only - * works if the token was returned by this Tokenizer. - */ - public boolean whitespaceAfter(CommandLine.Token token) { - return token.end < s.length() && s.charAt(token.end) == SPACE_CHAR; + public Token peek() throws NoSuchElementException { + if (!hasNext()) { + throw new NoSuchElementException(); + } + return tokens.get(pos + 1); } + + public void seek(int pos) throws NoSuchElementException { + if (pos < 0 || pos > tokens.siz... [truncated message content] |
From: <ls...@us...> - 2008-03-19 21:22:37
|
Revision: 3858 http://jnode.svn.sourceforge.net/jnode/?rev=3858&view=rev Author: lsantha Date: 2008-03-19 14:22:34 -0700 (Wed, 19 Mar 2008) Log Message: ----------- Swingpeer improvements. Modified Paths: -------------- trunk/core/src/openjdk/java/java/awt/Component.java trunk/core/src/openjdk/javax/javax/swing/text/StyleContext.java trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingBaseWindow.java trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingFramePeer.java Modified: trunk/core/src/openjdk/java/java/awt/Component.java =================================================================== --- trunk/core/src/openjdk/java/java/awt/Component.java 2008-03-16 20:26:16 UTC (rev 3857) +++ trunk/core/src/openjdk/java/java/awt/Component.java 2008-03-19 21:22:34 UTC (rev 3858) @@ -2710,7 +2710,7 @@ */ public FontMetrics getFontMetrics(Font font) { // REMIND: PlatformFont flag should be obsolete soon... - if (sun.font.FontManager.usePlatformFontMetrics()) { + if (/*jnode*/true || sun.font.FontManager.usePlatformFontMetrics()) { if (peer != null && !(peer instanceof LightweightPeer)) { return peer.getFontMetrics(font); Modified: trunk/core/src/openjdk/javax/javax/swing/text/StyleContext.java =================================================================== --- trunk/core/src/openjdk/javax/javax/swing/text/StyleContext.java 2008-03-16 20:26:16 UTC (rev 3857) +++ trunk/core/src/openjdk/javax/javax/swing/text/StyleContext.java 2008-03-19 21:22:34 UTC (rev 3858) @@ -264,9 +264,11 @@ if (f == null) { f = new Font(family, style, size); } + /* jnode if (! FontManager.fontSupportsDefaultEncoding(f)) { f = FontManager.getCompositeFontUIResource(f); } + */ FontKey key = new FontKey(family, style, size); fontTable.put(key, f); } Modified: trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingBaseWindow.java =================================================================== --- trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingBaseWindow.java 2008-03-16 20:26:16 UTC (rev 3857) +++ trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingBaseWindow.java 2008-03-19 21:22:34 UTC (rev 3858) @@ -112,7 +112,7 @@ /** * @see javax.swing.JInternalFrame#createRootPane() */ - protected final JRootPane createRootPane() { + protected JRootPane createRootPane() { return new RootPane(); } @@ -135,7 +135,7 @@ @Override public void update(Graphics g) { - super.update(g); //To change body of overridden methods use File | Settings | File Templates. + super.update(g); } /** Modified: trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingFramePeer.java =================================================================== --- trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingFramePeer.java 2008-03-16 20:26:16 UTC (rev 3857) +++ trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingFramePeer.java 2008-03-19 21:22:34 UTC (rev 3858) @@ -25,8 +25,13 @@ import java.awt.Image; import java.awt.MenuBar; import java.awt.Rectangle; +import java.awt.Graphics; +import java.awt.Container; import java.awt.peer.FramePeer; import java.beans.PropertyVetoException; +import javax.swing.JFrame; +import javax.swing.JComponent; +import javax.swing.JRootPane; final class SwingFrame extends SwingBaseWindow<Frame, SwingFrame> { @@ -34,8 +39,71 @@ super(awtFrame, title); } + @Override + public void repaint(long tm, int x, int y, int width, int height) { + super.repaint(tm, x, y, width, height); + if(target instanceof JFrame && isVisible()) + ((JFrame)target).getRootPane().repaint(tm, x, y, width, height); + } + + @Override + public void update(Graphics g) { + super.update(g); + if(target instanceof JFrame && isVisible()) + ((JFrame)target).getRootPane().update(g); + } + + @Override + protected void paintComponent(Graphics g) { + super.paintComponent(g); //To change body of overridden methods use File | Settings | File Templates. + } + + /** + * @see javax.swing.JInternalFrame#createRootPane() + */ + protected JRootPane createRootPane() { + return new NoContentRootPane(); + } + + @Override + protected void validateTree() { + super.validateTree(); + if(target instanceof JFrame) + ((JFrame)target).getRootPane().validate(); + } } +final class NullContentPane extends JComponent { + @Override + public void update(Graphics g) { + //empty + } + + @Override + public void paint(Graphics g) { + + } + + @Override + public void repaint() { + + } + + @Override + public void repaint(long tm, int x, int y, int width, int height) { + + } +} + +final class NoContentRootPane extends JRootPane { + /** + * @see javax.swing.JRootPane#createContentPane() + */ + protected Container createContentPane() { + return new NullContentPane(); + } + } + /** * @author Ewout Prangsma (ep...@us...) * @author Levente S\u00e1ntha This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cr...@us...> - 2008-03-21 08:41:08
|
Revision: 3859 http://jnode.svn.sourceforge.net/jnode/?rev=3859&view=rev Author: crawley Date: 2008-03-21 01:41:06 -0700 (Fri, 21 Mar 2008) Log Message: ----------- Restructured the completion data structures / code / control flow Modified Paths: -------------- trunk/core/src/driver/org/jnode/driver/console/CompletionInfo.java trunk/core/src/driver/org/jnode/driver/console/textscreen/KeyboardInputStream.java trunk/core/src/driver/org/jnode/driver/console/textscreen/Line.java trunk/fs/src/fs/org/jnode/fs/nfs/command/NFSHostNameArgument.java trunk/shell/src/shell/org/jnode/shell/CommandLine.java trunk/shell/src/shell/org/jnode/shell/CommandShell.java trunk/shell/src/shell/org/jnode/shell/RedirectingInterpreter.java trunk/shell/src/shell/org/jnode/shell/Shell.java trunk/shell/src/shell/org/jnode/shell/command/test/SuiteCommand.java trunk/shell/src/shell/org/jnode/shell/help/Argument.java trunk/shell/src/shell/org/jnode/shell/help/CommandLineElement.java trunk/shell/src/shell/org/jnode/shell/help/Help.java trunk/shell/src/shell/org/jnode/shell/help/Parameter.java trunk/shell/src/shell/org/jnode/shell/help/Syntax.java trunk/shell/src/shell/org/jnode/shell/help/argument/AliasArgument.java trunk/shell/src/shell/org/jnode/shell/help/argument/ClassNameArgument.java trunk/shell/src/shell/org/jnode/shell/help/argument/DeviceArgument.java trunk/shell/src/shell/org/jnode/shell/help/argument/EnumOptionArgument.java trunk/shell/src/shell/org/jnode/shell/help/argument/FileArgument.java trunk/shell/src/shell/org/jnode/shell/help/argument/HostNameArgument.java trunk/shell/src/shell/org/jnode/shell/help/argument/InetAddressArgument.java trunk/shell/src/shell/org/jnode/shell/help/argument/IntegerArgument.java trunk/shell/src/shell/org/jnode/shell/help/argument/ListArgument.java trunk/shell/src/shell/org/jnode/shell/help/argument/LongArgument.java trunk/shell/src/shell/org/jnode/shell/help/argument/OptionArgument.java trunk/shell/src/shell/org/jnode/shell/help/argument/PluginArgument.java trunk/shell/src/shell/org/jnode/shell/help/argument/PropertyNameArgument.java trunk/shell/src/shell/org/jnode/shell/help/argument/StringArgument.java trunk/shell/src/shell/org/jnode/shell/help/argument/StringListArgument.java trunk/shell/src/shell/org/jnode/shell/help/argument/ThreadNameArgument.java Modified: trunk/core/src/driver/org/jnode/driver/console/CompletionInfo.java =================================================================== --- trunk/core/src/driver/org/jnode/driver/console/CompletionInfo.java 2008-03-19 21:22:34 UTC (rev 3858) +++ trunk/core/src/driver/org/jnode/driver/console/CompletionInfo.java 2008-03-21 08:41:06 UTC (rev 3859) @@ -18,98 +18,150 @@ * 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.driver.console; +import java.util.Collections; +import java.util.TreeSet; +import java.util.SortedSet; + /** * @author Ewout Prangsma (ep...@us...) + * @author cr...@jn... */ public class CompletionInfo { - private String[] items = null; + private static final SortedSet<String> NO_COMPLETIONS = + Collections.unmodifiableSortedSet(new TreeSet<String>()); - private String completed = null; + private TreeSet<String> completions; - private boolean newPrompt = false; + private int completionStart = -1; /** - * @return Returns the completed. + * This method is called to register a possible completion. A null or empty + * completion string will be quietly ignored. + * + * @param completion the completion string + * @param partial if <code>true</code>, further completions of the + * completion string may be possible. */ - public String getCompleted() { - return completed; + public void addCompletion(String completion, boolean partial) { + if (completion == null || completion.length() == 0) { + return; + } + if (completions == null) { + completions = new TreeSet<String>(); + } + if (!partial) { + completion += ' '; + } + completions.add(completion); } /** - * @param completed - * The completed to set. + * This method is called to register a completion than cannot be completed + * further. A null or empty completion string will be quietly ignored. + * + * @param completion the completion string */ - public void setCompleted(String completed) { - this.completed = completed; + public void addCompletion(String completion) { + addCompletion(completion, false); } /** - * get the possible completions + * Retrieve the completion details. * - * @return Returns the items. + * @return a TreeSet consisting of all possible completions */ - public String[] getItems() { - return items; + public SortedSet<String> getCompletions() { + return completions == null ? NO_COMPLETIONS : completions; } /** - * Specify the possible completions - * - * @param items - * The items to set. + * Render for debug purposes */ - public void setItems(String[] items) { - this.items = items; - this.completed = null; - this.newPrompt = true; + public String toString() { + StringBuilder sb = new StringBuilder("CompletionInfo{"); + sb.append("competionStart=").append(completionStart); + sb.append(",completions="); + if (completions == null) { + sb.append("null"); + } else { + sb.append("{"); + boolean first = true; + for (String completion : completions) { + if (first) { + first = false; + } else { + sb.append(","); + } + sb.append(completion); + } + sb.append("]"); + } + return sb.toString(); } /** - * Do we have more than one possible completion ? + * The completion start is the offset in the original string of the first + * character to be replaced with the 'completed'. * - * @return + * @return the completion start position, or <code>-1</code> */ - public boolean hasItems() { - return items != null; + public int getCompletionStart() { + return completionStart; } /** - * Specify if we need a new prompt or not + * Set the completion start position. This can only be set once. After that, + * attempts to change the start position result in an + * IllegalArgumentException. * - * @param newPrompt + * @param completionStart */ - public void setNewPrompt(boolean newPrompt) { - this.newPrompt = newPrompt; + public void setCompletionStart(int completionStart) { + if (this.completionStart != completionStart) { + if (this.completionStart != -1) { + throw new IllegalArgumentException( + "completionStart cannot be changed"); + } + this.completionStart = completionStart; + } } /** - * @return true if we need to display a new prompt + * Get the combined completion string. If there are multiple alternatives, + * this will be the longest common left substring of the alternatives. If + * the substring is zero length, or if there were no alternatives in the + * first place, the result is <code>null</code>. + * + * @return the combined completion, or <code>null</code>. */ - public boolean needNewPrompt() { - return newPrompt; - } - - public String toString() { - StringBuilder sb = new StringBuilder("CompletionInfo{"); - sb.append("completed=").append(completed == null ? "null" : completed); - sb.append(",items="); - if (items == null) { - sb.append("null"); + public String getCompletion() { + if (completions == null) { + return null; } - else { - sb.append("["); - for (int i = 0; i < items.length; i++) { - if (i > 0) { - sb.append(","); + int nos = completions.size(); + if (nos == 0) { + return null; + } + if (nos == 1) { + return completions.first(); + } + String common = completions.first(); + for (String completion : completions) { + if (common != completion && !completion.startsWith(common)) { + for (int i = 0; i < common.length(); i++) { + if (common.charAt(i) != completion.charAt(i)) { + if (i == 0) { + return null; + } + common = common.substring(0, i); + break; + } } - sb.append(items[i] == null ? "null" : items[i]); } - sb.append("]"); } - sb.append(",newPrompt=").append(newPrompt).append("}"); - return sb.toString(); + return common; } } Modified: trunk/core/src/driver/org/jnode/driver/console/textscreen/KeyboardInputStream.java =================================================================== --- trunk/core/src/driver/org/jnode/driver/console/textscreen/KeyboardInputStream.java 2008-03-19 21:22:34 UTC (rev 3858) +++ trunk/core/src/driver/org/jnode/driver/console/textscreen/KeyboardInputStream.java 2008-03-21 08:41:06 UTC (rev 3859) @@ -223,8 +223,7 @@ // if it's the tab key, we want to trigger command line completion case '\t': if (completer != null) { - CompletionInfo completion = currentLine.complete(); - if (completion.needNewPrompt()) { + if (currentLine.complete()) { currentLine.start(true); } out.print(currentPrompt); Modified: trunk/core/src/driver/org/jnode/driver/console/textscreen/Line.java =================================================================== --- trunk/core/src/driver/org/jnode/driver/console/textscreen/Line.java 2008-03-19 21:22:34 UTC (rev 3858) +++ trunk/core/src/driver/org/jnode/driver/console/textscreen/Line.java 2008-03-21 08:41:06 UTC (rev 3859) @@ -22,6 +22,8 @@ package org.jnode.driver.console.textscreen; import java.util.Arrays; +import java.util.SortedSet; +import java.util.TreeSet; import org.jnode.driver.console.CompletionInfo; import org.jnode.driver.console.InputCompleter; @@ -158,63 +160,54 @@ } } - public CompletionInfo complete() { + public boolean complete() { CompletionInfo info = null; InputCompleter completer = console.getCompleter(); - if (posOnCurrentLine != currentLine.length()) { - String ending = currentLine.substring(posOnCurrentLine); - info = completer.complete(currentLine.substring(0, posOnCurrentLine)); - printList(info); - if (info.getCompleted() != null) { - setContent(info.getCompleted() + ending); - posOnCurrentLine = currentLine.length() - ending.length(); - } - } else { - info = completer.complete(currentLine.toString()); - printList(info); - if (info.getCompleted() != null) { - setContent(info.getCompleted()); - posOnCurrentLine = currentLine.length(); - } + String ending = + posOnCurrentLine != currentLine.length() ? currentLine.substring(posOnCurrentLine) : ""; + info = completer.complete(currentLine.substring(0, posOnCurrentLine)); + boolean res = printList(info); + String completion = info.getCompletion(); + if (completion != null) { + int startPos = info.getCompletionStart(); + setContent(currentLine.substring(0, startPos) + completion + ending); + // (This is the updated line's length ...) + posOnCurrentLine = currentLine.length() - ending.length(); } - - return info; + return res; } - protected void printList(CompletionInfo info) { - if ((info != null) && info.hasItems()) { - int oldPosOnCurrentLine = posOnCurrentLine; - moveEnd(); - refreshCurrentLine(); + protected boolean printList(CompletionInfo info) { + SortedSet<String> completions = info.getCompletions(); + if (completions == null || completions.size() <= 1) { + return false; + } + int oldPosOnCurrentLine = posOnCurrentLine; + moveEnd(); + refreshCurrentLine(); - out.println(); - String[] list = info.getItems(); - Arrays.sort(list); - - final int minItemsToSplit = 5; - if(list.length > minItemsToSplit) - { - list = splitInColumns(list); - } + out.println(); + String[] list = completions.toArray(new String[completions.size()]); - // display items column (may be single or multiple columns) - for (String item : list) - { - // item may actually be a single item or in fact multiple items - if((item.length() % SCREEN_WIDTH) == 0) - { - // we are already at the first column of the next line - out.print(item); - } - else - { - // we aren't at the first column of the next line - out.println(item); - } - } + final int minItemsToSplit = 5; + if (list.length > minItemsToSplit) { + list = splitInColumns(list); + } - posOnCurrentLine = oldPosOnCurrentLine; + // display items column (may be single or multiple columns) + for (String item : list) { + // item may actually be a single item or in fact multiple items + if (item.length() % SCREEN_WIDTH == 0) { + // we are already at the first column of the next line + out.print(item); + } + else { + // we aren't at the first column of the next line + out.println(item); + } } + posOnCurrentLine = oldPosOnCurrentLine; + return true; } protected String[] splitInColumns(String[] items) @@ -223,10 +216,8 @@ // compute the maximum width of items int maxWidth = 0; - for(String item : items) - { - if(item.length() > maxWidth) - { + for (String item : items) { + if (item.length() > maxWidth) { maxWidth = item.length(); } } @@ -239,21 +230,18 @@ String[] lines = new String[nbLines]; StringBuilder line = new StringBuilder(SCREEN_WIDTH); int lineNum = 0; - for(int itemNum = 0 ; itemNum < items.length ; ) - { - for(int c = 0 ; c < nbColumns ; c++) - { + for (int itemNum = 0 ; itemNum < items.length ; ) { + for (int c = 0 ; c < nbColumns ; c++) { final String item = items[itemNum++]; line.append(item); // add some blanks final int nbBlanks = columnWidth - item.length(); - for(int i = 0 ; i < nbBlanks ; i++) - { + for (int i = 0 ; i < nbBlanks ; i++) { line.append(' '); } - if(itemNum >= items.length) break; + if (itemNum >= items.length) break; } lines[lineNum++] = line.toString(); Modified: trunk/fs/src/fs/org/jnode/fs/nfs/command/NFSHostNameArgument.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/nfs/command/NFSHostNameArgument.java 2008-03-19 21:22:34 UTC (rev 3858) +++ trunk/fs/src/fs/org/jnode/fs/nfs/command/NFSHostNameArgument.java 2008-03-21 08:41:06 UTC (rev 3859) @@ -9,6 +9,7 @@ import java.util.ArrayList; import java.util.List; +import org.jnode.driver.console.CompletionInfo; import org.jnode.net.nfs.Protocol; import org.jnode.net.nfs.nfs2.mount.ExportEntry; import org.jnode.net.nfs.nfs2.mount.Mount1Client; @@ -26,22 +27,18 @@ super(name, description); } - public String complete(String partial) { + public void complete(CompletionInfo completion, String partial) { - if (partial == null) { - return null; - } - int index = partial.indexOf(':'); if (index == -1) { - return partial; + return; } final InetAddress host; try { host = InetAddress.getByName(partial.substring(0, index)); } catch (UnknownHostException e) { - return partial; + return; } String partialDirectory = partial.substring(index + 1); @@ -50,12 +47,10 @@ try { exportEntryList = AccessController .doPrivileged(new PrivilegedExceptionAction<List<ExportEntry>>() { - public List<ExportEntry> run() throws IOException, - MountException { - - Mount1Client client = new Mount1Client(host, - Protocol.TCP, -1, -1); - + public List<ExportEntry> run() + throws IOException, MountException { + Mount1Client client = + new Mount1Client(host, Protocol.TCP, -1, -1); List<ExportEntry> exportEntryList; try { exportEntryList = client.export(); @@ -64,34 +59,24 @@ try { client.close(); } catch (IOException e) { - + // squash } } } return exportEntryList; - } }); } catch (PrivilegedActionException e) { - - return partial; + return; } - List<String> valueList = new ArrayList<String>(); for (int i = 0; i < exportEntryList.size(); i++) { ExportEntry exportEntry = exportEntryList.get(i); - if (exportEntry.getDirectory().startsWith(partialDirectory)) { - valueList.add(partial.substring(0, index) + ":" + completion.addCompletion(partial.substring(0, index) + ":" + exportEntry.getDirectory()); } - } - - String completed = complete(partial, valueList); - - return completed; - } public InetAddress getAddress(ParsedArguments args) Modified: trunk/shell/src/shell/org/jnode/shell/CommandLine.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/CommandLine.java 2008-03-19 21:22:34 UTC (rev 3858) +++ trunk/shell/src/shell/org/jnode/shell/CommandLine.java 2008-03-21 08:41:06 UTC (rev 3859) @@ -22,8 +22,6 @@ package org.jnode.shell; import java.io.Closeable; -import java.util.Collections; -import java.util.List; import java.util.NoSuchElementException; import org.apache.log4j.Logger; @@ -34,7 +32,6 @@ import org.jnode.shell.help.Parameter; import org.jnode.shell.syntax.CommandSyntaxException; -import org.jnode.shell.syntax.AliasArgument; import org.jnode.shell.syntax.FileArgument; import org.jnode.shell.syntax.ArgumentBundle; import org.jnode.shell.syntax.ArgumentSyntax; @@ -404,27 +401,30 @@ * This field holds the "cooked" representation of command line token. * By the time we reach the CommandLine, all shell meta-characters * should have been processed so that the value of the field represents - * a command name or argument. + * a command name or argument. */ public final String token; /** * This field represents the type of the token. The meaning is - * interpreter specific. + * interpreter specific. The value -1 indicates that no token type is + * available. */ public final int tokenType; /** * This field denotes the character offset of the first character of * this token in the source character sequence passed to the - * interpreter. + * interpreter. The value -1 indicates that no source start position is + * available. */ public final int start; /** * This field denotes the character offset + 1 for the last character of * this token in the source character sequence passed to the - * interpreter. + * interpreter. The value -1 indicates that no source end position is + * available. */ public final int end; @@ -442,7 +442,7 @@ } public Token(String token) { - this(token, 0, 0, 0, false); + this(token, -1, -1, -1, false); } @Override @@ -623,9 +623,7 @@ throws CompletionException { Logger log = Logger.getLogger(CommandLine.class); String cmd = (commandToken == null) ? "" : commandToken.token.trim(); - String result = null; if (!cmd.equals("") && (argumentTokens.length > 0 || argumentAnticipated)) { - log.debug("doing argument completion"); try { // get command's help info CommandInfo cmdClass = shell.getCommandClass(cmd); @@ -639,18 +637,16 @@ } // perform completion of the command arguments based on the - // command's - // help info / syntax ... if any. - result = info.complete(this); - + // command's help info / syntax ... if any. + info.complete(completion, this); } catch (ClassNotFoundException ex) { throw new CompletionException("Command class not found", ex); } } else { // do completion on the command name - log.debug("doing command name completion"); - result = defaultArg.complete(cmd); + log.debug("completing '" + cmd + "'"); + defaultArg.complete(completion, cmd); + completion.setCompletionStart(commandToken == null ? 0 : commandToken.start); } - completion.setCompleted(result); } } Modified: trunk/shell/src/shell/org/jnode/shell/CommandShell.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/CommandShell.java 2008-03-19 21:22:34 UTC (rev 3858) +++ trunk/shell/src/shell/org/jnode/shell/CommandShell.java 2008-03-21 08:41:06 UTC (rev 3859) @@ -36,10 +36,7 @@ import java.security.AccessController; import java.security.PrivilegedAction; import java.text.DateFormat; -import java.util.ArrayList; -import java.util.Collections; import java.util.Date; -import java.util.List; import java.util.StringTokenizer; import javax.naming.NameNotFoundException; @@ -579,10 +576,7 @@ public CompletionInfo complete(String partial) { if (!readingCommand) { // dummy completion behavior for application input. - CompletionInfo completion = new CompletionInfo(); - completion.setCompleted(partial); - completion.setNewPrompt(true); - return completion; + return new CompletionInfo(); } // workaround to set the currentShell to this shell @@ -594,17 +588,13 @@ // do command completion completion = new CompletionInfo(); - boolean success = false; try { Completable cl = parseCommandLine(partial); if (cl != null) { cl.complete(completion, this); - if (!partial.equals(completion.getCompleted()) - && !completion.hasItems()) { - // we performed direct completion without listing - completion.setNewPrompt(false); + if (completion.getCompletionStart() == -1) { + completion.setCompletionStart(partial.length()); } - success = true; } } catch (ShellSyntaxException ex) { out.println(); // next line @@ -615,27 +605,12 @@ err.println("Problem in completer: " + ex.getMessage()); } - if (!success) { - // Make sure the caller knows to repaint the prompt - completion.setCompleted(partial); - completion.setNewPrompt(true); - } - // Make sure that the shell's completion context gets nulled. CompletionInfo myCompletion = completion; completion = null; return myCompletion; } - - public void list(String[] items) { - if (completion == null) { - throw new ShellFailureException( - "list called when no completion is in progress"); - } else { - completion.setItems(items); - } - } - + public void addCommandToHistory(String cmdLineStr) { // Add this command to the command history. if (isHistoryEnabled() && !cmdLineStr.equals(lastCommandLine)) { Modified: trunk/shell/src/shell/org/jnode/shell/RedirectingInterpreter.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/RedirectingInterpreter.java 2008-03-19 21:22:34 UTC (rev 3858) +++ trunk/shell/src/shell/org/jnode/shell/RedirectingInterpreter.java 2008-03-21 08:41:06 UTC (rev 3859) @@ -37,6 +37,7 @@ import org.jnode.shell.help.CompletionException; import org.jnode.shell.help.Help; import org.jnode.shell.help.Parameter; +import org.jnode.shell.help.argument.AliasArgument; import org.jnode.shell.help.argument.FileArgument; import org.jnode.shell.syntax.CommandSyntaxException; @@ -96,30 +97,31 @@ } CommandDescriptor lastDesc = commands.get(nosCommands - 1); CommandLine lastCommand = lastDesc.commandLine; - CommandLine.Token lastToken = tokenizer.last(); + final CommandLine.Token lastToken = tokenizer.last(); boolean whitespaceAfter = tokenizer.whitespaceAfterLast(); lastCommand.setArgumentAnticipated(whitespaceAfter); switch (completionContext) { case COMPLETE_ALIAS: case COMPLETE_ARG: case COMPLETE_PIPE: - break; + return lastCommand; case COMPLETE_INPUT: - if (lastDesc.fromFileName == null || !whitespaceAfter) { - return new RedirectionCompleter(line, lastToken.start); - } - break; case COMPLETE_OUTPUT: - if (lastDesc.toFileName == null || !whitespaceAfter) { - return new RedirectionCompleter(line, lastToken.start); + if (!whitespaceAfter) { + return new Completable() { + public void complete(CompletionInfo completion, + CommandShell shell) throws CompletionException { + new AliasArgument("?", null).complete(completion, lastToken.token); + } + }; } - break; + else { + return lastCommand; + } default: throw new ShellFailureException("bad completion context (" + completionContext + ")"); } - return new SubcommandCompleter(lastCommand, line, - whitespaceAfter ? lastToken.end : lastToken.start); } private List<CommandDescriptor> parse(Tokenizer tokenizer, String line, @@ -429,60 +431,4 @@ this.pipeTo = pipeTo; } } - - private abstract class EmbeddedCompleter implements Completable { - private final String partial; - private final int startPos; - - public EmbeddedCompleter(String partial, int startPos) { - this.partial = partial; - this.startPos = startPos; - } - - public String getCompletableString() { - return partial.substring(startPos); - } - - public void setFullCompleted(CompletionInfo completion, String completed) { - completion.setCompleted(partial.substring(0, startPos) + completed); - } - } - - private class SubcommandCompleter extends EmbeddedCompleter { - private final CommandLine subcommand; - - public SubcommandCompleter(CommandLine subcommand, String partial, - int startPos) { - super(partial, startPos); - this.subcommand = subcommand; - } - - public void complete(CompletionInfo completion, CommandShell shell) - throws CompletionException { - subcommand.complete(completion, shell); - setFullCompleted(completion, completion.getCompleted()); - } - } - - private class RedirectionCompleter extends EmbeddedCompleter { - - private final Help.Info fileParameter = - new Help.Info("file", - "default parameter for file redirection completion", - new Parameter(new FileArgument("file", "a file", - Argument.SINGLE), Parameter.MANDATORY)); - - public RedirectionCompleter(String partial, int startPos) { - super(partial, startPos); - } - - public void complete(CompletionInfo completion, CommandShell shell) - throws CompletionException { - CommandLine command = - new CommandLine("?", - new String[] { getCompletableString() }); - String result = fileParameter.complete(command); - setFullCompleted(completion, result); - } - } } Modified: trunk/shell/src/shell/org/jnode/shell/Shell.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/Shell.java 2008-03-19 21:22:34 UTC (rev 3858) +++ trunk/shell/src/shell/org/jnode/shell/Shell.java 2008-03-21 08:41:06 UTC (rev 3859) @@ -43,11 +43,6 @@ public SyntaxManager getSyntaxManager(); /** - * Shell callback to register a list of choices for command line completion. - */ - public void list(String[] items); - - /** * Gets the shell's command InputHistory object. Unlike getInputHistory, * this method is not modal. */ Modified: trunk/shell/src/shell/org/jnode/shell/command/test/SuiteCommand.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/command/test/SuiteCommand.java 2008-03-19 21:22:34 UTC (rev 3858) +++ trunk/shell/src/shell/org/jnode/shell/command/test/SuiteCommand.java 2008-03-21 08:41:06 UTC (rev 3859) @@ -31,6 +31,7 @@ import junit.framework.Test; import junit.framework.TestSuite; +import org.jnode.driver.console.CompletionInfo; import org.jnode.shell.help.Argument; import org.jnode.shell.help.Help; import org.jnode.shell.help.Parameter; @@ -110,19 +111,13 @@ super(name, description); } - public String complete(String partial) { - final List<String> categories = new ArrayList<String>(); + public void complete(CompletionInfo completion, String partial) { Set<String> availCategories = TestManager.getInstance().getCategories(); - - for(String availCategory : availCategories) - { - if(availCategory.startsWith(partial)) - { - categories.add(availCategory); + for (String availCategory : availCategories) { + if (availCategory.startsWith(partial)) { + completion.addCompletion(availCategory); } } - - return complete(partial, categories); } protected boolean isValidValue(String category) { Modified: trunk/shell/src/shell/org/jnode/shell/help/Argument.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/help/Argument.java 2008-03-19 21:22:34 UTC (rev 3858) +++ trunk/shell/src/shell/org/jnode/shell/help/Argument.java 2008-03-21 08:41:06 UTC (rev 3859) @@ -21,12 +21,8 @@ package org.jnode.shell.help; -import java.util.Collection; +import org.jnode.driver.console.CompletionInfo; -import javax.naming.NameNotFoundException; - -import org.jnode.shell.ShellUtils; - /** * @author qades */ @@ -66,25 +62,22 @@ private boolean satisfied = false; - public String complete(String partial) { - // No completion per default - return partial; + /** + * Perform argument completion on the supplied (partial) argument value. The + * results of the completion should be added to the supplied CompletionInfo. + * <p> + * The default behavior is to return the argument value as a partial completion. + * Subtypes of Argument should override this method if they are capable of doing + * non-trivial completion. Completions should be registered by calling one + * of the 'addCompletion' methods on the CompletionInfo. + * + * @param completion the CompletionInfo object for registering any completions. + * @param partial the argument string to be completed. + */ + public void complete(CompletionInfo completion, String partial) { + completion.addCompletion(partial, true); } - protected String complete(String partial, Collection<String> list) { - if (list.size() == 0) // none found - return partial; - - if (list.size() == 1) return (String) list.iterator().next() + " "; - - // list matching - String[] result = list.toArray(new String[list.size()]); - list(result); - - // return the common part, i.e. complete as much as possible - return common(result); - } - protected final void setValue(String value) { if (isMulti()) { String[] values = new String[ this.values.length + 1]; @@ -133,27 +126,4 @@ public final boolean isSatisfied() { return satisfied; } - - protected String common(String... items) { - if (items.length == 0) - return ""; - - String result = items[ 0]; - for (String item : items) { - while (!item.startsWith(result)) { - // shorten the result until it matches - result = result.substring(0, result.length() - 1); - } - } - return result; - } - - public void list(String... items) { - try { - ShellUtils.getShellManager().getCurrentShell().list(items); - } catch (NameNotFoundException ex) { - // should not happen! - System.err.println("Cannot find current shell: " + ex.getMessage()); - } - } } Modified: trunk/shell/src/shell/org/jnode/shell/help/CommandLineElement.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/help/CommandLineElement.java 2008-03-19 21:22:34 UTC (rev 3858) +++ trunk/shell/src/shell/org/jnode/shell/help/CommandLineElement.java 2008-03-21 08:41:06 UTC (rev 3859) @@ -21,6 +21,8 @@ package org.jnode.shell.help; +import org.jnode.driver.console.CompletionInfo; + /** * @author qades */ @@ -43,7 +45,7 @@ public abstract String format(); public abstract void describe(Help help); - public abstract String complete(String partial); + public abstract void complete(CompletionInfo completion, String partial); /** * Indicates if the element is satisfied. Modified: trunk/shell/src/shell/org/jnode/shell/help/Help.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/help/Help.java 2008-03-19 21:22:34 UTC (rev 3858) +++ trunk/shell/src/shell/org/jnode/shell/help/Help.java 2008-03-21 08:41:06 UTC (rev 3859) @@ -25,6 +25,7 @@ import javax.naming.NamingException; +import org.jnode.driver.console.CompletionInfo; import org.jnode.naming.InitialNaming; import org.jnode.plugin.PluginUtils; import org.jnode.shell.CommandLine; @@ -174,18 +175,17 @@ Help.getHelp().help(this, command); } - public String complete(CommandLine partial) throws CompletionException { + public String complete(CompletionInfo completion, CommandLine partial) + throws CompletionException { // The completion strategy is to try to complete each of the // syntaxes, and return the longest completion string. String max = ""; boolean foundCompletion = false; for (Syntax syntax : syntaxes) { try { - final String s = syntax.complete(partial); + syntax.complete(completion, partial); foundCompletion = true; - if (s.length() > max.length()) { - max = s; - } + } catch (CompletionException ex) { // just try the next syntax } Modified: trunk/shell/src/shell/org/jnode/shell/help/Parameter.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/help/Parameter.java 2008-03-19 21:22:34 UTC (rev 3858) +++ trunk/shell/src/shell/org/jnode/shell/help/Parameter.java 2008-03-21 08:41:06 UTC (rev 3859) @@ -21,6 +21,8 @@ package org.jnode.shell.help; +import org.jnode.driver.console.CompletionInfo; + /** * @author qades */ @@ -104,20 +106,20 @@ argument.describe(help); } - public final String complete(String partial) { - // delegate to argument, merely close the parameter if no argument exists - if (hasArgument()) { - if (Syntax.DEBUG) Syntax.LOGGER.debug("Parameter.complete: argument is " + - argument.format()); - return argument.complete(partial); - } - else { - // FIXME - this assumes that the partial string can never legitimately - // have leading/trailing whitespace. - if (Syntax.DEBUG) Syntax.LOGGER.debug("Parameter.complete: no argument"); - return partial.trim() + " "; + public final void complete(CompletionInfo completion, String partial) { + // delegate to argument, merely close the parameter if no argument exists + if (hasArgument()) { + if (Syntax.DEBUG) Syntax.LOGGER.debug("Parameter.complete: argument is " + + argument.format()); + argument.complete(completion, partial); + } + else { + // FIXME - this assumes that the partial string can never legitimately + // have leading/trailing whitespace. + if (Syntax.DEBUG) Syntax.LOGGER.debug("Parameter.complete: no argument"); + completion.addCompletion(" "); + } } - } public final boolean isSatisfied() { if( !hasArgument() ) Modified: trunk/shell/src/shell/org/jnode/shell/help/Syntax.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/help/Syntax.java 2008-03-19 21:22:34 UTC (rev 3858) +++ trunk/shell/src/shell/org/jnode/shell/help/Syntax.java 2008-03-21 08:41:06 UTC (rev 3859) @@ -27,6 +27,7 @@ import java.util.NoSuchElementException; import org.apache.log4j.Logger; +import org.jnode.driver.console.CompletionInfo; import org.jnode.shell.CommandLine; import org.jnode.shell.help.argument.OptionArgument; @@ -62,9 +63,10 @@ return params; } - public String complete(CommandLine partial) throws CompletionException { + public void complete(CompletionInfo completion, CommandLine partial) + throws CompletionException { Parameter param; - String value; + CommandLine.Token value; int tokenType; if (DEBUG) LOGGER.debug("Syntax.complete: this.description = " + this.description); @@ -81,7 +83,7 @@ partial.isArgumentAnticipated()); if (param != null && partial.isArgumentAnticipated()) { - value = ""; + value = null; tokenType = CommandLine.LITERAL; } else { param = visitor.getLastParam(); @@ -91,29 +93,24 @@ if (param == null) { if (DEBUG) LOGGER.debug("Syntax.complete: no param"); - return ""; + // completion.addCompletion(" "); + return; } if (DEBUG) LOGGER.debug("Syntax.complete: param = " + param.format() + ", value = " + value + ", tokenType = " + tokenType); - String res = ""; if (param.hasArgument()) { - res = param.complete(value); - // FIXME - we need to use the correct escaping syntax ... and ideally - // we need to know what escaping that was used in the original argument - // we are trying to complete. - if (res == null) { - res = param.isAnonymous() ? "" : ("-" + param.getName() + " "); + if (value != null) { + param.complete(completion, value.token); + completion.setCompletionStart(value.start); } - else if (tokenType == CommandLine.STRING) { - res = CommandLine.doEscape(res, true); + else { + param.complete(completion, ""); } } - if (partial.isArgumentAnticipated()) { - res = " " + res; + else if (!param.isAnonymous()) { + completion.addCompletion("-" + param.getName()); } - if (DEBUG) LOGGER.debug("Syntax.complete: returning '" + res + "'"); - return res; } synchronized ParsedArguments parse(CommandLine cmdLine) throws SyntaxErrorException { @@ -151,23 +148,23 @@ final ParameterIterator paramIterator = new ParameterIterator(); // FIXME - should use a Token iterator here ... - final Iterator<String> it = cmdLine.iterator(); + final Iterator<CommandLine.Token> it = cmdLine.tokenIterator(); boolean acceptNames = true; - String s = it.hasNext() ? it.next() : null; - while (s != null) { - if (DEBUG) LOGGER.debug("Syntax.visitor: arg '" + s + "'"); + CommandLine.Token token = it.hasNext() ? it.next() : null; + while (token != null) { + if (DEBUG) LOGGER.debug("Syntax.visitor: arg '" + token + "'"); if (param == null) { // Trying to match a Parameter. - if (acceptNames && "--".equals(s)) { + if (acceptNames && "--".equals(token)) { acceptNames = false; - s = it.hasNext() ? it.next() : null; + token = it.hasNext() ? it.next() : null; } else if (paramIterator.hasNext()) { param = (Parameter) paramIterator.next(); // FIXME real hacky stuff here!! I'm trying to stop anonymous parameters matching // "-name" ... except when they should ... if (param.isAnonymous()) { - if (s.charAt(0) != '-' || param.getArgument() instanceof OptionArgument) { + if (token.token.charAt(0) != '-' || param.getArgument() instanceof OptionArgument) { if (DEBUG) LOGGER.debug("Syntax.visitor: trying anonymous param " + param.format()); visitor.visitParameter(param); } @@ -175,10 +172,10 @@ param = null; } } - else if (acceptNames && s.equals("-" + param.getName())) { + else if (acceptNames && token.equals("-" + param.getName())) { if (DEBUG) LOGGER.debug("Syntax.visitor: trying named param " + param.format()); visitor.visitParameter(param); - s = it.hasNext() ? it.next() : null; + token = it.hasNext() ? it.next() : null; } else { if (DEBUG) LOGGER.debug("Syntax.visitor: skipping named param " + param.format()); @@ -186,8 +183,8 @@ } } else { - if (DEBUG) LOGGER.debug("Syntax.visitor: no param for '" + s + "'"); - throw new SyntaxErrorException("Unexpected argument '" + s + "'"); + if (DEBUG) LOGGER.debug("Syntax.visitor: no param for '" + token + "'"); + throw new SyntaxErrorException("Unexpected argument '" + token + "'"); } } if (param != null) { @@ -197,17 +194,17 @@ if (arg == null) { visitor.visitValue(null, last, CommandLine.LITERAL); } - else if (s != null) { - String value = visitor.visitValue(s, last, CommandLine.LITERAL); + else if (token != null) { + CommandLine.Token value = visitor.visitValue(token, last, CommandLine.LITERAL); if (visitor.isValueValid(arg, value, last)) { - arg.setValue(value); - s = it.hasNext() ? it.next() : null; + arg.setValue(value.token); + token = it.hasNext() ? it.next() : null; } else if (!param.isOptional()) { - if (DEBUG) LOGGER.debug("Syntax.visitor: bad value '" + s + + if (DEBUG) LOGGER.debug("Syntax.visitor: bad value '" + token + "' for mandatory param " + param.format()); throw new SyntaxErrorException("Invalid value for argument"); } else { - if (DEBUG) LOGGER.debug("Syntax.visitor: bad value '" + s + + if (DEBUG) LOGGER.debug("Syntax.visitor: bad value '" + token + "' optional param " + param.format()); if (DEBUG) LOGGER.debug("Syntax.visitor: clearing param"); param = null; @@ -254,14 +251,14 @@ public void visitParameter(Parameter p); - public String visitValue(String s, boolean last, int tokenType); + public CommandLine.Token visitValue(CommandLine.Token token, boolean last, int tokenType); - public boolean isValueValid(Argument arg, String value, boolean last); + public boolean isValueValid(Argument arg, CommandLine.Token value, boolean last); } private class CompletionVisitor implements CommandLineVisitor { private Parameter param = null; - private String value; + private CommandLine.Token value; private int tokenType; private boolean last; @@ -276,20 +273,21 @@ this.tokenType = 0; } - public String visitValue(String s, boolean last, int tokenType) { - if (DEBUG) LOGGER.debug("CompletionVisitor: value = '" + s + "', " + last + ", " + tokenType); + public CommandLine.Token visitValue( + CommandLine.Token token, boolean last, int tokenType) { + if (DEBUG) LOGGER.debug("CompletionVisitor: value = '" + token.token + "', " + last + ", " + tokenType); this.last = last; if (last) { - this.value = s; + this.value = token; this.tokenType = tokenType; } - return s; + return token; } - public boolean isValueValid(Argument arg, String value, boolean last) { + public boolean isValueValid(Argument arg, CommandLine.Token value, boolean last) { if (DEBUG) LOGGER.debug("CompletionVisitor: isValueValid " + arg.format() + ", " + last + ", " + tokenType); - boolean res = last || arg.isValidValue(value); + boolean res = last || arg.isValidValue(value.token); if (DEBUG) LOGGER.debug("CompletionVisitor: isValueValid -> " + res); return res; } @@ -298,7 +296,7 @@ return last ? this.param : null; } - public String getLastValue() { + public CommandLine.Token getLastValue() { return last ? this.value : null; } @@ -320,8 +318,8 @@ this.param = p; } - public String visitValue(String s, boolean last, int tokenType) { - if (last && "".equals(s)) return null; + public CommandLine.Token visitValue(CommandLine.Token s, boolean last, int tokenType) { + if (last && s == null) return null; valued = true; return s; } @@ -345,12 +343,12 @@ valued = false; } - public boolean isValueValid(Argument arg, String value, boolean last) { - return arg.isValidValue(value); + public boolean isValueValid(Argument arg, CommandLine.Token value, boolean last) { + return arg.isValidValue(value.token); } } - class ParameterIterator implements Iterator { + class ParameterIterator implements Iterator<Parameter> { final Parameter[] params = Syntax.this.params; final int length = params.length; @@ -363,7 +361,7 @@ return (nextParamsIdx < length); } - public Object next() { + public Parameter next() { if (nextParamsIdx < length) { return params[nextParamsIdx++]; } else { Modified: trunk/shell/src/shell/org/jnode/shell/help/argument/AliasArgument.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/help/argument/AliasArgument.java 2008-03-19 21:22:34 UTC (rev 3858) +++ trunk/shell/src/shell/org/jnode/shell/help/argument/AliasArgument.java 2008-03-21 08:41:06 UTC (rev 3859) @@ -21,11 +21,9 @@ package org.jnode.shell.help.argument; -import java.util.ArrayList; -import java.util.List; - import javax.naming.NameNotFoundException; +import org.jnode.driver.console.CompletionInfo; import org.jnode.shell.ShellUtils; import org.jnode.shell.alias.AliasManager; import org.jnode.shell.help.Argument; @@ -43,8 +41,7 @@ super(name, description); } - public String complete(String partial) { - final List<String> aliases = new ArrayList<String>(); + public void complete(CompletionInfo completion, String partial) { try { // get the alias manager final AliasManager aliasMgr = ShellUtils.getShellManager() @@ -53,14 +50,12 @@ // collect matching aliases for (String alias : aliasMgr.aliases()) { if (alias.startsWith(partial)) { - aliases.add(alias); + completion.addCompletion(alias); } } - - return complete(partial, aliases); } catch (NameNotFoundException ex) { // should not happen! - return partial; + return; } } } Modified: trunk/shell/src/shell/org/jnode/shell/help/argument/ClassNameArgument.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/help/argument/ClassNameArgument.java 2008-03-19 21:22:34 UTC (rev 3858) +++ trunk/shell/src/shell/org/jnode/shell/help/argument/ClassNameArgument.java 2008-03-21 08:41:06 UTC (rev 3859) @@ -40,7 +40,7 @@ // here the specific command line completion would be implemented - public Class getClass(ParsedArguments cmdLine) throws ClassNotFoundException { + public Class<?> getClass(ParsedArguments cmdLine) throws ClassNotFoundException { final ClassLoader cl = Thread.currentThread().getContextClassLoader(); return cl.loadClass(getValue(cmdLine)); } Modified: trunk/shell/src/shell/org/jnode/shell/help/argument/DeviceArgument.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/help/argument/DeviceArgument.java 2008-03-19 21:22:34 UTC (rev 3858) +++ trunk/shell/src/shell/org/jnode/shell/help/argument/DeviceArgument.java 2008-03-21 08:41:06 UTC (rev 3859) @@ -21,15 +21,13 @@ package org.jnode.shell.help.argument; -import java.util.ArrayList; -import java.util.List; - import javax.naming.NameNotFoundException; import org.jnode.driver.Device; import org.jnode.driver.DeviceAPI; import org.jnode.driver.DeviceManager; import org.jnode.driver.DeviceNotFoundException; +import org.jnode.driver.console.CompletionInfo; import org.jnode.naming.InitialNaming; import org.jnode.shell.help.Argument; import org.jnode.shell.help.ParsedArguments; @@ -71,8 +69,7 @@ } } - public String complete(String partial) { - final List<String> devIds = new ArrayList<String>(); + public void complete(CompletionInfo completion, String partial) { try { // get the alias manager final DeviceManager devMgr = InitialNaming @@ -85,13 +82,12 @@ final String devId = dev.getId(); if (devId.startsWith(partial)) { - devIds.add(devId); + completion.addCompletion(devId); } } - return complete(partial, devIds); } catch (NameNotFoundException ex) { // should not happen! - return partial; + return; } } } Modified: trunk/shell/src/shell/org/jnode/shell/help/argument/EnumOptionArgument.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/help/argument/EnumOptionArgument.java 2008-03-19 21:22:34 UTC (rev 3858) +++ trunk/shell/src/shell/org/jnode/shell/help/argument/EnumOptionArgument.java 2008-03-21 08:41:06 UTC (rev 3859) @@ -21,17 +21,14 @@ package org.jnode.shell.help.argument; -import java.util.ArrayList; -import java.util.List; +import java.lang.reflect.Array; +import org.jnode.driver.console.CompletionInfo; import org.jnode.shell.help.Argument; import org.jnode.shell.help.Help; import org.jnode.shell.help.Parameter; import org.jnode.shell.help.ParsedArguments; -import java.lang.Enum; -import java.lang.reflect.Array; - /** * @author qades */ @@ -61,16 +58,13 @@ option.describe(help); } - public String complete(String partial) { - final List<String> opts = new ArrayList<String>(); + public void complete(CompletionInfo completion, String partial) { for (EnumOption<T> option : options) { final String name = option.getName(); if (name.startsWith(partial)) { - opts.add(name); + completion.addCompletion(name); } } - - return complete(partial, opts); } public final T getEnum(ParsedArguments args, Class<T> type) { @@ -121,7 +115,7 @@ public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("Options: "); - for (EnumOption option : options) { + for (EnumOption<?> option : options) { sb.append(", "); sb.append(option.getName()); } Modified: trunk/shell/src/shell/org/jnode/shell/help/argument/FileArgument.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/help/argument/FileArgument.java 2008-03-19 21:22:34 UTC (rev 3858) +++ trunk/shell/src/shell/org/jnode/shell/help/argument/FileArgument.java 2008-03-21 08:41:06 UTC (rev 3859) @@ -24,10 +24,10 @@ import java.io.File; import java.security.AccessController; import java.security.PrivilegedAction; -import java.util.ArrayList; import java.util.HashSet; import java.util.List; +import org.jnode.driver.console.CompletionInfo; import org.jnode.shell.PathnamePattern; import org.jnode.shell.help.Argument; import org.jnode.shell.help.ParsedArguments; @@ -85,11 +85,11 @@ return files.toArray(new File[files.size()]); } - public String complete(String partial) { + public void complete(CompletionInfo completion, String partial) { // Get last full directory final int idx = partial.lastIndexOf(File.separatorChar); final String dir; - if(idx == 0){ + if (idx == 0) { dir = String.valueOf(File.separatorChar); } else if (idx > 0) { dir = partial.substring(0, idx); @@ -109,28 +109,21 @@ } } }); - if (names == null) { - return partial; - } else if (names.length == 0) { - return partial; - } else { - final ArrayList<String> list = new ArrayList<String>(names.length); + if (names != null && names.length > 0) { final String prefix = (dir.length() == 0) ? "" : dir.equals("/") ? "/" : dir + File.separatorChar; for (String n : names) { - final String name = prefix + n; + String name = prefix + n; if (name.startsWith(partial)) { - list.add(name); + if (new File(f, name).isDirectory()) { + name += File.separatorChar; + completion.addCompletion(name, true); + } + else { + completion.addCompletion(name); + } } } - String completed = complete(partial, list); - if (completed.endsWith(" ")) { - String path = completed.substring(0, completed.length() - 1); - if (new File(path).isDirectory()) { - completed = path + File.separatorChar; - } - } - return completed; } } } Modified: trunk/shell/src/shell/org/jnode/shell/help/argument/HostNameArgument.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/help/argument/HostNameArgument.java 2008-03-19 21:22:34 UTC (rev 3858) +++ trunk/shell/src/shell/org/jnode/shell/help/argument/HostNameArgument.java 2008-03-21 08:41:06 UTC (rev 3859) @@ -21,12 +21,12 @@ package org.jnode.shell.help.argument; +import java.net.InetAddress; +import java.net.UnknownHostException; + import org.jnode.shell.help.Argument; import org.jnode.shell.help.ParsedArguments; -import java.net.InetAddress; -import java.net.UnknownHostException; - /** * @author Martin Hartvig */ Modified: trunk/shell/src/shell/org/jnode/shell/help/argument/InetAddressArgument.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/help/argument/InetAddressArgument.java 2008-03-19 21:22:34 UTC (rev 3858) +++ trunk/shell/src/shell/org/jnode/shell/help/argument/InetAddressArgument.java 2008-03-21 08:41:06 UTC (rev 3859) @@ -21,7 +21,8 @@ package org.jnode.shell.help.argument; -import java.net.*; +import java.net.InetAddress; +import java.net.UnknownHostException; import org.jnode.shell.help.Argument; import org.jnode.shell.help.ParsedArguments; Modified: trunk/shell/src/shell/org/jnode/shell/help/argument/IntegerArgument.java =================================================================== --- trunk/shell/src/sh... [truncated message content] |
From: <ls...@us...> - 2008-03-24 22:07:15
|
Revision: 3880 http://jnode.svn.sourceforge.net/jnode/?rev=3880&view=rev Author: lsantha Date: 2008-03-24 15:07:11 -0700 (Mon, 24 Mar 2008) Log Message: ----------- AWT and SwingPeer improvements. Modified Paths: -------------- trunk/core/src/core/org/jnode/vm/VmSystem.java trunk/core/src/openjdk/javax/javax/swing/RepaintManager.java trunk/gui/src/awt/org/jnode/awt/JNodeToolkit.java trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingBaseWindowPeer.java trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingComponentPeer.java trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingFramePeer.java trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingToolkit.java trunk/gui/src/desktop/org/jnode/desktop/classic/TaskBar.java trunk/gui/src/desktop/org/jnode/desktop/classic/WindowBar.java Modified: trunk/core/src/core/org/jnode/vm/VmSystem.java =================================================================== --- trunk/core/src/core/org/jnode/vm/VmSystem.java 2008-03-24 19:38:41 UTC (rev 3879) +++ trunk/core/src/core/org/jnode/vm/VmSystem.java 2008-03-24 22:07:11 UTC (rev 3880) @@ -328,6 +328,8 @@ //internal classpath for javac res.put("sun.boot.class.path", ":"); + res.put("swing.handleTopLevelPaint", false); + } /** Modified: trunk/core/src/openjdk/javax/javax/swing/RepaintManager.java =================================================================== --- trunk/core/src/openjdk/javax/javax/swing/RepaintManager.java 2008-03-24 19:38:41 UTC (rev 3879) +++ trunk/core/src/openjdk/javax/javax/swing/RepaintManager.java 2008-03-24 22:07:11 UTC (rev 3880) @@ -195,8 +195,8 @@ else { BUFFER_STRATEGY_TYPE = BUFFER_STRATEGY_SPECIFIED_OFF; } - HANDLE_TOP_LEVEL_PAINT = "true".equals(AccessController.doPrivileged( - new GetPropertyAction("swing.handleTopLevelPaint", "true"))); + HANDLE_TOP_LEVEL_PAINT = false; /*jnode "true".equals(AccessController.doPrivileged( + new GetPropertyAction("swing.handleTopLevelPaint", "true")));*/ GraphicsEnvironment ge = GraphicsEnvironment. getLocalGraphicsEnvironment(); if (ge instanceof SunGraphicsEnvironment) { Modified: trunk/gui/src/awt/org/jnode/awt/JNodeToolkit.java =================================================================== --- trunk/gui/src/awt/org/jnode/awt/JNodeToolkit.java 2008-03-24 19:38:41 UTC (rev 3879) +++ trunk/gui/src/awt/org/jnode/awt/JNodeToolkit.java 2008-03-24 22:07:11 UTC (rev 3880) @@ -28,6 +28,7 @@ import gnu.java.security.action.GetPropertyAction; import java.awt.*; +import java.awt.geom.AffineTransform; import java.awt.datatransfer.Clipboard; import java.awt.im.InputMethodHighlight; import java.awt.image.BufferedImage; @@ -628,7 +629,7 @@ for(GraphicsConfiguration g_conf : configurations){ log.info(g_conf); } - String screen_size = (String)AccessController.doPrivileged(new GetPropertyAction("jnode.awt.screensize", "none")); + String screen_size = AccessController.doPrivileged(new GetPropertyAction("jnode.awt.screensize", "none")); if("none".equals(screen_size)) { config = (JNodeGraphicsConfiguration) fbDevice.getDefaultConfiguration(); } else { @@ -657,6 +658,8 @@ screenSize.width = config.getConfig().getScreenWidth(); screenSize.height = config.getConfig().getScreenHeight(); + //drawStartupScreen(); + final EventQueue eventQueue = getSystemEventQueueImpl(); this.keyboardHandler = new KeyboardHandler(eventQueue); this.mouseHandler = new MouseHandler(fbDevice.getDevice(), @@ -688,12 +691,19 @@ return rc; } + private void drawStartupScreen() { + AffineTransform tx = new AffineTransform(); + graphics.fill(new Rectangle(0,0, config.getBounds().width, config.getBounds().height), null, tx, Color.BLACK, Surface.PAINT_MODE); + for(int i = 0; i < 100; i ++) + graphics.draw(new Rectangle(100 + i,100 + i, config.getBounds().width - 2 * (100 + i), config.getBounds().height - 2 * (100 + i)), null, tx, (i % 2 == 0) ? Color.RED : Color.BLUE, Surface.PAINT_MODE); + } + public Dimension changeScreenSize(String screenSizeId) { - final JNodeFrameBufferDevice dev = (JNodeFrameBufferDevice) GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); - if (dev == null) { + final JNodeFrameBufferDevice device = (JNodeFrameBufferDevice) GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); + if (device == null) { throw new AWTError("No framebuffer fbDevice found"); } - GraphicsConfiguration[] configurations = dev.getConfigurations(); + GraphicsConfiguration[] configurations = device.getConfigurations(); JNodeGraphicsConfiguration conf = null; for (GraphicsConfiguration g_conf : configurations) { if (screenSizeId.equals(g_conf.toString())) { @@ -709,7 +719,7 @@ this.config = conf; log.info("Using: " + config); - this.api = dev.getAPI(); + this.api = device.getAPI(); try { float xs = (float) mouseHandler.getX() / (float) screenSize.width; @@ -722,16 +732,17 @@ //open the new this.graphics = api.open(config.getConfig()); if (graphics == null) { - log.debug("No Graphics for fbDevice: " + dev.getIDstring()); + log.debug("No Graphics for fbDevice: " + device.getIDstring()); } screenSize.width = config.getConfig().getScreenWidth(); screenSize.height = config.getConfig().getScreenHeight(); - this.mouseHandler = new MouseHandler(dev.getDevice(), screenSize, getSystemEventQueueImpl(), keyboardHandler); + this.mouseHandler = new MouseHandler(device.getDevice(), screenSize, getSystemEventQueueImpl(), keyboardHandler); mouseHandler.setCursor((int) (xs * screenSize.width), (int) (ys * screenSize.height)); getAwtContext().adjustDesktopSize(screenSize.width, screenSize.height); onResize(); + device.setDefaultConfiguration(this.config); return getScreenSize(); } catch (Exception e) { throw (AWTError) new AWTError(e.getMessage()).initCause(e); Modified: trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingBaseWindowPeer.java =================================================================== --- trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingBaseWindowPeer.java 2008-03-24 19:38:41 UTC (rev 3879) +++ trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingBaseWindowPeer.java 2008-03-24 22:07:11 UTC (rev 3880) @@ -59,9 +59,14 @@ public void run() { final JDesktopPane desktop = toolkit.getAwtContext().getDesktop(); desktop.add(peerComponent); - desktop.setSelectedFrame(peerComponent); - peerComponent.toFront(); - desktop.doLayout(); + try { + peerComponent.setSelected(true); + desktop.getDesktopManager().activateFrame(peerComponent); + peerComponent.toFront(); + desktop.doLayout(); + } catch (PropertyVetoException x){ + log.warn("",x); + } } }); } Modified: trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingComponentPeer.java =================================================================== --- trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingComponentPeer.java 2008-03-24 19:38:41 UTC (rev 3879) +++ trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingComponentPeer.java 2008-03-24 22:07:11 UTC (rev 3880) @@ -339,7 +339,6 @@ public boolean requestFocus(Component lightweightChild, boolean temporary, boolean focusedWindowChangeAllowed, long time, CausedFocusEvent.Cause cause) { peerComponent.requestFocus(); - org.jnode.vm.Unsafe.debug("SwingComponentPeer.requestFocus()\n"); try { Method processSynchronousLightweightTransferMethod = KeyboardFocusManager.class. Modified: trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingFramePeer.java =================================================================== --- trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingFramePeer.java 2008-03-24 19:38:41 UTC (rev 3879) +++ trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingFramePeer.java 2008-03-24 22:07:11 UTC (rev 3880) @@ -39,6 +39,7 @@ super(awtFrame, title); } + /* @Override public void repaint(long tm, int x, int y, int width, int height) { super.repaint(tm, x, y, width, height); @@ -52,10 +53,42 @@ if(target instanceof JFrame && isVisible()) ((JFrame)target).getRootPane().update(g); } + */ @Override + public void setMaximum(boolean b) throws PropertyVetoException { + super.setMaximum(b); + target.setBounds(this.getBounds()); + } + + @Override + public void setIcon(boolean b) throws PropertyVetoException { + super.setIcon(b); + target.setBounds(this.getBounds()); + } + + @Override + public void paintAll(Graphics g) { + super.paintAll(g); + // if(target instanceof JFrame && isVisible()) + // ((JFrame)target).getRootPane().paintAll(g); + } + + @Override + public void paint(Graphics g) { + super.paint(g); + if(target instanceof JFrame && isVisible()){ + JRootPane rp = ((JFrame) target).getRootPane(); + int x = rp.getX(), y = rp.getY(); + g.translate(x,y); + rp.paint(g); + g.translate(-x, -y); + } + } + + @Override protected void paintComponent(Graphics g) { - super.paintComponent(g); //To change body of overridden methods use File | Settings | File Templates. + super.paintComponent(g); } /** @@ -71,6 +104,60 @@ if(target instanceof JFrame) ((JFrame)target).getRootPane().validate(); } + + boolean requestingFocus = false; + @Override + public void requestFocus() { + if(target instanceof JFrame){ + if(!requestingFocus){ + requestingFocus = true; + target.requestFocus(); + requestingFocus = false; + } + } else + super.requestFocus(); + } + + @Override + public boolean requestFocus(boolean temporary) { + if(target instanceof JFrame){ + if(!requestingFocus){ + requestingFocus = true; + target.requestFocus(); + requestingFocus = false; + } + return true; + }else + return super.requestFocus(temporary); + } + + @Override + public boolean requestFocusInWindow() { + if(target instanceof JFrame) { + if(!requestingFocus){ + requestingFocus = true; + boolean ret = target.requestFocusInWindow(); + requestingFocus = false; + return ret; + } + return true; + } else + return super.requestFocusInWindow(); + } + + @Override + protected boolean requestFocusInWindow(boolean temporary) { + if(target instanceof JFrame) { + if(!requestingFocus){ + requestingFocus = true; + boolean ret = target.requestFocusInWindow(); + requestingFocus = false; + return ret; + } + return true; + } else + return super.requestFocusInWindow(temporary); + } } final class NullContentPane extends JComponent { Modified: trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingToolkit.java =================================================================== --- trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingToolkit.java 2008-03-24 19:38:41 UTC (rev 3879) +++ trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingToolkit.java 2008-03-24 22:07:11 UTC (rev 3880) @@ -341,7 +341,7 @@ //no AWT yet, drop the event return null; } - Component comp = desktopFrame.getDesktop().getComponentAt(x,y); + Component comp = desktopFrame.getComponentAt(x,y); if(comp instanceof SwingBaseWindow){ SwingBaseWindow base = (SwingBaseWindow) comp; if(base.isShowing()){ @@ -379,7 +379,7 @@ r.width = r.width - ins.left - ins.right; r.height = r.height - ins.top - ins.bottom; if (r.contains(x, y)) { - Component c = sfp.getAWTComponent().findComponentAt(x, y); + Component c = sfp.getAWTComponent().findComponentAt(x - r.x + ins.left, y - r.y + ins.top); if (c != null) { comp = c; } Modified: trunk/gui/src/desktop/org/jnode/desktop/classic/TaskBar.java =================================================================== --- trunk/gui/src/desktop/org/jnode/desktop/classic/TaskBar.java 2008-03-24 19:38:41 UTC (rev 3879) +++ trunk/gui/src/desktop/org/jnode/desktop/classic/TaskBar.java 2008-03-24 22:07:11 UTC (rev 3880) @@ -25,17 +25,7 @@ import org.jnode.plugin.ExtensionPoint; import org.jnode.awt.JNodeToolkit; -import javax.swing.JButton; -import javax.swing.JLabel; -import javax.swing.JMenu; -import javax.swing.JMenuItem; -import javax.swing.JPanel; -import javax.swing.JPopupMenu; -import javax.swing.SwingUtilities; -import javax.swing.UIManager; -import javax.swing.UnsupportedLookAndFeelException; -import javax.swing.LookAndFeel; -import javax.swing.JCheckBoxMenuItem; +import javax.swing.*; import javax.swing.border.BevelBorder; import javax.swing.border.EmptyBorder; import javax.swing.plaf.metal.DefaultMetalTheme; @@ -83,7 +73,7 @@ layout.setVgap(0); setLayout(layout); setBorder(new BevelBorder(BevelBorder.RAISED)); - startButton = new JButton("Start"); + startButton = new JButton("JNode", new ImageIcon(Desktop.loadImage("jnode_icon.png"))); startButton.setBorder(new EmptyBorder(1, 3, 1, 3)); add(startButton, BorderLayout.WEST); Modified: trunk/gui/src/desktop/org/jnode/desktop/classic/WindowBar.java =================================================================== --- trunk/gui/src/desktop/org/jnode/desktop/classic/WindowBar.java 2008-03-24 19:38:41 UTC (rev 3879) +++ trunk/gui/src/desktop/org/jnode/desktop/classic/WindowBar.java 2008-03-24 22:07:11 UTC (rev 3880) @@ -32,6 +32,7 @@ import javax.swing.JPopupMenu; import javax.swing.JMenuItem; import javax.swing.JDesktopPane; +import javax.swing.DesktopManager; import javax.swing.border.BevelBorder; import javax.swing.event.InternalFrameEvent; import javax.swing.event.InternalFrameListener; @@ -54,10 +55,10 @@ private final Map<JInternalFrame, FrameWrapper> wrappers; public WindowBar() { - FlowLayout layout = new FlowLayout(FlowLayout.LEFT, 2, 3); + FlowLayout layout = new FlowLayout(FlowLayout.LEFT, 1, 1); setLayout(layout); setBorder(new BevelBorder(BevelBorder.LOWERED)); - this.wrappers = new HashMap<JInternalFrame, FrameWrapper>(); + wrappers = new HashMap<JInternalFrame, FrameWrapper>(); } public void addFrame(final JInternalFrame frame) { @@ -92,7 +93,7 @@ private final JInternalFrame frame; /** - * @param iFrame + * @param iFrame the wrapped frame */ public FrameWrapper(JInternalFrame iFrame) { this.frame = iFrame; @@ -100,19 +101,23 @@ this.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { try { - org.jnode.vm.Unsafe.debug("WindowBar.action()\n"); - JInternalFrame frame = FrameWrapper.this.frame; - frame.setIcon(false); - frame.getDesktopPane().setSelectedFrame(frame); - frame.setSelected(true); - frame.toFront(); - frame.requestFocus(); - frame.repaint(); - frame.getDesktopPane().repaint(); + DesktopManager desktopManager = frame.getDesktopPane().getDesktopManager(); + if(frame.isIcon()){ + frame.setIcon(false); + desktopManager.deiconifyFrame(frame); + frame.setSelected(true); + desktopManager.activateFrame(frame); + } else if (frame.isSelected()) { + frame.setSelected(false); + desktopManager.deactivateFrame(frame); + frame.setIcon(true); + desktopManager.iconifyFrame(frame); + } else { + frame.setSelected(true); + desktopManager.activateFrame(frame); + } } catch (PropertyVetoException ex) { - org.jnode.vm.Unsafe.debug("WindowBar.action() - exception\n"); - ex.printStackTrace(); - //igonre + log.warn("", ex); } } }); @@ -169,7 +174,10 @@ minimize.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { try { + if(frame.isMaximum()) + frame.setMaximum(false); frame.setIcon(true); + frame.getDesktopPane().getDesktopManager().iconifyFrame(frame); }catch(PropertyVetoException e){ //ignore } @@ -180,19 +188,40 @@ maximize.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { try { + if (frame.isIcon()) + frame.setIcon(false); frame.setMaximum(true); + frame.getDesktopPane().getDesktopManager().maximizeFrame(frame); }catch(PropertyVetoException e){ //ignore } } }); + JMenuItem restore = new JMenuItem("Restore"); + frameActions.add(restore); + restore.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent event) { + try { + if (frame.isIcon()) + frame.setIcon(false); + if(frame.isMaximum()) + frame.setMaximum(false); + frame.setSelected(true); + frame.getDesktopPane().getDesktopManager().activateFrame(frame); + }catch(PropertyVetoException e){ + //ignore + } + } + }); + JMenuItem close = new JMenuItem("Close"); frameActions.add(close); close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { try { frame.setClosed(true); + frame.getDesktopPane().getDesktopManager().closeFrame(frame); }catch(PropertyVetoException e){ //ignore } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2008-03-25 22:10:54
|
Revision: 3881 http://jnode.svn.sourceforge.net/jnode/?rev=3881&view=rev Author: lsantha Date: 2008-03-25 15:10:53 -0700 (Tue, 25 Mar 2008) Log Message: ----------- AWT and SwingPeer improvements. Modified Paths: -------------- trunk/core/src/openjdk/vm/java/awt/image/NativeBufferedImage.java Added Paths: ----------- trunk/core/src/openjdk/vm/java/awt/image/NativeColorModel.java trunk/core/src/openjdk/vm/java/awt/image/NativeComponentSampleModel.java trunk/core/src/openjdk/vm/java/awt/image/NativeIndexColorModel.java trunk/core/src/openjdk/vm/java/awt/image/NativeKernel.java trunk/core/src/openjdk/vm/java/awt/image/NativeRaster.java trunk/core/src/openjdk/vm/java/awt/image/NativeSampleModel.java trunk/core/src/openjdk/vm/java/awt/image/NativeSinglePixelPackedSampleModel.java trunk/gui/images/jnode_icon.png Modified: trunk/core/src/openjdk/vm/java/awt/image/NativeBufferedImage.java =================================================================== --- trunk/core/src/openjdk/vm/java/awt/image/NativeBufferedImage.java 2008-03-24 22:07:11 UTC (rev 3880) +++ trunk/core/src/openjdk/vm/java/awt/image/NativeBufferedImage.java 2008-03-25 22:10:53 UTC (rev 3881) @@ -9,6 +9,6 @@ * @see java.awt.image.BufferedImage#initIDs() */ private static void initIDs() { - //todo implement it + //empty } } Added: trunk/core/src/openjdk/vm/java/awt/image/NativeColorModel.java =================================================================== --- trunk/core/src/openjdk/vm/java/awt/image/NativeColorModel.java (rev 0) +++ trunk/core/src/openjdk/vm/java/awt/image/NativeColorModel.java 2008-03-25 22:10:53 UTC (rev 3881) @@ -0,0 +1,13 @@ +package java.awt.image; + +/** + * @see java.awt.image.ColorModel + */ +class NativeColorModel { + /** + * @see java.awt.image.ColorModel#initIDs() + */ + private static void initIDs() { + //empty + } +} Added: trunk/core/src/openjdk/vm/java/awt/image/NativeComponentSampleModel.java =================================================================== --- trunk/core/src/openjdk/vm/java/awt/image/NativeComponentSampleModel.java (rev 0) +++ trunk/core/src/openjdk/vm/java/awt/image/NativeComponentSampleModel.java 2008-03-25 22:10:53 UTC (rev 3881) @@ -0,0 +1,13 @@ +package java.awt.image; + +/** + * @see java.awt.image.ComponentSampleModel + */ +class NativeComponentSampleModel { + /** + * @see java.awt.image.ComponentSampleModel#initIDs() + */ + private static void initIDs() { + //empty + } +} Added: trunk/core/src/openjdk/vm/java/awt/image/NativeIndexColorModel.java =================================================================== --- trunk/core/src/openjdk/vm/java/awt/image/NativeIndexColorModel.java (rev 0) +++ trunk/core/src/openjdk/vm/java/awt/image/NativeIndexColorModel.java 2008-03-25 22:10:53 UTC (rev 3881) @@ -0,0 +1,13 @@ +package java.awt.image; + +/** + * @see java.awt.image.IndexColorModel + */ +class NativeIndexColorModel { + /** + * @see java.awt.image.IndexColorModel#initIDs() + */ + private static void initIDs() { + //empty + } +} Added: trunk/core/src/openjdk/vm/java/awt/image/NativeKernel.java =================================================================== --- trunk/core/src/openjdk/vm/java/awt/image/NativeKernel.java (rev 0) +++ trunk/core/src/openjdk/vm/java/awt/image/NativeKernel.java 2008-03-25 22:10:53 UTC (rev 3881) @@ -0,0 +1,13 @@ +package java.awt.image; + +/** + * @see java.awt.image.Kernel + */ +class NativeKernel { + /** + * @see java.awt.image.Kernel#initIDs() + */ + private static void initIDs() { + //empty + } +} Added: trunk/core/src/openjdk/vm/java/awt/image/NativeRaster.java =================================================================== --- trunk/core/src/openjdk/vm/java/awt/image/NativeRaster.java (rev 0) +++ trunk/core/src/openjdk/vm/java/awt/image/NativeRaster.java 2008-03-25 22:10:53 UTC (rev 3881) @@ -0,0 +1,13 @@ +package java.awt.image; + +/** + * @see java.awt.image.Raster + */ +class NativeRaster { + /** + * @see java.awt.image.Raster#initIDs() + */ + private static void initIDs() { + //empty + } +} Added: trunk/core/src/openjdk/vm/java/awt/image/NativeSampleModel.java =================================================================== --- trunk/core/src/openjdk/vm/java/awt/image/NativeSampleModel.java (rev 0) +++ trunk/core/src/openjdk/vm/java/awt/image/NativeSampleModel.java 2008-03-25 22:10:53 UTC (rev 3881) @@ -0,0 +1,13 @@ +package java.awt.image; + +/** + * @see java.awt.image.SampleModel + */ +class NativeSampleModel { + /** + * @see java.awt.image.SampleModel#initIDs() + */ + private static void initIDs() { + //empty + } +} Added: trunk/core/src/openjdk/vm/java/awt/image/NativeSinglePixelPackedSampleModel.java =================================================================== --- trunk/core/src/openjdk/vm/java/awt/image/NativeSinglePixelPackedSampleModel.java (rev 0) +++ trunk/core/src/openjdk/vm/java/awt/image/NativeSinglePixelPackedSampleModel.java 2008-03-25 22:10:53 UTC (rev 3881) @@ -0,0 +1,13 @@ +package java.awt.image; + +/** + * @see java.awt.image.SinglePixelPackedSampleModel + */ +class NativeSinglePixelPackedSampleModel { + /** + * @see java.awt.image.SinglePixelPackedSampleModel#initIDs() + */ + private static void initIDs() { + //empty + } +} Added: trunk/gui/images/jnode_icon.png =================================================================== (Binary files differ) Property changes on: trunk/gui/images/jnode_icon.png ___________________________________________________________________ Name: svn:mime-type + application/octet-stream This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cr...@us...> - 2008-04-05 05:00:21
|
Revision: 3933 http://jnode.svn.sourceforge.net/jnode/?rev=3933&view=rev Author: crawley Date: 2008-04-04 22:00:18 -0700 (Fri, 04 Apr 2008) Log Message: ----------- Deal with unset 'completionStart' in a more central place. Modified Paths: -------------- trunk/core/src/driver/org/jnode/driver/console/textscreen/Line.java trunk/shell/src/shell/org/jnode/shell/CommandShell.java Modified: trunk/core/src/driver/org/jnode/driver/console/textscreen/Line.java =================================================================== --- trunk/core/src/driver/org/jnode/driver/console/textscreen/Line.java 2008-04-05 04:50:35 UTC (rev 3932) +++ trunk/core/src/driver/org/jnode/driver/console/textscreen/Line.java 2008-04-05 05:00:18 UTC (rev 3933) @@ -170,7 +170,12 @@ String completion = info.getCompletion(); if (completion != null) { int startPos = info.getCompletionStart(); - setContent(currentLine.substring(0, startPos) + completion + ending); + if (startPos == -1) { + setContent(currentLine.substring(0, posOnCurrentLine) + completion + ending); + } + else { + setContent(currentLine.substring(0, startPos) + completion + ending); + } // (This is the updated line's length ...) posOnCurrentLine = currentLine.length() - ending.length(); } Modified: trunk/shell/src/shell/org/jnode/shell/CommandShell.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/CommandShell.java 2008-04-05 04:50:35 UTC (rev 3932) +++ trunk/shell/src/shell/org/jnode/shell/CommandShell.java 2008-04-05 05:00:18 UTC (rev 3933) @@ -599,9 +599,6 @@ Completable cl = parseCommandLine(partial); if (cl != null) { cl.complete(completion, this); - if (completion.getCompletionStart() == -1) { - completion.setCompletionStart(partial.length()); - } } } catch (ShellSyntaxException ex) { out.println(); // next line This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cr...@us...> - 2008-04-06 15:09:58
|
Revision: 3942 http://jnode.svn.sourceforge.net/jnode/?rev=3942&view=rev Author: crawley Date: 2008-04-06 08:09:55 -0700 (Sun, 06 Apr 2008) Log Message: ----------- CompileCommand uses new LoadCompilerService method to get highest opt level. CompileCommand does more rigorous checks on the --level and --test args. Modified Paths: -------------- trunk/core/src/core/org/jnode/vm/LoadCompileService.java trunk/shell/src/shell/org/jnode/shell/command/CompileCommand.java Modified: trunk/core/src/core/org/jnode/vm/LoadCompileService.java =================================================================== --- trunk/core/src/core/org/jnode/vm/LoadCompileService.java 2008-04-06 15:07:36 UTC (rev 3941) +++ trunk/core/src/core/org/jnode/vm/LoadCompileService.java 2008-04-06 15:09:55 UTC (rev 3942) @@ -76,6 +76,17 @@ enableTestCompilers)); } } + + /** + * Get the highest supported optimization level for the regular or test compilers. + */ + public static int getHighestOptimizationLevel(boolean test) { + if (test) { + return service.testCompilers == null ? -1 : service.testCompilers.length - 1; + } else { + return service.compilers == null ? -1 : service.compilers.length - 1; + } + } /** * @see org.jnode.vm.classmgr.VmClassLoader#defineClass(java.lang.String, Modified: trunk/shell/src/shell/org/jnode/shell/command/CompileCommand.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/command/CompileCommand.java 2008-04-06 15:07:36 UTC (rev 3941) +++ trunk/shell/src/shell/org/jnode/shell/command/CompileCommand.java 2008-04-06 15:09:55 UTC (rev 3942) @@ -30,8 +30,7 @@ import org.jnode.shell.syntax.ClassNameArgument; import org.jnode.shell.syntax.FlagArgument; import org.jnode.shell.syntax.IntegerArgument; -import org.jnode.vm.VmArchitecture; -import org.jnode.vm.VmMagic; +import org.jnode.vm.LoadCompileService; import org.jnode.vm.classmgr.VmType; /** @@ -39,13 +38,11 @@ * @author cr...@jn... */ public class CompileCommand extends AbstractCommand { - // FIXME ... something should exposed the maximum compiler optimization levels - // via getter methods. The code below gives "MagicPermission is not granted ..." - private final VmArchitecture arch = VmMagic.currentProcessor().getArchitecture(); - private final Object[] compilers = arch.getCompilers(); - private final Object[] testCompilers = arch.getTestCompilers(); - private final int maxLevel = Math.max( - compilers.length, (testCompilers == null) ? 0 : testCompilers.length) - 1; + private final int maxTestLevel = + LoadCompileService.getHighestOptimizationLevel(true); + private final int maxNontestLevel = + LoadCompileService.getHighestOptimizationLevel(false); + private final int maxLevel = Math.max(maxTestLevel, maxNontestLevel); private final ClassNameArgument ARG_CLASS = new ClassNameArgument("classname", Argument.MANDATORY, "the class file to compile"); @@ -71,6 +68,21 @@ final int level = ARG_LEVEL.isSet() ? ARG_LEVEL.getValue() : 0; final boolean test = ARG_TEST.isSet(); + if (test) { + if (maxTestLevel == -1) { + err.println("No test compilers are currently registered"); + exit(1); + } + else if (maxTestLevel < level) { + err.println("The highest (test) optimization level is " + maxTestLevel); + exit(1); + } + } + else if (maxNontestLevel < level) { + err.println("The highest optimization level is " + maxNontestLevel); + exit(1); + } + final ClassLoader cl = Thread.currentThread().getContextClassLoader(); final Class<?> cls; try { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cr...@us...> - 2008-04-19 13:04:02
|
Revision: 3980 http://jnode.svn.sourceforge.net/jnode/?rev=3980&view=rev Author: crawley Date: 2008-04-19 06:03:58 -0700 (Sat, 19 Apr 2008) Log Message: ----------- Implement a mechanism for setting and clearing heap control flags. Initially the mechanism is being used for turning on/off Unsafe.debug tracing. The flags are set and cleared using new options for the 'gc' command. Modified Paths: -------------- trunk/core/src/core/org/jnode/vm/memmgr/VmHeapManager.java trunk/core/src/core/org/jnode/vm/memmgr/def/DefaultHeapManager.java trunk/core/src/core/org/jnode/vm/memmgr/def/GCManager.java trunk/shell/descriptors/org.jnode.shell.command.xml trunk/shell/src/shell/org/jnode/shell/command/GcCommand.java Modified: trunk/core/src/core/org/jnode/vm/memmgr/VmHeapManager.java =================================================================== --- trunk/core/src/core/org/jnode/vm/memmgr/VmHeapManager.java 2008-04-19 13:01:33 UTC (rev 3979) +++ trunk/core/src/core/org/jnode/vm/memmgr/VmHeapManager.java 2008-04-19 13:03:58 UTC (rev 3980) @@ -46,11 +46,23 @@ */ @MagicPermission public abstract class VmHeapManager extends VmSystemObject { + + public static int TRACE_BASIC = 1; // enable basic debugging of GC phases + public static int TRACE_ALLOC = 2; // enable debugging of GC internal allocation + public static int TRACE_TRIGGER = 4; // enable debugging of GC triggering / scheduling + public static int TRACE_OOM = 8; // enable debugging of OOM events + public static int TRACE_AD_HOC = 16; // enable ad hoc debugging + public static int TRACE_FLAGS = 31; // all of the above /** * Has this manager been initialized yet */ private boolean inited = false; + + /** + * The current debug flags + */ + protected int heapFlags = TRACE_BASIC | TRACE_OOM | TRACE_ALLOC; protected OutOfMemoryError OOME; @@ -114,7 +126,9 @@ final Object obj = allocObject((VmNormalClass< ? >) cls, size); if (obj == null) { - Unsafe.debug("Out of memory"); + if ((heapFlags & TRACE_OOM) != 0) { + debug("Out of memory"); + } throw OOME; } return obj; @@ -170,7 +184,9 @@ arrayCls.incTotalLength(elements); final Object obj = newArray0(arrayCls, elemSize, elements, slotSize); if (obj == null) { - Unsafe.debug("Out of memory"); + if ((heapFlags & TRACE_OOM) != 0) { + debug("Out of memory"); + } throw OOME; } @@ -349,4 +365,43 @@ */ public abstract void loadClasses(VmClassLoader loader) throws ClassNotFoundException; + + /** + * Get this heap's current flags + * @return the flags + */ + public int getHeapFlags() { + return heapFlags; + } + + /** + * Set this heap's flags + * @param reapFlags the new heap flags + * @return the previous heap flags + */ + public int setHeapFlags(int reapFlags) { + int res = this.heapFlags; + this.heapFlags = reapFlags; + return res; + } + + /** + * Output a debug message controlled by the heap trace flags. + * @param text + */ + public void debug(String text) { + if ((heapFlags & TRACE_FLAGS) != 0) { + Unsafe.debug(text); + } + } + + /** + * Output a debug message controlled by the heap trace flags. + * @param text + */ + protected void debug(int number) { + if ((heapFlags & TRACE_FLAGS) != 0) { + Unsafe.debug(number); + } + } } Modified: trunk/core/src/core/org/jnode/vm/memmgr/def/DefaultHeapManager.java =================================================================== --- trunk/core/src/core/org/jnode/vm/memmgr/def/DefaultHeapManager.java 2008-04-19 13:01:33 UTC (rev 3979) +++ trunk/core/src/core/org/jnode/vm/memmgr/def/DefaultHeapManager.java 2008-04-19 13:03:58 UTC (rev 3980) @@ -294,8 +294,10 @@ } try { if (gcActive) { - Unsafe.debug("Using GC Heap type"); - Unsafe.debug(vmClass.getName()); + if ((heapFlags & TRACE_ALLOC) != 0) { + debug("Using GC Heap type "); + debug(vmClass.getName()); + } result = gcHeap.alloc(vmClass, alignedSize); if (result == null) { helper.die("Out of GC heap memory."); @@ -322,14 +324,18 @@ // in this allocation, then we're in real panic. if (oomCount == 0) { oomCount++; - Unsafe.debug("<oom/>"); + if ((heapFlags & TRACE_OOM) != 0) { + debug("<oom/>"); + } gcThread.trigger(true); heap = firstNormalHeap; currentHeap = firstNormalHeap; } else { - Unsafe.debug("Out of memory in allocObject("); - Unsafe.debug(size); - Unsafe.debug(")"); + if ((heapFlags & TRACE_OOM) != 0) { + debug("Out of memory in allocObject("); + debug(size); + debug(")"); + } throw OOME; // Unsafe.die(); } @@ -353,7 +359,9 @@ allocatedSinceGcTrigger += alignedSize; if ((allocatedSinceGcTrigger > triggerSize) && (gcThread != null)) { - Unsafe.debug("<alloc:GC trigger/>"); + if ((heapFlags & TRACE_TRIGGER) != 0) { + debug("<alloc:GC trigger/>"); + } allocatedSinceGcTrigger = 0; gcThread.trigger(false); } Modified: trunk/core/src/core/org/jnode/vm/memmgr/def/GCManager.java =================================================================== --- trunk/core/src/core/org/jnode/vm/memmgr/def/GCManager.java 2008-04-19 13:01:33 UTC (rev 3979) +++ trunk/core/src/core/org/jnode/vm/memmgr/def/GCManager.java 2008-04-19 13:03:58 UTC (rev 3980) @@ -29,6 +29,7 @@ import org.jnode.vm.annotation.MagicPermission; import org.jnode.vm.memmgr.GCStatistics; import org.jnode.vm.memmgr.HeapHelper; +import org.jnode.vm.memmgr.VmHeapManager; import org.vmmagic.pragma.Uninterruptible; import org.vmmagic.unboxed.Word; @@ -94,7 +95,7 @@ stats.lastGCTime = System.currentTimeMillis(); final boolean locking = (writeBarrier != null); - final boolean verbose = debug; + final boolean verbose = (heapManager.getHeapFlags() & VmHeapManager.TRACE_BASIC) != 0; helper.stopThreadsAtSafePoint(); heapManager.setGcActive(true); try { @@ -103,7 +104,7 @@ //heapManager.setGcActive(true); try { if (verbose) { - Unsafe.debug("<mark/>"); + heapManager.debug("<mark/>"); } markHeap(bootHeap, firstHeap, locking); } finally { @@ -113,20 +114,20 @@ // Sweep if (verbose) { - Unsafe.debug("<sweep/>"); + heapManager.debug("<sweep/>"); } sweep(firstHeap); // Cleanup if (verbose) { - Unsafe.debug("<cleanup/>"); + heapManager.debug("<cleanup/>"); } cleanup(bootHeap, firstHeap); // Verification if (debug) { if (verbose) { - Unsafe.debug("<verify/>"); + heapManager.debug("<verify/>"); } if (false) { // Turn back to true in case of problems in the GC. Modified: trunk/shell/descriptors/org.jnode.shell.command.xml =================================================================== --- trunk/shell/descriptors/org.jnode.shell.command.xml 2008-04-19 13:01:33 UTC (rev 3979) +++ trunk/shell/descriptors/org.jnode.shell.command.xml 2008-04-19 13:03:58 UTC (rev 3980) @@ -103,7 +103,18 @@ </sequence> </syntax> <syntax alias="exit" description="Exit the current shell"/> - <syntax alias="gc" description="Run the garbage collector"/> + <syntax alias="gc"> + <empty description="Run the garbage collector"/> + <sequence description="Set heap debug flags"> + <option argLabel="set" longName="set"/> + <repeat minCount="1"><argument argLabel="debugFlag"/></repeat> + </sequence> + <sequence description="Clear heap debug flags"> + <option argLabel="clear" longName="clear"/> + <repeat minCount="1"><argument argLabel="debugFlag"/></repeat> + </sequence> + <option argLabel="show" longName="show" description="Show heap debug flags"/> + </syntax> <syntax alias="set"> <sequence description="Set a system property"> <argument argLabel="key"/> Modified: trunk/shell/src/shell/org/jnode/shell/command/GcCommand.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/command/GcCommand.java 2008-04-19 13:01:33 UTC (rev 3979) +++ trunk/shell/src/shell/org/jnode/shell/command/GcCommand.java 2008-04-19 13:03:58 UTC (rev 3980) @@ -26,17 +26,57 @@ import org.jnode.shell.AbstractCommand; import org.jnode.shell.CommandLine; +import org.jnode.shell.syntax.Argument; +import org.jnode.shell.syntax.EnumArgument; +import org.jnode.shell.syntax.FlagArgument; import org.jnode.util.NumberUtils; import org.jnode.vm.Vm; import org.jnode.vm.memmgr.GCStatistics; +import org.jnode.vm.memmgr.VmHeapManager; /** * @author epr + * @author cr...@jn... */ public class GcCommand extends AbstractCommand { + + private enum HeapFlag { + TRACE_BASIC(VmHeapManager.TRACE_BASIC), + TRACE_ALLOC(VmHeapManager.TRACE_ALLOC), + TRACE_TRIGGER(VmHeapManager.TRACE_TRIGGER), + TRACE_OOM(VmHeapManager.TRACE_OOM), + TRACE_AD_HOC(VmHeapManager.TRACE_AD_HOC), + all(-1); // All flags + + public final int flagBit; + + private HeapFlag(int flagBit) { + this.flagBit = flagBit; + } + } + + private class HeapDebugFlagArgument extends EnumArgument<HeapFlag> { + public HeapDebugFlagArgument() { + super("debugFlag", Argument.OPTIONAL | Argument.MULTIPLE, + HeapFlag.class, "the heap debug flags"); + } + @Override + protected String argumentKind() { + return "debug flag"; + } + } + + private final HeapDebugFlagArgument ARG_DEBUG_FLAGS = new HeapDebugFlagArgument(); + private final FlagArgument ARG_SET = + new FlagArgument("set", Argument.OPTIONAL, "set these debug flags"); + private final FlagArgument ARG_CLEAR = + new FlagArgument("clear", Argument.OPTIONAL, "clear these debug flags"); + private final FlagArgument ARG_SHOW = + new FlagArgument("show", Argument.OPTIONAL, "show the debug flags"); public GcCommand() { super("Run the garbage collector"); + registerArguments(ARG_DEBUG_FLAGS, ARG_CLEAR, ARG_SET, ARG_SHOW); } public static void main(String[] args) throws Exception { @@ -47,23 +87,63 @@ * Execute this command */ public void execute(CommandLine cmdLine, InputStream in, PrintStream out, PrintStream err) - throws Exception { - - final Runtime rt = Runtime.getRuntime(); - out.println("Memory size: " + NumberUtils.toBinaryByte(rt.totalMemory())); - out.println("Free memory: " + NumberUtils.toBinaryByte(rt.freeMemory())); - - out.println("Starting gc..."); - long start = System.currentTimeMillis(); - rt.gc(); - GCStatistics stats = Vm.getHeapManager().getStatistics(); - Thread.yield(); - long end = System.currentTimeMillis(); - - out.println("Memory size: " + NumberUtils.toBinaryByte(rt.totalMemory())); - out.println("Free memory: " + NumberUtils.toBinaryByte(rt.freeMemory())); - out.println("Time taken : " + (end-start) + "ms"); - out.println("Stats : " + stats.toString()); + throws Exception { + if (ARG_SET.isSet()) { + Vm.getHeapManager().setHeapFlags(getFlags()); + } + else if (ARG_CLEAR.isSet()) { + int flags = Vm.getHeapManager().getHeapFlags() ^ getFlags(); + Vm.getHeapManager().setHeapFlags(flags); + } + else if (ARG_SHOW.isSet()) { + showFlags(Vm.getHeapManager().getHeapFlags(), out); + } + else { + final Runtime rt = Runtime.getRuntime(); + out.println("Memory size: " + NumberUtils.toBinaryByte(rt.totalMemory())); + out.println("Free memory: " + NumberUtils.toBinaryByte(rt.freeMemory())); + + out.println("Starting gc..."); + long start = System.currentTimeMillis(); + rt.gc(); + GCStatistics stats = Vm.getHeapManager().getStatistics(); + Thread.yield(); + long end = System.currentTimeMillis(); + + out.println("Memory size: " + NumberUtils.toBinaryByte(rt.totalMemory())); + out.println("Free memory: " + NumberUtils.toBinaryByte(rt.freeMemory())); + out.println("Time taken : " + (end-start) + "ms"); + out.println("Stats : " + stats.toString()); + } } + private void showFlags(int flags, PrintStream out) { + StringBuilder sb = new StringBuilder(); + for (int flagBitMask = 1; flagBitMask != 0; flagBitMask = flagBitMask << 1) { + if ((flags & flagBitMask) != 0) { + for (HeapFlag hf : HeapFlag.values()) { + if (hf.flagBit == flagBitMask) { + sb.append(' ').append(hf.name()); + break; + } + } + } + } + if (sb.length() == 0) { + out.println("No heap debug flags set"); + } + else { + out.println("Heap debug flags:" + sb.toString()); + } + } + + private int getFlags() { + int debugFlags = 0; + if (ARG_DEBUG_FLAGS.isSet()) { + for (HeapFlag flag : ARG_DEBUG_FLAGS.getValues()) { + debugFlags |= flag.flagBit; + } + } + return debugFlags; + } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fd...@us...> - 2008-04-27 10:11:57
|
Revision: 4029 http://jnode.svn.sourceforge.net/jnode/?rev=4029&view=rev Author: fduminy Date: 2008-04-27 03:11:54 -0700 (Sun, 27 Apr 2008) Log Message: ----------- - fixed some bugs in kernel.asm data area - removed multiboot_infos data area + UnsafeX86.getMultibootInfos() Modified Paths: -------------- trunk/core/src/core/org/jnode/vm/x86/UnsafeX86.java trunk/core/src/native/x86/kernel.asm trunk/core/src/native/x86/unsafex86.asm trunk/gui/src/driver/org/jnode/driver/video/vesa/VESADriver.java Modified: trunk/core/src/core/org/jnode/vm/x86/UnsafeX86.java =================================================================== --- trunk/core/src/core/org/jnode/vm/x86/UnsafeX86.java 2008-04-27 07:09:02 UTC (rev 4028) +++ trunk/core/src/core/org/jnode/vm/x86/UnsafeX86.java 2008-04-27 10:11:54 UTC (rev 4029) @@ -79,7 +79,6 @@ public static final native Address getVbeInfos(); public static final native Address getVbeControlInfos(); public static final native Address getVbeModeInfos(); - public static final native Address getMultibootInfos(); /** * Merge 32-bit ARGB values at the given memory address. Modified: trunk/core/src/native/x86/kernel.asm =================================================================== --- trunk/core/src/native/x86/kernel.asm 2008-04-27 07:09:02 UTC (rev 4028) +++ trunk/core/src/native/x86/kernel.asm 2008-04-27 10:11:54 UTC (rev 4029) @@ -45,9 +45,6 @@ multiboot_ok: ; Copy the multiboot info block cld -%ifdef SETUP_VBE - mov [multiboot_infos], ebx -%endif mov esi,ebx mov edi,multiboot_info mov ecx,MBI_SIZE @@ -317,17 +314,11 @@ %ifdef SETUP_VBE multiboot_vbe: - dd 0 ; Entries times (VBE_ESIZE) db 0 vbe_control_info: - dd 0 ; Entries times (VBECTRLINFO_SIZE) db 0 vbe_mode_info: - dd 0 ; Entries times (VBEMODEINFO_SIZE) db 0 - -multiboot_infos: - dd 0 %endif \ No newline at end of file Modified: trunk/core/src/native/x86/unsafex86.asm =================================================================== --- trunk/core/src/native/x86/unsafex86.asm 2008-04-27 07:09:02 UTC (rev 4028) +++ trunk/core/src/native/x86/unsafex86.asm 2008-04-27 10:11:54 UTC (rev 4029) @@ -112,16 +112,6 @@ %endif ret -; Address getMultibootInfos(); -GLABEL Q53org5jnode2vm3x869UnsafeX8623getMultibootInfos2e2829Lorg2fvmmagic2funboxed2fAddress3b -%ifdef SETUP_VBE - mov AAX,multiboot_infos -%endif -%ifndef SETUP_VBE - mov AAX,0 -%endif - ret - ; void setupBootCode(Address memory, int[] gdtBase, int[] tss); GLABEL Q53org5jnode2vm3x869UnsafeX8623setupBootCode2e28Lorg2fvmmagic2funboxed2fAddress3b5bI5bI29V push ABX Modified: trunk/gui/src/driver/org/jnode/driver/video/vesa/VESADriver.java =================================================================== --- trunk/gui/src/driver/org/jnode/driver/video/vesa/VESADriver.java 2008-04-27 07:09:02 UTC (rev 4028) +++ trunk/gui/src/driver/org/jnode/driver/video/vesa/VESADriver.java 2008-04-27 10:11:54 UTC (rev 4029) @@ -120,15 +120,13 @@ Unsafe.debug("\nbegin VESADriver.startDevice"); System.err.println("\nbegin VESADriver.startDevice"); try { - Address multibootInfos = UnsafeX86.getMultibootInfos(); - Unsafe.debug("\nmultibootInfos="+NumberUtils.hex(multibootInfos.toInt())); - Address vbeControlInfo = UnsafeX86.getVbeControlInfos(); VbeInfoBlock vbeInfoBlock = new VbeInfoBlock(vbeControlInfo); if(vbeInfoBlock.isEmpty()) { throw new DriverException("can't start device (vbeInfoBlock is empty): grub haven't switched to graphic mode"); } + Unsafe.debug("vbeInfoBlock="+vbeInfoBlock); Address vbeModeInfo = UnsafeX86.getVbeModeInfos(); ModeInfoBlock modeInfoBlock = new ModeInfoBlock(vbeModeInfo); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cr...@us...> - 2008-05-02 14:32:14
|
Revision: 4039 http://jnode.svn.sourceforge.net/jnode/?rev=4039&view=rev Author: crawley Date: 2008-05-02 07:32:13 -0700 (Fri, 02 May 2008) Log Message: ----------- Changed low level console out/err streams from PrintStreams to OutputStreams. Added support for interception of console output to Shell / CommandShell. (Required to make 'udpout' work without messing with System.out/err.) Modified Paths: -------------- trunk/core/src/driver/org/jnode/driver/console/TextConsole.java trunk/core/src/driver/org/jnode/driver/console/textscreen/KeyboardInputStream.java trunk/core/src/driver/org/jnode/driver/console/textscreen/TextScreenConsolePlugin.java trunk/shell/src/shell/org/jnode/shell/CommandRunner.java trunk/shell/src/shell/org/jnode/shell/CommandShell.java trunk/shell/src/shell/org/jnode/shell/Shell.java trunk/shell/src/shell/org/jnode/shell/command/driver/console/ConsoleCommand.java Modified: trunk/core/src/driver/org/jnode/driver/console/TextConsole.java =================================================================== --- trunk/core/src/driver/org/jnode/driver/console/TextConsole.java 2008-05-02 14:26:52 UTC (rev 4038) +++ trunk/core/src/driver/org/jnode/driver/console/TextConsole.java 2008-05-02 14:32:13 UTC (rev 4039) @@ -22,6 +22,7 @@ package org.jnode.driver.console; import java.io.InputStream; +import java.io.OutputStream; import java.io.PrintStream; /** @@ -166,13 +167,13 @@ * Gets the error stream of this console. * @return */ - public PrintStream getErr(); + public OutputStream getErr(); /** * Gets the output stream of this console. * @return */ - public PrintStream getOut(); + public OutputStream getOut(); /** * Is the cursor visible. Modified: trunk/core/src/driver/org/jnode/driver/console/textscreen/KeyboardInputStream.java =================================================================== --- trunk/core/src/driver/org/jnode/driver/console/textscreen/KeyboardInputStream.java 2008-05-02 14:26:52 UTC (rev 4038) +++ trunk/core/src/driver/org/jnode/driver/console/textscreen/KeyboardInputStream.java 2008-05-02 14:32:13 UTC (rev 4039) @@ -106,7 +106,7 @@ } } this.console = console; - this.out = console.getOut(); + this.out = new PrintStream(console.getOut()); this.currentLine = new Line(console); this.pos = this.lim = 0; } Modified: trunk/core/src/driver/org/jnode/driver/console/textscreen/TextScreenConsolePlugin.java =================================================================== --- trunk/core/src/driver/org/jnode/driver/console/textscreen/TextScreenConsolePlugin.java 2008-05-02 14:26:52 UTC (rev 4038) +++ trunk/core/src/driver/org/jnode/driver/console/textscreen/TextScreenConsolePlugin.java 2008-05-02 14:32:13 UTC (rev 4039) @@ -21,6 +21,8 @@ package org.jnode.driver.console.textscreen; +import java.io.PrintStream; + import javax.naming.NamingException; import org.jnode.driver.console.ConsoleException; @@ -60,9 +62,9 @@ (ConsoleManager.CreateOptions.TEXT | ConsoleManager.CreateOptions.SCROLLABLE)); mgr.focus(first); - System.setOut(first.getOut()); - System.setErr(first.getErr()); - first.getOut().println(VmSystem.getBootLog()); + System.setOut(new PrintStream(first.getOut())); + System.setErr(new PrintStream(first.getErr())); + System.out.println(VmSystem.getBootLog()); } catch (ConsoleException ex) { throw new PluginException(ex); } catch (NamingException ex) { Modified: trunk/shell/src/shell/org/jnode/shell/CommandRunner.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/CommandRunner.java 2008-05-02 14:26:52 UTC (rev 4038) +++ trunk/shell/src/shell/org/jnode/shell/CommandRunner.java 2008-05-02 14:32:13 UTC (rev 4039) @@ -126,10 +126,10 @@ invoker.unblock(); } catch (SyntaxErrorException ex) { try { - Help.getInfo(cmdInfo.getCommandClass()).usage(shell.getConsole().getErr()); - shell.getConsole().getErr().println(ex.getMessage()); + Help.getInfo(cmdInfo.getCommandClass()).usage(shell.getErr()); + shell.getErr().println(ex.getMessage()); } catch (HelpException e) { - shell.getConsole().getErr().println("Exception while trying to get the command usage"); + shell.getErr().println("Exception while trying to get the command usage"); stackTrace(ex); } invoker.unblock(); @@ -137,11 +137,11 @@ setRC(ex.getStatus()); invoker.unblock(); } catch (Exception ex) { - shell.getConsole().getErr().println("Exception in command"); + shell.getErr().println("Exception in command"); stackTrace(ex); invoker.unblock(); } catch (Throwable ex) { - shell.getConsole().getErr().println("Fatal error in command"); + shell.getErr().println("Fatal error in command"); stackTrace(ex); invoker.unblock(); } @@ -161,7 +161,7 @@ void stackTrace(Throwable ex) { if (ex != null && isDebugEnabled()) { - ex.printStackTrace(shell.getConsole().getErr()); + ex.printStackTrace(shell.getErr()); } } Modified: trunk/shell/src/shell/org/jnode/shell/CommandShell.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/CommandShell.java 2008-05-02 14:26:52 UTC (rev 4038) +++ trunk/shell/src/shell/org/jnode/shell/CommandShell.java 2008-05-02 14:32:13 UTC (rev 4039) @@ -91,10 +91,14 @@ */ private static final Logger log = Logger.getLogger(CommandShell.class); - private PrintStream out; + private OutputStream out; + + private OutputStream err; + + private PrintStream outPs; + + private PrintStream errPs; - private PrintStream err; - private InputStream in; private AliasManager aliasMgr; @@ -178,6 +182,8 @@ console = cons; out = console.getOut(); err = console.getErr(); + outPs = new PrintStream(out); + errPs = new PrintStream(err); in = console.getIn(); SystemInputStream.getInstance().initialize(this.in); cons.setCompleter(this); @@ -197,8 +203,11 @@ PrintStream out, PrintStream err) throws ShellException { try { this.console = console; + // FIXME ... kludging the OutputStreams. this.out = out; this.err = err; + this.outPs = out; + this.errPs = err; this.in = in; SystemInputStream.getInstance().initialize(this.in); // cons.setCompleter(this); @@ -223,8 +232,8 @@ protected CommandShell(AliasManager aliasMgr, SyntaxManager syntaxMgr) { this.aliasMgr = aliasMgr; this.syntaxMgr = syntaxMgr; - this.err = System.err; - this.out = System.out; + this.errPs = System.err; + this.outPs = System.out; this.readingCommand = true; this.debugEnabled = true; } @@ -271,11 +280,11 @@ try { if (e.startsWith(COMMAND_KEY)) { final String cmd = e.substring(COMMAND_KEY.length()); - out.println(prompt() + cmd); + outPs.println(prompt() + cmd); processCommand(cmd, false); } } catch (Throwable ex) { - err.println("Error while processing bootarg commands: " + errPs.println("Error while processing bootarg commands: " + ex.getMessage()); stackTrace(ex); } @@ -291,7 +300,7 @@ runCommandFile(shell_ini); } } catch (IOException ex) { - err.println("Error while reading " + shell_ini + ": " + errPs.println("Error while reading " + shell_ini + ": " + ex.getMessage()); stackTrace(ex); } @@ -304,7 +313,7 @@ refreshFromProperties(); clearEof(); - out.print(prompt()); + outPs.print(prompt()); readingCommand = true; String line = readInputLine().trim(); if (line.length() > 0) { @@ -315,7 +324,7 @@ exited = true; } } catch (Throwable ex) { - err.println("Uncaught exception while processing command(s): " + errPs.println("Uncaught exception while processing command(s): " + ex.getMessage()); stackTrace(ex); } @@ -331,7 +340,7 @@ setCommandInvoker(System.getProperty(INVOKER_PROPERTY_NAME, INITIAL_INVOKER)); } catch (Exception ex) { - err.println(ex.getMessage()); + errPs.println(ex.getMessage()); stackTrace(ex); // Use the fallback invoker setCommandInvoker(FALLBACK_INVOKER); @@ -340,7 +349,7 @@ setCommandInterpreter(System.getProperty(INTERPRETER_PROPERTY_NAME, INITIAL_INTERPRETER)); } catch (Exception ex) { - err.println(ex.getMessage()); + errPs.println(ex.getMessage()); stackTrace(ex); // Use the fallback interpreter setCommandInterpreter(FALLBACK_INTERPRETER); @@ -356,13 +365,13 @@ setCommandInterpreter(System.getProperty(INTERPRETER_PROPERTY_NAME, "")); } catch (Exception ex) { - err.println(ex.getMessage()); + errPs.println(ex.getMessage()); stackTrace(ex); } try { setCommandInvoker(System.getProperty(INVOKER_PROPERTY_NAME, "")); } catch (Exception ex) { - err.println(ex.getMessage()); + errPs.println(ex.getMessage()); stackTrace(ex); } } @@ -371,7 +380,7 @@ throws IllegalArgumentException { if (!name.equals(this.invokerName)) { this.invoker = ShellUtils.createInvoker(name, this); - err.println("Switched to " + name + " invoker"); + errPs.println("Switched to " + name + " invoker"); this.invokerName = name; System.setProperty(INVOKER_PROPERTY_NAME, name); } @@ -381,7 +390,7 @@ throws IllegalArgumentException { if (!name.equals(this.interpreterName)) { this.interpreter = ShellUtils.createInterpreter(name); - err.println("Switched to " + name + " interpreter"); + errPs.println("Switched to " + name + " interpreter"); this.interpreterName = name; System.setProperty(INTERPRETER_PROPERTY_NAME, name); } @@ -389,7 +398,7 @@ private void stackTrace(Throwable ex) { if (this.debugEnabled) { - ex.printStackTrace(err); + ex.printStackTrace(errPs); } } @@ -423,7 +432,7 @@ try { rc = interpreter.interpret(this, cmdLineStr); } catch (ShellException ex) { - err.println("Shell exception: " + ex.getMessage()); + errPs.println("Shell exception: " + ex.getMessage()); rc = -1; stackTrace(ex); } @@ -604,13 +613,13 @@ cl.complete(completion, this); } } catch (ShellSyntaxException ex) { - out.println(); // next line - err.println("Cannot parse: " + ex.getMessage()); + outPs.println(); // next line + errPs.println("Cannot parse: " + ex.getMessage()); stackTrace(ex); } catch (CompletionException ex) { - out.println(); // next line - err.println("Problem in completer: " + ex.getMessage()); + outPs.println(); // next line + errPs.println("Problem in completer: " + ex.getMessage()); stackTrace(ex); } @@ -710,7 +719,7 @@ public int runCommandFile(File file) throws IOException { if (!file.exists()) { - err.println("File does not exist: " + file); + errPs.println("File does not exist: " + file); return -1; } try { @@ -727,7 +736,7 @@ try { rc = invokeCommand(line); } catch (ShellException ex) { - err.println("Shell exception: " + ex.getMessage()); + errPs.println("Shell exception: " + ex.getMessage()); stackTrace(ex); } } @@ -786,9 +795,9 @@ if (stream == CommandLine.DEFAULT_STDIN) { return getInputStream(); } else if (stream == CommandLine.DEFAULT_STDOUT) { - return out; + return outPs; } else if (stream == CommandLine.DEFAULT_STDERR) { - return err; + return errPs; } else if (stream == CommandLine.DEVNULL || stream == null) { return input ? new NullInputStream() : new NullOutputStream(); } else { @@ -830,4 +839,28 @@ public SyntaxManager getSyntaxManager() { return syntaxMgr; } + + public PrintStream getErr() { + return errPs; + } + + @Override + public void addConsoleOuputRecorder(OutputStream os) { + // FIXME do security check + if (out == null || err == null) { + throw new UnsupportedOperationException( + "Cannot intercept console output for this shell instance"); + } + if (out instanceof FanoutOutputStream) { + ((FanoutOutputStream) out).addStream(os); + ((FanoutOutputStream) err).addStream(os); + } + else { + out = new FanoutOutputStream(true, out, os); + outPs = new PrintStream(out); + err = new FanoutOutputStream(true, err, os); + errPs = new PrintStream(err); + } + errPs.println("Testing"); + } } Modified: trunk/shell/src/shell/org/jnode/shell/Shell.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/Shell.java 2008-05-02 14:26:52 UTC (rev 4038) +++ trunk/shell/src/shell/org/jnode/shell/Shell.java 2008-05-02 14:32:13 UTC (rev 4039) @@ -23,6 +23,7 @@ import java.io.File; import java.io.IOException; +import java.io.OutputStream; import org.jnode.driver.console.Console; import org.jnode.driver.console.InputCompleter; @@ -52,6 +53,13 @@ public InputHistory getCommandHistory(); /** + * Record all console output from the shell and commands launched by the shell. + * + * @param os The stream for recording output. + */ + public void addConsoleOuputRecorder(OutputStream os); + + /** * Returns the console where the shell is running. * @return the console */ Modified: trunk/shell/src/shell/org/jnode/shell/command/driver/console/ConsoleCommand.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/command/driver/console/ConsoleCommand.java 2008-05-02 14:26:52 UTC (rev 4038) +++ trunk/shell/src/shell/org/jnode/shell/command/driver/console/ConsoleCommand.java 2008-05-02 14:32:13 UTC (rev 4039) @@ -21,6 +21,8 @@ package org.jnode.shell.command.driver.console; +import java.io.PrintStream; + import javax.isolate.Isolate; import javax.isolate.IsolateStartupException; import javax.naming.NameNotFoundException; @@ -121,8 +123,8 @@ final ConsoleManager conMgr = sm.getCurrentShell().getConsole().getManager(); TextConsole console = createConsoleWithShell(conMgr); System.setIn(console.getIn()); - System.setOut(console.getOut()); - System.setErr(console.getErr()); + System.setOut(new PrintStream(console.getOut())); + System.setErr(new PrintStream(console.getErr())); } catch (Exception ex) { // FIXME @@ -149,11 +151,12 @@ String invokerName = System.getProperty(CommandShell.INVOKER_PROPERTY_NAME, ""); // FIXME this is a temporary hack until we decide what to do about these invokers if ("thread".equals(invokerName) || "default".equals(invokerName)) { - console.getErr().println( + PrintStream err = new PrintStream(console.getErr()); + err.println( "Warning: any commands run in this console via their main(String[]) will " + "have the 'wrong' System.out and System.err."); - console.getErr().println("The 'proclet' invoker should give better results."); - console.getErr().println("To use it, type 'exit', run 'set jnode.invoker proclet' " + + err.println("The 'proclet' invoker should give better results."); + err.println("To use it, type 'exit', run 'set jnode.invoker proclet' " + "in the F1 console and run 'console -n' again."); } return console; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fd...@us...> - 2008-05-03 14:41:26
|
Revision: 4048 http://jnode.svn.sourceforge.net/jnode/?rev=4048&view=rev Author: fduminy Date: 2008-05-03 07:41:25 -0700 (Sat, 03 May 2008) Log Message: ----------- AnnotateTask improvement : added a properties file for storing annotated classes timestamps Modified Paths: -------------- trunk/all/build.xml trunk/builder/src/builder/org/jnode/ant/taskdefs/AnnotateTask.java Modified: trunk/all/build.xml =================================================================== --- trunk/all/build.xml 2008-05-03 14:37:29 UTC (rev 4047) +++ trunk/all/build.xml 2008-05-03 14:41:25 UTC (rev 4048) @@ -721,13 +721,14 @@ </cp-compare> </target> - <!-- add annotations to compiled openjdk classes --> - <target name="openjdk-annotate" depends="assemble-projects"> + <target name="openjdk-annotate" depends="assemble-projects" + description="add annotations to compiled openjdk classes"> <echo message="openjdk-annotate"/> <taskdef name="oj-annotate" classname="org.jnode.ant.taskdefs.AnnotateTask" classpathref="cp-jnode"/> <oj-annotate annotationFile="${root.dir}/all/conf/openjdk-annotations.properties" + timestampFile="${build.dir}/timestamps.properties" trace="false" failonerror="true"> <fileset dir="${root.dir}/core/build/classes"> <patternset includes="**/*.class"/> Modified: trunk/builder/src/builder/org/jnode/ant/taskdefs/AnnotateTask.java =================================================================== --- trunk/builder/src/builder/org/jnode/ant/taskdefs/AnnotateTask.java 2008-05-03 14:37:29 UTC (rev 4047) +++ trunk/builder/src/builder/org/jnode/ant/taskdefs/AnnotateTask.java 2008-05-03 14:41:25 UTC (rev 4048) @@ -27,15 +27,15 @@ import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.Properties; -import java.util.List; -import java.util.ArrayList; import org.apache.tools.ant.BuildException; -import java.util.StringTokenizer; - import org.jnode.vm.annotation.MagicPermission; import org.jnode.vm.annotation.SharedStatics; import org.objectweb.asm.Attribute; @@ -52,10 +52,10 @@ /** * That ant task will add some annotations to some compiled classes * mentioned in a property file. - * For now, it's only necessary to add SharedStatics annotations to some + * For now, it's only necessary to add annotations to some * openjdk classes to avoid modifying the original source code. * - * @author Fabien DUMINY (fduminy at jnode.org) + * @author Fabien DUMINY (fduminy at jnode dot org) * */ public class AnnotateTask extends FileSetTask { @@ -63,39 +63,119 @@ private static final String MAGICPERMISSION_TYPE_DESC = Type.getDescriptor(MagicPermission.class); private File annotationFile; + private File timestampFile; private String[] classesFiles; - private Properties properties; + private Properties timestamps = new Properties(); + private Properties annotations = new Properties(); protected void doExecute() throws BuildException { - if(readProperties(annotationFile)) + try { - processFiles(); + if(readProperties()) + { + processFiles(); + } } + finally + { + saveTimestamps(); + } } - public final File getAnnotationFile() { - return annotationFile; - } - + /** + * Defines the annotation property file where are specified annotations to add + * @param annotationFile + */ public final void setAnnotationFile(File annotationFile) { this.annotationFile = annotationFile; } /** + * Defines the timestamp property file that is used to know if a class file + * has been recompiled since the annotation has been added + * (in such case, the annotation is lost and must be added again) + * + * @param timestampFile + */ + public final void setTimestampFile(File timestampFile) { + this.timestampFile = timestampFile; + } + + /** + * Save the new timestamps in a property file + */ + private void saveTimestamps() + { + FileOutputStream fos = null; + try + { + fos = new FileOutputStream(timestampFile); + timestamps.store(fos, "Here are the timestamps for classes with added annotations"); + } catch (IOException e) { + throw new BuildException(e); + } + finally + { + if(fos != null) + { + try { + fos.close(); + } catch (IOException e) { + throw new BuildException(e); + } + } + } + } + + /** * Read the properties file. For now, it simply contains a list of * classes that need the SharedStatics annotation. * * @return * @throws BuildException */ - private boolean readProperties(File file) throws BuildException + private boolean readProperties() throws BuildException { + readProperties("timestampFile", timestampFile, timestamps); + + readProperties("annotationFile", annotationFile, annotations); + if(annotations.isEmpty()) + { + System.err.println("WARNING: annotationFile is empty (or doesn't exist)"); + return false; + } + + classesFiles = (String[]) annotations.keySet().toArray(new String[annotations.size()]); + + // we must sort the classes in reverse order so that + // classes with longest package name will be used first + // (that is only necessary for classes whose name is the same + // but package is different ; typical such class name : "Constants") + Arrays.sort(classesFiles, Collections.reverseOrder()); + + return true; + } + + /** + * Generic method that read properties from a given file. + * + * @param name + * @param file + * @param properties + * @throws BuildException + */ + private void readProperties(String name, File file, Properties properties) throws BuildException + { if(file == null) { - throw new BuildException("annotationFile is mandatory"); + throw new BuildException(name + " is mandatory"); } + + if(!file.exists()) + { + return; + } - properties = new Properties(); FileInputStream fis = null; try { @@ -115,32 +195,23 @@ } } } - if(properties.isEmpty()) - { - System.err.println("WARNING: annotationFile is empty"); - return false; - } + } - classesFiles = (String[]) properties.keySet().toArray(new String[properties.size()]); - - // we must sort the classes in reverse order so that - // classes with longest package name will be used first - // (that is only necessary for classes whose name is the same - // but package is different ; typical such class name : "Constants") - Arrays.sort(classesFiles, Collections.reverseOrder()); - - return true; - } - - private String getAnnotations(File file) + /** + * Get the list of annotations for the given class file. + * + * @param classFile list of annotations with ',' as separator. null if no annotation for that class. + * @return + */ + private String getAnnotations(File classFile) { String annotations = null; - String filePath = file.getAbsolutePath(); + String classFilePath = classFile.getAbsolutePath(); for(String f : classesFiles) { - if(filePath.endsWith(f)) + if(classFilePath.endsWith(f)) { - annotations = properties.getProperty(f); + annotations = this.annotations.getProperty(f); break; } } @@ -148,22 +219,32 @@ return annotations; } + /** + * Actually process a class file (called from parent class) + */ @Override - protected void processFile(File file) throws IOException { - String annotations = getAnnotations(file); + protected void processFile(File classFile) throws IOException { + String annotations = getAnnotations(classFile); if(annotations == null) { return; } - File tmpFile = new File(file.getParentFile(), file.getName()+".tmp"); + long timestamp = Long.valueOf(timestamps.getProperty(classFile.getName(), "0")).longValue(); + if(classFile.lastModified() <= timestamp) + { + System.out.println("Skipping already annotated file "+classFile.getName()); + return; + } + + File tmpFile = new File(classFile.getParentFile(), classFile.getName()+".tmp"); FileInputStream fis = null; boolean classIsModified = false; try { - fis = new FileInputStream(file); - classIsModified = addAnnotation(file.getName(), fis, tmpFile, annotations); + fis = new FileInputStream(classFile); + classIsModified = addAnnotation(classFile, fis, tmpFile, annotations); } finally { @@ -177,21 +258,23 @@ { if(trace) { - traceClass(file, "before"); + traceClass(classFile, "before"); traceClass(tmpFile, "after"); } - if(!file.delete()) + if(!classFile.delete()) { - throw new IOException("can't delete "+file.getAbsolutePath()); + throw new IOException("can't delete "+classFile.getAbsolutePath()); } - if(!tmpFile.renameTo(file)) + if(!tmpFile.renameTo(classFile)) { throw new IOException("can't rename "+tmpFile.getAbsolutePath()); } } + + timestamps.setProperty(classFile.getName(), Long.toString(classFile.lastModified())); } /** @@ -224,7 +307,17 @@ System.out.println("----- end trace -----"); } - private boolean addAnnotation(String fileName, InputStream inputClass, File tmpFile, String annotations) throws BuildException { + /** + * Add an annotation to a class file + * + * @param classFile + * @param inputClass + * @param tmpFile + * @param annotations + * @return + * @throws BuildException + */ + private boolean addAnnotation(File classFile, InputStream inputClass, File tmpFile, String annotations) throws BuildException { boolean classIsModified = false; FileOutputStream outputClass = null; @@ -247,7 +340,7 @@ if(mcv.classIsModified()) { - System.out.println("adding annotations "+annotations+" to file "+fileName); + System.out.println("adding annotations "+annotations+" to file "+classFile.getName()); classIsModified = true; outputClass = new FileOutputStream(tmpFile); @@ -257,7 +350,7 @@ } } catch (Exception ex) { ex.printStackTrace(); - throw new BuildException("Unable to add annotations to file "+fileName, ex); + throw new BuildException("Unable to add annotations to file "+classFile.getName(), ex); } finally { @@ -266,14 +359,23 @@ try { outputClass.close(); } catch (IOException e) { - System.err.println("Can't close stream for file "+fileName); + System.err.println("Can't close stream for file "+classFile.getName()); } + + long timestamp = classFile.lastModified(); + tmpFile.setLastModified(timestamp); } } return classIsModified; } + /** + * Visitor for a class file that actually do the job of adding annotations in the class. + * + * @author fabien + * + */ private static class MarkerClassVisitor extends ClassAdapter { final private List<String> annotationTypeDescs; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |