From: <cr...@us...> - 2008-11-16 02:53:12
|
Revision: 4703 http://jnode.svn.sourceforge.net/jnode/?rev=4703&view=rev Author: crawley Date: 2008-11-16 02:53:07 +0000 (Sun, 16 Nov 2008) Log Message: ----------- Overhaul the help subsystem to make it easier to hook in ESC help, and support anticipated future developments. This also addresses a previously unnoticed problem where HelpCommand triggered class loading for all known aliases, and improves diagnostics for class load failure. This checkin will probably break 'old' syntax command completion (see issue #2802) but AFAIK, there are no extant commands using the 'old' syntax mechanism. Modified Paths: -------------- trunk/distr/src/emu/org/jnode/emu/Emu.java trunk/shell/src/shell/org/jnode/shell/CommandLine.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/DefaultCommandInvoker.java trunk/shell/src/shell/org/jnode/shell/command/HelpCommand.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/argument/EnumOptionArgument.java trunk/shell/src/shell/org/jnode/shell/help/argument/OptionArgument.java trunk/shell/src/shell/org/jnode/shell/help/def/SystemHelpPlugin.java trunk/shell/src/test/org/jnode/test/shell/Cassowary.java trunk/shell/src/test/org/jnode/test/shell/help/DefaultHelpTest.java trunk/shell/src/test/org/jnode/test/shell/syntax/AlternativesSyntaxTest.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 Added Paths: ----------- trunk/shell/src/shell/org/jnode/shell/help/EnhancedHelp.java trunk/shell/src/shell/org/jnode/shell/help/HelpFactory.java trunk/shell/src/shell/org/jnode/shell/help/def/DefaultHelpFactory.java trunk/shell/src/shell/org/jnode/shell/help/def/NewSyntaxHelp.java trunk/shell/src/shell/org/jnode/shell/help/def/OldSyntaxHelp.java trunk/shell/src/shell/org/jnode/shell/help/def/TextHelpBase.java Removed Paths: ------------- trunk/shell/src/shell/org/jnode/shell/help/def/DefaultHelp.java Modified: trunk/distr/src/emu/org/jnode/emu/Emu.java =================================================================== --- trunk/distr/src/emu/org/jnode/emu/Emu.java 2008-11-12 13:47:18 UTC (rev 4702) +++ trunk/distr/src/emu/org/jnode/emu/Emu.java 2008-11-16 02:53:07 UTC (rev 4703) @@ -19,8 +19,8 @@ import org.jnode.shell.alias.AliasManager; import org.jnode.shell.alias.def.DefaultAliasManager; import org.jnode.shell.def.DefaultShellManager; -import org.jnode.shell.help.Help; -import org.jnode.shell.help.def.DefaultHelp; +import org.jnode.shell.help.HelpFactory; +import org.jnode.shell.help.def.DefaultHelpFactory; import org.jnode.shell.syntax.DefaultSyntaxManager; import org.jnode.shell.syntax.SyntaxBundle; import org.jnode.shell.syntax.SyntaxManager; @@ -93,7 +93,7 @@ InitialNaming.bind(AliasManager.NAME, aliasMgr); InitialNaming.bind(ShellManager.NAME, new DefaultShellManager()); InitialNaming.bind(SyntaxManager.NAME, syntaxMgr); - InitialNaming.bind(Help.NAME, new DefaultHelp()); + InitialNaming.bind(HelpFactory.NAME, new DefaultHelpFactory()); } catch (NamingException ex) { throw new EmuException("Problem setting up InitialNaming bindings", ex); } Modified: trunk/shell/src/shell/org/jnode/shell/CommandLine.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/CommandLine.java 2008-11-12 13:47:18 UTC (rev 4702) +++ trunk/shell/src/shell/org/jnode/shell/CommandLine.java 2008-11-16 02:53:07 UTC (rev 4703) @@ -27,6 +27,7 @@ import org.jnode.shell.help.CompletionException; import org.jnode.shell.help.Help; import org.jnode.shell.help.HelpException; +import org.jnode.shell.help.HelpFactory; import org.jnode.shell.help.Parameter; import org.jnode.shell.io.CommandIO; import org.jnode.shell.io.CommandIOMarker; @@ -643,7 +644,7 @@ } else { // Otherwise, try old-style completion using the command's INFO try { - Help.Info info = Help.getInfo(cmdClass.getCommandClass()); + Help.Info info = HelpFactory.getInfo(cmdClass.getCommandClass()); info.complete(completion, this, shell.getOut()); } catch (HelpException ex) { // And fall back to old-style completion with an 'info' that Modified: trunk/shell/src/shell/org/jnode/shell/CommandRunner.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/CommandRunner.java 2008-11-12 13:47:18 UTC (rev 4702) +++ trunk/shell/src/shell/org/jnode/shell/CommandRunner.java 2008-11-16 02:53:07 UTC (rev 4703) @@ -30,7 +30,7 @@ import java.security.AccessController; import java.security.PrivilegedActionException; -import org.jnode.shell.help.Help; +import org.jnode.shell.help.HelpFactory; import org.jnode.shell.help.HelpException; import org.jnode.shell.help.SyntaxErrorException; import org.jnode.shell.io.CommandIO; @@ -144,7 +144,7 @@ } } catch (SyntaxErrorException ex) { try { - Help.getInfo(cmdInfo.getCommandClass()).usage(shellErr); + HelpFactory.getInfo(cmdInfo.getCommandClass()).usage(shellErr); shellErr.println(ex.getMessage()); } catch (HelpException e) { shellErr.println("Exception while trying to get the command usage"); Modified: trunk/shell/src/shell/org/jnode/shell/CommandShell.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/CommandShell.java 2008-11-12 13:47:18 UTC (rev 4702) +++ trunk/shell/src/shell/org/jnode/shell/CommandShell.java 2008-11-16 02:53:07 UTC (rev 4703) @@ -55,7 +55,6 @@ import org.jnode.naming.InitialNaming; import org.jnode.shell.alias.AliasManager; import org.jnode.shell.alias.NoSuchAliasException; -import org.jnode.shell.help.CompletionException; import org.jnode.shell.io.CommandIO; import org.jnode.shell.io.CommandInput; import org.jnode.shell.io.CommandInputOutput; Modified: trunk/shell/src/shell/org/jnode/shell/DefaultCommandInvoker.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/DefaultCommandInvoker.java 2008-11-12 13:47:18 UTC (rev 4702) +++ trunk/shell/src/shell/org/jnode/shell/DefaultCommandInvoker.java 2008-11-16 02:53:07 UTC (rev 4703) @@ -30,7 +30,7 @@ import java.security.PrivilegedAction; import java.security.PrivilegedActionException; -import org.jnode.shell.help.Help; +import org.jnode.shell.help.HelpFactory; import org.jnode.shell.help.SyntaxErrorException; import org.jnode.shell.io.CommandIO; import org.jnode.vm.VmExit; @@ -117,7 +117,7 @@ } } } catch (SyntaxErrorException ex) { - Help.getInfo(cmdInfo.getCommandClass()).usage(err); + HelpFactory.getInfo(cmdInfo.getCommandClass()).usage(err); err.println(ex.getMessage()); } catch (VmExit ex) { return ex.getStatus(); Modified: trunk/shell/src/shell/org/jnode/shell/command/HelpCommand.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/command/HelpCommand.java 2008-11-12 13:47:18 UTC (rev 4702) +++ trunk/shell/src/shell/org/jnode/shell/command/HelpCommand.java 2008-11-16 02:53:07 UTC (rev 4703) @@ -26,18 +26,17 @@ import javax.naming.NameNotFoundException; import org.jnode.shell.AbstractCommand; +import org.jnode.shell.CommandInfo; import org.jnode.shell.CommandLine; -import org.jnode.shell.Shell; +import org.jnode.shell.CommandShell; import org.jnode.shell.ShellUtils; import org.jnode.shell.alias.AliasManager; import org.jnode.shell.alias.NoSuchAliasException; import org.jnode.shell.help.Help; +import org.jnode.shell.help.HelpFactory; import org.jnode.shell.help.HelpException; import org.jnode.shell.syntax.AliasArgument; import org.jnode.shell.syntax.Argument; -import org.jnode.shell.syntax.ArgumentBundle; -import org.jnode.shell.syntax.SyntaxBundle; -import org.jnode.shell.syntax.SyntaxManager; /** * @author qades @@ -59,7 +58,9 @@ } @Override - public void execute() throws Exception { + public void execute() throws NameNotFoundException, ClassNotFoundException, NoSuchAliasException { + // The above exceptions are either bugs or configuration errors and should be allowed + // to propagate so that the shell can diagnose them appropriately. String alias; CommandLine commandLine = getCommandLine(); PrintWriter out = getOutput().getPrintWriter(); @@ -71,108 +72,53 @@ } else { alias = "help"; } - - Help.Info info = null; - SyntaxBundle syntaxes = null; - ArgumentBundle bundle = null; - String otherAliases = null; + CommandShell shell = null; try { - final Shell shell = ShellUtils.getShellManager().getCurrentShell(); - final AliasManager aliasManager = shell.getAliasManager(); - final SyntaxManager syntaxManager = shell.getSyntaxManager(); - Class<?> clazz = getCommandClass(aliasManager, alias); - bundle = getBundle(clazz, err); - if (bundle != null) { - syntaxes = syntaxManager.getSyntaxBundle(alias); - if (syntaxes == null) { - syntaxes = new SyntaxBundle(alias, bundle.createDefaultSyntax()); - } - } else { - info = Help.getInfo(clazz); - } - if (info != null || syntaxes != null) { - otherAliases = getOtherAliases(aliasManager, alias, clazz); - } - } catch (ClassNotFoundException ex) { - err.println("Alias not found: " + alias); - exit(1); - } catch (SecurityException ex) { - err.println("Access to class prevented by security manager"); - exit(2); - } catch (NameNotFoundException ex) { - err.println("Can't find the shell manager"); - exit(2); + shell = (CommandShell) ShellUtils.getShellManager().getCurrentShell(); + CommandInfo cmdInfo = shell.getCommandInfo(alias); + Help cmdHelp = HelpFactory.getHelpFactory().getHelp(alias, shell.getCommandInfo(alias)); + cmdHelp.help(out); + otherAliases(shell.getAliasManager(), alias, cmdInfo.getCommandClass().getName(), out); } catch (HelpException ex) { - err.println("No help information available for alias " + alias); + err.println("No help information is available for alias / class '" + alias + "'"); exit(1); + } catch (ClassNotFoundException ex) { + try { + String className = shell.getAliasManager().getAliasClassName(alias); + err.println("Cannot load class '" + className + "' for alias '" + alias + "'"); + } catch (NoSuchAliasException ex2) { + err.println("'" + alias + "' is neither an alias or a loadable class name"); + } + throw ex; + } catch (SecurityException ex) { + err.println("Security exception while loading the class associated with alias '" + alias + "'"); + err.println("Reported reason: " + ex.getLocalizedMessage()); + throw ex; } - - if (syntaxes != null) { - Help.getHelp().help(syntaxes, bundle, out); - } else if (info != null) { - Help.getHelp().help(info, alias, out); - } else { - out.println("No help information available: " + alias); - } - if (otherAliases != null) { - out.println(otherAliases); - } } - private ArgumentBundle getBundle(Class<?> clazz, PrintWriter err) { - try { - AbstractCommand command = (AbstractCommand) clazz.newInstance(); - return command.getArgumentBundle(); - } catch (ClassCastException e) { - // The target class cannot - } catch (InstantiationException e) { - err.println("Problem during instantiation of " + clazz.getName()); - exit(2); - } catch (IllegalAccessException e) { - err.println("Constructor for " + clazz.getName() + " is not accessible"); - exit(2); - } - return null; - } + private void otherAliases(AliasManager aliasManager, String thisAlias, + String aliasClass, PrintWriter out) throws NoSuchAliasException { + // NoSuchAliasException indicates a bug, and should be allowed to propagate. + StringBuilder sb = new StringBuilder(); - private Class<?> getCommandClass(AliasManager aliasManager, String commandName) - throws ClassNotFoundException { - try { - return aliasManager.getAliasClass(commandName); - } catch (NoSuchAliasException ex) { - // Not an alias -> assuming it's a class name - return Class.forName(commandName); - } - } - - private String getOtherAliases(AliasManager aliasManager, String alias, Class<?> aliasClass) { - boolean hasOtherAlias = false; - StringBuilder sb = new StringBuilder("Other aliases: "); - boolean first = true; - for (String otherAlias : aliasManager.aliases()) { - // exclude alias from the returned list - if (!otherAlias.equals(alias)) { - try { - Class<?> otherAliasClass = aliasManager.getAliasClass(otherAlias); - - if (aliasClass.equals(otherAliasClass)) { - // we have found another alias for the same command - hasOtherAlias = true; - if (!first) { - sb.append(","); - } - sb.append(otherAlias); - first = false; + // exclude thisAlias from the output + if (!otherAlias.equals(thisAlias)) { + String otherAliasClass = aliasManager.getAliasClassName(otherAlias); + // System.err.println("comparing '" + aliasClass + "' with '" + otherAliasClass + "'"); + if (aliasClass.equals(otherAliasClass)) { + // we have found another alias for the same command + if (sb.length() > 0) { + sb.append(", "); } - } catch (NoSuchAliasException nsae) { - // should never happen since we iterate on known aliases - } catch (ClassNotFoundException e) { - // should never happen since we iterate on known aliases + sb.append(otherAlias); } } } - return hasOtherAlias ? sb.toString() : null; + if (sb.length() > 0) { + out.println("Other aliases: " + sb); + } } } Modified: trunk/shell/src/shell/org/jnode/shell/help/Argument.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/help/Argument.java 2008-11-12 13:47:18 UTC (rev 4702) +++ trunk/shell/src/shell/org/jnode/shell/help/Argument.java 2008-11-16 02:53:07 UTC (rev 4703) @@ -55,7 +55,7 @@ return "<" + getName() + ">" + (isMulti() ? " ..." : ""); } - public void describe(Help help, PrintWriter out) { + public void describe(HelpFactory help, PrintWriter out) { help.describeArgument(this, out); } Modified: trunk/shell/src/shell/org/jnode/shell/help/CommandLineElement.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/help/CommandLineElement.java 2008-11-12 13:47:18 UTC (rev 4702) +++ trunk/shell/src/shell/org/jnode/shell/help/CommandLineElement.java 2008-11-16 02:53:07 UTC (rev 4703) @@ -46,7 +46,7 @@ } public abstract String format(); - public abstract void describe(Help help, PrintWriter out); + public abstract void describe(HelpFactory help, PrintWriter out); public abstract void complete(CompletionInfo completion, String partial); /** Added: trunk/shell/src/shell/org/jnode/shell/help/EnhancedHelp.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/help/EnhancedHelp.java (rev 0) +++ trunk/shell/src/shell/org/jnode/shell/help/EnhancedHelp.java 2008-11-16 02:53:07 UTC (rev 4703) @@ -0,0 +1,59 @@ +/* + * $Id: CommandLineElement.java 4556 2008-09-13 08:02:20Z crawley $ + * + * 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.shell.help; + +import java.io.PrintWriter; + +/** + * This enhanced help interface provides extra fine-grained help + * methods. + * + * @author cr...@jn... + */ +public interface EnhancedHelp extends Help { + /** + * Output the description (summary) text for the command. + * + * @param pw the help information is written here + */ + void description(PrintWriter pw); + + /** + * Output the argument descriptions for the command. + * + * @param pw the help information is written here + */ + public void arguments(PrintWriter pw); + + /** + * Output the option descriptions for the command. + * + * @param pw the help information is written here + */ + public void options(PrintWriter pw); + + /** + * Output the detailed help text for the command. + * + * @param pw the help information is written here + */ + public void details(PrintWriter pw); +} Modified: trunk/shell/src/shell/org/jnode/shell/help/Help.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/help/Help.java 2008-11-12 13:47:18 UTC (rev 4702) +++ trunk/shell/src/shell/org/jnode/shell/help/Help.java 2008-11-16 02:53:07 UTC (rev 4703) @@ -18,118 +18,41 @@ * 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.help; import java.io.PrintWriter; -import java.lang.reflect.Field; -import java.util.TreeSet; -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; -import org.jnode.shell.syntax.ArgumentBundle; -import org.jnode.shell.syntax.FlagArgument; -import org.jnode.shell.syntax.SyntaxBundle; /** - * @author qades - * @author Fabien DUMINY (fd...@jn...) + * This is the interface for an object that outputs command help. Different + * implementations support different command syntax mechanisms, and (in the + * future) will provide help in different output formats; e.g. plain text, + * HTML and so on. + * + * @author cr...@jn... */ -public abstract class Help { - public static final String BUNDLE_NAME = "messages"; // must be in our package - - public static final Class<Help> NAME = Help.class; - - public static final String INFO_FIELD_NAME = "HELP_INFO"; - - public static Help getHelp() throws HelpException { - try { - return InitialNaming.lookup(NAME); - } catch (NamingException ex) { - throw new HelpException("Help application not found"); - } - } - - public static String getLocalizedHelp(String messageKey) { - return PluginUtils.getLocalizedMessage(Help.class, - BUNDLE_NAME, messageKey); - } - - public static Info getInfo(Class<?> clazz) throws HelpException { - try { - Field helpInfo = clazz.getField(INFO_FIELD_NAME); - return (Help.Info) helpInfo.get(null); // static access - } catch (NoSuchFieldException ex) { - throw new HelpException("Command information not found"); - } catch (IllegalAccessException ex) { - throw new HelpException("Command information not accessible"); - } - } - +public interface Help { + /** - * Shows the help page for a command + * Output complete help for the command. * - * @param info the command info - * @param command a command name or alias which appears in the help - * @param out the destination for help output. + * @param pw the help information is written here */ - public abstract void help(Info info, String command, PrintWriter out); - + public void help(PrintWriter pw); + /** - * Shows the help page for a command + * Output the usage message(s) for the command. * - * @param syntaxes the command's syntax bundle - * @param bundle the command's argument bundle - * @param out the destination for help output. + * @param pw the help information is written here */ - public abstract void help(SyntaxBundle syntaxes, ArgumentBundle bundle, PrintWriter out); - + public void usage(PrintWriter pw); + /** - * Shows the usage line for a command - * - * @param info the command information - * @param out the destination for help output. + * This class is here for historical reasons. It is a key API class in the + * 'old' JNode syntax mechanism. */ - public abstract void usage(Info info, PrintWriter out); - - /** - * Shows the usage line for a command - * - * @param syntaxes the command's syntax bundle - * @param bundle the command's argument bundle - * @param out the destination for help output. - */ - public abstract void usage(SyntaxBundle syntaxes, ArgumentBundle bundle, PrintWriter out); - - /** - * Shows the description of a single argument. Used as a callback in - * {@link Argument#describe(Help)}. - */ - public abstract void describeArgument(Argument arg, PrintWriter out); - - /** - * Shows the description of a single argument. Used as a callback in - * {@link Argument#describe(Help)}. - */ - public abstract void describeArgument(org.jnode.shell.syntax.Argument<?> arg, PrintWriter out); - - /** - * Shows the description of a single FlagArgument. Used as a callback in - * {@link Argument#describe(Help)}. - */ - public abstract void describeOption(FlagArgument arg, - TreeSet<String> flagTokens, PrintWriter out); - - /** - * Shows the description of a single parameter. Used as a callback in - * {@link Parameter#describe(Help)}. - */ - public abstract void describeParameter(Parameter param, PrintWriter out); - public static class Info { private final String name; @@ -161,7 +84,7 @@ public void usage(PrintWriter out) { try { - Help.getHelp().usage(this, out); + HelpFactory.getHelpFactory().usage(this, out); } catch (HelpException ex) { ex.printStackTrace(); } @@ -173,7 +96,7 @@ * @throws HelpException */ public void help(String command, PrintWriter out) throws HelpException { - Help.getHelp().help(this, command, out); + HelpFactory.getHelpFactory().help(this, command, out); } public String complete(CompletionInfo completion, CommandLine partial, Added: trunk/shell/src/shell/org/jnode/shell/help/HelpFactory.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/help/HelpFactory.java (rev 0) +++ trunk/shell/src/shell/org/jnode/shell/help/HelpFactory.java 2008-11-16 02:53:07 UTC (rev 4703) @@ -0,0 +1,152 @@ +/* + * $Id: Help.java 4556 2008-09-13 08:02:20Z crawley $ + * + * 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.shell.help; + +import java.io.PrintWriter; +import java.lang.reflect.Field; +import java.util.TreeSet; + +import javax.naming.NamingException; + +import org.jnode.naming.InitialNaming; +import org.jnode.plugin.PluginUtils; +import org.jnode.shell.CommandInfo; +import org.jnode.shell.help.Help.Info; +import org.jnode.shell.syntax.ArgumentBundle; +import org.jnode.shell.syntax.FlagArgument; +import org.jnode.shell.syntax.SyntaxBundle; + +/** + * The HelpFactory class is the base class for the Help factory classes, and provides + * a static method for getting the default factory. Other methods in this class are + * here for historical reasons, and should be avoided where possible. + * + * @author qades + * @author Fabien DUMINY (fd...@jn...) + * @author cr...@jn... + */ +public abstract class HelpFactory { + public static final String BUNDLE_NAME = "messages"; // must be in our package + + public static final Class<HelpFactory> NAME = HelpFactory.class; + + public static final String INFO_FIELD_NAME = "HELP_INFO"; + + public static HelpFactory getHelpFactory() throws HelpException { + try { + return InitialNaming.lookup(NAME); + } catch (NamingException ex) { + throw new HelpException("Help factory not found"); + } + } + + public static String getLocalizedHelp(String messageKey) { + return PluginUtils.getLocalizedMessage(HelpFactory.class, + BUNDLE_NAME, messageKey); + } + + public static Info getInfo(Class<?> clazz) throws HelpException { + try { + Field helpInfo = clazz.getField(INFO_FIELD_NAME); + return (Help.Info) helpInfo.get(null); // static access + } catch (NoSuchFieldException ex) { + throw new HelpException("Command information not found"); + } catch (IllegalAccessException ex) { + throw new HelpException("Command information not accessible"); + } + } + + /** + * Obtain a CommanHelp object for a given command alias and its resolved CommandInfo. + * + * @param alias + * @param cmdInfo + * @return + * @throws HelpException + */ + public abstract Help getHelp( + String alias, CommandInfo cmdInfo) throws HelpException; + + // FIXME ... the remaining API methods are historical, and should not be used outside of + // the help package and its implementation packages. + + /** + * Shows the help page for a command + * + * @param info the command info + * @param command a command name or alias which appears in the help + * @param out the destination for help output. + */ + protected abstract void help(Info info, String command, PrintWriter out); + + /** + * Shows the help page for a command + * + * @param syntaxes the command's syntax bundle + * @param bundle the command's argument bundle + * @param out the destination for help output. + */ + protected abstract void help(SyntaxBundle syntaxes, ArgumentBundle bundle, PrintWriter out); + + /** + * Shows the usage line for a command + * + * @param info the command information + * @param out the destination for help output. + */ + protected abstract void usage(Info info, PrintWriter out); + + /** + * Shows the usage line for a command + * + * @param syntaxes the command's syntax bundle + * @param bundle the command's argument bundle + * @param out the destination for help output. + */ + protected abstract void usage(SyntaxBundle syntaxes, ArgumentBundle bundle, PrintWriter out); + + /** + * Shows the description of a single argument. Used as a callback in + * {@link Argument#describe(HelpFactory)}. + */ + protected abstract void describeArgument(Argument arg, PrintWriter out); + + /** + * Shows the description of a single argument. Used as a callback in + * {@link Argument#describe(HelpFactory)}. + */ + protected abstract void describeArgument(org.jnode.shell.syntax.Argument<?> arg, PrintWriter out); + + /** + * Shows the description of a single FlagArgument. Used as a callback in + * {@link Argument#describe(HelpFactory)}. + */ + protected abstract void describeOption(FlagArgument arg, + TreeSet<String> flagTokens, PrintWriter out); + + /** + * Shows the description of a single parameter. Used as a callback in + * {@link Parameter#describe(HelpFactory)}. + */ + protected abstract void describeParameter(Parameter param, PrintWriter out); + +} Modified: trunk/shell/src/shell/org/jnode/shell/help/Parameter.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/help/Parameter.java 2008-11-12 13:47:18 UTC (rev 4702) +++ trunk/shell/src/shell/org/jnode/shell/help/Parameter.java 2008-11-16 02:53:07 UTC (rev 4703) @@ -105,7 +105,7 @@ return (optional ? "[" + result + "]" : result); } - public void describe(Help help, PrintWriter out) { + public void describe(HelpFactory help, PrintWriter out) { if (!isAnonymous()) { help.describeParameter(this, out); } Modified: trunk/shell/src/shell/org/jnode/shell/help/argument/EnumOptionArgument.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/help/argument/EnumOptionArgument.java 2008-11-12 13:47:18 UTC (rev 4702) +++ trunk/shell/src/shell/org/jnode/shell/help/argument/EnumOptionArgument.java 2008-11-16 02:53:07 UTC (rev 4703) @@ -26,7 +26,7 @@ import org.jnode.driver.console.CompletionInfo; import org.jnode.shell.help.Argument; -import org.jnode.shell.help.Help; +import org.jnode.shell.help.HelpFactory; import org.jnode.shell.help.Parameter; import org.jnode.shell.help.ParsedArguments; @@ -55,7 +55,7 @@ return result.substring(1); } - public void describe(Help help, PrintWriter out) { + public void describe(HelpFactory help, PrintWriter out) { for (EnumOption<T> option : options) option.describe(help, out); } Modified: trunk/shell/src/shell/org/jnode/shell/help/argument/OptionArgument.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/help/argument/OptionArgument.java 2008-11-12 13:47:18 UTC (rev 4702) +++ trunk/shell/src/shell/org/jnode/shell/help/argument/OptionArgument.java 2008-11-16 02:53:07 UTC (rev 4703) @@ -25,7 +25,7 @@ import org.jnode.driver.console.CompletionInfo; import org.jnode.shell.help.Argument; -import org.jnode.shell.help.Help; +import org.jnode.shell.help.HelpFactory; import org.jnode.shell.help.Parameter; /** @@ -54,7 +54,7 @@ } @Override - public void describe(Help help, PrintWriter out) { + public void describe(HelpFactory help, PrintWriter out) { for (Option option : options) option.describe(help, out); } Deleted: trunk/shell/src/shell/org/jnode/shell/help/def/DefaultHelp.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/help/def/DefaultHelp.java 2008-11-12 13:47:18 UTC (rev 4702) +++ trunk/shell/src/shell/org/jnode/shell/help/def/DefaultHelp.java 2008-11-16 02:53:07 UTC (rev 4703) @@ -1,347 +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.shell.help.def; - -import java.io.PrintWriter; -import java.util.HashMap; -import java.util.Map; -import java.util.TreeSet; - -import org.jnode.shell.help.Argument; -import org.jnode.shell.help.Help; -import org.jnode.shell.help.Parameter; -import org.jnode.shell.help.Syntax; -import org.jnode.shell.syntax.ArgumentBundle; -import org.jnode.shell.syntax.FlagArgument; -import org.jnode.shell.syntax.OptionSyntax; -import org.jnode.shell.syntax.SyntaxBundle; - -/** - * @author qades - * @author Fabien DUMINY (fd...@jn...) - * @author cr...@jn... - */ -public class DefaultHelp extends Help { - public static final String RESOURCE_NAME = "messages.properties"; - private static final int NOMINAL_WIDTH = 75; - /* start with 80 spaces ... */ - private static String spaces = - " "; - - /** - * Create a new instance - */ - public DefaultHelp() { - } - - /** - * Shows the complete help for a command. - * - * @see Help#help(org.jnode.shell.help.Help.Info, String) - */ - public void help(Info info, String command, PrintWriter out) { - final Syntax[] syntaxes = info.getSyntaxes(); - final String name = command == null ? info.getName() : command; - for (int i = 0; i < syntaxes.length; i++) { - help(name, syntaxes[i], out); - if (i < syntaxes.length) { - out.println(); - } - } - } - - @Override - public void help(SyntaxBundle syntaxes, ArgumentBundle bundle, PrintWriter out) { - usage(syntaxes, bundle, out); - if (bundle.getDescription() != null) { - out.println("\n" + Help.getLocalizedHelp("help.description") + ":"); - format(out, new Cell[]{new Cell(4, NOMINAL_WIDTH - 4)}, - new String[]{bundle.getDescription()}); - } - Map<String, TreeSet<String>> flagMap = buildFlagMap(syntaxes); - boolean first = true; - for (org.jnode.shell.syntax.Argument<?> arg : bundle) { - if (arg instanceof FlagArgument) { - if (first) { - out.println("\n" + Help.getLocalizedHelp("help.options") + ":"); - first = false; - } - describeOption((FlagArgument) arg, flagMap.get(arg.getLabel()), out); - } - } - first = true; - for (org.jnode.shell.syntax.Argument<?> arg : bundle) { - if (!(arg instanceof FlagArgument)) { - if (first) { - out.println("\n" + Help.getLocalizedHelp("help.parameters") + ":"); - first = false; - } - describeArgument(arg, out); - } - } - } - - private Map<String, TreeSet<String>> buildFlagMap(SyntaxBundle syntaxes) { - HashMap<String, TreeSet<String>> res = new HashMap<String, TreeSet<String>>(); - for (org.jnode.shell.syntax.Syntax syntax : syntaxes.getSyntaxes()) { - buildFlagMap(syntax, res); - } - return res; - } - - private void buildFlagMap(org.jnode.shell.syntax.Syntax syntax, - HashMap<String, TreeSet<String>> res) { - if (syntax instanceof OptionSyntax) { - OptionSyntax os = (OptionSyntax) syntax; - String key = os.getArgName(); - TreeSet<String> options = res.get(key); - if (options == null) { - options = new TreeSet<String>(); - res.put(key, options); - } - String shortOptName = os.getShortOptName(); - if (shortOptName != null) { - options.add(shortOptName); - } - String longOptName = os.getLongOptName(); - if (longOptName != null) { - options.add(longOptName); - } - } else { - for (org.jnode.shell.syntax.Syntax child : syntax.getChildren()) { - buildFlagMap(child, res); - } - } - } - - /** - * Shows the help for a command syntax. - */ - public void help(String name, Syntax syntax, PrintWriter out) { - usage(name, syntax, out); - if (syntax.getDescription() != null) { - out.println("\n" + Help.getLocalizedHelp("help.description") + ":"); - format(out, new Cell[]{new Cell(4, NOMINAL_WIDTH - 4)}, - new String[]{syntax.getDescription()}); - } - final Parameter[] params = syntax.getParams(); - if (params.length != 0) { - out.println("\n" + Help.getLocalizedHelp("help.parameters") + ":"); - for (int i = 0; i < params.length; i++) { - params[i].describe(this, out); - } - } - } - - /** - * Shows the usage information of a command. - */ - public void usage(Info info, PrintWriter out) { - final Syntax[] syntaxes = info.getSyntaxes(); - for (int i = 0; i < syntaxes.length; i++) { - usage(info.getName(), syntaxes[i], out); - } - } - - /** - * Shows the usage information of a command. - */ - public void usage(String name, Syntax syntax, PrintWriter out) { - StringBuilder line = new StringBuilder(name); - final Parameter[] params = syntax.getParams(); - for (int i = 0; i < params.length; i++) { - line.append(' ').append(params[i].format()); - } - out.println(Help.getLocalizedHelp("help.usage") + ": " + line); - } - - @Override - public void usage(SyntaxBundle syntaxBundle, ArgumentBundle bundle, PrintWriter out) { - String command = syntaxBundle.getAlias(); - String usageText = Help.getLocalizedHelp("help.usage") + ":"; - int usageLength = usageText.length(); - int commandLength = command.length(); - Cell[] cells = - new Cell[]{new Cell(0, usageLength), new Cell(1, commandLength), - new Cell(1, NOMINAL_WIDTH - 2 - usageLength - commandLength)}; - String[] texts = new String[]{usageText, command, null}; - String[] texts2 = new String[]{"", "", null}; - org.jnode.shell.syntax.Syntax[] syntaxes = syntaxBundle.getSyntaxes(); - if (syntaxes.length > 0) { - for (int i = 0; i < syntaxes.length; i++) { - if (i == 1) { - texts[0] = getSpaces(usageLength); - } - texts[2] = syntaxes[i].format(bundle); - format(out, cells, texts); - texts2[2] = syntaxes[i].getDescription(); - format(out, cells, texts2); - } - } else { - texts[2] = ""; - format(out, cells, texts); - } - } - - public void describeParameter(Parameter param, PrintWriter out) { - format(out, new Cell[]{new Cell(2, 18), new Cell(2, NOMINAL_WIDTH - 22)}, - new String[]{param.getName(), param.getDescription()}); - } - - public void describeArgument(Argument arg, PrintWriter out) { - format(out, new Cell[]{new Cell(4, 16), new Cell(2, NOMINAL_WIDTH - 22)}, - new String[]{arg.getName(), arg.getDescription()}); - } - - @Override - public void describeArgument(org.jnode.shell.syntax.Argument<?> arg, PrintWriter out) { - String description = "(" + arg.getTypeDescription() + ") " + arg.getDescription(); - format(out, new Cell[]{new Cell(4, 16), new Cell(2, NOMINAL_WIDTH - 22)}, - new String[]{"<" + arg.getLabel() + ">", description}); - } - - @Override - public void describeOption(FlagArgument arg, TreeSet<String> flagTokens, PrintWriter out) { - StringBuffer sb = new StringBuffer(); - for (String flagToken : flagTokens) { - if (sb.length() > 0) { - sb.append(" | "); - } - sb.append(flagToken); - } - format(out, new Cell[]{new Cell(4, 16), new Cell(2, NOMINAL_WIDTH - 22)}, - new String[]{sb.toString(), arg.getDescription()}); - } - - protected void format(PrintWriter out, Cell[] cells, String[] texts) { - if (cells.length != texts.length) { - throw new IllegalArgumentException("Number of cells and texts must match"); - } - // The text remaining to be formatted for each column. - String[] remains = new String[texts.length]; - // The total count of characters remaining - int remainsCount = 0; - // Initialize 'remains' and 'remainsCount' for the first iteration - for (int i = 0; i < texts.length; i++) { - remains[i] = (texts[i] == null) ? "" : texts[i].trim(); - remainsCount += remains[i].length(); - } - - StringBuilder result = new StringBuilder(); - // Repeat while there is still text to output. - while (remainsCount > 0) { - // Each iteration uses 'fit' to get up to 'cell.width' characters from each column - // and then uses 'stamp' to append to them to the buffer with the leading margin - // and trailing padding as required. - remainsCount = 0; - for (int i = 0; i < cells.length; i++) { - String field = cells[i].fit(remains[i]); - remains[i] = remains[i].substring(field.length()); - remainsCount += remains[i].length(); - result.append(cells[i].stamp(field.trim())); - } - result.append('\n'); - } - out.print(result.toString()); - } - - /** - * Get a String consisting of 'count' spaces. - * - * @param count the number of spaces - * @return the string - */ - private static String getSpaces(int count) { - // The following assumes that 1) StringBuilder.append is efficient if you - // preallocate the StringBuilder, 2) StringBuilder.toString() does no character - // copying, and 3) String.substring(...) also does no character copying. - int len = spaces.length(); - if (count > len) { - StringBuilder sb = new StringBuilder(count); - for (int i = 0; i < count; i++) { - sb.append(' '); - } - spaces = sb.toString(); - return spaces; - } else if (count == len) { - return spaces; - } else { - return spaces.substring(0, count); - } - } - - /** - * A Cell is a template for formatting text for help messages. (It is 'protected' so that - * the unit test can declare a subclass ...) - */ - protected static class Cell { - - final String field; - final int margin; - final int width; - - /** - * Construct a Cell with a leading margin and a text width. - * - * @param margin the number of leading spaces for the Cell - * @param width the width of the text part of the Cell - */ - protected Cell(int margin, int width) { - this.margin = margin; - this.width = width; - - // for performance, we pre-build the field mask - this.field = getSpaces(margin + width); - } - - /** - * Heuristically, split of a head substring of 'text' to fit within this Cell's width. We try - * to split at a space character, but if this will make the text too ragged, we simply chop. - */ - protected String fit(String text) { - if (width >= text.length()) { - return text; - } - String hardFit = text.substring(0, width); - if (hardFit.endsWith(" ")) { - return hardFit; - } - int lastSpace = hardFit.lastIndexOf(' '); - if (lastSpace > 3 * width / 4) { - return hardFit.substring(0, lastSpace); - } else { - return hardFit; - } - } - - /** - * Stamp out a line with leading and trailing spaces to fill the Cell. - */ - protected String stamp(String text) { - if (text.length() > field.length()) - throw new IllegalArgumentException("Text length exceeds field width"); - return field.substring(0, margin) + text + field.substring(0, width - text.length()); - } - } - - -} Added: trunk/shell/src/shell/org/jnode/shell/help/def/DefaultHelpFactory.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/help/def/DefaultHelpFactory.java (rev 0) +++ trunk/shell/src/shell/org/jnode/shell/help/def/DefaultHelpFactory.java 2008-11-16 02:53:07 UTC (rev 4703) @@ -0,0 +1,387 @@ +/* + * $Id: DefaultHelp.java 4556 2008-09-13 08:02:20Z crawley $ + * + * 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.shell.help.def; + +import java.io.PrintWriter; +import java.util.HashMap; +import java.util.Map; +import java.util.TreeSet; + +import org.jnode.shell.Command; +import org.jnode.shell.CommandInfo; +import org.jnode.shell.Shell; +import org.jnode.shell.ShellUtils; +import org.jnode.shell.help.Argument; +import org.jnode.shell.help.Help; +import org.jnode.shell.help.HelpException; +import org.jnode.shell.help.HelpFactory; +import org.jnode.shell.help.Parameter; +import org.jnode.shell.help.Syntax; +import org.jnode.shell.syntax.ArgumentBundle; +import org.jnode.shell.syntax.FlagArgument; +import org.jnode.shell.syntax.OptionSyntax; +import org.jnode.shell.syntax.SyntaxBundle; +import org.jnode.shell.syntax.SyntaxManager; + +/** + * @author qades + * @author Fabien DUMINY (fd...@jn...) + * @author cr...@jn... + */ +public class DefaultHelpFactory extends HelpFactory { + public static final String RESOURCE_NAME = "messages.properties"; + private static final int NOMINAL_WIDTH = 75; + /* start with 80 spaces ... */ + private static String spaces = + " "; + + /** + * Create a new instance + */ + public DefaultHelpFactory() { + } + + @Override + public Help getHelp(String alias, CommandInfo cmdInfo) throws HelpException { + Help.Info info = null; + SyntaxBundle syntaxes = null; + ArgumentBundle bundle = null; + try { + final Shell shell = ShellUtils.getShellManager().getCurrentShell(); + final SyntaxManager syntaxManager = shell.getSyntaxManager(); + Class<?> clazz = cmdInfo.getCommandClass(); + Command cmd = cmdInfo.createCommandInstance(); + if (cmd != null) { + bundle = cmd.getArgumentBundle(); + syntaxes = syntaxManager.getSyntaxBundle(alias); + if (syntaxes == null) { + syntaxes = new SyntaxBundle(alias, bundle.createDefaultSyntax()); + } + } else { + info = HelpFactory.getInfo(clazz); + } + } catch (HelpException ex) { + throw ex; + } catch (Exception ex) { + throw new HelpException(ex.getMessage(), ex); + } + + if (info != null && alias != null) { + return new OldSyntaxHelp(info, alias); + } else if (syntaxes != null && bundle != null) { + return new NewSyntaxHelp(syntaxes, bundle); + } else { + return null; + } + } + + /** + * Shows the complete help for a command. + * + * @see HelpFactory#help(org.jnode.shell.help.HelpFactory.Info, String) + */ + public void help(Help.Info info, String command, PrintWriter out) { + final Syntax[] syntaxes = info.getSyntaxes(); + final String name = command == null ? info.getName() : command; + for (int i = 0; i < syntaxes.length; i++) { + help(name, syntaxes[i], out); + if (i < syntaxes.length) { + out.println(); + } + } + } + + @Override + public void help(SyntaxBundle syntaxes, ArgumentBundle bundle, PrintWriter out) { + usage(syntaxes, bundle, out); + if (bundle.getDescription() != null) { + out.println("\n" + HelpFactory.getLocalizedHelp("help.description") + ":"); + format(out, new Cell[]{new Cell(4, NOMINAL_WIDTH - 4)}, + new String[]{bundle.getDescription()}); + } + Map<String, TreeSet<String>> flagMap = buildFlagMap(syntaxes); + boolean first = true; + for (org.jnode.shell.syntax.Argument<?> arg : bundle) { + if (arg instanceof FlagArgument) { + if (first) { + out.println("\n" + HelpFactory.getLocalizedHelp("help.options") + ":"); + first = false; + } + describeOption((FlagArgument) arg, flagMap.get(arg.getLabel()), out); + } + } + first = true; + for (org.jnode.shell.syntax.Argument<?> arg : bundle) { + if (!(arg instanceof FlagArgument)) { + if (first) { + out.println("\n" + HelpFactory.getLocalizedHelp("help.parameters") + ":"); + first = false; + } + describeArgument(arg, out); + } + } + } + + private Map<String, TreeSet<String>> buildFlagMap(SyntaxBundle syntaxes) { + HashMap<String, TreeSet<String>> res = new HashMap<String, TreeSet<String>>(); + for (org.jnode.shell.syntax.Syntax syntax : syntaxes.getSyntaxes()) { + buildFlagMap(syntax, res); + } + return res; + } + + private void buildFlagMap(org.jnode.shell.syntax.Syntax syntax, + HashMap<String, TreeSet<String>> res) { + if (syntax instanceof OptionSyntax) { + OptionSyntax os = (OptionSyntax) syntax; + String key = os.getArgName(); + TreeSet<String> options = res.get(key); + if (options == null) { + options = new TreeSet<String>(); + res.put(key, options); + } + String shortOptName = os.getShortOptName(); + if (shortOptName != null) { + options.add(shortOptName); + } + String longOptName = os.getLongOptName(); + if (longOptName != null) { + options.add(longOptName); + } + } else { + for (org.jnode.shell.syntax.Syntax child : syntax.getChildren()) { + buildFlagMap(child, res); + } + } + } + + /** + * Shows the help for a command syntax. + */ + public void help(String name, Syntax syntax, PrintWriter out) { + usage(name, syntax, out); + if (syntax.getDescription() != null) { + out.println("\n" + HelpFactory.getLocalizedHelp("help.description") + ":"); + format(out, new Cell[]{new Cell(4, NOMINAL_WIDTH - 4)}, + new String[]{syntax.getDescription()}); + } + final Parameter[] params = syntax.getParams(); + if (params.length != 0) { + out.println("\n" + HelpFactory.getLocalizedHelp("help.parameters") + ":"); + for (int i = 0; i < params.length; i++) { + params[i].describe(this, out); + } + } + } + + /** + * Shows the usage information of a command. + */ + public void usage(Help.Info info, PrintWriter out) { + final Syntax[] syntaxes = info.getSyntaxes(); + for (int i = 0; i < syntaxes.length; i++) { + usage(info.getName(), syntaxes[i], out); + } + } + + /** + * Shows the usage information of a command. + */ + public void usage(String name, Syntax syntax, PrintWriter out) { + StringBuilder line = new StringBuilder(name); + final Parameter[] params = syntax.getParams(); + for (int i = 0; i < params.length; i++) { + line.append(' ').append(params[i].format()); + } + out.println(HelpFactory.getLocalizedHelp("help.usage") + ": " + line); + } + + @Override + public void usage(SyntaxBundle syntaxBundle, ArgumentBundle bundle, PrintWriter out) { + String command = syntaxBundle.getAlias(); + String usageText = HelpFactory.getLocalizedHelp("help.usage") + ":"; + int usageLength = usageText.length(); + int commandLength = command.length(); + Cell[] cells = + new Cell[]{new Cell(0, usageLength), new Cell(1, commandLength), + new Cell(1, NOMINAL_WIDTH - 2 - usageLength - commandLength)}; + String[] texts = new String[]{usageText, command, null}; + String[] texts2 = new String[]{"", "", null}; + org.jnode.shell.syntax.Syntax[] syntaxes = syntaxBundle.getSyntaxes(); + if (syntaxes.length > 0) { + for (int i = 0; i < syntaxes.length; i++) { + if (i == 1) { + texts[0] = getSpaces(usageLength); + } + texts[2] = syntaxes[i].format(bundle); + format(out, cells, texts); + texts2[2] = syntaxes[i].getDescription(); + format(out, cells, texts2); + } + } else { + texts[2] = ""; + format(out, cells, texts); + } + } + + public void describeParameter(Parameter param, PrintWriter out) { + format(out, new Cell[]{new Cell(2, 18), new Cell(2, NOMINAL_WIDTH - 22)}, + new String[]{param.getName(), param.getDescription()}); + } + + public void describeArgument(Argument arg, PrintWriter out) { + format(out, new Cell[]{new Cell(4, 16), new Cell(2, NOMINAL_WIDTH - 22)}, + new String[]{arg.getName(), arg.getDescription()}); + } + + @Override + public void describeArgument(org.jnode.shell.syntax.Argument<?> arg, PrintWriter out) { + String description = "(" + arg.getTypeDescription() + ") " + arg.getDescription(); + format(out, new Cell[]{new Cell(4, 16), new Cell(2, NOMINAL_WIDTH - 22)}, + new String[]{"<" + arg.getLabel() + ">", description}); + } + + @Override + public void describeOption(FlagArgument arg, TreeSet<String> flagTokens, PrintWriter out) { + StringBuffer sb = new StringBuffer(); + for (String flagToken : flagTokens) { + if (sb.length() > 0) { + sb.append(" | "); + } + sb.append(flagToken); + } + format(out, new Cell[]{new Cell(4, 16), new Cell(2, NOMINAL_WIDTH - 22)}, + new String[]{sb.toString(), arg.getDescription()}); + } + + protected void format(PrintWriter out, Cell[] cells, String[] texts) { + if (cells.length != texts.length) { + throw new IllegalArgumentException("Number of cells and texts must match"); + } + // The text remaining to be formatted for each column. + String[] remains = new String[texts.length]; + // The total count of characters remaining + int remainsCount = 0; + // Initialize 'remains' and 'remainsCount' for the first iteration + for (int i = 0; i < texts.length; i++) { + remains[i] = (texts[i] == null) ? "" : texts[i].trim(); + remainsCount += remains[i].length(); + } + + StringBuilder result = new StringBuilder(); + // Repeat while there is still text to output. + while (remainsCount > 0) { + // Each iteration uses 'fit' to get up to 'cell.width' characters from each column + // and then uses 'stamp' to append to them to the buffer with the leading margin + // and trailing padding as required. + remainsCount = 0; + for (int i = 0; i < cells.length; i++) { + String field = cells[i].fit(remains[i]); + remains[i] = remains[i].substring(field.length()); + remainsCount += remains[i].length(); + result.append(cells[i].stamp(field.trim())); + } + result.append('\n'); + } + out.print(result.toString()); + } + + /** + * Get a String consisting of 'count' spaces. + * + * @param count the number of spaces + * @return the string + */ + private static String getSpaces(int count) { + // The following assumes that 1) StringBuilder.append is efficient if you + // preallocate the StringBuilder, 2) StringBuilder.toString() does no character + // copying, and 3) String.substring(...) also does no character copying. + int len = spaces.length(); + if (count > len) { + StringBuilder sb = new StringBuilder(count); + for (int i = 0; i < count; i++) { + sb.append(' '); + } + spaces = sb.toString(); + return spaces; + } else if (count == len) { + return spaces; + } else { + return spaces.substring(0, count); + } + } + + /** + * A Cell is a template for formatting text for help messages. (It is 'protected' so that + * the unit test can declare a subclass ...) + */ + protected static class Cell { + + final Str... [truncated message content] |
From: <cr...@us...> - 2008-11-17 07:50:27
|
Revision: 4705 http://jnode.svn.sourceforge.net/jnode/?rev=4705&view=rev Author: crawley Date: 2008-11-17 07:50:22 +0000 (Mon, 17 Nov 2008) Log Message: ----------- checkstyle fixes Modified Paths: -------------- trunk/core/src/driver/org/jnode/driver/console/textscreen/KeyboardReader.java trunk/gui/src/test/org/jnode/test/gui/FBTest.java trunk/shell/src/shell/org/jnode/shell/CommandShell.java Modified: trunk/core/src/driver/org/jnode/driver/console/textscreen/KeyboardReader.java =================================================================== --- trunk/core/src/driver/org/jnode/driver/console/textscreen/KeyboardReader.java 2008-11-17 07:04:13 UTC (rev 4704) +++ trunk/core/src/driver/org/jnode/driver/console/textscreen/KeyboardReader.java 2008-11-17 07:50:22 UTC (rev 4705) @@ -21,7 +21,6 @@ package org.jnode.driver.console.textscreen; import java.awt.event.KeyEvent; -import java.io.CharArrayWriter; import java.io.IOException; import java.io.Reader; import java.io.Writer; Modified: trunk/gui/src/test/org/jnode/test/gui/FBTest.java =================================================================== --- trunk/gui/src/test/org/jnode/test/gui/FBTest.java 2008-11-17 07:04:13 UTC (rev 4704) +++ trunk/gui/src/test/org/jnode/test/gui/FBTest.java 2008-11-17 07:50:22 UTC (rev 4705) @@ -29,10 +29,9 @@ import java.awt.geom.Line2D; import java.awt.geom.QuadCurve2D; import java.awt.geom.Rectangle2D; -import java.io.InputStream; -import java.io.PrintStream; import java.util.ArrayList; import java.util.Collection; + import org.apache.log4j.Logger; import org.jnode.driver.Device; import org.jnode.driver.DeviceUtils; @@ -40,7 +39,6 @@ import org.jnode.driver.video.FrameBufferConfiguration; import org.jnode.driver.video.Surface; import org.jnode.shell.AbstractCommand; -import org.jnode.shell.CommandLine; import org.jnode.shell.syntax.Argument; import org.jnode.shell.syntax.DeviceArgument; import org.jnode.shell.syntax.IntegerArgument; Modified: trunk/shell/src/shell/org/jnode/shell/CommandShell.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/CommandShell.java 2008-11-17 07:04:13 UTC (rev 4704) +++ trunk/shell/src/shell/org/jnode/shell/CommandShell.java 2008-11-17 07:50:22 UTC (rev 4705) @@ -51,7 +51,6 @@ import org.jnode.driver.console.InputHistory; import org.jnode.driver.console.TextConsole; import org.jnode.driver.console.textscreen.KeyboardReader; -import org.jnode.driver.console.textscreen.KeyboardReaderAction; import org.jnode.naming.InitialNaming; import org.jnode.shell.alias.AliasManager; import org.jnode.shell.alias.NoSuchAliasException; @@ -153,12 +152,6 @@ */ private String lastInputLine = ""; - /** - * Flag to know when to wait (while input is happening). This is (hopefully) - * a thread safe implementation. * - */ - private volatile boolean threadSuspended = false; - private CommandInvoker invoker; private String invokerName; @@ -753,7 +746,7 @@ * application in the application input history. */ private class HistoryInputStream extends FilterInputStream { - // TODO - revisit for support of multi-byte character encodings. + // TODO - replace with a Reader private StringBuilder line = new StringBuilder(); public HistoryInputStream(InputStream in) { @@ -851,7 +844,6 @@ private void exit0() { exited = true; - threadSuspended = false; } private synchronized boolean isExited() { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2008-11-17 13:47:03
|
Revision: 4706 http://jnode.svn.sourceforge.net/jnode/?rev=4706&view=rev Author: lsantha Date: 2008-11-17 13:46:59 +0000 (Mon, 17 Nov 2008) Log Message: ----------- Improved isolate support for GUI applications. Modified Paths: -------------- trunk/core/src/core/org/jnode/vm/isolate/VmIsolate.java trunk/core/src/openjdk/java/java/awt/DefaultKeyboardFocusManager.java trunk/core/src/openjdk/java/java/awt/KeyboardFocusManager.java trunk/core/src/openjdk/java/java/awt/Toolkit.java trunk/core/src/openjdk/sun/sun/awt/SunToolkit.java trunk/gui/src/awt/org/jnode/awt/JNodeToolkit.java trunk/gui/src/awt/org/jnode/awt/KeyboardHandler.java trunk/gui/src/awt/org/jnode/awt/MouseHandler.java trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingBaseWindow.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/SwingToolkit.java Modified: trunk/core/src/core/org/jnode/vm/isolate/VmIsolate.java =================================================================== --- trunk/core/src/core/org/jnode/vm/isolate/VmIsolate.java 2008-11-17 07:50:22 UTC (rev 4705) +++ trunk/core/src/core/org/jnode/vm/isolate/VmIsolate.java 2008-11-17 13:46:59 UTC (rev 4706) @@ -416,6 +416,12 @@ //only this isolate may call this method testIsolate(isolate); + //todo add similar checks to other exit modes too + synchronized (this) { + if(!this.state.equals(State.STARTED)) + return; + } + changeState(State.EXITING); this.exitReason = IsolateStatus.ExitReason.SELF_EXIT; Modified: trunk/core/src/openjdk/java/java/awt/DefaultKeyboardFocusManager.java =================================================================== --- trunk/core/src/openjdk/java/java/awt/DefaultKeyboardFocusManager.java 2008-11-17 07:50:22 UTC (rev 4705) +++ trunk/core/src/openjdk/java/java/awt/DefaultKeyboardFocusManager.java 2008-11-17 13:46:59 UTC (rev 4706) @@ -669,6 +669,7 @@ // Then we need to deactive the active Window as well. // No need to synthesize in other cases, because // WINDOW_ACTIVATED will handle it if necessary. + if(activeWindow != null) //jnode sometimes this is null, todo check it why sendMessage(activeWindow, new WindowEvent(activeWindow, WindowEvent.WINDOW_DEACTIVATED, Modified: trunk/core/src/openjdk/java/java/awt/KeyboardFocusManager.java =================================================================== --- trunk/core/src/openjdk/java/java/awt/KeyboardFocusManager.java 2008-11-17 07:50:22 UTC (rev 4705) +++ trunk/core/src/openjdk/java/java/awt/KeyboardFocusManager.java 2008-11-17 13:46:59 UTC (rev 4706) @@ -173,9 +173,21 @@ return getCurrentKeyboardFocusManager(AppContext.getAppContext()); } + //jnode-- + private static KeyboardFocusManager kbfm; synchronized static KeyboardFocusManager getCurrentKeyboardFocusManager(AppContext appcontext) { + if (kbfm == null) { + kbfm = new DefaultKeyboardFocusManager(); + } + return kbfm; + } + //--jnode + /* original + synchronized static KeyboardFocusManager + getCurrentKeyboardFocusManager(AppContext appcontext) + { KeyboardFocusManager manager = (KeyboardFocusManager) appcontext.get(KeyboardFocusManager.class); if (manager == null) { @@ -184,6 +196,7 @@ } return manager; } + */ /** * Sets the current KeyboardFocusManager instance for the calling thread's @@ -468,9 +481,13 @@ return null; } - return (focusOwner.appContext == AppContext.getAppContext()) + /*jnode + TODO remove it if we use per appcontext focus manager + return (focusOwner.appContext == AppContext.getAppContext()) ? focusOwner : null; + */ + return focusOwner; } } Modified: trunk/core/src/openjdk/java/java/awt/Toolkit.java =================================================================== --- trunk/core/src/openjdk/java/java/awt/Toolkit.java 2008-11-17 07:50:22 UTC (rev 4705) +++ trunk/core/src/openjdk/java/java/awt/Toolkit.java 2008-11-17 13:46:59 UTC (rev 4706) @@ -67,6 +67,7 @@ import sun.security.util.SecurityConstants; import sun.util.CoreResourceBundleControl; +import org.jnode.vm.VmSystem; /** * This class is the abstract superclass of all actual @@ -866,6 +867,10 @@ try { //jnode ClassLoader cl = Thread.currentThread().getContextClassLoader(); + if(cl == null) + cl = Toolkit.class.getClassLoader(); + if(cl == null) + cl = VmSystem.getSystemClassLoader().asClassLoader(); cls = cl.loadClass(nm); } catch (ClassNotFoundException e) { ClassLoader cl = ClassLoader.getSystemClassLoader(); Modified: trunk/core/src/openjdk/sun/sun/awt/SunToolkit.java =================================================================== --- trunk/core/src/openjdk/sun/sun/awt/SunToolkit.java 2008-11-17 07:50:22 UTC (rev 4705) +++ trunk/core/src/openjdk/sun/sun/awt/SunToolkit.java 2008-11-17 13:46:59 UTC (rev 4706) @@ -612,11 +612,17 @@ if (eventContext != null && !eventContext.equals(appContext)) { log.fine("Event posted on wrong app context : " + event); } - PostEventQueue postEventQueue = + /*jnode: post queues are not used at this time + PostEventQueue postEventQueue = (PostEventQueue)appContext.get(POST_EVENT_QUEUE_KEY); if(postEventQueue != null) { postEventQueue.postEvent(event); } + */ + EventQueue eventQueue = (EventQueue) appContext.get(AppContext.EVENT_QUEUE_KEY); + if (eventQueue != null) { + eventQueue.postEvent(event); + } } /* Modified: trunk/gui/src/awt/org/jnode/awt/JNodeToolkit.java =================================================================== --- trunk/gui/src/awt/org/jnode/awt/JNodeToolkit.java 2008-11-17 07:50:22 UTC (rev 4705) +++ trunk/gui/src/awt/org/jnode/awt/JNodeToolkit.java 2008-11-17 13:46:59 UTC (rev 4706) @@ -26,8 +26,8 @@ import gnu.java.awt.peer.ClasspathFontPeer; import gnu.java.awt.peer.EmbeddedWindowPeer; import gnu.java.security.action.GetPropertyAction; - import java.awt.AWTError; +import java.awt.AWTEvent; import java.awt.AWTException; import java.awt.Color; import java.awt.Component; @@ -50,6 +50,7 @@ import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; +import java.awt.event.ComponentEvent; import java.awt.geom.AffineTransform; import java.awt.im.InputMethodHighlight; import java.awt.image.BufferedImage; @@ -75,10 +76,8 @@ import java.util.Map; import java.util.Properties; import java.util.Set; - import javax.imageio.ImageIO; import javax.naming.NamingException; - import org.apache.log4j.Logger; import org.jnode.awt.font.FontManager; import org.jnode.awt.image.BufferedImageSurface; @@ -91,16 +90,19 @@ import org.jnode.driver.video.Surface; import org.jnode.driver.video.UnknownConfigurationException; import org.jnode.naming.InitialNaming; - +import org.jnode.vm.annotation.SharedStatics; +import sun.awt.AppContext; +import sun.awt.SunToolkit; import sun.awt.image.ToolkitImage; /** * @author epr * @author Levente S\u00e1ntha */ +@SharedStatics public abstract class JNodeToolkit extends ClasspathToolkit implements FrameBufferAPIOwner { protected static final Logger log = Logger.getLogger(JNodeToolkit.class); - + private final Object initCloseLock = new Object(); private EventQueue waitingNativeQueue; private Clipboard systemClipboard; @@ -121,6 +123,23 @@ public JNodeToolkit() { refCount = 0; systemClipboard = new Clipboard("JNodeSystemClipboard"); + + //initialize the main AppContext + AppContext appContext = AppContext.getAppContext(); + + synchronized (this) { + if (appContext.get(AppContext.EVENT_QUEUE_KEY) == null || _eventQueue == null) { + String eqName = System.getProperty("AWT.EventQueueClass", "org.jnode.awt.JNodeEventQueue"); + try { + _eventQueue = (JNodeEventQueue) Class.forName(eqName).newInstance(); + } catch (Exception e) { + e.printStackTrace(); + System.err.println("Failed loading " + eqName + ": " + e); + _eventQueue = new JNodeEventQueue(); + } + appContext.put(AppContext.EVENT_QUEUE_KEY, _eventQueue); + } + } } /** @@ -148,7 +167,7 @@ } public static boolean isGuiActive() { - final Toolkit tk = getDefaultToolkit(); + final Toolkit tk = Toolkit.getDefaultToolkit(); if (!(tk instanceof JNodeToolkit)) { throw new AWTError("Toolkit is not a JNodeToolkit"); } @@ -156,8 +175,7 @@ } public static void startGui() { - clearDefaultToolkit(); - final Toolkit tk = getDefaultToolkit(); + final Toolkit tk = Toolkit.getDefaultToolkit(); if (!(tk instanceof JNodeToolkit)) { throw new AWTError("Toolkit is not a JNodeToolkit"); } @@ -165,7 +183,7 @@ } public static void initGui() { - final Toolkit tk = getDefaultToolkit(); + final Toolkit tk = Toolkit.getDefaultToolkit(); if (!(tk instanceof JNodeToolkit)) { throw new AWTError("Toolkit is not a JNodeToolkit"); } @@ -173,15 +191,16 @@ } public static void stopGui() { - final Toolkit tk = getDefaultToolkit(); + final Toolkit tk = Toolkit.getDefaultToolkit(); if (!(tk instanceof JNodeToolkit)) { throw new AWTError("Toolkit is not a JNodeToolkit"); } ((JNodeToolkit) tk).decRefCount(true); + Toolkit.clearDefaultToolkit(); } public static void refreshGui() { - final Toolkit tk = getDefaultToolkit(); + final Toolkit tk = Toolkit.getDefaultToolkit(); if (!(tk instanceof JNodeToolkit)) { throw new AWTError("Toolkit is not a JNodeToolkit"); } @@ -193,7 +212,7 @@ } public static void waitUntilStopped() { - final Toolkit tk = getDefaultToolkit(); + final Toolkit tk = Toolkit.getDefaultToolkit(); if (!(tk instanceof JNodeToolkit)) { throw new AWTError("Toolkit is not a JNodeToolkit"); } @@ -602,16 +621,33 @@ * @return The event queue */ protected final EventQueue getSystemEventQueueImpl() { + AppContext ac = AppContext.getAppContext(); + if (ac != null) { + EventQueue eq = (EventQueue) ac.get(AppContext.EVENT_QUEUE_KEY); + if (eq != null) { + return eq; + } + } + if ((_eventQueue == null) || (!_eventQueue.isLive() && isGuiActive())) { synchronized (this) { if ((_eventQueue == null) || (!_eventQueue.isLive() && isGuiActive())) { _eventQueue = new JNodeEventQueue(); } + + if (ac != null && ac.get(AppContext.EVENT_QUEUE_KEY) == null) { + ac.put(AppContext.EVENT_QUEUE_KEY, _eventQueue); + } } } + return _eventQueue; } + public final synchronized EventQueue getMainEventQueue() { + return _eventQueue; + } + public Frame getTop() { return top; } @@ -786,22 +822,23 @@ config.getBounds().height - 2 * (100 + i)), null, tx, (i % 2 == 0) ? Color.RED : Color.BLUE, Surface.PAINT_MODE); } - + private JNodeFrameBufferDevice getDevice() { final JNodeFrameBufferDevice device = (JNodeFrameBufferDevice) GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); if (device == null) { throw new AWTError("No framebuffer fbDevice found"); } - + return device; } private GraphicsConfiguration[] configs; + public GraphicsConfiguration[] getConfigurations() { if (configs == null) { final GraphicsConfiguration[] configurations = getDevice().getConfigurations(); - + configs = new GraphicsConfiguration[configurations.length]; System.arraycopy(configurations, 0, configs, 0, configurations.length); Arrays.sort(configs, new Comparator<GraphicsConfiguration>() { @@ -809,7 +846,7 @@ public int compare(GraphicsConfiguration o1, GraphicsConfiguration o2) { final Rectangle b1 = o1.getBounds(); final Rectangle b2 = o2.getBounds(); - + int comp; if (b1.getWidth() > b2.getWidth()) { comp = +1; @@ -824,15 +861,15 @@ comp = 0; } } - + return comp; } - + }); } return configs; } - + public Dimension changeScreenSize(JNodeGraphicsConfiguration config) { final JNodeFrameBufferDevice device = getDevice(); @@ -900,7 +937,7 @@ graphicsMode = false; initCloseLock.notifyAll(); } - + api.releaseOwnership(this); } @@ -910,7 +947,7 @@ public final void joinGUI() { try { api.requestOwnership(this); - + this.graphics = api.open(config.getConfig()); this.keyboardHandler = new KeyboardHandler(_eventQueue); this.mouseHandler = new MouseHandler(fbDevice.getDevice(), @@ -1102,14 +1139,14 @@ //todo implementit return null; } - + @Override public void ownershipLost() { if (isGuiActive()) { leaveGUI(); } } - + @Override public void ownershipGained() { startAwt(); @@ -1117,7 +1154,7 @@ static void startAwt() { if (JNodeToolkit.isGuiActive()) { - ((JNodeToolkit) JNodeToolkit.getDefaultToolkit()).joinGUI(); + ((JNodeToolkit) Toolkit.getDefaultToolkit()).joinGUI(); JNodeToolkit.waitUntilStopped(); } else { JNodeToolkit.startGui(); @@ -1142,13 +1179,13 @@ JNodeToolkit.waitUntilStopped(); } } - ((JNodeToolkit) JNodeToolkit.getDefaultToolkit()).runExitAction(); + ((JNodeToolkit) Toolkit.getDefaultToolkit()).runExitAction(); } - + /** * Set the action to be performed after the GUI has been shutdown, and * before control is returned to (for instance) the CommandShell. - * + * * @param exitAction an action, or <code>null</code>. */ public static void setExitAction(Runnable exitAction) { @@ -1156,7 +1193,7 @@ // is currently used potentially offers a small window for some other // thread to insert an action that would then be executed in the security // context of the GUI's owner.) - ((JNodeToolkit) JNodeToolkit.getDefaultToolkit()).exitAction = exitAction; + ((JNodeToolkit) Toolkit.getDefaultToolkit()).exitAction = exitAction; } private synchronized void runExitAction() { @@ -1164,4 +1201,37 @@ exitAction.run(); } } + + /** + * Post the given event on the system eventqueue. + */ + public final void postEvent(AWTEvent event) { + Object source = event.getSource(); + if (source instanceof Component) { + AppContext ac = SunToolkit.targetToAppContext(source); + if (ac != null) { + java.awt.EventQueue eq = (java.awt.EventQueue) ac.get(sun.awt.AppContext.EVENT_QUEUE_KEY); + if (eq != null) { + eq.postEvent(event); + return; + } + } + } + getSystemEventQueueImpl().postEvent(event); + } + + public static void postToTarget(ComponentEvent event, Component target) { + EventQueue queue; + AppContext ac = SunToolkit.targetToAppContext(target); + if (ac == null) { + queue = Toolkit.getDefaultToolkit().getSystemEventQueue(); + } else { + queue = (EventQueue) ac.get(sun.awt.AppContext.EVENT_QUEUE_KEY); + if (queue == null) { + queue = Toolkit.getDefaultToolkit().getSystemEventQueue(); + } + } + + queue.postEvent(event); + } } Modified: trunk/gui/src/awt/org/jnode/awt/KeyboardHandler.java =================================================================== --- trunk/gui/src/awt/org/jnode/awt/KeyboardHandler.java 2008-11-17 07:50:22 UTC (rev 4705) +++ trunk/gui/src/awt/org/jnode/awt/KeyboardHandler.java 2008-11-17 13:46:59 UTC (rev 4706) @@ -256,7 +256,8 @@ } KeyEvent ke = new KeyEvent(source, id, time, modifiers, keyCode, keyChar); - eventQueue.postEvent(ke); + + JNodeToolkit.postToTarget(ke, source); } private boolean processSystemKey(KeyboardEvent event) { Modified: trunk/gui/src/awt/org/jnode/awt/MouseHandler.java =================================================================== --- trunk/gui/src/awt/org/jnode/awt/MouseHandler.java 2008-11-17 07:50:22 UTC (rev 4705) +++ trunk/gui/src/awt/org/jnode/awt/MouseHandler.java 2008-11-17 13:46:59 UTC (rev 4706) @@ -442,7 +442,8 @@ " p.x=" + p.x + " p.y=" + p.y +"\n"); } */ - eventQueue.postEvent(event); + + JNodeToolkit.postToTarget(event, source); } private Component findSource() { Modified: trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingBaseWindow.java =================================================================== --- trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingBaseWindow.java 2008-11-17 07:50:22 UTC (rev 4705) +++ trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingBaseWindow.java 2008-11-17 13:46:59 UTC (rev 4706) @@ -25,6 +25,7 @@ import java.awt.Color; import java.awt.Component; import java.awt.Container; +import java.awt.EventQueue; import java.awt.Frame; import java.awt.Graphics; import java.awt.Insets; @@ -39,6 +40,8 @@ import javax.swing.RootPaneContainer; import javax.swing.SwingUtilities; import javax.swing.UIManager; +import sun.awt.AppContext; +import sun.awt.SunToolkit; /** * Base class for peer implementation that subclass {@link java.awt.Window}. @@ -84,7 +87,9 @@ public void paint(Graphics g) { super.paint(g); if (target instanceof RootPaneContainer && isVisible()) { - target.paint(g.create()); + //target.paint(g.create()); + swingPeer.postPaintEvent(); + //JNodeToolkit.postToTarget(new PaintEvent(target, PaintEvent.UPDATE, target.getBounds()), target); } } @@ -116,7 +121,17 @@ * @see java.awt.Component#processEvent(java.awt.AWTEvent) */ protected final void processEvent(AWTEvent event) { - target.dispatchEvent(SwingToolkit.convertEvent(event, target)); + AppContext ac = SunToolkit.targetToAppContext(target); + if (ac == null) { + target.dispatchEvent(SwingToolkit.convertEvent(event, target)); + } else { + EventQueue eq = (EventQueue) ac.get(AppContext.EVENT_QUEUE_KEY); + if (eq == null) { + target.dispatchEvent(SwingToolkit.convertEvent(event, target)); + } else { + eq.postEvent(SwingToolkit.convertEvent(event, target)); + } + } } /** Modified: trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingBaseWindowPeer.java =================================================================== --- trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingBaseWindowPeer.java 2008-11-17 07:50:22 UTC (rev 4705) +++ trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingBaseWindowPeer.java 2008-11-17 13:46:59 UTC (rev 4706) @@ -21,23 +21,28 @@ package org.jnode.awt.swingpeers; +import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dialog; +import java.awt.EventQueue; import java.awt.Graphics; import java.awt.Insets; import java.awt.Point; +import java.awt.Toolkit; import java.awt.Window; -import java.awt.Color; +import java.awt.event.InvocationEvent; import java.awt.event.WindowEvent; import java.awt.peer.WindowPeer; import java.beans.PropertyVetoException; import javax.swing.JComponent; import javax.swing.JDesktopPane; -import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.event.InternalFrameEvent; import javax.swing.event.InternalFrameListener; +import org.jnode.awt.JNodeToolkit; +import sun.awt.AppContext; +import sun.awt.SunToolkit; /** * @author Ewout Prangsma (ep...@us...) @@ -70,7 +75,7 @@ * Add this window to the desktop. */ protected final void addToDesktop() { - SwingUtilities.invokeLater(new Runnable() { + Runnable run = new Runnable() { public void run() { final JDesktopPane desktop = toolkit.getAwtContext().getDesktop(); desktop.add(peerComponent); @@ -83,7 +88,19 @@ log.warn("", x); } } - }); + }; + + final JDesktopPane desktop = toolkit.getAwtContext().getDesktop(); + AppContext ac = SunToolkit.targetToAppContext(desktop); + if (ac != null) { + EventQueue eq = (EventQueue) ac.get(AppContext.EVENT_QUEUE_KEY); + if (eq != null) { + eq.postEvent(new InvocationEvent(Toolkit.getDefaultToolkit(), run)); + return; + } + } + //shouldn't get here + throw new RuntimeException("Desktop event queue not found!"); } /** @@ -174,7 +191,7 @@ * Fire a WindowEvent with a given id to the awtComponent. */ private final void fireWindowEvent(int id) { - getToolkitImpl().postEvent(new WindowEvent(targetComponent, id)); + JNodeToolkit.postToTarget(new WindowEvent(targetComponent, id), targetComponent); } public void updateAlwaysOnTop() { Modified: trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingComponentPeer.java =================================================================== --- trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingComponentPeer.java 2008-11-17 07:50:22 UTC (rev 4705) +++ trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingComponentPeer.java 2008-11-17 13:46:59 UTC (rev 4706) @@ -29,7 +29,6 @@ import java.awt.Container; import java.awt.Cursor; import java.awt.Dimension; -import java.awt.EventQueue; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; @@ -55,6 +54,7 @@ import org.jnode.awt.GraphicsFactory; import org.jnode.awt.JNodeGenericPeer; import org.jnode.awt.JNodeGraphics2D; +import org.jnode.awt.JNodeToolkit; import sun.awt.CausedFocusEvent; /** @@ -277,7 +277,8 @@ */ protected final void postPaintEvent() { if (targetComponent != null) { - toolkit.postEvent(new PaintEvent(targetComponent, PaintEvent.PAINT, targetComponent.getBounds())); + final PaintEvent event = new PaintEvent(targetComponent, PaintEvent.PAINT, targetComponent.getBounds()); + JNodeToolkit.postToTarget(event, targetComponent); } } @@ -403,18 +404,14 @@ if (fl != null) { postPaintEvent(); - toolkit.postEvent(fl); - //XWindow.sendEvent(fl); + JNodeToolkit.postToTarget(fl, currentOwner); } - toolkit.postEvent(fg); - //XWindow.sendEvent(fg); + JNodeToolkit.postToTarget(fg, (Component) fg.getSource()); return true; } catch (Exception x) { x.printStackTrace(); - org.jnode.vm.Unsafe.debug("SwingComponentPeer.requestFocus() exception\n"); - org.jnode.vm.Unsafe.debugStackTrace(); return false; } } @@ -508,8 +505,7 @@ * @param what */ protected final void fireComponentEvent(int what) { - final EventQueue queue = toolkit.getSystemEventQueue(); - queue.postEvent(new ComponentEvent(targetComponent, what)); + JNodeToolkit.postToTarget(new ComponentEvent(targetComponent, what), targetComponent); } public void layout() { Modified: trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingToolkit.java =================================================================== --- trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingToolkit.java 2008-11-17 07:50:22 UTC (rev 4705) +++ trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingToolkit.java 2008-11-17 13:46:59 UTC (rev 4706) @@ -32,6 +32,7 @@ import java.awt.Component; import java.awt.Container; import java.awt.Dialog; +import java.awt.EventQueue; import java.awt.FileDialog; import java.awt.Font; import java.awt.Frame; @@ -51,9 +52,11 @@ import java.awt.Shape; import java.awt.TextArea; import java.awt.TextField; +import java.awt.Toolkit; import java.awt.Window; import java.awt.dnd.DragGestureEvent; import java.awt.dnd.peer.DragSourceContextPeer; +import java.awt.event.InvocationEvent; import java.awt.image.BufferedImage; import java.awt.peer.ButtonPeer; import java.awt.peer.CanvasPeer; @@ -85,12 +88,16 @@ import javax.swing.RepaintManager; import javax.swing.SwingUtilities; import javax.swing.UIManager; +import javax.swing.border.Border; +import javax.swing.border.EmptyBorder; import javax.swing.plaf.metal.MetalLookAndFeel; import javax.swing.plaf.metal.OceanTheme; -import javax.swing.border.Border; -import javax.swing.border.EmptyBorder; import org.jnode.awt.JNodeAwtContext; import org.jnode.awt.JNodeToolkit; +import org.jnode.vm.annotation.SharedStatics; +import sun.awt.AWTAutoShutdown; +import sun.awt.AppContext; +import sun.awt.SunToolkit; /** * AWT toolkit implemented entirely with JFC peers, thus allowing a lightweight @@ -99,6 +106,7 @@ * @author Levente S\u00e1ntha * @author Ewout Prangsma (ep...@us...) */ +@SharedStatics public final class SwingToolkit extends JNodeToolkit { /** @@ -155,13 +163,6 @@ } /** - * Post the given event on the system eventqueue. - */ - public final void postEvent(AWTEvent event) { - getSystemEventQueueImpl().postEvent(event); - } - - /** * Paint all the lightweight children of the given container. * * @param awtContainer @@ -247,31 +248,112 @@ return null; } - protected FramePeer createFrame(Frame target) { - if (!isGuiActive()) { - //throw new AWTError("AWT is currently not available"); - initGui(); - } - if (target instanceof DesktopFrame) { - setTop(target); - log.debug("createFrame:desktopFramePeer(" + target + ")"); - // Only desktop is real frame - return new DesktopFramePeer(this, (DesktopFrame) target); - } else /*if (target instanceof JFrame) */ { + protected FramePeer createFrame(final Frame target) { + final FramePeer[] ret = new FramePeer[1]; + + Runnable run = new Runnable() { + public void run() { + + if (!isGuiActive()) { + //throw new AWTError("AWT is currently not available"); + initGui(); + } + if (target instanceof DesktopFrame) { + setTop(target); + log.debug("createFrame:desktopFramePeer(" + target + ")"); + // Only desktop is real frame + //return new DesktopFramePeer(SwingToolkit.this, (DesktopFrame) target); + synchronized (ret) { + ret[0] = new DesktopFramePeer(SwingToolkit.this, (DesktopFrame) target); + try { + AWTAutoShutdown.class.getMethod("registerPeer", Object.class, Object.class). + invoke(AWTAutoShutdown.getInstance(), target, ret[0]); + } catch (Exception x) { + x.printStackTrace(); + } + } + } else /*if (target instanceof JFrame) */ { + if (!isGuiActive()) { + throw new AWTError("Gui is not active"); + } + log.debug("createFrame:normal(" + target + ")"); + // Other frames are emulated + //return new SwingFramePeer(SwingToolkit.this, target); + synchronized (ret) { + ret[0] = new SwingFramePeer(SwingToolkit.this, target); + } + } /*else { if (!isGuiActive()) { throw new AWTError("Gui is not active"); } log.debug("createFrame:normal(" + target + ")"); // Other frames are emulated - return new SwingFramePeer(this, target); - } /*else { - if (!isGuiActive()) { - throw new AWTError("Gui is not active"); - } - log.debug("createFrame:normal(" + target + ")"); - // Other frames are emulated return new SwingJFramePeer(this, target); } */ + } + }; + + //peer frames should be created in the same app context where the desktop is + //todo refactor this into a generic inter-appcontext invoke and wait + AppContext ac = SunToolkit.targetToAppContext(target); + if (ac != null) { + EventQueue eq = (EventQueue) ac.get(sun.awt.AppContext.EVENT_QUEUE_KEY); + if (eq != null) { + try { + EventQueue.class.getMethod("initDispatchThread").invoke(eq); + } catch (Exception x) { + x.printStackTrace(); + } + } + } + + // invoke and wait -- + EventQueue eq = getMainEventQueue(); + + if (eq == getSystemEventQueueImpl()) { + run.run(); + synchronized (ret) { + return ret[0]; + } + } + + try { + Thread edt = (Thread) EventQueue.class.getField("dispatchThread").get(eq); + if (Thread.currentThread() == edt) { + run.run(); + synchronized (ret) { + return ret[0]; + } + } + } catch (Exception x) { + throw new RuntimeException(x); + } + + class AWTInvocationLock { + } + Object lock = new AWTInvocationLock(); + + InvocationEvent event = new InvocationEvent(Toolkit.getDefaultToolkit(), run, lock, true); + + try { + synchronized (lock) { + eq.postEvent(event); + lock.wait(); + } + } catch (Exception x) { + throw new RuntimeException(x); + } + + Throwable eventThrowable = event.getThrowable(); + if (eventThrowable != null) { + throw new RuntimeException(eventThrowable); + } + + // --invoke and wait + + synchronized (ret) { + return ret[0]; + } } protected LabelPeer createLabel(Label target) { @@ -469,7 +551,7 @@ try { MetalLookAndFeel.setCurrentTheme(new OceanTheme()); - UIManager.setLookAndFeel(new MetalLookAndFeel()); + UIManager.setLookAndFeel(new MetalLookAndFeel()); } catch (Exception x) { log.warn("Look And Feel not found: ", x); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2008-11-17 13:53:57
|
Revision: 4707 http://jnode.svn.sourceforge.net/jnode/?rev=4707&view=rev Author: lsantha Date: 2008-11-17 13:53:52 +0000 (Mon, 17 Nov 2008) Log Message: ----------- Style fixes. Modified Paths: -------------- trunk/core/src/core/org/jnode/vm/isolate/IsolateThreadFactory.java trunk/core/src/core/org/jnode/vm/isolate/VmIsolate.java trunk/core/src/core/org/jnode/vm/scheduler/Monitor.java trunk/core/src/core/org/jnode/vm/scheduler/MonitorManager.java trunk/core/src/core/org/jnode/vm/scheduler/VmThread.java trunk/shell/src/shell/org/jnode/shell/help/EnhancedHelp.java Modified: trunk/core/src/core/org/jnode/vm/isolate/IsolateThreadFactory.java =================================================================== --- trunk/core/src/core/org/jnode/vm/isolate/IsolateThreadFactory.java 2008-11-17 13:46:59 UTC (rev 4706) +++ trunk/core/src/core/org/jnode/vm/isolate/IsolateThreadFactory.java 2008-11-17 13:53:52 UTC (rev 4707) @@ -3,12 +3,6 @@ import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; import org.jnode.vm.classmgr.VmIsolatedStatics; -import org.jnode.vm.Vm; -import org.jnode.vm.VmSystem; -import org.jnode.plugin.PluginManager; -import org.jnode.naming.InitialNaming; -import javax.naming.NameNotFoundException; -import javax.isolate.IsolateStartupException; class IsolateThreadFactory implements ThreadFactory { final ThreadGroup group; @@ -29,11 +23,11 @@ } } - Thread t = new IsolateFactoryThread(group, namePrefix + threadNumber.getAndIncrement(), isolatedStatics){ + Thread t = new IsolateFactoryThread(group, namePrefix + threadNumber.getAndIncrement(), isolatedStatics) { public void start() { - org.jnode.vm.Unsafe.debug("factory 1 thread start() " + this.getName() +"\n"); + org.jnode.vm.Unsafe.debug("factory 1 thread start() " + this.getName() + "\n"); // getVmThread().switchToIsolate(isolatedStatics); - super.start(); + super.start(); } }; /* @@ -46,16 +40,14 @@ */ //t.setContextClassLoader(piManager.getRegistry().getPluginsClassLoader()); // if (t.isDaemon()) - // t.setDaemon(false); - // if (t.getPriority() != Thread.NORM_PRIORITY) - // t.setPriority(Thread.NORM_PRIORITY + 2); + // t.setDaemon(false); + // if (t.getPriority() != Thread.NORM_PRIORITY) + // t.setPriority(Thread.NORM_PRIORITY + 2); return t; } } - - class IsolateThreadFactory2 implements ThreadFactory { final ThreadGroup group; final AtomicInteger threadNumber = new AtomicInteger(1); @@ -70,18 +62,18 @@ group = isolate.getThreadGroup(); namePrefix = "isolate-" + isolate.getId() + "-executor-"; isolatedStatics = isolate.getIsolatedStaticsTable(); - factoryThread = new Thread(group, new Runnable(){ + factoryThread = new Thread(group, new Runnable() { public void run() { - while(true) { + while (true) { synchronized (lock) { try { - while(runnable == null) { + while (runnable == null) { lock.wait(); } - newThread = new Thread(group, runnable, namePrefix + threadNumber.getAndIncrement()){ + newThread = new Thread(group, runnable, namePrefix + threadNumber.getAndIncrement()) { public void start() { - org.jnode.vm.Unsafe.debug("factory thread start() " + this.getName() +"\n"); + org.jnode.vm.Unsafe.debug("factory thread start() " + this.getName() + "\n"); super.start(); } }; @@ -93,7 +85,7 @@ } } } - },"isolate-" + isolate.getId() + "-thread-factory-"); + }, "isolate-" + isolate.getId() + "-thread-factory-"); factoryThread.start(); } @@ -105,7 +97,7 @@ newThread = null; runnable = r; lock.notifyAll(); - while(newThread == null) { + while (newThread == null) { try { lock.wait(); } catch (InterruptedException x) { @@ -178,7 +170,8 @@ } - newThread = new IsolateFactoryThread(group, null, namePrefix + threadNumber.getAndIncrement(), null); + newThread = new IsolateFactoryThread(group, null, namePrefix + + threadNumber.getAndIncrement(), null); } catch (Exception x) { x.printStackTrace(); } @@ -209,4 +202,4 @@ } } -*/ \ No newline at end of file +*/ Modified: trunk/core/src/core/org/jnode/vm/isolate/VmIsolate.java =================================================================== --- trunk/core/src/core/org/jnode/vm/isolate/VmIsolate.java 2008-11-17 13:46:59 UTC (rev 4706) +++ trunk/core/src/core/org/jnode/vm/isolate/VmIsolate.java 2008-11-17 13:53:52 UTC (rev 4707) @@ -48,12 +48,12 @@ import org.jnode.vm.VmIOContext; import org.jnode.vm.VmMagic; import org.jnode.vm.VmSystem; -import org.jnode.vm.scheduler.VmThread; import org.jnode.vm.annotation.MagicPermission; import org.jnode.vm.annotation.PrivilegedActionPragma; import org.jnode.vm.annotation.SharedStatics; import org.jnode.vm.classmgr.VmIsolatedStatics; import org.jnode.vm.classmgr.VmType; +import org.jnode.vm.scheduler.VmThread; /** * VM specific implementation of the Isolate class. @@ -304,9 +304,9 @@ this.isolatedStaticsTable = new VmIsolatedStatics(VmMagic.currentProcessor().getIsolatedStatics(), arch, new Unsafe.UnsafeObjectResolver()); this.creator = currentIsolate(); - if(getRoot().executor == null && isRoot()) { + if (getRoot().executor == null && isRoot()) { //initialize the root executor on the creation of the first child - getRoot().invokeAndWait(new Runnable(){ + getRoot().invokeAndWait(new Runnable() { public void run() { //org.jnode.vm.Unsafe.debug("Root executor ready\n"); } @@ -418,7 +418,7 @@ //todo add similar checks to other exit modes too synchronized (this) { - if(!this.state.equals(State.STARTED)) + if (!this.state.equals(State.STARTED)) return; } @@ -463,7 +463,7 @@ Thread thread = ta[i]; if (current != thread) { thread.getVmThread().stopForced(null); - } else { + } else { found = true; } } @@ -497,7 +497,7 @@ this.exitCode = status; } - if(vmThread.getName().indexOf("-AWT-stopper") > - 1) { + if (vmThread.getName().indexOf("-AWT-stopper") > -1) { doExit(); } else { disposeAppContext(true); @@ -558,7 +558,7 @@ private void doExit() { try { - if(!threadGroup.isDestroyed()) + if (!threadGroup.isDestroyed()) threadGroup.destroy(); } catch (Throwable t) { t.printStackTrace(); @@ -714,28 +714,28 @@ */ // public void invokeAndWait(final Runnable task) { - //TODO implement VmIsolate.invokeAndWait(Runnable) - /* - if(this == StaticData.rootIsolate){ - task.run(); - return; - } + //TODO implement VmIsolate.invokeAndWait(Runnable) + /* + if(this == StaticData.rootIsolate){ + task.run(); + return; + } - synchronized(taskSync){ - taskList.add(task); - taskSync.notifyAll(); - } + synchronized(taskSync){ + taskList.add(task); + taskSync.notifyAll(); + } - synchronized(task){ - while(taskList.contains(task)){ - try { - task.wait(); - }catch(InterruptedException e){ - // - } + synchronized(task){ + while(taskList.contains(task)){ + try { + task.wait(); + }catch(InterruptedException e){ + // } } - */ + } + */ // } /* private class TaskExecutor implements Runnable{ @@ -780,14 +780,14 @@ * @param task the task as a Runnable object */ public synchronized void invokeAndWait(final Runnable task) { - if(executor == null) { + if (executor == null) { executor = java.util.concurrent.Executors.newSingleThreadExecutor(new IsolateThreadFactory2(this)); } - if(task == null) + if (task == null) return; - + try { - if(executor.submit(task).get() != null) { + if (executor.submit(task).get() != null) { throw new RuntimeException("Execution failed!"); } } catch (Exception x) { @@ -802,11 +802,11 @@ */ public synchronized void invokeLater(final Runnable task) { org.jnode.vm.Unsafe.debug("invokeLater Called - 0\n"); - if(executor == null) { + if (executor == null) { executor = java.util.concurrent.Executors.newSingleThreadExecutor(new IsolateThreadFactory(this)); org.jnode.vm.Unsafe.debug("invokeAndWait executor created - 0\n"); } - if(task == null) + if (task == null) return; try { @@ -817,28 +817,28 @@ } } - boolean isEDT(){ - if(appContext == null) + boolean isEDT() { + if (appContext == null) return false; try { Object eq = appContext.getClass().getMethod("get", Object.class). invoke(appContext, appContext.getClass().getField("EVENT_QUEUE_KEY").get(null)); - if(eq == null) + if (eq == null) return false; org.jnode.vm.Unsafe.debug("isEDT - 1\n"); Object t = eq.getClass().getField("dispatchThread").get(eq); - if(t == null) + if (t == null) return false; org.jnode.vm.Unsafe.debug("isEDT edt=" + t + "\n"); org.jnode.vm.Unsafe.debug("isEDT currenThread=" + Thread.currentThread() + "\n"); return t == Thread.currentThread(); - }catch (Exception x) { + } catch (Exception x) { throw new RuntimeException(x); } /* @@ -850,13 +850,13 @@ } */ - // return false; - } + // return false; + } private Object appContext; private void disposeAppContext(boolean intraIsolate) { - if(appSupport != null) { + if (appSupport != null) { appSupport.stop(intraIsolate); } else { stopAllThreads(); @@ -864,7 +864,6 @@ } /** - * * @param intraIsolate * @deprecated */ @@ -879,10 +878,10 @@ org.jnode.vm.Unsafe.debug("disposeAppContextCalled - 000\n"); org.jnode.vm.Unsafe.debugStackTrace(); org.jnode.vm.Unsafe.debug("disposeAppContextCalled - 000 " + intraIsolate + "\n"); - if(appContext != null) { + if (appContext != null) { org.jnode.vm.Unsafe.debug("disposeAppContextCalled - 0001\n"); org.jnode.vm.Unsafe.debug("disposeAppContextCalled - 0002\n"); - if(intraIsolate && is_edt) { + if (intraIsolate && is_edt) { org.jnode.vm.Unsafe.debug("disposeAppContextCalled - 0003\n"); Thread t = new Thread(new Runnable() { public void run() { @@ -906,16 +905,18 @@ } else { org.jnode.vm.Unsafe.debug("disposeAppContextCalled - 0004\n"); org.jnode.vm.Unsafe.debug("disposeAppContextCalled - 0\n"); - getRoot().invokeAndWait(new Runnable(){ + getRoot().invokeAndWait(new Runnable() { public void run() { try { org.jnode.vm.Unsafe.debug("disposeAppContextCalled - 1\n"); org.jnode.vm.Unsafe.debug("disposeAppContextCalled appcontext: " + appContext + "\n"); - org.jnode.vm.Unsafe.debug("disposeAppContextCalled appcontext.getClass(): " + appContext.getClass() + "\n"); - org.jnode.vm.Unsafe.debug("disposeAppContextCalled appcontext.getClass().dispose: " + appContext.getClass().getMethod("dispose") + "\n"); + org.jnode.vm.Unsafe.debug( + "disposeAppContextCalled appcontext.getClass(): " + appContext.getClass() + "\n"); + org.jnode.vm.Unsafe.debug("disposeAppContextCalled appcontext.getClass().dispose: " + + appContext.getClass().getMethod("dispose") + "\n"); appContext.getClass().getMethod("dispose").invoke(appContext); org.jnode.vm.Unsafe.debug("disposeAppContextCalled - 2\n"); - }catch (Exception x) { + } catch (Exception x) { x.printStackTrace(); } } @@ -1171,7 +1172,7 @@ } public ThreadGroup getThreadGroup() { - if(threadGroup == null) { + if (threadGroup == null) { throw new IllegalStateException("Isolate not available"); } return threadGroup; @@ -1182,6 +1183,7 @@ @SharedStatics private static class AppSupport { private static boolean awtSupport; + static { try { Class.forName("java.awt.Toolkit"); @@ -1199,7 +1201,7 @@ } boolean isAWTReady() { - if(!awtSupport) + if (!awtSupport) return false; try { @@ -1210,7 +1212,7 @@ } void start() throws Exception { - if(isAWTReady()) { + if (isAWTReady()) { synchronized (this) { appContext = Class.forName("sun.awt.SunToolkit").getMethod("createNewAppContext").invoke(null); } @@ -1219,91 +1221,91 @@ void stop(boolean intraIsolate) { boolean done = false; - if(awtSupport) { + if (awtSupport) { synchronized (this) { - if(appContext != null) { + if (appContext != null) { disposeAppContext(intraIsolate); done = true; } } } - if(!done) { + if (!done) { vmIsolate.stopAllThreads(); vmIsolate.doExit(); } } - boolean isEDT(){ - if(appContext == null) - return false; + boolean isEDT() { + if (appContext == null) + return false; - try { - Object eq = appContext.getClass().getMethod("get", Object.class). - invoke(appContext, appContext.getClass().getField("EVENT_QUEUE_KEY").get(null)); - if(eq == null) - return false; + try { + Object eq = appContext.getClass().getMethod("get", Object.class). + invoke(appContext, appContext.getClass().getField("EVENT_QUEUE_KEY").get(null)); + if (eq == null) + return false; - Object t = eq.getClass().getField("dispatchThread").get(eq); - if(t == null) - return false; + Object t = eq.getClass().getField("dispatchThread").get(eq); + if (t == null) + return false; - return t == Thread.currentThread(); - }catch (Exception x) { - throw new RuntimeException(x); + return t == Thread.currentThread(); + } catch (Exception x) { + throw new RuntimeException(x); + } + /* + try { + return (Boolean) Class.forName("java.awt.EventQueue"). + getMethod("isDispatchThread").invoke(null); + } catch (Exception x) { + throw new RuntimeException(x); + + } + */ + // return false; } - /* - try { - return (Boolean) Class.forName("java.awt.EventQueue"). - getMethod("isDispatchThread").invoke(null); - } catch (Exception x) { - throw new RuntimeException(x); - } - */ - // return false; - } - - private void disposeAppContext(boolean intraIsolate) { - final Object appContext; - final boolean is_edt; - synchronized (this) { - is_edt = isEDT(); - appContext = this.appContext; - this.appContext = null; - } - if(appContext != null) { - if(intraIsolate && is_edt) { - Thread t = new Thread(new Runnable() { - public void run() { - getRoot().invokeAndWait(new Runnable() { - public void run() { - try { - appContext.getClass().getMethod("dispose").invoke(appContext); - } catch (Exception x) { - x.printStackTrace(); + private void disposeAppContext(boolean intraIsolate) { + final Object appContext; + final boolean is_edt; + synchronized (this) { + is_edt = isEDT(); + appContext = this.appContext; + this.appContext = null; + } + if (appContext != null) { + if (intraIsolate && is_edt) { + Thread t = new Thread(new Runnable() { + public void run() { + getRoot().invokeAndWait(new Runnable() { + public void run() { + try { + appContext.getClass().getMethod("dispose").invoke(appContext); + } catch (Exception x) { + x.printStackTrace(); + } } + }); + vmIsolate.stopAllThreads(); + vmIsolate.doExit(); + } + }, "isolate-" + vmIsolate.getId() + "-AWT-stopper"); + t.start(); + } else { + getRoot().invokeAndWait(new Runnable() { + public void run() { + try { + appContext.getClass().getMethod("dispose").invoke(appContext); + } catch (Exception x) { + x.printStackTrace(); } - }); - vmIsolate.stopAllThreads(); - vmIsolate.doExit(); - } - }, "isolate-" + vmIsolate.getId() + "-AWT-stopper"); - t.start(); - } else { - getRoot().invokeAndWait(new Runnable(){ - public void run() { - try { - appContext.getClass().getMethod("dispose").invoke(appContext); - }catch (Exception x) { - x.printStackTrace(); } - } - }); - vmIsolate.stopAllThreads(); + }); + vmIsolate.stopAllThreads(); + } } } } - } } Modified: trunk/core/src/core/org/jnode/vm/scheduler/Monitor.java =================================================================== --- trunk/core/src/core/org/jnode/vm/scheduler/Monitor.java 2008-11-17 13:46:59 UTC (rev 4706) +++ trunk/core/src/core/org/jnode/vm/scheduler/Monitor.java 2008-11-17 13:53:52 UTC (rev 4707) @@ -556,15 +556,15 @@ @Inline private void addToOwner() { Monitor lom = owner.getLastOwnedMonitor(); - if(lom == null) { + if (lom == null) { //the first monitor owner.setLastOwnedMonitor(this); } else { - if(lom.owner != this.owner) { + if (lom.owner != this.owner) { //todo error return; } else { - if(lom == this) { + if (lom == this) { //no need to add it return; } else { @@ -578,16 +578,16 @@ @Inline private void dropFromOwner() { - if(owner == null) { + if (owner == null) { //error return; } Monitor lom = owner.getLastOwnedMonitor(); - if(lom == null) + if (lom == null) return; - if(lom != this) + if (lom != this) return; owner.setLastOwnedMonitor(lom.previous); Modified: trunk/core/src/core/org/jnode/vm/scheduler/MonitorManager.java =================================================================== --- trunk/core/src/core/org/jnode/vm/scheduler/MonitorManager.java 2008-11-17 13:46:59 UTC (rev 4706) +++ trunk/core/src/core/org/jnode/vm/scheduler/MonitorManager.java 2008-11-17 13:53:52 UTC (rev 4707) @@ -102,7 +102,7 @@ // thin lock owned by another thread. int ownerId = oldlockword.and(Word.fromIntZeroExtend(ObjectFlags.THREAD_ID_MASK)).toInt(); VmThread thread = VmMagic.currentProcessor().getScheduler().getThreadById(ownerId); - if(thread == null) { + if (thread == null) { //the owner of the lock was destroyed //aquire the lock in fast fashion statusPtr.store(statusFlags.or(tid)); @@ -283,7 +283,7 @@ int lockcount = 1 + oldlockword.and(Word.fromIntZeroExtend(ObjectFlags.LOCK_COUNT_MASK)). rshl(ObjectFlags.LOCK_COUNT_SHIFT).toInt(); int ownerId = oldlockword.and(Word.fromIntZeroExtend(ObjectFlags.THREAD_ID_MASK)).toInt(); - if(thread == null) { + if (thread == null) { thread = VmMagic.currentProcessor().getScheduler().getThreadById(ownerId); } m.initialize(thread, lockcount); Modified: trunk/core/src/core/org/jnode/vm/scheduler/VmThread.java =================================================================== --- trunk/core/src/core/org/jnode/vm/scheduler/VmThread.java 2008-11-17 13:46:59 UTC (rev 4706) +++ trunk/core/src/core/org/jnode/vm/scheduler/VmThread.java 2008-11-17 13:53:52 UTC (rev 4707) @@ -440,7 +440,7 @@ private final void doStop() { //release monitors Monitor lom = lastOwnedMonitor; - while(lom != null) { + while (lom != null) { Monitor prev = lom.getPrevious(); lom.release(this); if (prev == lom) Modified: trunk/shell/src/shell/org/jnode/shell/help/EnhancedHelp.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/help/EnhancedHelp.java 2008-11-17 13:46:59 UTC (rev 4706) +++ trunk/shell/src/shell/org/jnode/shell/help/EnhancedHelp.java 2008-11-17 13:53:52 UTC (rev 4707) @@ -18,7 +18,7 @@ * 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.help; +package org.jnode.shell.help; import java.io.PrintWriter; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fd...@us...> - 2008-11-17 22:55:38
|
Revision: 4708 http://jnode.svn.sourceforge.net/jnode/?rev=4708&view=rev Author: fduminy Date: 2008-11-17 22:55:33 +0000 (Mon, 17 Nov 2008) Log Message: ----------- - integrated jnode contributions into mauve - added binary of latest mauve (jnode's custom test list : testslists, latest list from mauve: testslists.orig) - added sources of latest mauve - removed unecessary jnode plugins related to mauve Modified Paths: -------------- trunk/all/conf/tests-plugin-list.xml trunk/core/descriptors/gnu.mauve.xml trunk/core/lib/mauve-src.jar trunk/core/lib/mauve.jar trunk/core/src/test/org/jnode/test/mauve/PluginTestHarness.java trunk/core/src/test/org/jtestserver/server/commands/MauveTestRunner.java Added Paths: ----------- trunk/core/descriptors/gnu.mauve.plugin.xml Removed Paths: ------------- trunk/core/descriptors/gnu.mauve.core.xml trunk/core/descriptors/gnu.mauve.java.lang.xml trunk/core/descriptors/gnu.mauve.java.util.xml trunk/core/src/test/org/jnode/test/mauve/CheckResult.java trunk/core/src/test/org/jnode/test/mauve/ClassResult.java trunk/core/src/test/org/jnode/test/mauve/HTMLGenerator.java trunk/core/src/test/org/jnode/test/mauve/MauveTestCommand.java trunk/core/src/test/org/jnode/test/mauve/MauveTests.java trunk/core/src/test/org/jnode/test/mauve/PackageResult.java trunk/core/src/test/org/jnode/test/mauve/Result.java trunk/core/src/test/org/jnode/test/mauve/RunResult.java trunk/core/src/test/org/jnode/test/mauve/SingleTestHarness.java trunk/core/src/test/org/jnode/test/mauve/TestResult.java trunk/core/src/test/org/jnode/test/mauve/XMLReportConstants.java trunk/core/src/test/org/jnode/test/mauve/XMLReportParser.java trunk/core/src/test/org/jnode/test/mauve/XMLReportWriter.java trunk/core/src/test/org/jnode/test/mauve/compare/ Modified: trunk/all/conf/tests-plugin-list.xml =================================================================== --- trunk/all/conf/tests-plugin-list.xml 2008-11-17 13:53:52 UTC (rev 4707) +++ trunk/all/conf/tests-plugin-list.xml 2008-11-17 22:55:33 UTC (rev 4708) @@ -10,9 +10,7 @@ <plugin id="org.junit"/> <plugin id="gnu.mauve"/> - <plugin id="gnu.mauve.core"/> - <plugin id="gnu.mauve.java.util"/> - <plugin id="gnu.mauve.java.lang"/> + <plugin id="gnu.mauve.plugin"/> <plugin id="org.objectweb.asm"/> <plugin id="net.sf.cglib"/> Deleted: trunk/core/descriptors/gnu.mauve.core.xml =================================================================== --- trunk/core/descriptors/gnu.mauve.core.xml 2008-11-17 13:53:52 UTC (rev 4707) +++ trunk/core/descriptors/gnu.mauve.core.xml 2008-11-17 22:55:33 UTC (rev 4708) @@ -1,32 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE plugin SYSTEM "jnode.dtd"> - -<plugin id="gnu.mauve.core" - name="Mauve java.lang testlets" - version="@VERSION@" - system="false" - provider-name="Mauve" - provider-url="http://sources.redhat.com/mauve/" - license-name="gpl"> - - <runtime> - <library name="mauve.jar"> - <!-- export name="gnu/testlet/*"/ --> - <export name="*"/> - </library> - <library name="jnode-core.jar"> - <export name="org/jnode/test/mauve/*"/> - <export name="org/jnode/test/mauve/compare/*"/> - </library> - </runtime> - - <extension point="org.jnode.shell.aliases"> - <alias name="mauve-plugin" class="org.jnode.test.mauve.PluginTestHarness"/> - <alias name="mauve-simple" class="org.jnode.test.mauve.SingleTestHarness"/> - <alias name="testCommand" class="org.jnode.test.mauve.MauveTestCommand"/> - </extension> - - <extension point="org.jnode.security.permissions"> - <permission class="java.security.AllPermission" /> - </extension> -</plugin> Deleted: trunk/core/descriptors/gnu.mauve.java.lang.xml =================================================================== --- trunk/core/descriptors/gnu.mauve.java.lang.xml 2008-11-17 13:53:52 UTC (rev 4707) +++ trunk/core/descriptors/gnu.mauve.java.lang.xml 2008-11-17 22:55:33 UTC (rev 4708) @@ -1,25 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE plugin SYSTEM "jnode.dtd"> - -<plugin id="gnu.mauve.java.lang" - name="Mauve core classes" - version="@VERSION@" - system="false" - provider-name="Mauve" - provider-url="http://sources.redhat.com/mauve/" - license-name="gpl"> - - <runtime> - <library name="mauve.jar"> - <export name="gnu/testlet/java/lang/**/*"/> - </library> - </runtime> - - <requires> - <import plugin="gnu.mauve.core"/> - </requires> - - <extension point="org.jnode.security.permissions"> - <permission class="java.security.AllPermission" /> - </extension> -</plugin> Deleted: trunk/core/descriptors/gnu.mauve.java.util.xml =================================================================== --- trunk/core/descriptors/gnu.mauve.java.util.xml 2008-11-17 13:53:52 UTC (rev 4707) +++ trunk/core/descriptors/gnu.mauve.java.util.xml 2008-11-17 22:55:33 UTC (rev 4708) @@ -1,25 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE plugin SYSTEM "jnode.dtd"> - -<plugin id="gnu.mauve.java.util" - name="Mauve core classes" - version="@VERSION@" - system="false" - provider-name="Mauve" - provider-url="http://sources.redhat.com/mauve/" - license-name="gpl"> - - <runtime> - <library name="mauve.jar"> - <export name="gnu/testlet/java/util/**/*"/> - </library> - </runtime> - - <requires> - <import plugin="gnu.mauve.core"/> - </requires> - - <extension point="org.jnode.security.permissions"> - <permission class="java.security.AllPermission" /> - </extension> -</plugin> Added: trunk/core/descriptors/gnu.mauve.plugin.xml =================================================================== --- trunk/core/descriptors/gnu.mauve.plugin.xml (rev 0) +++ trunk/core/descriptors/gnu.mauve.plugin.xml 2008-11-17 22:55:33 UTC (rev 4708) @@ -0,0 +1,26 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plugin SYSTEM "jnode.dtd"> + +<fragment id="gnu.mauve.plugin" + name="Mauve extensions for JNode" + version="@VERSION@" + plugin-id="gnu.mauve" + plugin-version="@VERSION@" + provider-name="JNode.org" + provider-url="http://www.jnode.org/" + license-name="gpl"> + + <runtime> + <library name="jnode-core.jar"> + <export name="org/jnode/test/mauve/*"/> + </library> + </runtime> + + <extension point="org.jnode.shell.aliases"> + <alias name="mauve-plugin" class="org.jnode.test.mauve.PluginTestHarness"/> + </extension> + + <extension point="org.jnode.security.permissions"> + <permission class="java.security.AllPermission" /> + </extension> +</fragment> Modified: trunk/core/descriptors/gnu.mauve.xml =================================================================== --- trunk/core/descriptors/gnu.mauve.xml 2008-11-17 13:53:52 UTC (rev 4707) +++ trunk/core/descriptors/gnu.mauve.xml 2008-11-17 22:55:33 UTC (rev 4708) @@ -18,6 +18,8 @@ <extension point="org.jnode.shell.aliases"> <alias name="mauve" class="gnu.testlet.runner.Mauve"/> <alias name="mauve-filter" class="gnu.testlet.runner.Filter"/> + <alias name="mauve-compare" class="gnu.testlet.runner.compare.ReportComparator"/> + <alias name="mauve-single" class="gnu.testlet.SingleTestHarness"/> </extension> <extension point="org.jnode.security.permissions"> Modified: trunk/core/lib/mauve-src.jar =================================================================== (Binary files differ) Modified: trunk/core/lib/mauve.jar =================================================================== (Binary files differ) Deleted: trunk/core/src/test/org/jnode/test/mauve/CheckResult.java =================================================================== --- trunk/core/src/test/org/jnode/test/mauve/CheckResult.java 2008-11-17 13:53:52 UTC (rev 4707) +++ trunk/core/src/test/org/jnode/test/mauve/CheckResult.java 2008-11-17 22:55:33 UTC (rev 4708) @@ -1,192 +0,0 @@ -// Tags: not-a-test -// Copyright (C) 2004 by Object Refinery Limited -// Written by David Gilbert (dav...@ob...) -// Modified by Levente S\u00e1ntha (ls...@jn...) -// Modified by Peter Barth (pe...@jn...) -// Modified by Fabien DUMINY (fd...@jn...) - -// This file is part of Mauve Reporter. - -// Mauve Reporter is free software; you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation; either version 2 of the License, or -// (at your option) any later version. - -// Mauve Reporter 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 General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Mauve Reporter; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - -package org.jnode.test.mauve; - -/** - * Records the details of a check that is performed by Mauve. - */ -public class CheckResult implements Result { - - /** - * The check number. - */ - private int number; - - /** - * The check point string. - */ - private String checkPoint; - - /** - * A flag that indicates whether or not the check passed. - */ - private boolean passed; - - /** - * The expected result (converted to a string). - */ - private String expected; - - /** - * The actual result (converted to a string). - */ - private String actual; - - /** - * The log output for the check. - */ - private StringBuffer log; - - /** - * Creates a new check. - * - * @param number the check number. - * @param passed a flag that indicates whether or not the check passed. - */ - CheckResult(int number, boolean passed) { - this.number = number; - this.passed = passed; - } - - /** - * Returns the check number. - * - * @return The check number. - */ - public int getNumber() { - return this.number; - } - - /** - * Sets the check number. - * - * @param number the number. - */ - void setNumber(int number) { - this.number = number; - } - - /** - * Returns a flag that indicates whether or not the check passed. - * - * @return A boolean. - */ - public boolean getPassed() { - return passed; - } - - /** - * Sets the flag that indicates whether or not the check passed. - * - * @param passed the flag. - */ - void setPassed(boolean passed) { - this.passed = passed; - } - - /** - * Returns the check point string. - * - * @return The check point string. - */ - public String getCheckPoint() { - return checkPoint; - } - - /** - * Sets the check point string. - * - * @param checkPoint the check point string. - */ - void setCheckPoint(String checkPoint) { - this.checkPoint = checkPoint; - } - - /** - * Returns a string representing the actual value. - * - * @return The actual value. - */ - public String getActual() { - if (actual == null) - return "n/a"; - return actual; - } - - /** - * Sets the actual value. - * - * @param actual the actual value. - */ - void setActual(String actual) { - this.actual = actual; - } - - /** - * Returns the expected value. - * - * @return The expected value. - */ - public String getExpected() { - if (expected == null) - return "n/a"; - return expected; - } - - /** - * Sets the expected value. - * - * @param expected the expected value. - */ - void setExpected(String expected) { - this.expected = expected; - } - - /** - * Returns the log. - * - * @return The log. - */ - public String getLog() { - if (log == null) - return ""; - return log.toString(); - } - - /** - * Appends the specified message to the log. - * - * @param message the message to append. - */ - void appendToLog(String message) { - if (log == null) - log = new StringBuffer(); - log.append(message); - } - - @Override - public String getName() { - return Integer.toString(number); - } -} Deleted: trunk/core/src/test/org/jnode/test/mauve/ClassResult.java =================================================================== --- trunk/core/src/test/org/jnode/test/mauve/ClassResult.java 2008-11-17 13:53:52 UTC (rev 4707) +++ trunk/core/src/test/org/jnode/test/mauve/ClassResult.java 2008-11-17 22:55:33 UTC (rev 4708) @@ -1,134 +0,0 @@ -// Tags: not-a-test -// Copyright (C) 2004 by Object Refinery Limited -// Written by David Gilbert (dav...@ob...) -// Modified by Levente S\u00e1ntha (ls...@jn...) -// Modified by Peter Barth (pe...@jn...) -// Modified by Fabien DUMINY (fd...@jn...) - -// This file is part of Mauve Reporter. - -// Mauve Reporter is free software; you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation; either version 2 of the License, or -// (at your option) any later version. - -// Mauve Reporter 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 General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Mauve Reporter; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -package org.jnode.test.mauve; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -/** - * Represents the result of running all the tests for a particular class. - */ -public class ClassResult implements Comparable, Result { - - /** - * The name of the test (usually the class name). - */ - private String name; - - /** - * A list containing results for each test applied for the class. - */ - private List testResults; - private boolean sorted = true; - - /** - * Creates a new result, initially empty. - * - * @param name the class name. - */ - ClassResult(String name) { - this.name = name; - testResults = new ArrayList(); - } - - /** - * Returns the test name (this is most often the name of the method - * being tested). - * - * @return The test name. - */ - public String getName() { - return name; - } - - /** - * Sets the test name. - * - * @param name the name. - */ - void setName(String name) { - this.name = name; - } - - /** - * Adds a test result. - * - * @param result the test result. - */ - public void add(TestResult result) { - testResults.add(result); - sorted = false; - } - - /** - * Returns an iterator that provides access to all the tests for - * this class. - * - * @return An iterator. - */ - public Iterator getTestIterator() { - if (!sorted) { - Collections.sort(testResults); - sorted = true; - } - return testResults.iterator(); - } - - /** - * Returns the total number of checks performed for this class. - * - * @return The check count. - */ - public int getCheckCount() { - int result = 0; - Iterator iterator = testResults.iterator(); - while (iterator.hasNext()) { - TestResult test = (TestResult) iterator.next(); - result = result + test.getCheckCount(); - } - return result; - } - - /** - * Returns the number of checks with the specified status. - * - * @param passed the check status. - * @return The number of checks passed or failed. - */ - public int getCheckCount(boolean passed) { - int result = 0; - Iterator iterator = testResults.iterator(); - while (iterator.hasNext()) { - TestResult test = (TestResult) iterator.next(); - result = result + test.getCheckCount(passed); - } - return result; - } - - public int compareTo(Object obj) { - ClassResult that = (ClassResult) obj; - return getName().compareTo(that.getName()); - } -} Deleted: trunk/core/src/test/org/jnode/test/mauve/HTMLGenerator.java =================================================================== --- trunk/core/src/test/org/jnode/test/mauve/HTMLGenerator.java 2008-11-17 13:53:52 UTC (rev 4707) +++ trunk/core/src/test/org/jnode/test/mauve/HTMLGenerator.java 2008-11-17 22:55:33 UTC (rev 4708) @@ -1,443 +0,0 @@ -// Copyright (C) 2004 by Object Refinery Limited -// Written by David Gilbert (dav...@ob...) -// Modified by Levente S\u00e1ntha (ls...@jn...) -// Modified by Peter Barth (pe...@jn...) - -// This file is part of Mauve Reporter. - -// Mauve Reporter is free software; you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation; either version 2 of the License, or -// (at your option) any later version. - -// Mauve Reporter 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 General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Mauve Reporter; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -package org.jnode.test.mauve; - -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.io.Writer; -import java.text.DateFormat; -import java.util.Date; -import java.util.Iterator; - -/** - * Generates a collection of HTML files that summarise the results - * of a Mauve run. This is a quick-and-dirty implementation!! - */ -public class HTMLGenerator { - - /** - * Creates an HTML report in the specified directory. - * - * @param run the Mauve run results. - * @param rootDirectory the root directory. - */ - public static void createReport(RunResult run, File rootDirectory) throws IOException { - // write basic HTML with info about package - File summaryFile = new File(rootDirectory, "index.html"); - Writer out = new OutputStreamWriter(new FileOutputStream(summaryFile), "UTF-8"); - PrintWriter writer = new PrintWriter(out); - writer.println("<HTML>"); - writer.println("<HEAD><TITLE>Mauve Run: " + run.getName() + "</TITLE>"); - writer.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /></HEAD>"); - writer.println("<BODY>"); - writer.println("<h1>Mauve Run</h1>"); - writer.println("<h2>Summary:</h2>"); - int checkCount = run.getCheckCount(); - int passed = run.getCheckCount(true); - int failed = checkCount - passed; - writer.println("Run Date: " + - DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG).format(new Date()) + "<br>"); - writer.println("Passed: " + passed + "<br>"); - writer.println("Failed: " + failed + "<p>"); - - writer.println("<h2>Environment:</h2>"); - - writer.println("<table BORDER=\"0\" CELLPADDING=\"0\">"); - writer.println("<tr>"); - writer.println("<td bgcolor=\"black\" VALIGN=\"TOP\">"); - writer.println("<table BORDER=\"0\" WIDTH=\"100%\" CELLSPACING=\"1\" CELLPADDING=\"3\">"); - writer.println("<tr>"); - writer.println("<td bgcolor=\"lightGray\">Property:</td>"); - writer.println("<td bgcolor=\"lightGray\">Value:</td>"); - writer.println("</tr>"); - - writePropertyRow("java.version", System.getProperty("java.version"), writer); - writePropertyRow("java.vendor", System.getProperty("java.vendor"), writer); - writePropertyRow("java.vendor.url", System.getProperty("java.vendor.url"), writer); - writePropertyRow("os.name", System.getProperty("os.name"), writer); - writePropertyRow("os.arch", System.getProperty("os.arch"), writer); - writePropertyRow("os.version", System.getProperty("os.version"), writer); - - writePropertyRow("java.vm.specification.version", System.getProperty("java.vm.specification.version"), writer); - writePropertyRow("java.vm.specification.vendor", System.getProperty("java.vm.specification.vendor"), writer); - writePropertyRow("java.vm.specification.name", System.getProperty("java.vm.specification.name"), writer); - writePropertyRow("java.vm.version", System.getProperty("java.vm.version"), writer); - writePropertyRow("java.vm.vendor", System.getProperty("java.vm.vendor"), writer); - writePropertyRow("java.vm.name", System.getProperty("java.vm.name"), writer); - writePropertyRow("java.specification.version", System.getProperty("java.specification.version"), writer); - writePropertyRow("java.specification.vendor", System.getProperty("java.specification.vendor"), writer); - writePropertyRow("java.specification.name", System.getProperty("java.specification.name"), writer); - writePropertyRow("java.class.version", System.getProperty("java.class.version"), writer); - - writer.println("</table>"); - writer.println("</td>"); - writer.println("</tr>"); - writer.println("</table><p>"); - - writer.println("<h2>Results:</h2>"); - - writer.println("<table BORDER=\"0\" width=\"100%\" CELLPADDING=\"0\">"); - writer.println("<tr>"); - writer.println("<td bgcolor=\"black\" VALIGN=\"TOP\">"); - writer.println("<table BORDER=\"0\" WIDTH=\"100%\" CELLSPACING=\"1\" CELLPADDING=\"3\">"); - writer.println("<tr>"); - writer.println("<td bgcolor=\"lightGray\">Package:</td>"); - writer.println("<td bgcolor=\"lightGray\">Passed:</td>"); - writer.println("<td bgcolor=\"lightGray\">Failed:</td>"); - writer.println("<td bgcolor=\"lightGray\">Total:</td>"); - writer.println("</tr>"); - - // loop through tests writing test results - String top = null; - Iterator iterator = run.getPackageIterator(); - while (iterator.hasNext()) { - PackageResult packageResult = (PackageResult) iterator.next(); - String packageName = packageResult.getName().replace('.', '/'); - String name; - System.out.println("Generating " + packageName); - if (top != null && packageName.startsWith(top)) - name = " + " + packageName.substring(top.length() + 1); - else { - top = packageName; - name = packageName; - } - // (1) write the summary line for the class HTML file - writer.println("<tr>"); - writer.println( - "<td bgcolor=\"white\"><a href=\"" + packageName + "/package_index.html\"" + ">" + name + "</a></td>"); - writer.println("<td bgcolor=\"white\">" + packageResult.getCheckCount(true) + "</td>"); - writer.println("<td bgcolor=\"white\">" + packageResult.getCheckCount(false) + "</td>"); - writer.println("<td bgcolor=\"white\">" + packageResult.getCheckCount() + "</td>"); - writer.println("</tr>"); - // (2) generate an HTML page for the test and subfiles - // for the tests - try { - HTMLGenerator.createPackageReport(packageResult, rootDirectory); - } catch (Exception e) { - String temp = packageResult.getName().replace('.', '/'); - System.err.println("Couldn't create package report for " + temp); - File tempDir = new File(rootDirectory, packageName); - tempDir.mkdirs(); - File tempFile = new File(tempDir, "package_index.html"); - tempFile.createNewFile(); - } - } - writer.println("</table>"); - writer.println("</td>"); - writer.println("</tr>"); - writer.println("</table>"); - writer.println("<p>"); - Iterator missing = run.getMissingTestsIterator(); - Iterator failures = run.getFaultyTestsIterator(); - if (missing.hasNext() || failures.hasNext()) { - writer.println("<h2>Unrunnable tests:</h2>"); - - writer.println("<table BORDER=\"0\" width=\"100%\" CELLPADDING=\"0\">"); - writer.println("<tr>"); - writer.println("<td bgcolor=\"black\" VALIGN=\"TOP\">"); - writer.println("<table BORDER=\"0\" WIDTH=\"100%\" CELLSPACING=\"1\" CELLPADDING=\"3\">"); - writer.println("<tr>"); - writer.println("<td bgcolor=\"lightGray\">name:</td>"); - writer.println("<td bgcolor=\"lightGray\">problem:</td>"); - writer.println("</tr>"); - while (missing.hasNext()) - writer.println("<tr><td bgcolor=\"white\">" + (String) missing.next() + - "</td><td bgcolor=\"white\">Class not found</td></tr>"); - while (failures.hasNext()) { - String[] fail = (String[]) failures.next(); - writer.println("<tr><td bgcolor=\"white\">" + fail[0] + "</td><td bgcolor=\"white\">" + - fail[1] + "</td></tr>"); - } - writer.println("</table>"); - writer.println("</td>"); - writer.println("</tr>"); - writer.println("</table>"); - } - - writer.println("</BODY>"); - writer.println("</HTML>"); - writer.close(); - } - - /** - * Writes a row in a table for a pair of strings. - * - * @param property the property key. - * @param value the property value. - * @param writer the output stream. - */ - private static void writePropertyRow(String property, String value, PrintWriter writer) { - writer.println("<tr>"); - writer.println("<td bgcolor=\"white\">" + property + "</td>"); - writer.println("<td bgcolor=\"white\">" + value + "</td>"); - writer.println("</tr>"); - } - - /** - * Returns the number of directory levels in the specified package name. - * - * @param name the name. - * @return The number of directory levels. - */ - private static int countLevels(String name) { - int result = 1; - for (int i = 0; i < name.length(); i++) { - if (name.charAt(i) == '/') result++; - } - return result; - } - - /** - * Creates an HTML page that summaries a package, and processes all the classes within - * the package. - * - * @param packageResult the package result. - * @param rootDirectory the root directory. - */ - public static void createPackageReport(PackageResult packageResult, File rootDirectory) throws IOException { - // create directory for package - String packageName = packageResult.getName().replace('.', '/'); - String prefix = ""; - int levels = countLevels(packageName); - for (int i = 0; i < levels; i++) - prefix += "../"; - File packageDirectory = new File(rootDirectory, packageName); - packageDirectory.mkdirs(); - - // write basic HTML with info about package - File summaryFile = new File(packageDirectory, "package_index.html"); - OutputStream out = new BufferedOutputStream(new FileOutputStream(summaryFile)); - PrintWriter writer = new PrintWriter(out); - writer.println("<HTML>"); - writer.println("<HEAD><TITLE>Package Summary: " + packageResult.getName() + "</TITLE></HEAD>"); - writer.println("<BODY>"); - writer.println("<h2>Package: " + packageResult.getName() + "</h2>"); - writer.println("<a href=\"" + prefix + "index.html\">Summary page</a><p>"); - int checkCount = packageResult.getCheckCount(); - int passed = packageResult.getCheckCount(true); - int failed = checkCount - passed; - writer.println("Passed: " + passed + "<br>"); - writer.println("Failed: " + failed + "<p>"); - writer.println("<table BORDER=\"0\" width=\"100%\" CELLPADDING=\"0\">"); - writer.println("<tr>"); - writer.println("<td bgcolor=\"black\" VALIGN=\"TOP\">"); - writer.println("<table BORDER=\"0\" WIDTH=\"100%\" CELLSPACING=\"1\" CELLPADDING=\"3\">"); - writer.println("<tr>"); - writer.println("<td bgcolor=\"lightGray\">Class:</td>"); - writer.println("<td bgcolor=\"lightGray\">Passed:</td>"); - writer.println("<td bgcolor=\"lightGray\">Failed:</td>"); - writer.println("<td bgcolor=\"lightGray\">Total:</td>"); - writer.println("</tr>"); - - // loop through tests writing test results - Iterator iterator = packageResult.getClassIterator(); - while (iterator.hasNext()) { - ClassResult classResult = (ClassResult) iterator.next(); - // (1) write the summary line for the class HTML file - writer.println("<tr>"); - writer.println("<td bgcolor=\"white\"><a href=\"" + classResult.getName() + "/class_index.html\"" + ">" + - classResult.getName() + "</a></td>"); - writer.println("<td bgcolor=\"white\">" + classResult.getCheckCount(true) + "</td>"); - writer.println("<td bgcolor=\"white\">" + classResult.getCheckCount(false) + "</td>"); - writer.println("<td bgcolor=\"white\">" + classResult.getCheckCount() + "</td>"); - writer.println("</tr>"); - // (2) generate an HTML page for the test and subfiles - // for the tests - HTMLGenerator.createClassReport(classResult, packageResult.getName(), packageDirectory); - } - // close the class file - writer.println("</table>"); - writer.println("</td>"); - writer.println("</tr>"); - writer.println("</table>"); - writer.println("</BODY>"); - writer.println("</HTML>"); - writer.close(); - } - - /** - * Creates an HTML page summarising the results for a class, and processes all the tests for - * the class. - * - * @param classResult the class results. - * @param packageName the package name. - * @param packageDirectory the package directory. - */ - public static void createClassReport(ClassResult classResult, String packageName, File packageDirectory) - throws IOException { - // create directory for class - File classDirectory = new File(packageDirectory, classResult.getName()); - classDirectory.mkdirs(); - - // write basic HTML with info about class - File testFile = new File(classDirectory, "class_index.html"); - OutputStream out = new BufferedOutputStream(new FileOutputStream(testFile)); - PrintWriter writer = new PrintWriter(out); - writer.println("<HTML>"); - writer.println("<HEAD><TITLE>Class Summary: " + packageName + "." + classResult.getName() + "</TITLE></HEAD>"); - writer.println("<BODY>"); - writer.println("<h2>Class: " + "<a href=\"../package_index.html\">" + packageName + "</a>." + - classResult.getName() + "</h2>"); - int checkCount = classResult.getCheckCount(); - int passed = classResult.getCheckCount(true); - int failed = checkCount - passed; - writer.println("Passed: " + passed + "<br>"); - writer.println("Failed: " + failed + "<p>"); - writer.println("<table BORDER=\"0\" width=\"100%\" CELLPADDING=\"0\">"); - writer.println("<tr>"); - writer.println("<td bgcolor=\"black\" VALIGN=\"TOP\">"); - writer.println("<table BORDER=\"0\" WIDTH=\"100%\" CELLSPACING=\"1\" CELLPADDING=\"3\">"); - writer.println("<tr>"); - writer.println("<td bgcolor=\"lightGray\">Test:</td>"); - writer.println("<td bgcolor=\"lightGray\">Passed:</td>"); - writer.println("<td bgcolor=\"lightGray\">Failed:</td>"); - writer.println("<td bgcolor=\"lightGray\">Total:</td>"); - writer.println("</tr>"); - - // loop through tests writing test results - Iterator iterator = classResult.getTestIterator(); - while (iterator.hasNext()) { - TestResult testResult = (TestResult) iterator.next(); - // (1) write the summary line for the class HTML file - writer.println("<tr>"); - writer.println("<td bgcolor=\"white\"><a href=\"" + testResult.getName() + ".html\"" + ">" + - testResult.getName() + "</a></td>"); - writer.println("<td bgcolor=\"white\">" + testResult.getCheckCount(true) + "</td>"); - writer.println("<td bgcolor=\"white\">" + testResult.getCheckCount(false) + "</td>"); - writer.println("<td bgcolor=\"white\">" + testResult.getCheckCount() + "</td>"); - writer.println("</tr>"); - // (2) generate an HTML page for the test and subfiles - // for the tests - HTMLGenerator.createTestReport(testResult, classResult.getName(), classDirectory); - } - // close the class file - writer.println("</table>"); - writer.println("</td>"); - writer.println("</tr>"); - writer.println("</table>"); - writer.println("</BODY>"); - writer.println("</HTML>"); - writer.close(); - } - - /** - * Creates an HTML page that summarises a test. - * - * @param testResult the test result. - * @param className the class name. - * @param classDirectory the class directory. - */ - public static void createTestReport(TestResult testResult, String className, File classDirectory) - throws IOException { - - // write basic HTML for test - File testFile = new File(classDirectory, testResult.getName() + ".html"); - Writer out = new OutputStreamWriter(new FileOutputStream(testFile), "UTF-8"); - PrintWriter writer = new PrintWriter(out); - writer.println("<HTML>"); - writer.println("<HEAD><TITLE>Test Summary: " + className + "." + testResult.getName() + "</TITLE>\n"); - writer.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /></HEAD>"); - writer.println("<BODY>"); - writer - .println("<h2>Test: <a href=\"class_index.html\">" + className + "</a>." + testResult.getName() + "</h2>"); - int checkCount = testResult.getCheckCount(); - int passed = testResult.getCheckCount(true); - int failed = checkCount - passed; - writer.println("Passed: " + passed + "<br>"); - writer.println("Failed: " + failed + "<p>"); - writer.println("<table BORDER=\"0\" width=\"100%\" CELLPADDING=\"0\">"); - writer.println("<tr>"); - writer.println("<td bgcolor=\"black\" VALIGN=\"TOP\">"); - writer.println("<table BORDER=\"0\" WIDTH=\"100%\" CELLSPACING=\"1\" CELLPADDING=\"3\">"); - writer.println("<tr>"); - writer.println("<td bgcolor=\"lightGray\">Check Number:</td>"); - writer.println("<td bgcolor=\"lightGray\">Check Point:</td>"); - writer.println("<td bgcolor=\"lightGray\">Passed?:</td>"); - writer.println("<td bgcolor=\"lightGray\">Expected:</td>"); - writer.println("<td bgcolor=\"lightGray\">Actual:</td>"); - writer.println("</tr>"); - - // loop through checks adding a summary line for each check - Iterator iterator = testResult.getCheckIterator(); - while (iterator.hasNext()) { - CheckResult check = (CheckResult) iterator.next(); - // write a summary line (ID, pass/fail, actual, expected); - writer.println("<tr><td bgcolor=\"white\">" + check.getNumber() + - "</td><td bgcolor=\"white\">" + check.getCheckPoint() + - "</td><td bgcolor=\"" + (check.getPassed() ? "white" : "red") + "\">" + - check.getPassed() + "</td><td bgcolor=\"white\">" + check.getExpected() + - "</td><td bgcolor=\"white\">" + check.getActual() + "</td>"); - if (!check.getPassed()) { - try { - createLogReport(check, className, testResult.getName(), classDirectory); - } catch (Exception e) { - System.err.println("Couldn't write report for class " + className); - File temp = new File(classDirectory, testResult.getName() + "_log.html"); - temp.createNewFile(); - } - } - writer.println("</td>"); - writer.println("</tr>"); - } - writer.println("</table>"); - writer.println("</td>"); - writer.println("</tr>"); - writer.println("</table>"); - if (testResult.isFailed()) { - writer.println("<h2>Run aborted due to exception</h2>"); - writer.println("<pre>" + testResult.getFailedMessage() + "</pre>"); - } - writer.println("</BODY>"); - writer.println("</HTML>"); - writer.close(); - } - - /** - * Creates an HTML page that summarises the log for a check. - * - * @param checkResult the test result. - * @param className the class name. - * @param testName the test name. - * @param classDirectory the class directory. - */ - public static void createLogReport(CheckResult checkResult, String className, String testName, File classDirectory) - throws IOException { - - // write basic HTML for test - File logFile = new File(classDirectory, testName + "_log.html"); - OutputStream out = new BufferedOutputStream(new FileOutputStream(logFile)); - PrintWriter writer = new PrintWriter(out); - writer.println("<HTML>"); - writer.println("<HEAD><TITLE>Log: " + testName + "</TITLE>"); - writer.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /></HEAD>"); - writer.println("<BODY>"); - writer.println(checkResult.getLog()); - writer.println("</BODY>"); - writer.println("</HTML>"); - - writer.close(); - } -} Deleted: trunk/core/src/test/org/jnode/test/mauve/MauveTestCommand.java =================================================================== --- trunk/core/src/test/org/jnode/test/mauve/MauveTestCommand.java 2008-11-17 13:53:52 UTC (rev 4707) +++ trunk/core/src/test/org/jnode/test/mauve/MauveTestCommand.java 2008-11-17 22:55:33 UTC (rev 4708) @@ -1,493 +0,0 @@ -// Copyright (C) 2004, 2005 by Object Refinery Limited -// Copyright (C) 2005 by <za...@kd...> -// Written by David Gilbert (dav...@ob...) -// Written by Thomas Zander <za...@kd...> -// Modified by Levente S\u00e1ntha (ls...@jn...) -// Modified by Peter Barth (pe...@jn...) -// Modified by Fabien DUMINY (fd...@jn...) - -// This file is part of Mauve. - -// Mauve is free software; you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation; either version 2, or (at your option) -// any later version. - -// Mauve 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 General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Mauve; see the file COPYING. If not, write to -// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -// Boston, MA 02110-1301 USA. -package org.jnode.test.mauve; - -import gnu.testlet.ResourceNotFoundException; -import gnu.testlet.TestHarness; -import gnu.testlet.Testlet; -import java.io.BufferedReader; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.LineNumberReader; -import java.io.PrintWriter; -import java.io.Reader; -import java.util.Locale; - -/** - * Modified Mauve Test Suite - * - * @author peda - */ -public class MauveTestCommand extends TestHarness { - - private String lastCheckPoint; - - private int checksSinceLastCheckPoint; - - private ClassResult classResult; - - private TestResult currentTest; - - private CheckResult currentCheck; - - private RunResult result; - - private static int counter = 0; - - /** - * runs tests - * - * @param file the text file containing test class names. - * @param prefix the prefix for each test class (usually 'gnu.testlet'). - * @param output the name of the directory for writing output. - */ - public synchronized void execute(String file, String prefix, String output) { - - // save the default locale, some tests change the default and we want - // to restore it before generating the HTML report... - Locale savedLocale = Locale.getDefault(); - - File out = new File(output); - if (out.exists() && !out.isDirectory()) - throw new IllegalArgumentException("Output should be a directory"); - - if (!out.exists()) - out.mkdirs(); - - result = new RunResult("Mauve Test Run"); - currentCheck = new CheckResult(0, false); - - // initialize - // run tests and collect results - File f = new File(file); - try { - - FileReader testsToRun = new FileReader(f); - LineNumberReader r = new LineNumberReader(testsToRun); - - while (r.ready()) { - - String line = r.readLine(); - - if ("".equals(line)) - continue; - - System.out.println(line); - - // check the line is not commented - // load the listed class - try { - Class c = Class.forName(line); - // strip prefix ('gnu.testlet.') from front of name - String temp = line.substring(prefix.length()); - // suffix is the name for the TestResult - String testName = temp.substring(temp.lastIndexOf('.') + 1); - - temp = temp.substring(0, temp.lastIndexOf('.')); - String className = temp - .substring(temp.lastIndexOf('.') + 1); - if (className.equals("Double") || className.equals("Float") - || className.equals("Key")) { - if (!temp.startsWith("java.lang.")) { - temp = temp.substring(0, temp.lastIndexOf('.')); - className = temp - .substring(temp.lastIndexOf('.') + 1) - + '.' + className; - } - } - - String packageName = "default package"; - int index = temp.lastIndexOf('.'); - if (index >= 0) - packageName = temp.substring(0, temp.lastIndexOf('.')); - - // remaining suffix is name for ClassResult - // rest of text is name for PackageResult - PackageResult pr = result.getPackageResult(packageName); - if (pr == null) - pr = new PackageResult(packageName); - - classResult = pr.getClassResult(className); - if (classResult == null) - classResult = new ClassResult(className); - - Testlet testlet; - try { - testlet = (Testlet) c.newInstance(); - } catch (ClassCastException e) { - System.err.println("Not a test (does not implement Testlet): " + line); - result.addFaultyTest(line, "Does not implement Testlet"); - continue; // not a test - } catch (Throwable t) { // instanciation errors etc.. - t.printStackTrace(System.out); - result.addFaultyTest(line, t.getMessage()); - continue; - } - - currentTest = new TestResult(testName); - checksSinceLastCheckPoint = 0; - lastCheckPoint = "-"; - try { - testlet.test(this); - } catch (Throwable t) { - t.printStackTrace(System.out); - currentTest.failed(t); - } - - classResult.add(currentTest); - if (pr.indexOf(classResult) < 0) - pr.add(classResult); - if (result.indexOf(pr) == -1) - result.add(pr); - } catch (ClassNotFoundException e) { - System.err.println("Could not load test: " + line); - result.addMissingTest(line); - } - - counter++; -// System.out.println("Done " + counter + " tests so far."); -// if ((counter % 20) == 0) { - // System.out.println("next 20 tests done, running gc..."); - // System.gc(); - // } - } - } catch (FileNotFoundException e) { - throw new IllegalArgumentException(e.getMessage()); - } catch (IOException e) { - e.printStackTrace(System.out); - } - - // tests are complete so restore the default locale - Locale.setDefault(savedLocale); - - // write results to HTML - System.out.println("Creating HTML report..."); - try { - HTMLGenerator.createReport(result, out); - } catch (IOException e) { - System.out.println("failed to write HTML due to following error:"); - e.printStackTrace(System.out); - } - - System.out.println("Creating XML report..."); - try { - // new XMLGenerator(result).generate(new File(out, "results.xml")); - - String timestamp = String.valueOf(System.currentTimeMillis()); - File fx = new File(out, "results-" + timestamp + ".xml"); - new XMLReportWriter(true).write(result, fx); - System.out.println("XML file written to " + fx.getAbsolutePath()); - } catch (IOException e) { - System.out.println("failed to write XML due to following error:"); - e.printStackTrace(System.out); - } - - System.out.println("DONE!"); - } - - /** - * Records the result of a boolean check. - * - * @param result the result. - */ - public void check(boolean result) { - currentCheck.setPassed(result); - checkDone(); - } - - /** - * Checks the two objects for equality and records the result of the check. - * - * @param result the actual result. - * @param expected the expected result. - */ - public void check(Object result, Object expected) { - currentCheck.setPassed((result != null) ? result.equals(expected) : (expected == null)); - currentCheck.setActual((result != null) ? result.toString() : "null"); - currentCheck.setExpected((expected != null) ? expected.toString() : "null"); - checkDone(); - } - - /** - * Checks two booleans for equality and records the result of the check. - * - * @param result the actual result. - * @param expected the expected result. - */ - public void check(boolean result, boolean expected) { - currentCheck.setPassed(result == expected); - currentCheck.setActual(String.valueOf(result)); - currentCheck.setExpected(String.valueOf(expected)); - checkDone(); - } - - /** - * Checks two ints for equality and records the result of the check. - * - * @param result the actual result. - * @param expected the expected result. - */ - public void check(int result, int expected) { - currentCheck.setPassed(result == expected); - currentCheck.setActual(String.valueOf(result)); - currentCheck.setExpected(String.valueOf(expected)); - checkDone(); - } - - /** - * Checks two longs for equality and records the result of the check. - * - * @param result the actual result. - * @param expected the expected result. - */ - public void check(long result, long expected) { - currentCheck.setPassed(result == expected); - currentCheck.setActual(String.valueOf(result)); - currentCheck.setExpected(String.valueOf(expected)); - checkDone(); - } - - /** - * Checks two doubles for equality and records the result of the check. - * - * @param result the actual result. - * @param expected the expected result. - */ - public void check(double result, double expected) { - currentCheck.setPassed((result == expected ? (result != 0) || (1 / result == 1 / expected) : (result != result) - && (expected != expected))); - currentCheck.setActual(String.valueOf(result)); - currentCheck.setExpected(String.valueOf(expected)); - checkDone(); - } - - /** - * Records a check point. This can be used to mark a known place in a - * testlet. It is useful if you have a large number of tests -- it makes it - * easier to find a failing test in the source code. - * - * @param name the check point name. - */ - public void checkPoint(String name) { - lastCheckPoint = name; - checksSinceLastCheckPoint = 0; - } - - private void checkDone() { - currentCheck.setNumber(++checksSinceLastCheckPoint); - currentCheck.setCheckPoint(lastCheckPoint); - currentTest.add(currentCheck); - currentCheck = new CheckResult(0, false); - currentCheck.setCheckPoint(lastCheckPoint); - } - - /** - * Writes a message to the debug log along with a newline. - * - * @param message the message. - */ - public void debug(String message) { - debug(message, true); - } - - /** - * Writes a message to the debug log with or without a newline. - * - * @param message the message. - * @param newline a flag to control whether or not a newline is added. - */ - public void debug(String message, boolean newline) { - currentCheck.appendToLog(message); - if (newline) - currentCheck.appendToLog("\n"); - } - - /** - * Writes the contents of an array to the log. - * - * @param o the array of objects. - * @param desc the description. - */ - public void debug(Object[] o, String desc) { - StringBuffer logMessage = new StringBuffer(); - logMessage.append("Object array: "); - logMessage.append(desc); - if (o == null) - logMessage.append("null"); - else - expand(o, logMessage); - currentCheck.appendToLog(logMessage.toString()); - currentCheck.appendToLog("\n"); - } - - // recursive helper method for debug(Object[], String) - private void expand(Object[] array, StringBuffer buf) { - for (int i = 0; i < array.length; i++) { - buf.append("obj[" + i + "]: "); - if (array[i] instanceof Object[]) - expand((Object[]) array[i], buf); - else if (array[i] != null) - buf.append(array[i].toString()); - else - buf.append("null"); - if (i < array.length) - buf.append(", "); - } - } - - /** - * Writes a stack trace for the specified exception to the log for the - * current check. - * - * @param ex the exception. - */ - public void debug(Throwable ex) { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - PrintWriter w = new PrintWriter(out, false); - ex.printStackTrace(w); - w.close(); - try { - out.close(); - debug(out.toString(), true); - } catch (IOException e) { - /* this should never happen.. */ - } - } - - /** - * This will print a message when in verbose mode. - * - * @param message the message. - */ - public void verbose(String message) { - debug(message, true); - } - - public Reader getResourceReader(String name) throws ResourceNotFoundException { - return new BufferedReader( - new InputStreamReader(getResourceStream(name))); - } - - public InputStream getResourceStream(String name) throws ResourceNotFoundException { - // The following code assumes File.separator is a single character. - if (File.separator.length() > 1) - throw new Error("File.separator length is greater than 1"); - String realName = name.replace('#', File.separator.charAt(0)); - try { - return new FileInputStream(getSourceDirectory() + File.separator + realName); - } catch (FileNotFoundException ex) { - throw new ResourceNotFoundException(ex.getLocalizedMessage() + ": " - + getSourceDirectory() + File.separator + realName); - } - } - - public String getSourceDirectory() { - return null; // TODO - } - - public File getResourceFile(String name) throws ResourceNotFoundException { - // The following code assumes File.separator is a single character. - if (File.separator.length() > 1) - throw new Error("File.separator length is greater than 1"); - String realName = name.replace('#', File.separator.charAt(0)); - File f = new File(getSourceDirectory() + File.separator + realName); - if (!f.exists()) { - throw new ResourceNotFoundException("cannot find mauve resource file" + ": " - + getSourceDirectory() + File.separator + realName); - } - return f; - } - - /** - * Provide a directory name for writing temporary files. - * - * @return The temporary directory name. - */ - public String getTempDirectory() { - // TODO - return "/tmp"; - } - - /** - * Runs the application to generate an HTML report for a collection of Mauve - * tests. - * - * @param args the command line arguments. - */ - public static void main(String[] args) { - // -prefix <package-prefix> - // -output <root-directory-for-HTML-output> - String file = "tests"; - String prefix = "gnu.testlet."; - String output = "results"; - for (int i = 0; i < args.length; i++) { - String a = args[i]; - if (a.equals("--prefix") || a.equals("-p")) { - if (i < args.length) { - prefix = args[i + 1]; - i++; - } else { - System.err.println("prefix: value missing"); - return; - } - } else if (a.equals("--output") || a.equals("-o")) { - if (i < args.length) { - output = args[i + 1]; - i++; - } else { - System.err.println("output: value missing"); - return; - } - } else if (a.equals("--help") || a.equals("-h")) { - System.out.println("Usage: Mauve [options] [inputfile]"); - System.out - .println("reads test-class names from inputfile and executes them;"); - System.out - .println("If no inputfile is passed, then tests.txt will be used"); - System.out.println(" options:"); - System.out.println(" --help -h this help"); - System.out - .println(" --output -o the output directory [results]"); - System.out - .println(" --prefix -p package prefix [gnu.testlet]"); - return; - } else - file = a; - } - try { - new MauveTestCommand().execute(file, prefix, output); - } catch (IllegalArgumentException e) { - System.err.println(e.getMessage()); - System.err.println("Try --help for more info"); - } - System.exit(0); - } -} Deleted: trunk/core/src/test/org/jnode/test/mauve/MauveTests.java =================================================================== --- trunk/core/src/test/org/jnode/test/mauve/MauveTests.java 2008-11-17 13:53:52 UTC (rev 4707) +++ trunk/core/src/test/org/jnode/test/mauve/MauveTests.java 2008-11-17 22:55:33 UTC (rev 4708) @@ -1,120 +0,0 @@ -// Copyright (c) 2008 Fabien DUMINY (fd...@jn...) - -// This file is part of Mauve. - -// Mauve is free software; you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation; either version 2, or (at your option) -// any later version. - -// Mauve 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 General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Mauve; see the file COPYING. If not, write to -// the Free Software Foundation, 59 Temple Place - Suite 330, -// Boston, MA 02111-1307, USA. */ - -package org.jnode.test.mauve; - -import java.io.File; -import java.io.IOException; -import java.io.PrintWriter; - -import org.jnode.test.mauve.compare.HTMLComparisonWriter; -import org.jnode.test.mauve.compare.ReportComparator; -import org.jnode.test.mauve.compare.RunComparison; -import org.jnode.test.mauve.compare.TextComparisonWriter; - -/** - * Contains a test program for various functions like xml import/export of mauve results, - * comparison of 2 mauve results with results saved in xml or html format. - * - * @author fabien - * - */ -public class MauveTests { - - public static void main(String[] args) throws IOException { - RunResult runResult = createRunResult(1, 2, 0, 3, 1); - System.out.println("========================="); - - System.out.println("\n--- writing XML file ---"); - File f = File.createTempFile("XMLReport", ".xml"); - f.deleteOnExit(); - new XMLReportWriter().write(runResult, f); - System.out.println("\n--- COMPACT MODE:"); - new XMLReportWriter(true).write(runResult, new PrintWriter(System.out)); - System.out.println("\n--- NORMAL MODE:"); - new XMLReportWriter(false).write(runResult, new PrintWriter(System.out)); - HTMLGenerator.createReport(runResult, f.getParentFile()); - System.out.println("========================"); - - System.out.println("\n--- parsing XML file ---"); - RunResult rr = new XMLReportParser().parse(f); - System.out.println("rr = " + rr); - System.out.println("========================"); - - RunResult runResult2 = createRunResult(2, 2, 1, 3, 0); - System.out.println("========================\n"); - - ReportComparator c = new ReportComparator(runResult, runResult2); - RunComparison comp = c.compare(); - - System.out.println("\n--- comparison result in text ---"); - new TextComp... [truncated message content] |
From: <cr...@us...> - 2008-11-22 03:25:49
|
Revision: 4712 http://jnode.svn.sourceforge.net/jnode/?rev=4712&view=rev Author: crawley Date: 2008-11-22 03:25:44 +0000 (Sat, 22 Nov 2008) Log Message: ----------- Refine Argument / FileArgument with EXISTING / NONEXISTENT flags. Modified Paths: -------------- 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/CpCommand.java trunk/fs/src/fs/org/jnode/fs/command/DFCommand.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/HexdumpCommand.java trunk/fs/src/fs/org/jnode/fs/command/Md5SumCommand.java trunk/fs/src/fs/org/jnode/fs/command/MkdirCommand.java trunk/shell/src/shell/org/jnode/shell/syntax/Argument.java trunk/shell/src/shell/org/jnode/shell/syntax/FileArgument.java Modified: trunk/fs/src/fs/org/jnode/fs/command/CatCommand.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/command/CatCommand.java 2008-11-21 21:37:51 UTC (rev 4711) +++ trunk/fs/src/fs/org/jnode/fs/command/CatCommand.java 2008-11-22 03:25:44 UTC (rev 4712) @@ -52,11 +52,11 @@ public class CatCommand extends AbstractCommand { private final FileArgument ARG_FILE = - new FileArgument("file", Argument.OPTIONAL | Argument.MULTIPLE, + new FileArgument("file", Argument.OPTIONAL | Argument.MULTIPLE | Argument.EXISTING, "the files to be concatenated"); private final URLArgument ARG_URL = - new URLArgument("url", Argument.OPTIONAL | Argument.MULTIPLE, + new URLArgument("url", Argument.OPTIONAL | Argument.MULTIPLE | Argument.EXISTING, "the urls to be concatenated"); private final FlagArgument FLAG_URLS = Modified: trunk/fs/src/fs/org/jnode/fs/command/CdCommand.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/command/CdCommand.java 2008-11-21 21:37:51 UTC (rev 4711) +++ trunk/fs/src/fs/org/jnode/fs/command/CdCommand.java 2008-11-22 03:25:44 UTC (rev 4712) @@ -39,7 +39,7 @@ public class CdCommand extends AbstractCommand { private final FileArgument ARG_DIR = new FileArgument( - "directory", Argument.OPTIONAL, "the directory to change to"); + "directory", Argument.OPTIONAL | Argument.EXISTING, "the directory to change to"); public CdCommand() { super("Change the current directory"); Modified: trunk/fs/src/fs/org/jnode/fs/command/CpCommand.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/command/CpCommand.java 2008-11-21 21:37:51 UTC (rev 4711) +++ trunk/fs/src/fs/org/jnode/fs/command/CpCommand.java 2008-11-22 03:25:44 UTC (rev 4712) @@ -50,7 +50,8 @@ static final byte MODE_UPDATE = 3; private final FileArgument ARG_SOURCE = - new FileArgument("source", Argument.MANDATORY + Argument.MULTIPLE, "source files or directories"); + new FileArgument("source", Argument.MANDATORY | Argument.MULTIPLE | Argument.EXISTING, + "source files or directories"); private final FileArgument ARG_TARGET = new FileArgument("target", Argument.MANDATORY, "target file or directory"); Modified: trunk/fs/src/fs/org/jnode/fs/command/DFCommand.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/command/DFCommand.java 2008-11-21 21:37:51 UTC (rev 4711) +++ trunk/fs/src/fs/org/jnode/fs/command/DFCommand.java 2008-11-22 03:25:44 UTC (rev 4712) @@ -45,7 +45,7 @@ public class DFCommand extends AbstractCommand { private final DeviceArgument ARG_DEVICE = new DeviceArgument( - "device", Argument.OPTIONAL, + "device", Argument.OPTIONAL | Argument.EXISTING, "The device for which disk usage inforrmation should be displayed"); public DFCommand() { Modified: trunk/fs/src/fs/org/jnode/fs/command/DeleteCommand.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/command/DeleteCommand.java 2008-11-21 21:37:51 UTC (rev 4711) +++ trunk/fs/src/fs/org/jnode/fs/command/DeleteCommand.java 2008-11-22 03:25:44 UTC (rev 4712) @@ -45,7 +45,7 @@ public class DeleteCommand extends AbstractCommand { private final FileArgument ARG_PATHS = new FileArgument( - "paths", Argument.MANDATORY | Argument.MULTIPLE, + "paths", Argument.MANDATORY | Argument.MULTIPLE | Argument.EXISTING, "the files or directories to be deleted"); private final FlagArgument FLAG_RECURSIVE = new FlagArgument( "recursive", Argument.OPTIONAL, Modified: trunk/fs/src/fs/org/jnode/fs/command/DirCommand.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/command/DirCommand.java 2008-11-21 21:37:51 UTC (rev 4711) +++ trunk/fs/src/fs/org/jnode/fs/command/DirCommand.java 2008-11-22 03:25:44 UTC (rev 4712) @@ -45,7 +45,8 @@ private static final SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd HH:mm"); private final FileArgument ARG_PATH = new FileArgument( - "path", Argument.OPTIONAL + Argument.MULTIPLE, "the file or directory to list"); + "path", Argument.OPTIONAL | Argument.MULTIPLE | Argument.EXISTING, + "the file or directory to list"); public DirCommand() { super("List files or directories"); Modified: trunk/fs/src/fs/org/jnode/fs/command/EjectCommand.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/command/EjectCommand.java 2008-11-21 21:37:51 UTC (rev 4711) +++ trunk/fs/src/fs/org/jnode/fs/command/EjectCommand.java 2008-11-22 03:25:44 UTC (rev 4712) @@ -37,7 +37,7 @@ public class EjectCommand extends AbstractCommand { private final DeviceArgument ARG_DEVICE = new DeviceArgument( - "device", Argument.MANDATORY, "device to eject the medium from", + "device", Argument.MANDATORY | Argument.EXISTING, "device to eject the medium from", RemovableDeviceAPI.class); public EjectCommand() { Modified: trunk/fs/src/fs/org/jnode/fs/command/HexdumpCommand.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/command/HexdumpCommand.java 2008-11-21 21:37:51 UTC (rev 4711) +++ trunk/fs/src/fs/org/jnode/fs/command/HexdumpCommand.java 2008-11-22 03:25:44 UTC (rev 4712) @@ -24,10 +24,10 @@ */ public class HexdumpCommand extends AbstractCommand { private final FileArgument ARG_FILE = new FileArgument( - "file", Argument.OPTIONAL, "the file to print out"); + "file", Argument.OPTIONAL | Argument.EXISTING, "the file to print out"); private final URLArgument ARG_URL = new URLArgument( - "url", Argument.OPTIONAL, "the url to print out"); + "url", Argument.OPTIONAL | Argument.EXISTING, "the url to print out"); public HexdumpCommand() { super("Print a hexadecimal dump of a given file (or URL)"); Modified: trunk/fs/src/fs/org/jnode/fs/command/Md5SumCommand.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/command/Md5SumCommand.java 2008-11-21 21:37:51 UTC (rev 4711) +++ trunk/fs/src/fs/org/jnode/fs/command/Md5SumCommand.java 2008-11-22 03:25:44 UTC (rev 4712) @@ -50,13 +50,13 @@ public class Md5SumCommand extends AbstractCommand { private final FileArgument ARG_PATHS = new FileArgument( - "paths", Argument.OPTIONAL | Argument.MULTIPLE, + "paths", Argument.OPTIONAL | Argument.MULTIPLE | Argument.EXISTING, "the files (or directories) to be calculate MD5 digests for"); private final FlagArgument FLAG_RECURSIVE = new FlagArgument( "recursive", Argument.OPTIONAL, "if set, recursively calculate MD5 digests for the contents of any directory"); private final FileArgument ARG_CHECKFILE = new FileArgument( - "checkfile", Argument.OPTIONAL | Argument.SINGLE, + "checkfile", Argument.OPTIONAL | Argument.SINGLE | Argument.EXISTING, "check MD5 digests for files listed in this file"); Modified: trunk/fs/src/fs/org/jnode/fs/command/MkdirCommand.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/command/MkdirCommand.java 2008-11-21 21:37:51 UTC (rev 4711) +++ trunk/fs/src/fs/org/jnode/fs/command/MkdirCommand.java 2008-11-22 03:25:44 UTC (rev 4712) @@ -35,7 +35,7 @@ public class MkdirCommand extends AbstractCommand { private final FileArgument ARG_DIR = new FileArgument( - "directory", Argument.MANDATORY, "the directory to create"); + "directory", Argument.MANDATORY | Argument.NONEXISTENT, "the directory to create"); public MkdirCommand() { super("Create a new directory"); Modified: trunk/shell/src/shell/org/jnode/shell/syntax/Argument.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/syntax/Argument.java 2008-11-21 21:37:51 UTC (rev 4711) +++ trunk/shell/src/shell/org/jnode/shell/syntax/Argument.java 2008-11-22 03:25:44 UTC (rev 4712) @@ -55,15 +55,45 @@ */ public abstract class Argument<V> { - public static final int OPTIONAL = 0x00; - public static final int MANDATORY = 0x01; + /** + * This Argument flag indicates that the Argument is optional. + */ + public static final int OPTIONAL = 0x001; + + /** + * This Argument flag indicates that the Argument is mandatory. At least + * one instance of this Argument must be supplied. + */ + public static final int MANDATORY = 0x002; - public static final int SINGLE = 0x00; - public static final int MULTIPLE = 0x04; + /** + * This Argument flag indicates that the Argument may have at most one value. + */ + public static final int SINGLE = 0x004; + /** + * This Argument flag indicates that multiple instances of this Argument may + * be provided. + */ + public static final int MULTIPLE = 0x008; + + /** + * This Argument flag indicates that an Argument's value must denote an entity + * that already exists in whatever domain that the Argument values corresponds to. + */ + public static final int EXISTING = 0x010; + + /** + * This Argument flag indicates that an Argument's value must denote an entity + * that does not exists in whatever domain that the Argument values corresponds to. + */ + public static final int NONEXISTENT = 0x020; + private final String label; private final boolean mandatory; private final boolean multiple; + private final boolean existing; + private final boolean nonexistent; private final String description; protected final List<V> values = new ArrayList<V>(); @@ -80,22 +110,36 @@ * @param vArray A template array used by the getValues method. It is * typically zero length. * @param description Optional documentation for the argument. + * @throws IllegalArgumentException if the flags are inconsistent */ - protected Argument(String label, int flags, V[] vArray, String description) { + protected Argument(String label, int flags, V[] vArray, String description) + throws IllegalArgumentException { super(); + if ((flags & EXISTING) != 0 && (flags & NONEXISTENT) != 0) { + throw new IllegalArgumentException("inconsistent flags: EXISTING and NONEXISTENT"); + } + if ((flags & SINGLE) != 0 && (flags & MULTIPLE) != 0) { + throw new IllegalArgumentException("inconsistent flags: SINGLE and MULTIPLE"); + } + if ((flags & MANDATORY) != 0 && (flags & OPTIONAL) != 0) { + throw new IllegalArgumentException("inconsistent flags: MANDATORY and OPTIONAL"); + } this.label = label; this.description = description; this.mandatory = (flags & MANDATORY) != 0; this.multiple = (flags & MULTIPLE) != 0; + this.existing = (flags & EXISTING) != 0; + this.nonexistent = (flags & NONEXISTENT) != 0; this.vArray = vArray; } /** - * Reconstruct and return this Arguments flags as passed to the constructor. + * Reconstruct and return Argument flags equiivalent to those passed to the constructor. * @return the flags. */ public int getFlags() { - return (mandatory ? MANDATORY : 0) | (multiple ? MULTIPLE : 0); + return ((mandatory ? MANDATORY : OPTIONAL) | (multiple ? MULTIPLE : SINGLE) | + (existing ? EXISTING : 0) | (nonexistent ? NONEXISTENT : 0)); } /** @@ -212,6 +256,22 @@ return multiple; } + /** + * If this method returns <code>true</code>, an Argument value must correspond + * to an existing entity in the domain of entities denoted by the Argument type. + */ + public boolean isExisting() { + return existing; + } + + /** + * If this method returns <code>true</code>, an Argument value must <i>not</i> correspond + * to an existing entity in the domain of entities denoted by the Argument type. + */ + public boolean isNonexistent() { + return nonexistent; + } + void setBundle(ArgumentBundle bundle) { this.bundle = bundle; } Modified: trunk/shell/src/shell/org/jnode/shell/syntax/FileArgument.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/syntax/FileArgument.java 2008-11-21 21:37:51 UTC (rev 4711) +++ trunk/shell/src/shell/org/jnode/shell/syntax/FileArgument.java 2008-11-22 03:25:44 UTC (rev 4712) @@ -29,7 +29,9 @@ import org.jnode.shell.CommandLine.Token; /** - * This argument class performs completion against the file system namespace. + * This argument class performs completion against the file system namespace. This + * Argument class understands the {@link Argument#EXISTING} and {@link Argument#NONEXISTENT} + * flags when accepting argument values, but not (yet) when completing them. * * @author cr...@jn... */ @@ -45,9 +47,15 @@ @Override protected File doAccept(Token token) throws CommandSyntaxException { - // FIXME ... do proper filename checks ... if (token.token.length() > 0) { - return new File(token.token); + File file = new File(token.token); + if (isExisting() && !file.exists()) { + throw new CommandSyntaxException("this file or directory does not exist"); + } + if (isNonexistent() && file.exists()) { + throw new CommandSyntaxException("this file or directory already exist"); + } + return file; } else { throw new CommandSyntaxException("invalid file name"); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cr...@us...> - 2008-11-22 06:47:15
|
Revision: 4713 http://jnode.svn.sourceforge.net/jnode/?rev=4713&view=rev Author: crawley Date: 2008-11-22 06:47:09 +0000 (Sat, 22 Nov 2008) Log Message: ----------- Removing 'old syntax' code Modified Paths: -------------- trunk/shell/descriptors/org.jnode.shell.xml trunk/shell/src/shell/org/jnode/shell/CommandLine.java trunk/shell/src/shell/org/jnode/shell/CommandRunner.java trunk/shell/src/shell/org/jnode/shell/DefaultCommandInvoker.java trunk/shell/src/shell/org/jnode/shell/help/Help.java trunk/shell/src/shell/org/jnode/shell/help/HelpFactory.java trunk/shell/src/shell/org/jnode/shell/help/def/DefaultHelpFactory.java trunk/shell/src/test/org/jnode/test/shell/CompletionTest.java Removed Paths: ------------- trunk/net/src/net/org/jnode/net/help/argument/ trunk/shell/src/shell/org/jnode/shell/help/Argument.java trunk/shell/src/shell/org/jnode/shell/help/Parameter.java trunk/shell/src/shell/org/jnode/shell/help/ParsedArguments.java trunk/shell/src/shell/org/jnode/shell/help/Syntax.java trunk/shell/src/shell/org/jnode/shell/help/argument/ trunk/shell/src/shell/org/jnode/shell/help/def/OldSyntaxHelp.java trunk/shell/src/test/org/jnode/test/shell/MyCatCommand.java trunk/shell/src/test/org/jnode/test/shell/MyDirCommand.java Modified: trunk/shell/descriptors/org.jnode.shell.xml =================================================================== --- trunk/shell/descriptors/org.jnode.shell.xml 2008-11-22 03:25:44 UTC (rev 4712) +++ trunk/shell/descriptors/org.jnode.shell.xml 2008-11-22 06:47:09 UTC (rev 4713) @@ -20,7 +20,6 @@ <export name="org.jnode.shell.alias.def.*"/> <export name="org.jnode.shell.def.*"/> <export name="org.jnode.shell.help.*"/> - <export name="org.jnode.shell.help.argument.*"/> <export name="org.jnode.shell.help.def.*"/> <export name="org.jnode.shell.io.*"/> <export name="org.jnode.shell.isolate.*"/> Modified: trunk/shell/src/shell/org/jnode/shell/CommandLine.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/CommandLine.java 2008-11-22 03:25:44 UTC (rev 4712) +++ trunk/shell/src/shell/org/jnode/shell/CommandLine.java 2008-11-22 06:47:09 UTC (rev 4713) @@ -25,14 +25,16 @@ import org.jnode.driver.console.CompletionInfo; import org.jnode.shell.help.CompletionException; -import org.jnode.shell.help.Help; -import org.jnode.shell.help.HelpException; -import org.jnode.shell.help.HelpFactory; -import org.jnode.shell.help.Parameter; import org.jnode.shell.io.CommandIO; import org.jnode.shell.io.CommandIOMarker; +import org.jnode.shell.syntax.AliasArgument; +import org.jnode.shell.syntax.Argument; import org.jnode.shell.syntax.ArgumentBundle; +import org.jnode.shell.syntax.ArgumentSyntax; import org.jnode.shell.syntax.CommandSyntaxException; +import org.jnode.shell.syntax.FileArgument; +import org.jnode.shell.syntax.RepeatSyntax; +import org.jnode.shell.syntax.Syntax; import org.jnode.shell.syntax.SyntaxBundle; /** @@ -95,22 +97,6 @@ private static final String[] NO_ARGS = new String[0]; private static final Token[] NO_TOKENS = new Token[0]; - @SuppressWarnings("deprecation") - private final Help.Info defaultInfo = new Help.Info("file", - "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 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 Token commandToken; private final Token[] argumentTokens; @@ -631,34 +617,33 @@ throw new CompletionException("Problem creating a command instance", ex); } - // Get the command's argument bundle, or the default one. + // Get the command's argument bundle and syntax ArgumentBundle bundle = (command == null) ? null : command.getArgumentBundle(); - - // Get a syntax for the alias, or a default one. SyntaxBundle syntaxes = shell.getSyntaxManager().getSyntaxBundle(cmd); - + + if (bundle == null) { + // We're missing the argument bundle. We assume this is a 'classic' Java application + // that does its own argument parsing and completion like a UNIX shell; i.e. + // completing each argument as a pathname. + Syntax syntax = new RepeatSyntax(new ArgumentSyntax("argument")); + syntaxes = new SyntaxBundle(cmd, syntax); + bundle = new ArgumentBundle( + new FileArgument("argument", Argument.MULTIPLE)); + } else if (syntaxes == null) { + // We're missing the syntax, but we do have an argument bundle. Generate + // a default syntax from the bundle. + syntaxes = new SyntaxBundle(cmd, bundle.createDefaultSyntax()); + } try { - // Try new-style completion if we have a Syntax - if (bundle != null) { - bundle.complete(this, syntaxes, completion); - } else { - // Otherwise, try old-style completion using the command's INFO - try { - Help.Info info = HelpFactory.getInfo(cmdClass.getCommandClass()); - info.complete(completion, this, shell.getOut()); - } catch (HelpException ex) { - // And fall back to old-style completion with an 'info' that - // specifies a sequence of 'file' names. - // FIXME ... - defaultInfo.complete(completion, this, shell.getOut()); - } - } + bundle.complete(this, syntaxes, completion); } catch (CommandSyntaxException ex) { throw new CompletionException("Command syntax problem", ex); } } else { - // do completion on the command name - defaultArg.complete(completion, cmd); + // We haven't got a command name yet, so complete the partial command name string + // as an AliasArgument. + AliasArgument cmdNameArg = new AliasArgument("cmdName", Argument.SINGLE); + cmdNameArg.complete(completion, cmd); completion.setCompletionStart(commandToken == null ? 0 : commandToken.start); } } Modified: trunk/shell/src/shell/org/jnode/shell/CommandRunner.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/CommandRunner.java 2008-11-22 03:25:44 UTC (rev 4712) +++ trunk/shell/src/shell/org/jnode/shell/CommandRunner.java 2008-11-22 06:47:09 UTC (rev 4713) @@ -144,7 +144,7 @@ } } catch (SyntaxErrorException ex) { try { - HelpFactory.getInfo(cmdInfo.getCommandClass()).usage(shellErr); + HelpFactory.getHelpFactory().getHelp(commandLine.getCommandName(), cmdInfo).usage(shellErr); shellErr.println(ex.getMessage()); } catch (HelpException e) { shellErr.println("Exception while trying to get the command usage"); Modified: trunk/shell/src/shell/org/jnode/shell/DefaultCommandInvoker.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/DefaultCommandInvoker.java 2008-11-22 03:25:44 UTC (rev 4712) +++ trunk/shell/src/shell/org/jnode/shell/DefaultCommandInvoker.java 2008-11-22 06:47:09 UTC (rev 4713) @@ -117,7 +117,7 @@ } } } catch (SyntaxErrorException ex) { - HelpFactory.getInfo(cmdInfo.getCommandClass()).usage(err); + HelpFactory.getHelpFactory().getHelp(cmdName, cmdInfo).usage(err); err.println(ex.getMessage()); } catch (VmExit ex) { return ex.getStatus(); Deleted: trunk/shell/src/shell/org/jnode/shell/help/Argument.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/help/Argument.java 2008-11-22 03:25:44 UTC (rev 4712) +++ trunk/shell/src/shell/org/jnode/shell/help/Argument.java 2008-11-22 06:47:09 UTC (rev 4713) @@ -1,131 +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.shell.help; - -import java.io.PrintWriter; - -import org.jnode.driver.console.CompletionInfo; - -/** - * @author qades - */ -public class Argument extends CommandLineElement { - - public static final boolean SINGLE = false; - - public static final boolean MULTI = true; - - private static final String[] NO_VALUES = new String[0]; - - private final boolean multi; - - public Argument(String name, String description, boolean multi) { - super(name, description); - this.multi = multi; - } - - public Argument(String name, String description) { - this(name, description, SINGLE); - } - - public boolean isMulti() { - return multi; - } - - public String format() { - return "<" + getName() + ">" + (isMulti() ? " ..." : ""); - } - - public void describe(HelpFactory help, PrintWriter out) { - help.describeArgument(this, out); - } - - // Command line completion - private String[] values = NO_VALUES; - - private boolean satisfied = false; - - /** - * 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 final void setValue(String value) { - if (isMulti()) { - String[] values = new String[ this.values.length + 1]; - System.arraycopy(this.values, 0, values, 0, this.values.length); - values[ this.values.length] = value; - this.values = values; - } else { - this.values = new String[] {value}; - } - setSatisfied(!isMulti()); - } - - /** - * Override this method to check if a given value "fits" this argument. - * - * @param value - * @return true if value, false otherwise. - */ - protected boolean isValidValue(String value) { - return true; - } - - public final String getValue(ParsedArguments args) { - String[] result = getValues(args); - if ((result == null) || (result.length == 0)) return null; - return result[ 0]; - } - - public final String[] getValues(ParsedArguments args) { - return args.getValues(this); - } - - final String[] getValues() { - return values; - } - - protected final void clear() { - this.values = new String[ 0]; - setSatisfied(false); - } - - protected final void setSatisfied(boolean satisfied) { - this.satisfied = satisfied; - } - - public final boolean isSatisfied() { - return satisfied; - } -} Modified: trunk/shell/src/shell/org/jnode/shell/help/Help.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/help/Help.java 2008-11-22 03:25:44 UTC (rev 4712) +++ trunk/shell/src/shell/org/jnode/shell/help/Help.java 2008-11-22 06:47:09 UTC (rev 4713) @@ -22,9 +22,6 @@ import java.io.PrintWriter; -import org.jnode.driver.console.CompletionInfo; -import org.jnode.shell.CommandLine; - /** * This is the interface for an object that outputs command help. Different * implementations support different command syntax mechanisms, and (in the @@ -48,120 +45,4 @@ * @param pw the help information is written here */ public void usage(PrintWriter pw); - - /** - * This class is here for historical reasons. It is a key API class in the - * 'old' JNode syntax mechanism. - */ - public static class Info { - - private final String name; - - private final Syntax[] syntaxes; - - public Info(String name, Syntax... syntaxes) { - this.name = name; - this.syntaxes = syntaxes; - } - - public Info(String name, String description, Parameter... params) { - this(name, new Syntax(description, params)); - } - - /** - * Gets the name of this command - */ - public String getName() { - return name; - } - - /** - * Gets the syntaxes allowed for this command - */ - public Syntax[] getSyntaxes() { - return syntaxes; - } - - public void usage(PrintWriter out) { - try { - HelpFactory.getHelpFactory().usage(this, out); - } catch (HelpException ex) { - ex.printStackTrace(); - } - } - - /** - * Prints the help message. - * @param command command name or alias which appears in the help message - * @throws HelpException - */ - public void help(String command, PrintWriter out) throws HelpException { - HelpFactory.getHelpFactory().help(this, command, out); - } - - public String complete(CompletionInfo completion, CommandLine partial, - PrintWriter out) 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 { - syntax.complete(completion, partial); - foundCompletion = true; - - } catch (CompletionException ex) { - // just try the next syntax - } - } - if (!foundCompletion) { - out.println(); - usage(out); - throw new CompletionException("Invalid command syntax"); - } - return max; - } - - /** - * Parse the supplied command arguments against this object's syntax(es). - * @param args the command arguments - * @return the resulting binding of parameters/arguments to values. - * @throws SyntaxErrorException - * @deprecated use parse(CommandLine) instead. - * - */ - public ParsedArguments parse(String... args) throws SyntaxErrorException { - return parse(new CommandLine(args)); - } - - /** - * Parse the supplied CommandLine against this object's syntax(es). - * - * @param cmdLine the CommandLine - * @return the resulting binding of parameters/arguments to values. - * @throws SyntaxErrorException - */ - public ParsedArguments parse(CommandLine cmdLine) throws SyntaxErrorException { - for (int i = 0; i < syntaxes.length; i++) { - Syntax s = syntaxes[i]; - // FIXME ... it appears that s.parse is a stateful operation. If that is - // the case, we should either synchronize on s for s.parse + s.clearArguments, - // or move the s.clearArgument call into s.parse. - try { - return s.parse(cmdLine); - } catch (SyntaxErrorException ex) { - s.clearArguments(); - if (syntaxes.length == 1) { - // If there was only one syntax, propagate the exception so that - // we can tell the user why the arguments didn't match. - throw ex; - } - } - } - - // There were no syntaxes, or we have tried more than one syntax and they - // all have failed. - throw new SyntaxErrorException("No matching syntax found"); - } - } } Modified: trunk/shell/src/shell/org/jnode/shell/help/HelpFactory.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/help/HelpFactory.java 2008-11-22 03:25:44 UTC (rev 4712) +++ trunk/shell/src/shell/org/jnode/shell/help/HelpFactory.java 2008-11-22 06:47:09 UTC (rev 4713) @@ -22,7 +22,6 @@ package org.jnode.shell.help; import java.io.PrintWriter; -import java.lang.reflect.Field; import java.util.TreeSet; import javax.naming.NamingException; @@ -30,7 +29,6 @@ import org.jnode.naming.InitialNaming; import org.jnode.plugin.PluginUtils; import org.jnode.shell.CommandInfo; -import org.jnode.shell.help.Help.Info; import org.jnode.shell.syntax.ArgumentBundle; import org.jnode.shell.syntax.FlagArgument; import org.jnode.shell.syntax.SyntaxBundle; @@ -63,17 +61,6 @@ return PluginUtils.getLocalizedMessage(HelpFactory.class, BUNDLE_NAME, messageKey); } - - public static Info getInfo(Class<?> clazz) throws HelpException { - try { - Field helpInfo = clazz.getField(INFO_FIELD_NAME); - return (Help.Info) helpInfo.get(null); // static access - } catch (NoSuchFieldException ex) { - throw new HelpException("Command information not found"); - } catch (IllegalAccessException ex) { - throw new HelpException("Command information not accessible"); - } - } /** * Obtain a CommanHelp object for a given command alias and its resolved CommandInfo. @@ -92,15 +79,6 @@ /** * Shows the help page for a command * - * @param info the command info - * @param command a command name or alias which appears in the help - * @param out the destination for help output. - */ - protected abstract void help(Info info, String command, PrintWriter out); - - /** - * Shows the help page for a command - * * @param syntaxes the command's syntax bundle * @param bundle the command's argument bundle * @param out the destination for help output. @@ -110,14 +88,6 @@ /** * Shows the usage line for a command * - * @param info the command information - * @param out the destination for help output. - */ - protected abstract void usage(Info info, PrintWriter out); - - /** - * Shows the usage line for a command - * * @param syntaxes the command's syntax bundle * @param bundle the command's argument bundle * @param out the destination for help output. @@ -128,12 +98,6 @@ * Shows the description of a single argument. Used as a callback in * {@link Argument#describe(HelpFactory)}. */ - protected abstract void describeArgument(Argument arg, PrintWriter out); - - /** - * Shows the description of a single argument. Used as a callback in - * {@link Argument#describe(HelpFactory)}. - */ protected abstract void describeArgument(org.jnode.shell.syntax.Argument<?> arg, PrintWriter out); /** @@ -143,10 +107,4 @@ protected abstract void describeOption(FlagArgument arg, TreeSet<String> flagTokens, PrintWriter out); - /** - * Shows the description of a single parameter. Used as a callback in - * {@link Parameter#describe(HelpFactory)}. - */ - protected abstract void describeParameter(Parameter param, PrintWriter out); - } Deleted: trunk/shell/src/shell/org/jnode/shell/help/Parameter.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/help/Parameter.java 2008-11-22 03:25:44 UTC (rev 4712) +++ trunk/shell/src/shell/org/jnode/shell/help/Parameter.java 2008-11-22 06:47:09 UTC (rev 4713) @@ -1,146 +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.shell.help; - -import java.io.PrintWriter; - -import org.jnode.driver.console.CompletionInfo; - -/** - * @author qades - */ -public class Parameter extends CommandLineElement { - - public static final String ANONYMOUS = ""; - public static final String NO_DESCRIPTION = ""; - public static final Argument NO_ARGUMENT = null; - public static final boolean OPTIONAL = true; - public static final boolean MANDATORY = false; - - private final Argument argument; - private final boolean optional; - - - public Parameter(String name, String description, Argument argument, boolean optional) { - super(name, description); - this.argument = argument; - this.optional = optional; - } - - public Parameter(String name, String description, boolean optional) { - this(name, description, NO_ARGUMENT, optional); - } - - public Parameter(String name, String description, Argument argument) { - this(name, description, argument, OPTIONAL); - } - - public Parameter(Argument argument, boolean optional) { - this(ANONYMOUS, NO_DESCRIPTION, argument, optional); - } - - /** - * A non-optional parameter - * - * @param argument - */ - public Parameter(Argument argument) { - this(ANONYMOUS, NO_DESCRIPTION, argument, MANDATORY); - } - - public final boolean isAnonymous() { - return ANONYMOUS.equals(getName()); - } - - public final String getDescription() { - if (isAnonymous()) { - return NO_DESCRIPTION; - } - return super.getDescription(); - } - - public final boolean hasArgument() { - return argument != NO_ARGUMENT; - } - - public final Argument getArgument() { - return argument; - } - - public final boolean isOptional() { - return optional; - } - - public String format() { - String result = ""; - if (!isAnonymous()) { - result += "-" + getName(); - // be aware of trailing space - if (hasArgument() && (argument.format().length() != 0)) { - result += " "; - } - } - if (hasArgument()) { - result += argument.format(); - } - return (optional ? "[" + result + "]" : result); - } - - public void describe(HelpFactory help, PrintWriter out) { - if (!isAnonymous()) { - help.describeParameter(this, out); - } - if (hasArgument()) { - argument.describe(help, out); - } - } - - 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()) { - return true; - } - return argument.isSatisfied(); - } - - public final boolean isSet(ParsedArguments args) { - return args.isSet(this); - } - -} Deleted: trunk/shell/src/shell/org/jnode/shell/help/ParsedArguments.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/help/ParsedArguments.java 2008-11-22 03:25:44 UTC (rev 4712) +++ trunk/shell/src/shell/org/jnode/shell/help/ParsedArguments.java 2008-11-22 06:47:09 UTC (rev 4713) @@ -1,77 +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.shell.help; - -import java.util.Map; - -/** - * @author qades - */ -public class ParsedArguments { - - private final Map<CommandLineElement, String[]> args; - - ParsedArguments(Map<CommandLineElement, String[]> args) { - this.args = args; - } - - public final int size() { - return args.size(); - } - - final String[] getValues(Argument arg) { - return (String[]) args.get(arg); - } - - final boolean isSet(Parameter param) { - return args.containsKey(param); - } - - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("{"); - for (Map.Entry<CommandLineElement, String[]> entry : args.entrySet()) { - if (sb.charAt(sb.length() - 1) != '{') { - sb.append(','); - } - sb.append(entry.getKey().format()).append("->"); - if (entry.getValue() == null) { - sb.append("null"); - } else { - sb.append('['); - for (String value : entry.getValue()) { - if (sb.charAt(sb.length() - 1) != '[') { - sb.append(','); - } - if (value == null) { - sb.append("null"); - } else { - sb.append('"').append(value).append('"'); - } - } - sb.append(']'); - } - } - sb.append("}"); - return sb.toString(); - } -} Deleted: trunk/shell/src/shell/org/jnode/shell/help/Syntax.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/help/Syntax.java 2008-11-22 03:25:44 UTC (rev 4712) +++ trunk/shell/src/shell/org/jnode/shell/help/Syntax.java 2008-11-22 06:47:09 UTC (rev 4713) @@ -1,367 +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.shell.help; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -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; - -/** - * @author qades - * @author cr...@jn... - */ -@SuppressWarnings("deprecation") -public class Syntax { - - public static final boolean DEBUG = false; - public static final Logger LOGGER = Logger.getLogger(Syntax.class); - - private final String description; - - private final Parameter[] params; - - public Syntax(String description, Parameter... params) { - this.description = description; - this.params = params; - } - - /** - * Gets the description of this syntax - */ - public String getDescription() { - return description; - } - - /** - * Gets the parameters of this syntax - */ - public Parameter[] getParams() { - return params; - } - - public void complete(CompletionInfo completion, CommandLine partial) throws CompletionException { - Parameter param; - CommandLine.Token value; - int tokenType; - - if (DEBUG) LOGGER.debug("Syntax.complete: this.description = " + this.description); - - CompletionVisitor visitor = new CompletionVisitor(); - try { - param = visitCommandLine(partial, visitor); - } catch (SyntaxErrorException ex) { - throw new CompletionException(ex.getMessage()); - } - - if (DEBUG) LOGGER.debug("Syntax.complete: initial param = " + - ((param == null) ? "null" : param.format()) + ", argumentAnticipated = " + - partial.isArgumentAnticipated()); - - if (param != null && partial.isArgumentAnticipated()) { - value = null; - tokenType = CommandLine.LITERAL; - } else { - param = visitor.getLastParam(); - value = visitor.getLastValue(); - tokenType = visitor.getLastTokenType(); - } - - if (param == null) { - if (DEBUG) LOGGER.debug("Syntax.complete: no param"); - // completion.addCompletion(" "); - return; - } - if (DEBUG) LOGGER.debug("Syntax.complete: param = " + param.format() + ", value = " + value + - ", tokenType = " + tokenType); - - if (param.hasArgument()) { - if (value != null) { - param.complete(completion, value.token); - completion.setCompletionStart(value.start); - } else { - param.complete(completion, ""); - } - } else if (!param.isAnonymous()) { - completion.addCompletion("-" + param.getName()); - } - } - - synchronized ParsedArguments parse(CommandLine cmdLine) throws SyntaxErrorException { - if (DEBUG) LOGGER.debug("Syntax.parse: this.description = " + this.description); - - if (params.length == 0) { - if (cmdLine.getLength() == 0) { - if (DEBUG) LOGGER.debug("Syntax.parse: returning no args"); - return new ParsedArguments(new HashMap<CommandLineElement, String[]>()); - } - if (DEBUG) LOGGER.debug("Syntax.parse: takes no parameter"); - throw new SyntaxErrorException("Syntax takes no parameter"); - } - - final ParseVisitor visitor = new ParseVisitor(); - visitCommandLine(cmdLine, visitor); - final ParsedArguments result = new ParsedArguments(visitor.getArgumentMap()); - - // check if all mandatory parameters are set - for (Parameter p : params) { - if (!p.isOptional() && !p.isSet(result)) { - if (DEBUG) LOGGER.debug("Syntax.parse: parameter " + p.format() + " not set"); - throw new SyntaxErrorException("Mandatory parameter " + p.format() + " not set"); - } - } - if (DEBUG) LOGGER.debug("Syntax.parse: returning '" + result.toString() + "'"); - return result; - } - - private synchronized Parameter visitCommandLine( - CommandLine cmdLine, CommandLineVisitor visitor) - throws SyntaxErrorException { - clearArguments(); - Parameter param = null; - final ParameterIterator paramIterator = new ParameterIterator(); - - // FIXME - should use a Token iterator here ... - final Iterator<CommandLine.Token> it = cmdLine.tokenIterator(); - boolean acceptNames = true; - 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(token)) { - acceptNames = false; - 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 (token.token.charAt(0) != '-' || param.getArgument() instanceof OptionArgument) { - if (DEBUG) LOGGER.debug("Syntax.visitor: trying anonymous param " + param.format()); - visitor.visitParameter(param); - } else { - param = null; - } - } else if (acceptNames && token.equals("-" + param.getName())) { - if (DEBUG) LOGGER.debug("Syntax.visitor: trying named param " + param.format()); - visitor.visitParameter(param); - token = it.hasNext() ? it.next() : null; - } else { - if (DEBUG) LOGGER.debug("Syntax.visitor: skipping named param " + param.format()); - param = null; - } - } else { - if (DEBUG) LOGGER.debug("Syntax.visitor: no param for '" + token + "'"); - throw new SyntaxErrorException("Unexpected argument '" + token + "'"); - } - } - if (param != null) { - // Have a Parameter. Trying to match its Argument. - final boolean last = !it.hasNext() && !cmdLine.isArgumentAnticipated(); - Argument arg = param.getArgument(); - if (arg == null) { - visitor.visitValue(null, 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.token); - token = it.hasNext() ? it.next() : null; - } else if (!param.isOptional()) { - 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 '" + token + - "' optional param " + param.format()); - if (DEBUG) LOGGER.debug("Syntax.visitor: clearing param"); - param = null; - } - } else if (!param.isOptional()) { - if (DEBUG) LOGGER.debug("Syntax.visitor: missing arg for mandatory param " + param.format()); - // FIXME .. what if param is anonymous? - throw new SyntaxErrorException("Missing argument value for '" + - param.getName() + "' option"); - } - - if (param != null && param.isSatisfied()) { - if (DEBUG) LOGGER.debug("Syntax.visitor: param " + param.format() + " is satisfied"); - if (!last || cmdLine.isArgumentAnticipated()) { - if (DEBUG) LOGGER.debug("Syntax.visitor: clearing param"); - param = null; - } - } - } - } - while (param == null && paramIterator.hasNext()) { - param = (Parameter) paramIterator.next(); - if (param.isAnonymous()) { - if (DEBUG) LOGGER.debug("Syntax.visitor: setting param " + param.format() + " at end"); - break; - } - param = null; - } - return param; - } - - final void clearArguments() { - for (Parameter param : params) - if (param.hasArgument()) param.getArgument().clear(); - } - - /** - * Visitor for command line elements. - * - * @author Ewout Prangsma (ep...@us...) - */ - private interface CommandLineVisitor { - - public void visitParameter(Parameter p); - - public CommandLine.Token visitValue(CommandLine.Token token, boolean last, int tokenType); - - public boolean isValueValid(Argument arg, CommandLine.Token value, boolean last); - } - - private class CompletionVisitor implements CommandLineVisitor { - private Parameter param = null; - private CommandLine.Token value; - private int tokenType; - private boolean last; - - public CompletionVisitor() { - } - - public void visitParameter(Parameter p) { - if (DEBUG) LOGGER.debug("CompletionVisitor: param = " + p.format()); - this.param = p; - this.last = true; - this.value = null; - this.tokenType = 0; - } - - 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 = token; - this.tokenType = tokenType; - } - return token; - } - - 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.token); - if (DEBUG) LOGGER.debug("CompletionVisitor: isValueValid -> " + res); - return res; - } - - public Parameter getLastParam() { - return last ? this.param : null; - } - - public CommandLine.Token getLastValue() { - return last ? this.value : null; - } - - public int getLastTokenType() { - return last ? this.tokenType : -1; - } - } - - private class ParseVisitor implements CommandLineVisitor { - - Map<CommandLineElement, String[]> result = new HashMap<CommandLineElement, String[]>(); - - Parameter param = null; - - boolean valued = false; - - public void visitParameter(Parameter p) { - finishParameter(); - this.param = p; - } - - public CommandLine.Token visitValue(CommandLine.Token s, boolean last, int tokenType) { - if (last && s == null) return null; - valued = true; - return s; - } - - final Map<CommandLineElement, String[]> getArgumentMap() { - finishParameter(); - return result; - } - - void finishParameter() { - if (param == null) return; - - if (valued || !param.hasArgument()) { - result.put(param, null); // mark it as "set" - } - if (param.hasArgument()) { - Argument arg = param.getArgument(); - result.put(arg, arg.getValues()); - } - param = null; - valued = false; - } - - public boolean isValueValid(Argument arg, CommandLine.Token value, boolean last) { - return arg.isValidValue(value.token); - } - } - - class ParameterIterator implements Iterator<Parameter> { - final Parameter[] params = Syntax.this.params; - final int length = params.length; - - private int nextParamsIdx = 0; - - public ParameterIterator() { - } - - public boolean hasNext() { - return (nextParamsIdx < length); - } - - public Parameter next() { - if (nextParamsIdx < length) { - return params[nextParamsIdx++]; - } else { - throw new NoSuchElementException(); - } - } - - public void remove() { - throw new UnsupportedOperationException(); - } - } -} Modified: trunk/shell/src/shell/org/jnode/shell/help/def/DefaultHelpFactory.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/help/def/DefaultHelpFactory.java 2008-11-22 03:25:44 UTC (rev 4712) +++ trunk/shell/src/shell/org/jnode/shell/help/def/DefaultHelpFactory.java 2008-11-22 06:47:09 UTC (rev 4713) @@ -29,12 +29,9 @@ import org.jnode.shell.CommandInfo; import org.jnode.shell.Shell; import org.jnode.shell.ShellUtils; -import org.jnode.shell.help.Argument; import org.jnode.shell.help.Help; import org.jnode.shell.help.HelpException; import org.jnode.shell.help.HelpFactory; -import org.jnode.shell.help.Parameter; -import org.jnode.shell.help.Syntax; import org.jnode.shell.syntax.ArgumentBundle; import org.jnode.shell.syntax.FlagArgument; import org.jnode.shell.syntax.OptionSyntax; @@ -61,13 +58,11 @@ @Override public Help getHelp(String alias, CommandInfo cmdInfo) throws HelpException { - Help.Info info = null; SyntaxBundle syntaxes = null; ArgumentBundle bundle = null; try { final Shell shell = ShellUtils.getShellManager().getCurrentShell(); final SyntaxManager syntaxManager = shell.getSyntaxManager(); - Class<?> clazz = cmdInfo.getCommandClass(); Command cmd = cmdInfo.createCommandInstance(); if (cmd != null) { bundle = cmd.getArgumentBundle(); @@ -75,40 +70,18 @@ if (syntaxes == null) { syntaxes = new SyntaxBundle(alias, bundle.createDefaultSyntax()); } - } else { - info = HelpFactory.getInfo(clazz); - } - } catch (HelpException ex) { - throw ex; + } } catch (Exception ex) { throw new HelpException(ex.getMessage(), ex); } - if (info != null && alias != null) { - return new OldSyntaxHelp(info, alias); - } else if (syntaxes != null && bundle != null) { + if (syntaxes != null && bundle != null) { return new NewSyntaxHelp(syntaxes, bundle); } else { return null; } } - /** - * Shows the complete help for a command. - * - * @see HelpFactory#help(org.jnode.shell.help.HelpFactory.Info, String) - */ - public void help(Help.Info info, String command, PrintWriter out) { - final Syntax[] syntaxes = info.getSyntaxes(); - final String name = command == null ? info.getName() : command; - for (int i = 0; i < syntaxes.length; i++) { - help(name, syntaxes[i], out); - if (i < syntaxes.length) { - out.println(); - } - } - } - @Override public void help(SyntaxBundle syntaxes, ArgumentBundle bundle, PrintWriter out) { usage(syntaxes, bundle, out); @@ -173,47 +146,6 @@ } } - /** - * Shows the help for a command syntax. - */ - public void help(String name, Syntax syntax, PrintWriter out) { - usage(name, syntax, out); - if (syntax.getDescription() != null) { - out.println("\n" + HelpFactory.getLocalizedHelp("help.description") + ":"); - format(out, new Cell[]{new Cell(4, NOMINAL_WIDTH - 4)}, - new String[]{syntax.getDescription()}); - } - final Parameter[] params = syntax.getParams(); - if (params.length != 0) { - out.println("\n" + HelpFactory.getLocalizedHelp("help.parameters") + ":"); - for (int i = 0; i < params.length; i++) { - params[i].describe(this, out); - } - } - } - - /** - * Shows the usage information of a command. - */ - public void usage(Help.Info info, PrintWriter out) { - final Syntax[] syntaxes = info.getSyntaxes(); - for (int i = 0; i < syntaxes.length; i++) { - usage(info.getName(), syntaxes[i], out); - } - } - - /** - * Shows the usage information of a command. - */ - public void usage(String name, Syntax syntax, PrintWriter out) { - StringBuilder line = new StringBuilder(name); - final Parameter[] params = syntax.getParams(); - for (int i = 0; i < params.length; i++) { - line.append(' ').append(params[i].format()); - } - out.println(HelpFactory.getLocalizedHelp("help.usage") + ": " + line); - } - @Override public void usage(SyntaxBundle syntaxBundle, ArgumentBundle bundle, PrintWriter out) { String command = syntaxBundle.getAlias(); @@ -241,17 +173,7 @@ format(out, cells, texts); } } - - public void describeParameter(Parameter param, PrintWriter out) { - format(out, new Cell[]{new Cell(2, 18), new Cell(2, NOMINAL_WIDTH - 22)}, - new String[]{param.getName(), param.getDescription()}); - } - - public void describeArgument(Argument arg, PrintWriter out) { - format(out, new Cell[]{new Cell(4, 16), new Cell(2, NOMINAL_WIDTH - 22)}, - new String[]{arg.getName(), arg.getDescription()}); - } - + @Override public void describeArgument(org.jnode.shell.syntax.Argument<?> arg, PrintWriter out) { String description = "(" + arg.getTypeDescription() + ") " + arg.getDescription(); Deleted: trunk/shell/src/shell/org/jnode/shell/help/def/OldSyntaxHelp.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/help/def/OldSyntaxHelp.java 2008-11-22 03:25:44 UTC (rev 4712) +++ trunk/shell/src/shell/org/jnode/shell/help/def/OldSyntaxHelp.java 2008-11-22 06:47:09 UTC (rev 4713) @@ -1,88 +0,0 @@ -package org.jnode.shell.help.def; - -import java.io.PrintWriter; - -import org.jnode.shell.help.Argument; -import org.jnode.shell.help.Help; -import org.jnode.shell.help.HelpFactory; -import org.jnode.shell.help.Parameter; -import org.jnode.shell.help.Syntax; - -/** - * This Help implementation provides for 'old' syntax commands in plain text format. - * - * @author cr...@jn... - */ -public class OldSyntaxHelp extends TextHelpBase implements Help { - private final Info info; - private final String command; - - public OldSyntaxHelp(Info info, String command) { - this.info = info; - this.command = command; - } - - @Override - public void help(PrintWriter pw) { - final Syntax[] syntaxes = info.getSyntaxes(); - for (int i = 0; i < syntaxes.length; i++) { - help(syntaxes[i], pw); - if (i < syntaxes.length) { - pw.println(); - } - } - } - - @Override - public void usage(PrintWriter pw) { - final Syntax[] syntaxes = info.getSyntaxes(); - for (int i = 0; i < syntaxes.length; i++) { - usage(syntaxes[i], pw); - if (i < syntaxes.length) { - pw.println(); - } - } - } - - private String commandName() { - return command == null ? info.getName() : command; - } - - /** - * Shows the help for a command syntax. - */ - public void help(Syntax syntax, PrintWriter pw) { - usage(syntax, pw); - if (syntax.getDescription() != null) { - pw.println("\n" + HelpFactory.getLocalizedHelp("help.description") + ":"); - format(pw, new TextCell[]{new TextCell(4, NOMINAL_WIDTH - 4)}, - new String[]{syntax.getDescription()}); - } - final Parameter[] params = syntax.getParams(); - if (params.length != 0) { - pw.println("\n" + HelpFactory.getLocalizedHelp("help.parameters") + ":"); - for (int i = 0; i < params.length; i++) { - describeParameter(params[i], pw); - } - } - } - - private void usage(Syntax syntax, PrintWriter pw) { - StringBuilder line = new StringBuilder(commandName()); - final Parameter[] params = syntax.getParams(); - for (int i = 0; i < params.length; i++) { - line.append(' ').append(params[i].format()); - } - pw.println(HelpFactory.getLocalizedHelp("help.usage") + ": " + line); - } - - public void describeParameter(Parameter param, PrintWriter out) { - format(out, new TextCell[]{new TextCell(2, 18), new TextCell(2, NOMINAL_WIDTH - 22)}, - new String[]{param.getName(), param.getDescription()}); - } - - public void describeArgument(Argument arg, PrintWriter out) { - format(out, new TextCell[]{new TextCell(4, 16), new TextCell(2, NOMINAL_WIDTH - 22)}, - new String[]{arg.getName(), arg.getDescription()}); - } -} Modified: trunk/shell/src/test/org/jnode/test/shell/CompletionTest.java =================================================================== --- trunk/shell/src/test/org/jnode/test/shell/CompletionTest.java 2008-11-22 03:25:44 UTC (rev 4712) +++ trunk/shell/src/test/org/jnode/test/shell/CompletionTest.java 2008-11-22 06:47:09 UTC (rev 4713) @@ -131,59 +131,6 @@ } } - public void testDefaultInterpreterOldSyntax() throws Exception { - TestCommandShell cs = new TestCommandShell(); - cs.setCommandInterpreter("default"); - - checkCompletions(cs, "", aliasCompletions, -1); - checkCompletions(cs, "di", new String[]{"dir "}, 0); - checkCompletions(cs, "dir", new String[]{"dir "}, 0); - checkCompletions(cs, "dir ", new String[]{"Four/", "One ", "Three ", "Two "}, -1); - checkCompletions(cs, "dir T", new String[]{"Three ", "Two "}, 4); - - // The default interpreter doesn't recognize '>' '<' or '|' as anything special. - // Therefore it should just try to complete them as filenames ... and fail. - checkCompletions(cs, "dir |", new String[]{}, -1); - checkCompletions(cs, "dir | ", new String[]{}, -1); // dir takes one argument only - checkCompletions(cs, "cat | ", new String[]{"Four/", "One ", "Three ", "Two "}, -1); - checkCompletions(cs, "cat | ca", new String[]{}, -1); - checkCompletions(cs, "cat >", new String[]{}, -1); - checkCompletions(cs, "cat > ", new String[]{"Four/", "One ", "Three ", "Two "}, -1); - checkCompletions(cs, "cat <", new String[]{}, -1); - checkCompletions(cs, "cat < ", new String[]{"Four/", "One ", "Three ", "Two "}, -1); - } - - public void testOldSyntaxOptions() throws Exception { - TestCommandShell cs = new TestCommandShell(); - cs.setCommandInterpreter("default"); - - // For bug #4418 - checkCompletions(cs, "cat -", new String[]{"-u "}, -2); - checkCompletions(cs, "cat -u", new String[]{"-u "}, -2); - - // And some more ... - } - - public void testRedirectingInterpreterOldSyntax() throws Exception { - TestCommandShell cs = new TestCommandShell(); - cs.setCommandInterpreter("redirecting"); - - checkCompletions(cs, "", aliasCompletions, -1); - checkCompletions(cs, "di", new String[]{"dir "}, 0); - checkCompletions(cs, "dir", new String[]{"dir "}, 0); - checkCompletions(cs, "dir ", new String[]{"Four/", "One ", "Three ", "Two "}, -1); - checkCompletions(cs, "dir T", new String[]{"Three ", "Two "}, 4); - checkCompletions(cs, "dir |", aliasCompletions, -1); - checkCompletions(cs, "dir | ", aliasCompletions, -1); - checkCompletions(cs, "cat |", aliasCompletions, -1); - checkCompletions(cs, "cat | ", aliasCompletions, -1); - checkCompletions(cs, "cat | ca", new String[]{"cat "}, 6); - checkCompletions(cs, "cat >", new String[]{"Four/", "One ", "Three ", "Two "}, -1); - checkCompletions(cs, "cat > ", new String[]{"Four/", "One ", "Three ", "Two "}, -1); - checkCompletions(cs, "cat <", new String[]{"Four/", "One ", "Three ", "Two "}, -1); - checkCompletions(cs, "cat < ", new String[]{"Four/", "One ", "Three ", "Two "}, -1); - } - public void testDefaultInterpreterNewSyntax() throws Exception { TestCommandShell cs = new TestCommandShell(); cs.setCommandInterpreter("default"); Deleted: trunk/shell/src/test/org/jnode/test/shell/MyCatCommand.java =================================================================== --- trunk/shell/src/test/org/jnode/test/shell/MyCatCommand.java 2008-11-22 03:25:44 UTC (rev 4712) +++ trunk/shell/src/test/org/jnode/test/shell/MyCatCommand.java 2008-11-22 06:47:09 UTC (rev 4713) @@ -1,63 +0,0 @@ -/* - * $Id: CatCommand.java 3603 2007-11-25 21:43:50Z 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.test.shell; - -import org.jnode.shell.AbstractCommand; -import org.jnode.shell.help.Help; -import org.jnode.shell.help.Parameter; -import org.jnode.shell.help.Syntax; -import org.jnode.shell.help.argument.FileArgument; -import org.jnode.shell.help.argument.URLArgument; - -/** - * Cut down test class - */ -@SuppressWarnings("deprecation") -public class MyCatCommand extends AbstractCommand { - - static final FileArgument ARG_FILE = new FileArgument("file", - "the files to be concatenated", true); - - static final URLArgument ARG_URL = new URLArgument("url", - "the files to be concatenated", true); - - public static Help.Info HELP_INFO = new Help.Info("cat", - new Syntax[]{ - new Syntax( - "Fetch the argument urls and copy their contents to standard output.", - new Parameter[]{ - new Parameter("u", - "selects urls rather than pathnames", - ARG_URL, Parameter.MANDATORY)}), - new Syntax( - "Read the argument files, copying their contents to standard output. " + - "If there are no arguments, standard input is read until EOF is reached; " + - "e.g. ^D when reading keyboard input.", - new Parameter[]{ - new Parameter(ARG_FILE, Parameter.OPTIONAL)}) - - }); - - public void execute() throws Exception { - } - -} Deleted: trunk/shell/src/test/org/jnode/test/shell/MyDirCommand.java =================================================================== --- trunk/shell/src/test/org/jnode/test/shell/MyDirCommand.java 2008-11-22 03:25:44 UTC (rev 4712) +++ trunk/shell/src/test/org/jnode/test/shell/MyDirCommand.java 2008-11-22 06:47:09 UTC (rev 4713) @@ -1,44 +0,0 @@ -/* - * $Id: DirCommand.java 3590 2007-11-17 19:28:05Z 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.test.shell; - -import org.jnode.shell.AbstractCommand; -import org.jnode.shell.help.Help; -import org.jnode.shell.help.Parameter; -import org.jnode.shell.help.argument.FileArgument; - -/** - * Cut down test class ... dir done the old way - */ -@SuppressWarnings("deprecation") -public class MyDirCommand extends AbstractCommand { - static final FileArgument ARG_PATH = new FileArgument("path", "the path to list contents of"); - public static Help.Info HELP_INFO = - new Help.Info( - "dir", - "List the entries of the given path", - new Parameter[]{new Parameter(ARG_PATH, Parameter.OPTIONAL)}); - - public void execute() throws Exception { - // suddenly ... nothing happened - } -} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2008-11-23 20:42:13
|
Revision: 4726 http://jnode.svn.sourceforge.net/jnode/?rev=4726&view=rev Author: lsantha Date: 2008-11-23 20:42:09 +0000 (Sun, 23 Nov 2008) Log Message: ----------- openjdk integration Modified Paths: -------------- trunk/core/descriptors/org.classpath.ext.xml trunk/core/src/classpath/gnu/gnu/java/awt/peer/GLightweightPeer.java trunk/core/src/classpath/gnu/gnu/java/awt/peer/swing/SwingComponentPeer.java trunk/core/src/icedtea/sun/util/CoreResourceBundleControl.java trunk/gui/src/awt/org/jnode/awt/swingpeers/DesktopFramePeer.java trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingComponentPeer.java trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingDialogPeer.java Modified: trunk/core/descriptors/org.classpath.ext.xml =================================================================== --- trunk/core/descriptors/org.classpath.ext.xml 2008-11-23 20:34:38 UTC (rev 4725) +++ trunk/core/descriptors/org.classpath.ext.xml 2008-11-23 20:42:09 UTC (rev 4726) @@ -61,6 +61,7 @@ <export name="sun.awt.dnd.*"/> <export name="sun.awt.geom.*"/> <export name="sun.awt.shell.*"/> + <export name="sun.awt.util.*"/> <export name="sun.dc.path.*"/> <export name="sun.dc.pr.*"/> <export name="sun.font.*"/> Modified: trunk/core/src/classpath/gnu/gnu/java/awt/peer/GLightweightPeer.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/awt/peer/GLightweightPeer.java 2008-11-23 20:34:38 UTC (rev 4725) +++ trunk/core/src/classpath/gnu/gnu/java/awt/peer/GLightweightPeer.java 2008-11-23 20:42:09 UTC (rev 4726) @@ -62,6 +62,7 @@ import java.awt.peer.ContainerPeer; import java.awt.peer.LightweightPeer; import sun.awt.CausedFocusEvent; +import sun.java2d.pipe.Region; /** * A stub class that implements the ComponentPeer and ContainerPeer @@ -455,4 +456,8 @@ public boolean requestFocus(Component lightweightChild, boolean temporary, boolean focusedWindowChangeAllowed, long time, CausedFocusEvent.Cause cause) { return false; } + + public void applyShape(Region shape) { + + } } Modified: trunk/core/src/classpath/gnu/gnu/java/awt/peer/swing/SwingComponentPeer.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/awt/peer/swing/SwingComponentPeer.java 2008-11-23 20:34:38 UTC (rev 4725) +++ trunk/core/src/classpath/gnu/gnu/java/awt/peer/swing/SwingComponentPeer.java 2008-11-23 20:42:09 UTC (rev 4726) @@ -68,6 +68,7 @@ import javax.swing.JComponent; import javax.swing.RepaintManager; import sun.awt.CausedFocusEvent; +import sun.java2d.pipe.Region; /** * The base class for Swing based component peers. This provides the basic @@ -1117,4 +1118,7 @@ swingComponent.getJComponent().requestFocus(); return swingComponent != null; } + + public void applyShape(Region shape) { + } } Modified: trunk/core/src/icedtea/sun/util/CoreResourceBundleControl.java =================================================================== --- trunk/core/src/icedtea/sun/util/CoreResourceBundleControl.java 2008-11-23 20:34:38 UTC (rev 4725) +++ trunk/core/src/icedtea/sun/util/CoreResourceBundleControl.java 2008-11-23 20:42:09 UTC (rev 4726) @@ -71,6 +71,26 @@ public static CoreResourceBundleControl getRBControlInstance() { return resourceBundleControlInstance; } + + /** + * This method is to provide a customized ResourceBundle.Control to speed + * up the search of resources in JDK, with the bundle's package name check. + * + * @param bundleName bundle name to check + * @return the instance of resource bundle control if the bundle is JDK's, + * otherwise returns null. + */ + public static CoreResourceBundleControl getRBControlInstance(String bundleName) { + if (bundleName.startsWith("com.sun.") || + bundleName.startsWith("java.") || + bundleName.startsWith("javax.") || + bundleName.startsWith("sun.")) { + return resourceBundleControlInstance; + } else { + return null; + } + } + /* * @returns a list of candidate locales to search from. Modified: trunk/gui/src/awt/org/jnode/awt/swingpeers/DesktopFramePeer.java =================================================================== --- trunk/gui/src/awt/org/jnode/awt/swingpeers/DesktopFramePeer.java 2008-11-23 20:34:38 UTC (rev 4725) +++ trunk/gui/src/awt/org/jnode/awt/swingpeers/DesktopFramePeer.java 2008-11-23 20:42:09 UTC (rev 4726) @@ -54,6 +54,7 @@ import org.jnode.awt.JNodeGraphics2D; import org.jnode.awt.GraphicsFactory; import sun.awt.CausedFocusEvent; +import sun.java2d.pipe.Region; /** * @author Ewout Prangsma (ep...@us...) @@ -657,4 +658,8 @@ .getBounds())); } } + + public void applyShape(Region shape) { + //TODO implement it + } } Modified: trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingComponentPeer.java =================================================================== --- trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingComponentPeer.java 2008-11-23 20:34:38 UTC (rev 4725) +++ trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingComponentPeer.java 2008-11-23 20:42:09 UTC (rev 4726) @@ -56,6 +56,7 @@ import org.jnode.awt.JNodeGraphics2D; import org.jnode.awt.JNodeToolkit; import sun.awt.CausedFocusEvent; +import sun.java2d.pipe.Region; /** * Base class for virtual component peers. Satisfies the requirements for AWT @@ -530,4 +531,8 @@ public void reparent(ContainerPeer parent) { //TODO implement it } + + public void applyShape(Region shape) { + //TODO + } } Modified: trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingDialogPeer.java =================================================================== --- trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingDialogPeer.java 2008-11-23 20:34:38 UTC (rev 4725) +++ trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingDialogPeer.java 2008-11-23 20:42:09 UTC (rev 4726) @@ -22,7 +22,9 @@ package org.jnode.awt.swingpeers; import java.awt.Dialog; +import java.awt.Window; import java.awt.peer.DialogPeer; +import java.util.List; /** * AWT dialog peer implemented as a {@link javax.swing.JInternalFrame}. @@ -52,6 +54,10 @@ super.setTitle(title); } } + + public void blockWindows(List<Window> windows) { + //TODO implement it + } } final class SwingDialog extends SwingBaseWindow<Dialog, SwingDialog> { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cr...@us...> - 2008-11-26 13:40:33
|
Revision: 4748 http://jnode.svn.sourceforge.net/jnode/?rev=4748&view=rev Author: crawley Date: 2008-11-26 13:40:30 +0000 (Wed, 26 Nov 2008) Log Message: ----------- Moved BasicNameSpace to core and fixed it so that it can be used by all classic JVM apps/tests/emulators that need it. Created DummyPluginDescriptor in core for same. Tweaked Emu's jnode.interpreter/invoker/debug properties to get it working again. Modified Paths: -------------- trunk/core/src/core/org/jnode/naming/AbstractNameSpace.java trunk/distr/src/emu/org/jnode/emu/Emu.java trunk/distr/src/emu/org/jnode/emu/ShellEmu.java trunk/distr/src/test/org/jnode/apps/jpartition/utils/device/DeviceUtils.java trunk/gui/src/test/org/jnode/test/gui/Emu.java trunk/shell/src/test/org/jnode/test/shell/Cassowary.java Added Paths: ----------- trunk/core/src/core/org/jnode/naming/BasicNameSpace.java trunk/core/src/core/org/jnode/plugin/model/DummyPluginDescriptor.java Removed Paths: ------------- trunk/distr/src/test/org/jnode/apps/jpartition/utils/BasicNameSpace.java Modified: trunk/core/src/core/org/jnode/naming/AbstractNameSpace.java =================================================================== --- trunk/core/src/core/org/jnode/naming/AbstractNameSpace.java 2008-11-25 10:44:10 UTC (rev 4747) +++ trunk/core/src/core/org/jnode/naming/AbstractNameSpace.java 2008-11-26 13:40:30 UTC (rev 4748) @@ -61,7 +61,6 @@ l.serviceBound(lookup(name)); } catch (NameNotFoundException e) { // no service bound for that name => ignore - Unsafe.debugStackTrace(e); } } Added: trunk/core/src/core/org/jnode/naming/BasicNameSpace.java =================================================================== --- trunk/core/src/core/org/jnode/naming/BasicNameSpace.java (rev 0) +++ trunk/core/src/core/org/jnode/naming/BasicNameSpace.java 2008-11-26 13:40:30 UTC (rev 4748) @@ -0,0 +1,72 @@ +/* + * $Id: Label.java 4159 2008-05-30 16:15:41Z 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.naming; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import javax.naming.NameAlreadyBoundException; +import javax.naming.NameNotFoundException; +import javax.naming.NamingException; + +/** + * This implementation of NameSpace does not make use of Class.getVmClass() and + * therefore can be used in JNode applications / test cases / frameworks designed + * to run on a classic Java VM. + * + * @author cr...@jn... + */ +public final class BasicNameSpace extends AbstractNameSpace { + protected final Map<Class<?>, Object> namespace = new HashMap<Class<?>, Object>(); + + public <T> void bind(Class<T> name, T service) + throws NamingException, NameAlreadyBoundException { + if (name == null) { + throw new IllegalArgumentException("name == null"); + } + synchronized (namespace) { + if (namespace.containsKey(name)) { + throw new NameAlreadyBoundException(name.getName()); + } + namespace.put(name, service); + } + } + + @SuppressWarnings("unchecked") + public <T> T lookup(Class<T> name) throws NameNotFoundException { + synchronized (namespace) { + T res = (T) namespace.get(name); + if (res == null) { + throw new NameNotFoundException(name.getName()); + } + return res; + } + } + + public Set<Class<?>> nameSet() { + return namespace.keySet(); + } + + public void unbind(Class<?> name) { + namespace.remove(name); + } +} Added: trunk/core/src/core/org/jnode/plugin/model/DummyPluginDescriptor.java =================================================================== --- trunk/core/src/core/org/jnode/plugin/model/DummyPluginDescriptor.java (rev 0) +++ trunk/core/src/core/org/jnode/plugin/model/DummyPluginDescriptor.java 2008-11-26 13:40:30 UTC (rev 4748) @@ -0,0 +1,133 @@ +package org.jnode.plugin.model; + +import org.jnode.plugin.Extension; +import org.jnode.plugin.ExtensionPoint; +import org.jnode.plugin.Plugin; +import org.jnode.plugin.PluginDescriptor; +import org.jnode.plugin.PluginDescriptorListener; +import org.jnode.plugin.PluginException; +import org.jnode.plugin.PluginPrerequisite; +import org.jnode.plugin.Runtime; + +public class DummyPluginDescriptor implements PluginDescriptor { + + private boolean systemPlugin; + + public DummyPluginDescriptor(boolean systemPlugin) { + this.systemPlugin = systemPlugin; + } + + public void addListener(PluginDescriptorListener listener) { + // TODO Auto-generated method stub + + } + + public boolean depends(String id) { + // TODO Auto-generated method stub + return false; + } + + public String getCustomPluginClassName() { + // TODO Auto-generated method stub + return null; + } + + public ExtensionPoint getExtensionPoint(String extensionPointId) { + // TODO Auto-generated method stub + return null; + } + + public ExtensionPoint[] getExtensionPoints() { + // TODO Auto-generated method stub + return null; + } + + public Extension[] getExtensions() { + // TODO Auto-generated method stub + return null; + } + + public String getId() { + // TODO Auto-generated method stub + return null; + } + + public String getLicenseName() { + // TODO Auto-generated method stub + return null; + } + + public String getLicenseUrl() { + // TODO Auto-generated method stub + return null; + } + + public String getName() { + // TODO Auto-generated method stub + return null; + } + + public Plugin getPlugin() throws PluginException { + // TODO Auto-generated method stub + return null; + } + + public ClassLoader getPluginClassLoader() { + // TODO Auto-generated method stub + return null; + } + + public PluginPrerequisite[] getPrerequisites() { + // TODO Auto-generated method stub + return null; + } + + public int getPriority() { + // TODO Auto-generated method stub + return 0; + } + + public String getProviderName() { + // TODO Auto-generated method stub + return null; + } + + public String getProviderUrl() { + // TODO Auto-generated method stub + return null; + } + + public Runtime getRuntime() { + // TODO Auto-generated method stub + return null; + } + + public String getVersion() { + // TODO Auto-generated method stub + return null; + } + + public boolean hasCustomPluginClass() { + // TODO Auto-generated method stub + return false; + } + + public boolean isAutoStart() { + // TODO Auto-generated method stub + return false; + } + + public boolean isFragment() { + // TODO Auto-generated method stub + return false; + } + + public boolean isSystemPlugin() { + return systemPlugin; + } + + public void removeListener(PluginDescriptorListener listener) { + // TODO Auto-generated method stub + + } +} Modified: trunk/distr/src/emu/org/jnode/emu/Emu.java =================================================================== --- trunk/distr/src/emu/org/jnode/emu/Emu.java 2008-11-25 10:44:10 UTC (rev 4747) +++ trunk/distr/src/emu/org/jnode/emu/Emu.java 2008-11-26 13:40:30 UTC (rev 4748) @@ -1,3 +1,23 @@ +/* + * $Id: NameSpace.java 4564 2008-09-18 22:01:10Z 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.emu; import java.io.BufferedReader; @@ -13,6 +33,7 @@ import javax.naming.NamingException; import org.jnode.naming.AbstractNameSpace; +import org.jnode.naming.BasicNameSpace; import org.jnode.naming.InitialNaming; import org.jnode.nanoxml.XMLElement; import org.jnode.shell.ShellManager; @@ -29,6 +50,9 @@ import org.jnode.shell.syntax.XMLSyntaxSpecAdapter; /** + * This class is the core of a light-weight JNode emulator that allows (some) JNode + * applications to be run using a classic JVM in the context of a JNode development sandbox. + * * @author Levente S\u00e1ntha * @author Stephen Crawley */ @@ -57,29 +81,8 @@ root = new File("").getAbsoluteFile(); System.err.println("Assuming that the JNode root is '" + root + "'"); } - InitialNaming.setNameSpace(new AbstractNameSpace() { - private Map<Class<?>, Object> space = new HashMap<Class<?>, Object>(); + InitialNaming.setNameSpace(new BasicNameSpace()); - public <T> void bind(Class<T> name, T service) throws NamingException, NameAlreadyBoundException { - if (space.get(name) != null) throw new NameAlreadyBoundException(); - space.put(name, service); - } - - public void unbind(Class<?> name) { - space.remove(name); - } - - public <T> T lookup(Class<T> name) throws NameNotFoundException { - T obj = (T) space.get(name); - if (obj == null) throw new NameNotFoundException(name.getName()); - return obj; - } - - public Set<Class<?>> nameSet() { - return space.keySet(); - } - }); - try { InitialNaming.bind(DeviceManager.NAME, DeviceManager.INSTANCE); AliasManager aliasMgr = @@ -89,7 +92,9 @@ for (String pluginName : PLUGIN_NAMES) { configurePluginCommands(root, pluginName, aliasMgr, syntaxMgr); } - System.setProperty("jnode.invoker", "default"); + System.setProperty("jnode.invoker", "thread"); + System.setProperty("jnode.interpreter", "redirecting"); + System.setProperty("jnode.debug", "true"); InitialNaming.bind(AliasManager.NAME, aliasMgr); InitialNaming.bind(ShellManager.NAME, new DefaultShellManager()); InitialNaming.bind(SyntaxManager.NAME, syntaxMgr); Modified: trunk/distr/src/emu/org/jnode/emu/ShellEmu.java =================================================================== --- trunk/distr/src/emu/org/jnode/emu/ShellEmu.java 2008-11-25 10:44:10 UTC (rev 4747) +++ trunk/distr/src/emu/org/jnode/emu/ShellEmu.java 2008-11-26 13:40:30 UTC (rev 4748) @@ -4,6 +4,7 @@ import org.jnode.driver.console.ConsoleManager; import org.jnode.driver.console.swing.SwingTextScreenConsoleManager; +import org.jnode.driver.console.textscreen.TextScreenConsoleManager; import org.jnode.shell.CommandShell; /** @@ -17,7 +18,7 @@ return; } initEnv(argv.length > 0 ? new File(argv[0]) : null); - SwingTextScreenConsoleManager cm = new SwingTextScreenConsoleManager(); + TextScreenConsoleManager cm = new SwingTextScreenConsoleManager(); new Thread(new CommandShell(cm.createConsole( "Console 1", (ConsoleManager.CreateOptions.TEXT | Deleted: trunk/distr/src/test/org/jnode/apps/jpartition/utils/BasicNameSpace.java =================================================================== --- trunk/distr/src/test/org/jnode/apps/jpartition/utils/BasicNameSpace.java 2008-11-25 10:44:10 UTC (rev 4747) +++ trunk/distr/src/test/org/jnode/apps/jpartition/utils/BasicNameSpace.java 2008-11-26 13:40:30 UTC (rev 4748) @@ -1,36 +0,0 @@ -/** - * - */ -package org.jnode.apps.jpartition.utils; - -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -import javax.naming.NameAlreadyBoundException; -import javax.naming.NameNotFoundException; -import javax.naming.NamingException; - -import org.jnode.naming.AbstractNameSpace; - -public final class BasicNameSpace extends AbstractNameSpace { - protected final Map<Class<?>, Object> namespace = new HashMap<Class<?>, Object>(); - - public <T> void bind(Class<T> name, T service) - throws NamingException, NameAlreadyBoundException { - namespace.put(name, service); - } - - @SuppressWarnings("unchecked") - public <T> T lookup(Class<T> name) throws NameNotFoundException { - return (T) namespace.get(name); - } - - public Set<Class<?>> nameSet() { - return namespace.keySet(); - } - - public void unbind(Class<?> name) { - namespace.remove(name); - } -} Modified: trunk/distr/src/test/org/jnode/apps/jpartition/utils/device/DeviceUtils.java =================================================================== --- trunk/distr/src/test/org/jnode/apps/jpartition/utils/device/DeviceUtils.java 2008-11-25 10:44:10 UTC (rev 4747) +++ trunk/distr/src/test/org/jnode/apps/jpartition/utils/device/DeviceUtils.java 2008-11-26 13:40:30 UTC (rev 4748) @@ -9,7 +9,6 @@ import org.apache.log4j.Logger; import org.jnode.apps.jpartition.ErrorReporter; import org.jnode.apps.jpartition.swingview.FileDeviceView; -import org.jnode.apps.jpartition.utils.BasicNameSpace; import org.jnode.apps.vmware.disk.VMWareDisk; import org.jnode.apps.vmware.disk.tools.DiskFactory; import org.jnode.driver.Device; @@ -20,6 +19,7 @@ import org.jnode.driver.bus.ide.IDEDevice; import org.jnode.fs.service.FileSystemService; import org.jnode.fs.service.def.FileSystemPlugin; +import org.jnode.naming.BasicNameSpace; import org.jnode.naming.InitialNaming; import org.jnode.naming.NameSpace; import org.jnode.plugin.Extension; @@ -30,6 +30,7 @@ import org.jnode.plugin.PluginException; import org.jnode.plugin.PluginPrerequisite; import org.jnode.plugin.Runtime; +import org.jnode.plugin.model.DummyPluginDescriptor; import org.jnode.test.fs.driver.stubs.StubDeviceManager; import org.jnode.util.OsUtils; @@ -49,124 +50,7 @@ InitialNaming.bind(DeviceManager.NAME, StubDeviceManager.INSTANCE); - PluginDescriptor desc = new PluginDescriptor() { - - public void addListener(PluginDescriptorListener listener) { - // TODO Auto-generated method stub - - } - - public boolean depends(String id) { - // TODO Auto-generated method stub - return false; - } - - public String getCustomPluginClassName() { - // TODO Auto-generated method stub - return null; - } - - public ExtensionPoint getExtensionPoint(String extensionPointId) { - // TODO Auto-generated method stub - return null; - } - - public ExtensionPoint[] getExtensionPoints() { - // TODO Auto-generated method stub - return null; - } - - public Extension[] getExtensions() { - // TODO Auto-generated method stub - return null; - } - - public String getId() { - // TODO Auto-generated method stub - return null; - } - - public String getLicenseName() { - // TODO Auto-generated method stub - return null; - } - - public String getLicenseUrl() { - // TODO Auto-generated method stub - return null; - } - - public String getName() { - // TODO Auto-generated method stub - return null; - } - - public Plugin getPlugin() throws PluginException { - // TODO Auto-generated method stub - return null; - } - - public ClassLoader getPluginClassLoader() { - // TODO Auto-generated method stub - return null; - } - - public PluginPrerequisite[] getPrerequisites() { - // TODO Auto-generated method stub - return null; - } - - public int getPriority() { - // TODO Auto-generated method stub - return 0; - } - - public String getProviderName() { - // TODO Auto-generated method stub - return null; - } - - public String getProviderUrl() { - // TODO Auto-generated method stub - return null; - } - - public Runtime getRuntime() { - // TODO Auto-generated method stub - return null; - } - - public String getVersion() { - // TODO Auto-generated method stub - return null; - } - - public boolean hasCustomPluginClass() { - // TODO Auto-generated method stub - return false; - } - - public boolean isAutoStart() { - // TODO Auto-generated method stub - return false; - } - - public boolean isFragment() { - // TODO Auto-generated method stub - return false; - } - - public boolean isSystemPlugin() { - // TODO Auto-generated method stub - return true; - } - - public void removeListener(PluginDescriptorListener listener) { - // TODO Auto-generated method stub - - } - - }; + PluginDescriptor desc = new DummyPluginDescriptor(true); FileSystemService fss = new FileSystemPlugin(desc); namespace.bind(FileSystemService.class, fss); } catch (NameAlreadyBoundException e) { Modified: trunk/gui/src/test/org/jnode/test/gui/Emu.java =================================================================== --- trunk/gui/src/test/org/jnode/test/gui/Emu.java 2008-11-25 10:44:10 UTC (rev 4747) +++ trunk/gui/src/test/org/jnode/test/gui/Emu.java 2008-11-26 13:40:30 UTC (rev 4748) @@ -18,6 +18,7 @@ import org.jnode.driver.DeviceToDriverMapper; import org.jnode.driver.DriverException; import org.jnode.naming.AbstractNameSpace; +import org.jnode.naming.BasicNameSpace; import org.jnode.naming.InitialNaming; import org.jnode.plugin.Extension; import org.jnode.plugin.ExtensionPoint; @@ -34,28 +35,7 @@ public class Emu { protected static void initEnv() throws NamingException { if (true) { - InitialNaming.setNameSpace(new AbstractNameSpace() { - private Map<Class<?>, Object> space = new HashMap<Class<?>, Object>(); - - public <T> void bind(Class<T> name, T service) throws NamingException, NameAlreadyBoundException { - if (space.get(name) != null) throw new NameAlreadyBoundException(); - space.put(name, service); - } - - public void unbind(Class<?> name) { - space.remove(name); - } - - public <T> T lookup(Class<T> name) throws NameNotFoundException { - T obj = (T) space.get(name); - if (obj == null) throw new NameNotFoundException(name.getName()); - return obj; - } - - public Set<Class<?>> nameSet() { - return space.keySet(); - } - }); + InitialNaming.setNameSpace(new BasicNameSpace()); InitialNaming.bind(DeviceManager.NAME, DeviceManager.INSTANCE); final AliasManager aliasMgr = new DefaultAliasManager(new DummyExtensionPoint()); final ShellManager shellMgr = new DefaultShellManager(); Modified: trunk/shell/src/test/org/jnode/test/shell/Cassowary.java =================================================================== --- trunk/shell/src/test/org/jnode/test/shell/Cassowary.java 2008-11-25 10:44:10 UTC (rev 4747) +++ trunk/shell/src/test/org/jnode/test/shell/Cassowary.java 2008-11-26 13:40:30 UTC (rev 4748) @@ -30,6 +30,7 @@ import org.apache.log4j.BasicConfigurator; import org.jnode.naming.AbstractNameSpace; +import org.jnode.naming.BasicNameSpace; import org.jnode.naming.InitialNaming; import org.jnode.shell.ShellManager; import org.jnode.shell.alias.AliasManager; @@ -51,33 +52,7 @@ if (initialized) { return; } - InitialNaming.setNameSpace(new AbstractNameSpace() { - private Map<Class<?>, Object> space = new HashMap<Class<?>, Object>(); - - public <T> void bind(Class<T> name, T service) - throws NamingException, NameAlreadyBoundException { - if (space.get(name) != null) { - throw new NameAlreadyBoundException(); - } - space.put(name, service); - } - - public void unbind(Class<?> name) { - space.remove(name); - } - - public <T> T lookup(Class<T> name) throws NameNotFoundException { - T obj = (T) space.get(name); - if (obj == null) { - throw new NameNotFoundException(name.getName()); - } - return obj; - } - - public Set<Class<?>> nameSet() { - return space.keySet(); - } - }); + InitialNaming.setNameSpace(new BasicNameSpace()); InitialNaming.bind(DeviceManager.NAME, DeviceManager.INSTANCE); AliasManager alias_mgr = new DefaultAliasManager(new DummyExtensionPoint()).createAliasManager(); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2008-11-27 18:43:16
|
Revision: 4750 http://jnode.svn.sourceforge.net/jnode/?rev=4750&view=rev Author: lsantha Date: 2008-11-27 18:43:10 +0000 (Thu, 27 Nov 2008) Log Message: ----------- Created emu source tree in core and moved BasicNameSpace and DummyPluginDescriptor to it. Modified Paths: -------------- trunk/core/build.xml trunk/core/core.iml trunk/distr/src/emu/org/jnode/emu/Emu.java trunk/distr/src/test/org/jnode/apps/jpartition/utils/device/DeviceUtils.java trunk/gui/src/test/org/jnode/test/gui/Emu.java trunk/shell/src/test/org/jnode/test/shell/Cassowary.java Added Paths: ----------- trunk/core/src/emu/ trunk/core/src/emu/org/ trunk/core/src/emu/org/jnode/ trunk/core/src/emu/org/jnode/emu/ trunk/core/src/emu/org/jnode/emu/naming/ trunk/core/src/emu/org/jnode/emu/naming/BasicNameSpace.java trunk/core/src/emu/org/jnode/emu/plugin/ trunk/core/src/emu/org/jnode/emu/plugin/model/ trunk/core/src/emu/org/jnode/emu/plugin/model/DummyPluginDescriptor.java Removed Paths: ------------- trunk/core/src/core/org/jnode/naming/BasicNameSpace.java trunk/core/src/core/org/jnode/plugin/model/DummyPluginDescriptor.java Modified: trunk/core/build.xml =================================================================== --- trunk/core/build.xml 2008-11-26 22:25:38 UTC (rev 4749) +++ trunk/core/build.xml 2008-11-27 18:43:10 UTC (rev 4750) @@ -47,6 +47,7 @@ <pathelement location="${my-src.dir}/driver"/> <pathelement location="${my-src.dir}/icedtea"/> <pathelement location="${my-src.dir}/test"/> + <pathelement location="${my-src.dir}/emu"/> </path> <path id="my-sources"> <path refid="my-sources1"/> Modified: trunk/core/core.iml =================================================================== --- trunk/core/core.iml 2008-11-26 22:25:38 UTC (rev 4749) +++ trunk/core/core.iml 2008-11-27 18:43:10 UTC (rev 4750) @@ -13,6 +13,7 @@ <sourceFolder url="file://$MODULE_DIR$/src/classpath/vm" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src/core" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src/driver" isTestSource="false" /> + <sourceFolder url="file://$MODULE_DIR$/src/emu" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src/endorsed/nanoxml" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src/icedtea" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src/mmtk-vm" isTestSource="false" /> Deleted: trunk/core/src/core/org/jnode/naming/BasicNameSpace.java =================================================================== --- trunk/core/src/core/org/jnode/naming/BasicNameSpace.java 2008-11-26 22:25:38 UTC (rev 4749) +++ trunk/core/src/core/org/jnode/naming/BasicNameSpace.java 2008-11-27 18:43:10 UTC (rev 4750) @@ -1,72 +0,0 @@ -/* - * $Id: Label.java 4159 2008-05-30 16:15:41Z 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.naming; - -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -import javax.naming.NameAlreadyBoundException; -import javax.naming.NameNotFoundException; -import javax.naming.NamingException; - -/** - * This implementation of NameSpace does not make use of Class.getVmClass() and - * therefore can be used in JNode applications / test cases / frameworks designed - * to run on a classic Java VM. - * - * @author cr...@jn... - */ -public final class BasicNameSpace extends AbstractNameSpace { - protected final Map<Class<?>, Object> namespace = new HashMap<Class<?>, Object>(); - - public <T> void bind(Class<T> name, T service) - throws NamingException, NameAlreadyBoundException { - if (name == null) { - throw new IllegalArgumentException("name == null"); - } - synchronized (namespace) { - if (namespace.containsKey(name)) { - throw new NameAlreadyBoundException(name.getName()); - } - namespace.put(name, service); - } - } - - @SuppressWarnings("unchecked") - public <T> T lookup(Class<T> name) throws NameNotFoundException { - synchronized (namespace) { - T res = (T) namespace.get(name); - if (res == null) { - throw new NameNotFoundException(name.getName()); - } - return res; - } - } - - public Set<Class<?>> nameSet() { - return namespace.keySet(); - } - - public void unbind(Class<?> name) { - namespace.remove(name); - } -} Deleted: trunk/core/src/core/org/jnode/plugin/model/DummyPluginDescriptor.java =================================================================== --- trunk/core/src/core/org/jnode/plugin/model/DummyPluginDescriptor.java 2008-11-26 22:25:38 UTC (rev 4749) +++ trunk/core/src/core/org/jnode/plugin/model/DummyPluginDescriptor.java 2008-11-27 18:43:10 UTC (rev 4750) @@ -1,133 +0,0 @@ -package org.jnode.plugin.model; - -import org.jnode.plugin.Extension; -import org.jnode.plugin.ExtensionPoint; -import org.jnode.plugin.Plugin; -import org.jnode.plugin.PluginDescriptor; -import org.jnode.plugin.PluginDescriptorListener; -import org.jnode.plugin.PluginException; -import org.jnode.plugin.PluginPrerequisite; -import org.jnode.plugin.Runtime; - -public class DummyPluginDescriptor implements PluginDescriptor { - - private boolean systemPlugin; - - public DummyPluginDescriptor(boolean systemPlugin) { - this.systemPlugin = systemPlugin; - } - - public void addListener(PluginDescriptorListener listener) { - // TODO Auto-generated method stub - - } - - public boolean depends(String id) { - // TODO Auto-generated method stub - return false; - } - - public String getCustomPluginClassName() { - // TODO Auto-generated method stub - return null; - } - - public ExtensionPoint getExtensionPoint(String extensionPointId) { - // TODO Auto-generated method stub - return null; - } - - public ExtensionPoint[] getExtensionPoints() { - // TODO Auto-generated method stub - return null; - } - - public Extension[] getExtensions() { - // TODO Auto-generated method stub - return null; - } - - public String getId() { - // TODO Auto-generated method stub - return null; - } - - public String getLicenseName() { - // TODO Auto-generated method stub - return null; - } - - public String getLicenseUrl() { - // TODO Auto-generated method stub - return null; - } - - public String getName() { - // TODO Auto-generated method stub - return null; - } - - public Plugin getPlugin() throws PluginException { - // TODO Auto-generated method stub - return null; - } - - public ClassLoader getPluginClassLoader() { - // TODO Auto-generated method stub - return null; - } - - public PluginPrerequisite[] getPrerequisites() { - // TODO Auto-generated method stub - return null; - } - - public int getPriority() { - // TODO Auto-generated method stub - return 0; - } - - public String getProviderName() { - // TODO Auto-generated method stub - return null; - } - - public String getProviderUrl() { - // TODO Auto-generated method stub - return null; - } - - public Runtime getRuntime() { - // TODO Auto-generated method stub - return null; - } - - public String getVersion() { - // TODO Auto-generated method stub - return null; - } - - public boolean hasCustomPluginClass() { - // TODO Auto-generated method stub - return false; - } - - public boolean isAutoStart() { - // TODO Auto-generated method stub - return false; - } - - public boolean isFragment() { - // TODO Auto-generated method stub - return false; - } - - public boolean isSystemPlugin() { - return systemPlugin; - } - - public void removeListener(PluginDescriptorListener listener) { - // TODO Auto-generated method stub - - } -} Copied: trunk/core/src/emu/org/jnode/emu/naming/BasicNameSpace.java (from rev 4749, trunk/core/src/core/org/jnode/naming/BasicNameSpace.java) =================================================================== --- trunk/core/src/emu/org/jnode/emu/naming/BasicNameSpace.java (rev 0) +++ trunk/core/src/emu/org/jnode/emu/naming/BasicNameSpace.java 2008-11-27 18:43:10 UTC (rev 4750) @@ -0,0 +1,73 @@ +/* + * $Id: Label.java 4159 2008-05-30 16:15:41Z 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.emu.naming; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import javax.naming.NameAlreadyBoundException; +import javax.naming.NameNotFoundException; +import javax.naming.NamingException; +import org.jnode.naming.AbstractNameSpace; + +/** + * This implementation of NameSpace does not make use of Class.getVmClass() and + * therefore can be used in JNode applications / test cases / frameworks designed + * to run on a classic Java VM. + * + * @author cr...@jn... + */ +public final class BasicNameSpace extends AbstractNameSpace { + protected final Map<Class<?>, Object> namespace = new HashMap<Class<?>, Object>(); + + public <T> void bind(Class<T> name, T service) + throws NamingException, NameAlreadyBoundException { + if (name == null) { + throw new IllegalArgumentException("name == null"); + } + synchronized (namespace) { + if (namespace.containsKey(name)) { + throw new NameAlreadyBoundException(name.getName()); + } + namespace.put(name, service); + } + } + + @SuppressWarnings("unchecked") + public <T> T lookup(Class<T> name) throws NameNotFoundException { + synchronized (namespace) { + T res = (T) namespace.get(name); + if (res == null) { + throw new NameNotFoundException(name.getName()); + } + return res; + } + } + + public Set<Class<?>> nameSet() { + return namespace.keySet(); + } + + public void unbind(Class<?> name) { + namespace.remove(name); + } +} Copied: trunk/core/src/emu/org/jnode/emu/plugin/model/DummyPluginDescriptor.java (from rev 4749, trunk/core/src/core/org/jnode/plugin/model/DummyPluginDescriptor.java) =================================================================== --- trunk/core/src/emu/org/jnode/emu/plugin/model/DummyPluginDescriptor.java (rev 0) +++ trunk/core/src/emu/org/jnode/emu/plugin/model/DummyPluginDescriptor.java 2008-11-27 18:43:10 UTC (rev 4750) @@ -0,0 +1,133 @@ +package org.jnode.emu.plugin.model; + +import org.jnode.plugin.Extension; +import org.jnode.plugin.ExtensionPoint; +import org.jnode.plugin.Plugin; +import org.jnode.plugin.PluginDescriptor; +import org.jnode.plugin.PluginDescriptorListener; +import org.jnode.plugin.PluginException; +import org.jnode.plugin.PluginPrerequisite; +import org.jnode.plugin.Runtime; + +public class DummyPluginDescriptor implements PluginDescriptor { + + private boolean systemPlugin; + + public DummyPluginDescriptor(boolean systemPlugin) { + this.systemPlugin = systemPlugin; + } + + public void addListener(PluginDescriptorListener listener) { + // TODO Auto-generated method stub + + } + + public boolean depends(String id) { + // TODO Auto-generated method stub + return false; + } + + public String getCustomPluginClassName() { + // TODO Auto-generated method stub + return null; + } + + public ExtensionPoint getExtensionPoint(String extensionPointId) { + // TODO Auto-generated method stub + return null; + } + + public ExtensionPoint[] getExtensionPoints() { + // TODO Auto-generated method stub + return null; + } + + public Extension[] getExtensions() { + // TODO Auto-generated method stub + return null; + } + + public String getId() { + // TODO Auto-generated method stub + return null; + } + + public String getLicenseName() { + // TODO Auto-generated method stub + return null; + } + + public String getLicenseUrl() { + // TODO Auto-generated method stub + return null; + } + + public String getName() { + // TODO Auto-generated method stub + return null; + } + + public Plugin getPlugin() throws PluginException { + // TODO Auto-generated method stub + return null; + } + + public ClassLoader getPluginClassLoader() { + // TODO Auto-generated method stub + return null; + } + + public PluginPrerequisite[] getPrerequisites() { + // TODO Auto-generated method stub + return null; + } + + public int getPriority() { + // TODO Auto-generated method stub + return 0; + } + + public String getProviderName() { + // TODO Auto-generated method stub + return null; + } + + public String getProviderUrl() { + // TODO Auto-generated method stub + return null; + } + + public Runtime getRuntime() { + // TODO Auto-generated method stub + return null; + } + + public String getVersion() { + // TODO Auto-generated method stub + return null; + } + + public boolean hasCustomPluginClass() { + // TODO Auto-generated method stub + return false; + } + + public boolean isAutoStart() { + // TODO Auto-generated method stub + return false; + } + + public boolean isFragment() { + // TODO Auto-generated method stub + return false; + } + + public boolean isSystemPlugin() { + return systemPlugin; + } + + public void removeListener(PluginDescriptorListener listener) { + // TODO Auto-generated method stub + + } +} Modified: trunk/distr/src/emu/org/jnode/emu/Emu.java =================================================================== --- trunk/distr/src/emu/org/jnode/emu/Emu.java 2008-11-26 22:25:38 UTC (rev 4749) +++ trunk/distr/src/emu/org/jnode/emu/Emu.java 2008-11-27 18:43:10 UTC (rev 4750) @@ -24,16 +24,10 @@ import java.io.File; import java.io.FileReader; import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import javax.naming.NameAlreadyBoundException; -import javax.naming.NameNotFoundException; import javax.naming.NamingException; -import org.jnode.naming.AbstractNameSpace; -import org.jnode.naming.BasicNameSpace; +import org.jnode.emu.naming.BasicNameSpace; import org.jnode.naming.InitialNaming; import org.jnode.nanoxml.XMLElement; import org.jnode.shell.ShellManager; Modified: trunk/distr/src/test/org/jnode/apps/jpartition/utils/device/DeviceUtils.java =================================================================== --- trunk/distr/src/test/org/jnode/apps/jpartition/utils/device/DeviceUtils.java 2008-11-26 22:25:38 UTC (rev 4749) +++ trunk/distr/src/test/org/jnode/apps/jpartition/utils/device/DeviceUtils.java 2008-11-27 18:43:10 UTC (rev 4750) @@ -19,18 +19,11 @@ import org.jnode.driver.bus.ide.IDEDevice; import org.jnode.fs.service.FileSystemService; import org.jnode.fs.service.def.FileSystemPlugin; -import org.jnode.naming.BasicNameSpace; +import org.jnode.emu.naming.BasicNameSpace; +import org.jnode.emu.plugin.model.DummyPluginDescriptor; import org.jnode.naming.InitialNaming; import org.jnode.naming.NameSpace; -import org.jnode.plugin.Extension; -import org.jnode.plugin.ExtensionPoint; -import org.jnode.plugin.Plugin; import org.jnode.plugin.PluginDescriptor; -import org.jnode.plugin.PluginDescriptorListener; -import org.jnode.plugin.PluginException; -import org.jnode.plugin.PluginPrerequisite; -import org.jnode.plugin.Runtime; -import org.jnode.plugin.model.DummyPluginDescriptor; import org.jnode.test.fs.driver.stubs.StubDeviceManager; import org.jnode.util.OsUtils; Modified: trunk/gui/src/test/org/jnode/test/gui/Emu.java =================================================================== --- trunk/gui/src/test/org/jnode/test/gui/Emu.java 2008-11-26 22:25:38 UTC (rev 4749) +++ trunk/gui/src/test/org/jnode/test/gui/Emu.java 2008-11-27 18:43:10 UTC (rev 4750) @@ -2,13 +2,8 @@ import java.util.ArrayList; import java.util.Collections; -import java.util.HashMap; import java.util.List; -import java.util.Map; -import java.util.Set; -import javax.naming.NameAlreadyBoundException; -import javax.naming.NameNotFoundException; import javax.naming.NamingException; import org.apache.log4j.Logger; @@ -17,8 +12,7 @@ import org.jnode.driver.DeviceFinder; import org.jnode.driver.DeviceToDriverMapper; import org.jnode.driver.DriverException; -import org.jnode.naming.AbstractNameSpace; -import org.jnode.naming.BasicNameSpace; +import org.jnode.emu.naming.BasicNameSpace; import org.jnode.naming.InitialNaming; import org.jnode.plugin.Extension; import org.jnode.plugin.ExtensionPoint; Modified: trunk/shell/src/test/org/jnode/test/shell/Cassowary.java =================================================================== --- trunk/shell/src/test/org/jnode/test/shell/Cassowary.java 2008-11-26 22:25:38 UTC (rev 4749) +++ trunk/shell/src/test/org/jnode/test/shell/Cassowary.java 2008-11-27 18:43:10 UTC (rev 4750) @@ -20,17 +20,10 @@ */ package org.jnode.test.shell; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -import javax.naming.NameAlreadyBoundException; -import javax.naming.NameNotFoundException; import javax.naming.NamingException; import org.apache.log4j.BasicConfigurator; -import org.jnode.naming.AbstractNameSpace; -import org.jnode.naming.BasicNameSpace; +import org.jnode.emu.naming.BasicNameSpace; import org.jnode.naming.InitialNaming; import org.jnode.shell.ShellManager; import org.jnode.shell.alias.AliasManager; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cr...@us...> - 2008-11-29 08:31:54
|
Revision: 4754 http://jnode.svn.sourceforge.net/jnode/?rev=4754&view=rev Author: crawley Date: 2008-11-29 08:31:48 +0000 (Sat, 29 Nov 2008) Log Message: ----------- More refactoring of Emu related stuff Modified Paths: -------------- trunk/core/src/emu/org/jnode/emu/plugin/model/DummyPluginDescriptor.java trunk/distr/src/emu/org/jnode/emu/Emu.java trunk/gui/src/test/org/jnode/test/gui/Emu.java trunk/shell/src/test/org/jnode/test/shell/Cassowary.java Added Paths: ----------- trunk/core/src/emu/org/jnode/emu/plugin/model/DummyConfigurationElement.java trunk/core/src/emu/org/jnode/emu/plugin/model/DummyExtension.java trunk/core/src/emu/org/jnode/emu/plugin/model/DummyExtensionPoint.java Removed Paths: ------------- trunk/distr/src/emu/org/jnode/emu/DummyExtensionPoint.java trunk/shell/src/test/org/jnode/test/shell/DummyExtensionPoint.java Added: trunk/core/src/emu/org/jnode/emu/plugin/model/DummyConfigurationElement.java =================================================================== --- trunk/core/src/emu/org/jnode/emu/plugin/model/DummyConfigurationElement.java (rev 0) +++ trunk/core/src/emu/org/jnode/emu/plugin/model/DummyConfigurationElement.java 2008-11-29 08:31:48 UTC (rev 4754) @@ -0,0 +1,71 @@ +/* + * $Id: CommandInfo.java 4193 2008-06-04 14:39:34Z crawley $ + * + * 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.emu.plugin.model; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import org.jnode.plugin.ConfigurationElement; +import org.jnode.plugin.PluginDescriptor; + +/** + * Dummy configuration element for configuring plugins outside of the normal JNode framework. + * Most methods have dummy implementations. If you come across a use-case that requires + * a non-dummy implementation, please implement the method in this class rather than + * subclassing. + * + * @author cr...@jn... + */ +public class DummyConfigurationElement implements ConfigurationElement { + + private Map<String, String> map = new HashMap<String, String>(); + + @Override + public Set<String> attributeNames() { + return map.keySet(); + } + + @Override + public String getAttribute(String name) { + return map.get(name); + } + + @Override + public PluginDescriptor getDeclaringPluginDescriptor() { + return null; + } + + @Override + public ConfigurationElement[] getElements() { + return null; + } + + @Override + public String getName() { + return null; + } + + public void addAttribute(String name, String value) { + map.put(name, value); + } + +} Added: trunk/core/src/emu/org/jnode/emu/plugin/model/DummyExtension.java =================================================================== --- trunk/core/src/emu/org/jnode/emu/plugin/model/DummyExtension.java (rev 0) +++ trunk/core/src/emu/org/jnode/emu/plugin/model/DummyExtension.java 2008-11-29 08:31:48 UTC (rev 4754) @@ -0,0 +1,83 @@ +/* + * $Id: CommandInfo.java 4193 2008-06-04 14:39:34Z crawley $ + * + * 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.emu.plugin.model; + +import java.util.ArrayList; +import java.util.List; + +import org.jnode.plugin.ConfigurationElement; +import org.jnode.plugin.Extension; +import org.jnode.plugin.PluginDescriptor; + + +/** + * Dummy plugin extension for configuring plugins outside of the normal JNode framework. + * Most methods have dummy implementations. If you come across a use-case that requires + * a non-dummy implementation, please implement the method in this class rather than + * subclassing. + * + * @author cr...@jn... + */ +public class DummyExtension implements Extension { + + private List<ConfigurationElement> elements; + + @Override + public ConfigurationElement[] getConfigurationElements() { + if (elements != null) { + return elements.toArray(new ConfigurationElement[elements.size()]); + } + return new ConfigurationElement[0]; + } + + public void addElement(ConfigurationElement element) { + if (elements == null) { + elements = new ArrayList<ConfigurationElement>(1); + } + elements.add(element); + } + + @Override + public PluginDescriptor getDeclaringPluginDescriptor() { + return null; + } + + @Override + public String getExtensionPointPluginId() { + return null; + } + + @Override + public String getExtensionPointUniqueIdentifier() { + return null; + } + + @Override + public String getSimpleIdentifier() { + return null; + } + + @Override + public String getUniqueIdentifier() { + return null; + } + +} Added: trunk/core/src/emu/org/jnode/emu/plugin/model/DummyExtensionPoint.java =================================================================== --- trunk/core/src/emu/org/jnode/emu/plugin/model/DummyExtensionPoint.java (rev 0) +++ trunk/core/src/emu/org/jnode/emu/plugin/model/DummyExtensionPoint.java 2008-11-29 08:31:48 UTC (rev 4754) @@ -0,0 +1,95 @@ +/* + * $Id: CommandInfo.java 4193 2008-06-04 14:39:34Z crawley $ + * + * 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.emu.plugin.model; + +import java.util.ArrayList; +import java.util.List; + +import org.jnode.plugin.Extension; +import org.jnode.plugin.ExtensionPoint; +import org.jnode.plugin.ExtensionPointListener; +import org.jnode.plugin.PluginDescriptor; + +/** + * Dummy plugin extension point for configuring plugins outside of the normal JNode framework. + * Most methods have dummy implementations. If you come across a use-case that requires + * a non-dummy implementation, please implement the method in this class rather than + * subclassing. + * + * @author Levente S\u00e1ntha + * @author cr...@jn... + */ +public class DummyExtensionPoint implements ExtensionPoint { + + private final String id; + private final String uid; + private final String name; + private List<Extension> extensions; + + public DummyExtensionPoint() { + this("A", "aaa", "B"); + } + + public DummyExtensionPoint(String id, String uid, String name) { + this.id = id; + this.uid = uid; + this.name = name; + } + + public String getSimpleIdentifier() { + return id; + } + + public String getUniqueIdentifier() { + return uid; + } + + public String getName() { + return name; + } + + public Extension[] getExtensions() { + if (extensions != null) { + return extensions.toArray(new Extension[extensions.size()]); + } + return new Extension[0]; + } + + public void addExtension(Extension extension) { + if (extensions == null) { + extensions = new ArrayList<Extension>(1); + } + extensions.add(extension); + } + + public void addListener(ExtensionPointListener listener) { + } + + public void addPriorityListener(ExtensionPointListener listener) { + } + + public void removeListener(ExtensionPointListener listener) { + } + + public PluginDescriptor getDeclaringPluginDescriptor() { + return null; + } +} Modified: trunk/core/src/emu/org/jnode/emu/plugin/model/DummyPluginDescriptor.java =================================================================== --- trunk/core/src/emu/org/jnode/emu/plugin/model/DummyPluginDescriptor.java 2008-11-29 01:01:48 UTC (rev 4753) +++ trunk/core/src/emu/org/jnode/emu/plugin/model/DummyPluginDescriptor.java 2008-11-29 08:31:48 UTC (rev 4754) @@ -1,5 +1,28 @@ +/* + * $Id: CommandInfo.java 4193 2008-06-04 14:39:34Z crawley $ + * + * 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.emu.plugin.model; +import java.util.ArrayList; +import java.util.List; + import org.jnode.plugin.Extension; import org.jnode.plugin.ExtensionPoint; import org.jnode.plugin.Plugin; @@ -9,116 +32,121 @@ import org.jnode.plugin.PluginPrerequisite; import org.jnode.plugin.Runtime; +/** + * Dummy plugin descriptor for configuring plugins outside of the normal JNode framework. + * Most methods have dummy implementations. If you come across a use-case that requires + * a non-dummy implementation, please implement the method in this class rather than + * subclassing. + * + * @author scr...@jn... + */ public class DummyPluginDescriptor implements PluginDescriptor { private boolean systemPlugin; + private List<ExtensionPoint> extensionPoints = null; public DummyPluginDescriptor(boolean systemPlugin) { this.systemPlugin = systemPlugin; } public void addListener(PluginDescriptorListener listener) { - // TODO Auto-generated method stub - } public boolean depends(String id) { - // TODO Auto-generated method stub return false; } public String getCustomPluginClassName() { - // TODO Auto-generated method stub return null; } public ExtensionPoint getExtensionPoint(String extensionPointId) { - // TODO Auto-generated method stub + if (extensionPoints != null) { + for (ExtensionPoint ep : extensionPoints) { + if (ep.getSimpleIdentifier().equals(extensionPointId)) { + return ep; + } + } + } return null; } public ExtensionPoint[] getExtensionPoints() { - // TODO Auto-generated method stub - return null; + if (extensionPoints == null) { + return null; + } else { + return extensionPoints.toArray(new ExtensionPoint[extensionPoints.size()]); + } } + + public void addExtensionPoint(ExtensionPoint ep) { + if (extensionPoints == null) { + extensionPoints = new ArrayList<ExtensionPoint>(1); + } + extensionPoints.add(ep); + } public Extension[] getExtensions() { - // TODO Auto-generated method stub return null; } public String getId() { - // TODO Auto-generated method stub return null; } public String getLicenseName() { - // TODO Auto-generated method stub return null; } public String getLicenseUrl() { - // TODO Auto-generated method stub return null; } public String getName() { - // TODO Auto-generated method stub return null; } public Plugin getPlugin() throws PluginException { - // TODO Auto-generated method stub return null; } public ClassLoader getPluginClassLoader() { - // TODO Auto-generated method stub return null; } public PluginPrerequisite[] getPrerequisites() { - // TODO Auto-generated method stub return null; } public int getPriority() { - // TODO Auto-generated method stub return 0; } public String getProviderName() { - // TODO Auto-generated method stub return null; } public String getProviderUrl() { - // TODO Auto-generated method stub return null; } public Runtime getRuntime() { - // TODO Auto-generated method stub return null; } public String getVersion() { - // TODO Auto-generated method stub return null; } public boolean hasCustomPluginClass() { - // TODO Auto-generated method stub return false; } public boolean isAutoStart() { - // TODO Auto-generated method stub return false; } public boolean isFragment() { - // TODO Auto-generated method stub return false; } Deleted: trunk/distr/src/emu/org/jnode/emu/DummyExtensionPoint.java =================================================================== --- trunk/distr/src/emu/org/jnode/emu/DummyExtensionPoint.java 2008-11-29 01:01:48 UTC (rev 4753) +++ trunk/distr/src/emu/org/jnode/emu/DummyExtensionPoint.java 2008-11-29 08:31:48 UTC (rev 4754) @@ -1,43 +0,0 @@ -/* - * $Id$ - */ -package org.jnode.emu; - -import org.jnode.plugin.Extension; -import org.jnode.plugin.ExtensionPoint; -import org.jnode.plugin.ExtensionPointListener; -import org.jnode.plugin.PluginDescriptor; - -/** - * @author Levente S\u00e1ntha - */ -class DummyExtensionPoint implements ExtensionPoint { - public String getSimpleIdentifier() { - return "A"; - } - - public String getUniqueIdentifier() { - return "aaa"; - } - - public String getName() { - return "B"; - } - - public Extension[] getExtensions() { - return new Extension[0]; - } - - public void addListener(ExtensionPointListener listener) { - } - - public void addPriorityListener(ExtensionPointListener listener) { - } - - public void removeListener(ExtensionPointListener listener) { - } - - public PluginDescriptor getDeclaringPluginDescriptor() { - return null; - } -} Modified: trunk/distr/src/emu/org/jnode/emu/Emu.java =================================================================== --- trunk/distr/src/emu/org/jnode/emu/Emu.java 2008-11-29 01:01:48 UTC (rev 4753) +++ trunk/distr/src/emu/org/jnode/emu/Emu.java 2008-11-29 08:31:48 UTC (rev 4754) @@ -28,6 +28,7 @@ import javax.naming.NamingException; import org.jnode.emu.naming.BasicNameSpace; +import org.jnode.emu.plugin.model.DummyExtensionPoint; import org.jnode.naming.InitialNaming; import org.jnode.nanoxml.XMLElement; import org.jnode.shell.ShellManager; Modified: trunk/gui/src/test/org/jnode/test/gui/Emu.java =================================================================== --- trunk/gui/src/test/org/jnode/test/gui/Emu.java 2008-11-29 01:01:48 UTC (rev 4753) +++ trunk/gui/src/test/org/jnode/test/gui/Emu.java 2008-11-29 08:31:48 UTC (rev 4754) @@ -13,6 +13,7 @@ import org.jnode.driver.DeviceToDriverMapper; import org.jnode.driver.DriverException; import org.jnode.emu.naming.BasicNameSpace; +import org.jnode.emu.plugin.model.DummyExtensionPoint; import org.jnode.naming.InitialNaming; import org.jnode.plugin.Extension; import org.jnode.plugin.ExtensionPoint; @@ -38,37 +39,6 @@ } } - private static class DummyExtensionPoint implements ExtensionPoint { - public String getSimpleIdentifier() { - return "A"; - } - - public String getUniqueIdentifier() { - return "aaa"; - } - - public String getName() { - return "B"; - } - - public Extension[] getExtensions() { - return new Extension[0]; - } - - public void addListener(ExtensionPointListener listener) { - } - - public void addPriorityListener(ExtensionPointListener listener) { - } - - public void removeListener(ExtensionPointListener listener) { - } - - public PluginDescriptor getDeclaringPluginDescriptor() { - return null; - } - } - public static class DeviceManager extends AbstractDeviceManager { public static final Logger log = Logger.getLogger(DeviceManager.class); Modified: trunk/shell/src/test/org/jnode/test/shell/Cassowary.java =================================================================== --- trunk/shell/src/test/org/jnode/test/shell/Cassowary.java 2008-11-29 01:01:48 UTC (rev 4753) +++ trunk/shell/src/test/org/jnode/test/shell/Cassowary.java 2008-11-29 08:31:48 UTC (rev 4754) @@ -24,6 +24,7 @@ import org.apache.log4j.BasicConfigurator; import org.jnode.emu.naming.BasicNameSpace; +import org.jnode.emu.plugin.model.DummyExtensionPoint; import org.jnode.naming.InitialNaming; import org.jnode.shell.ShellManager; import org.jnode.shell.alias.AliasManager; Deleted: trunk/shell/src/test/org/jnode/test/shell/DummyExtensionPoint.java =================================================================== --- trunk/shell/src/test/org/jnode/test/shell/DummyExtensionPoint.java 2008-11-29 01:01:48 UTC (rev 4753) +++ trunk/shell/src/test/org/jnode/test/shell/DummyExtensionPoint.java 2008-11-29 08:31:48 UTC (rev 4754) @@ -1,43 +0,0 @@ -/* - * $Id$ - */ -package org.jnode.test.shell; - -import org.jnode.plugin.Extension; -import org.jnode.plugin.ExtensionPoint; -import org.jnode.plugin.ExtensionPointListener; -import org.jnode.plugin.PluginDescriptor; - -/** - * @author Levente S\u00e1ntha - */ -class DummyExtensionPoint implements ExtensionPoint { - public String getSimpleIdentifier() { - return "A"; - } - - public String getUniqueIdentifier() { - return "aaa"; - } - - public String getName() { - return "B"; - } - - public Extension[] getExtensions() { - return new Extension[0]; - } - - public void addListener(ExtensionPointListener listener) { - } - - public void addPriorityListener(ExtensionPointListener listener) { - } - - public void removeListener(ExtensionPointListener listener) { - } - - public PluginDescriptor getDeclaringPluginDescriptor() { - return null; - } -} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2008-12-02 09:08:58
|
Revision: 4769 http://jnode.svn.sourceforge.net/jnode/?rev=4769&view=rev Author: lsantha Date: 2008-12-02 09:08:54 +0000 (Tue, 02 Dec 2008) Log Message: ----------- Updated InetlliJ IDEA project files to version 8. Modified Paths: -------------- trunk/JNode.ipr 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/sound/sound.iml trunk/textui/textui.iml Modified: trunk/JNode.ipr =================================================================== --- trunk/JNode.ipr 2008-12-02 08:56:50 UTC (rev 4768) +++ trunk/JNode.ipr 2008-12-02 09:08:54 UTC (rev 4769) @@ -7,6 +7,7 @@ <antReference projectDefault="true" /> <customJdkName value="" /> <maximumHeapSize value="128" /> + <maximumStackSize value="32" /> <properties /> </buildFile> </component> @@ -62,6 +63,33 @@ <option name="TERNARY_OPERATION_WRAP" value="1" /> <option name="ARRAY_INITIALIZER_WRAP" value="1" /> <option name="ASSIGNMENT_WRAP" value="1" /> + <ADDITIONAL_INDENT_OPTIONS fileType="groovy"> + <option name="INDENT_SIZE" value="2" /> + <option name="CONTINUATION_INDENT_SIZE" value="8" /> + <option name="TAB_SIZE" value="4" /> + <option name="USE_TAB_CHARACTER" value="false" /> + <option name="SMART_TABS" value="false" /> + <option name="LABEL_INDENT_SIZE" value="0" /> + <option name="LABEL_INDENT_ABSOLUTE" value="false" /> + </ADDITIONAL_INDENT_OPTIONS> + <ADDITIONAL_INDENT_OPTIONS fileType="gsp"> + <option name="INDENT_SIZE" value="2" /> + <option name="CONTINUATION_INDENT_SIZE" value="8" /> + <option name="TAB_SIZE" value="4" /> + <option name="USE_TAB_CHARACTER" value="false" /> + <option name="SMART_TABS" value="false" /> + <option name="LABEL_INDENT_SIZE" value="0" /> + <option name="LABEL_INDENT_ABSOLUTE" value="false" /> + </ADDITIONAL_INDENT_OPTIONS> + <ADDITIONAL_INDENT_OPTIONS fileType="java"> + <option name="INDENT_SIZE" value="4" /> + <option name="CONTINUATION_INDENT_SIZE" value="4" /> + <option name="TAB_SIZE" value="4" /> + <option name="USE_TAB_CHARACTER" value="false" /> + <option name="SMART_TABS" value="false" /> + <option name="LABEL_INDENT_SIZE" value="-4" /> + <option name="LABEL_INDENT_ABSOLUTE" value="false" /> + </ADDITIONAL_INDENT_OPTIONS> <ADDITIONAL_INDENT_OPTIONS fileType="js"> <option name="INDENT_SIZE" value="4" /> <option name="CONTINUATION_INDENT_SIZE" value="8" /> @@ -71,6 +99,33 @@ <option name="LABEL_INDENT_SIZE" value="0" /> <option name="LABEL_INDENT_ABSOLUTE" value="false" /> </ADDITIONAL_INDENT_OPTIONS> + <ADDITIONAL_INDENT_OPTIONS fileType="jsp"> + <option name="INDENT_SIZE" value="4" /> + <option name="CONTINUATION_INDENT_SIZE" value="8" /> + <option name="TAB_SIZE" value="4" /> + <option name="USE_TAB_CHARACTER" value="false" /> + <option name="SMART_TABS" value="false" /> + <option name="LABEL_INDENT_SIZE" value="0" /> + <option name="LABEL_INDENT_ABSOLUTE" value="false" /> + </ADDITIONAL_INDENT_OPTIONS> + <ADDITIONAL_INDENT_OPTIONS fileType="scala"> + <option name="INDENT_SIZE" value="2" /> + <option name="CONTINUATION_INDENT_SIZE" value="8" /> + <option name="TAB_SIZE" value="2" /> + <option name="USE_TAB_CHARACTER" value="false" /> + <option name="SMART_TABS" value="false" /> + <option name="LABEL_INDENT_SIZE" value="0" /> + <option name="LABEL_INDENT_ABSOLUTE" value="false" /> + </ADDITIONAL_INDENT_OPTIONS> + <ADDITIONAL_INDENT_OPTIONS fileType="xml"> + <option name="INDENT_SIZE" value="4" /> + <option name="CONTINUATION_INDENT_SIZE" value="8" /> + <option name="TAB_SIZE" value="4" /> + <option name="USE_TAB_CHARACTER" value="false" /> + <option name="SMART_TABS" value="false" /> + <option name="LABEL_INDENT_SIZE" value="0" /> + <option name="LABEL_INDENT_ABSOLUTE" value="false" /> + </ADDITIONAL_INDENT_OPTIONS> </value> </option> <option name="USE_PER_PROJECT_SETTINGS" value="true" /> @@ -114,6 +169,7 @@ <option name="ADDITIONAL_OPTIONS_STRING" value="" /> <option name="MAXIMUM_HEAP_SIZE" value="128" /> </component> + <component name="Encoding" useUTFGuessing="true" native2AsciiForPropertiesFiles="false" /> <component name="EntryPointsManager"> <entry_points version="2.0" /> </component> @@ -288,6 +344,9 @@ </item> </group> </component> + <component name="ProjectDetails"> + <option name="projectName" value="JNode" /> + </component> <component name="ProjectFileVersion" converted="true" /> <component name="ProjectModuleManager"> <modules> @@ -304,7 +363,7 @@ <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="1.6 - jnode" project-jdk-type="JavaSDK" /> + <component name="ProjectRootManager" version="2" languageLevel="JDK_1_5" assert-keyword="true" jdk-15="true" project-jdk-name="1.6 - jnode" project-jdk-type="JavaSDK" /> <component name="ResourceManagerContainer"> <option name="myResourceBundles"> <value> @@ -337,7 +396,7 @@ </entry> </map> </option> - <option name="myVersion" value="123" /> + <option name="myVersion" value="124" /> </component> <component name="VcsDirectoryMappings"> <mapping directory="" vcs="svn" /> Modified: trunk/all/all.iml =================================================================== --- trunk/all/all.iml 2008-12-02 08:56:50 UTC (rev 4768) +++ trunk/all/all.iml 2008-12-02 09:08:54 UTC (rev 4769) @@ -7,7 +7,6 @@ <content url="file://$MODULE_DIR$" /> <orderEntry type="inheritedJdk" /> <orderEntry type="sourceFolder" forTests="false" /> - <orderEntryProperties /> </component> </module> Modified: trunk/builder/builder.iml =================================================================== --- trunk/builder/builder.iml 2008-12-02 08:56:50 UTC (rev 4768) +++ trunk/builder/builder.iml 2008-12-02 09:08:54 UTC (rev 4769) @@ -121,7 +121,15 @@ </library> </orderEntry> <orderEntry type="module" module-name="fs" /> - <orderEntryProperties /> + <orderEntry type="module-library"> + <library> + <CLASSES> + <root url="jar://$MODULE_DIR$/../core/lib/ant.jar!/" /> + </CLASSES> + <JAVADOC /> + <SOURCES /> + </library> + </orderEntry> </component> </module> Modified: trunk/core/core.iml =================================================================== --- trunk/core/core.iml 2008-12-02 08:56:50 UTC (rev 4768) +++ trunk/core/core.iml 2008-12-02 09:08:54 UTC (rev 4769) @@ -53,7 +53,33 @@ </SOURCES> </library> </orderEntry> - <orderEntryProperties /> + <orderEntry type="module-library" exported=""> + <library> + <CLASSES> + <root url="jar://$MODULE_DIR$/lib/ant.jar!/" /> + </CLASSES> + <JAVADOC /> + <SOURCES /> + </library> + </orderEntry> + <orderEntry type="module-library"> + <library> + <CLASSES> + <root url="jar://$MODULE_DIR$/lib/junit.jar!/" /> + </CLASSES> + <JAVADOC /> + <SOURCES /> + </library> + </orderEntry> + <orderEntry type="module-library"> + <library> + <CLASSES> + <root url="jar://$MODULE_DIR$/lib/junit-4.5.jar!/" /> + </CLASSES> + <JAVADOC /> + <SOURCES /> + </library> + </orderEntry> </component> </module> Modified: trunk/distr/distr.iml =================================================================== --- trunk/distr/distr.iml 2008-12-02 08:56:50 UTC (rev 4768) +++ trunk/distr/distr.iml 2008-12-02 09:08:54 UTC (rev 4769) @@ -38,7 +38,6 @@ </orderEntry> <orderEntry type="module" module-name="gui" /> <orderEntry type="module" module-name="fs" /> - <orderEntryProperties /> </component> </module> Modified: trunk/fs/fs.iml =================================================================== --- trunk/fs/fs.iml 2008-12-02 08:56:50 UTC (rev 4768) +++ trunk/fs/fs.iml 2008-12-02 09:08:54 UTC (rev 4769) @@ -63,7 +63,6 @@ <SOURCES /> </library> </orderEntry> - <orderEntryProperties /> </component> </module> Modified: trunk/gui/gui.iml =================================================================== --- trunk/gui/gui.iml 2008-12-02 08:56:50 UTC (rev 4768) +++ trunk/gui/gui.iml 2008-12-02 09:08:54 UTC (rev 4769) @@ -17,7 +17,6 @@ <orderEntry type="module" module-name="core" /> <orderEntry type="library" name="core" level="project" /> <orderEntry type="module" module-name="shell" /> - <orderEntryProperties /> </component> </module> Modified: trunk/jnode.iml =================================================================== --- trunk/jnode.iml 2008-12-02 08:56:50 UTC (rev 4768) +++ trunk/jnode.iml 2008-12-02 09:08:54 UTC (rev 4769) @@ -18,7 +18,6 @@ </content> <orderEntry type="inheritedJdk" /> <orderEntry type="sourceFolder" forTests="false" /> - <orderEntryProperties /> </component> </module> Modified: trunk/net/net.iml =================================================================== --- trunk/net/net.iml 2008-12-02 08:56:50 UTC (rev 4768) +++ trunk/net/net.iml 2008-12-02 09:08:54 UTC (rev 4769) @@ -33,7 +33,6 @@ <SOURCES /> </library> </orderEntry> - <orderEntryProperties /> </component> </module> Modified: trunk/shell/shell.iml =================================================================== --- trunk/shell/shell.iml 2008-12-02 08:56:50 UTC (rev 4768) +++ trunk/shell/shell.iml 2008-12-02 09:08:54 UTC (rev 4769) @@ -22,7 +22,6 @@ <SOURCES /> </library> </orderEntry> - <orderEntryProperties /> </component> </module> Modified: trunk/sound/sound.iml =================================================================== --- trunk/sound/sound.iml 2008-12-02 08:56:50 UTC (rev 4768) +++ trunk/sound/sound.iml 2008-12-02 09:08:54 UTC (rev 4769) @@ -10,7 +10,6 @@ </content> <orderEntry type="inheritedJdk" /> <orderEntry type="sourceFolder" forTests="false" /> - <orderEntryProperties /> </component> </module> Modified: trunk/textui/textui.iml =================================================================== --- trunk/textui/textui.iml 2008-12-02 08:56:50 UTC (rev 4768) +++ trunk/textui/textui.iml 2008-12-02 09:08:54 UTC (rev 4769) @@ -11,7 +11,6 @@ <orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="module" module-name="core" /> <orderEntry type="module" module-name="shell" /> - <orderEntryProperties /> </component> </module> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2008-12-07 11:11:09
|
Revision: 4772 http://jnode.svn.sourceforge.net/jnode/?rev=4772&view=rev Author: lsantha Date: 2008-12-07 11:11:06 +0000 (Sun, 07 Dec 2008) Log Message: ----------- Renamed org.classpath.core plugin to rt. Modified Paths: -------------- trunk/all/conf/system-plugin-list.xml trunk/core/descriptors/javax.ext.tools.xml trunk/core/descriptors/mx4j.xml trunk/core/descriptors/org.classpath.core.xml trunk/core/descriptors/org.classpath.ext.awt.xml trunk/core/descriptors/org.classpath.ext.corba.xml trunk/core/descriptors/org.classpath.ext.core.xml trunk/core/descriptors/org.classpath.ext.imageio.xml trunk/core/descriptors/org.classpath.ext.jdwp.xml trunk/core/descriptors/org.classpath.ext.management.xml trunk/core/descriptors/org.classpath.ext.print.xml trunk/core/descriptors/org.classpath.ext.sql.xml trunk/core/descriptors/org.classpath.ext.xml trunk/core/descriptors/org.classpath.ext.xml.xml trunk/core/descriptors/org.classpath.tools.xml trunk/core/descriptors/org.jnode.vm.core.xml Modified: trunk/all/conf/system-plugin-list.xml =================================================================== --- trunk/all/conf/system-plugin-list.xml 2008-12-07 11:07:18 UTC (rev 4771) +++ trunk/all/conf/system-plugin-list.xml 2008-12-07 11:11:06 UTC (rev 4772) @@ -8,7 +8,7 @@ <plugin id="org.apache.jakarta.log4j"/> <plugin id="nanoxml"/> - <plugin id="org.classpath.core"/> + <plugin id="rt"/> <plugin id="org.jnode.runtime"/> <plugin id="org.jnode.runtime.core"/> Modified: trunk/core/descriptors/javax.ext.tools.xml =================================================================== --- trunk/core/descriptors/javax.ext.tools.xml 2008-12-07 11:07:18 UTC (rev 4771) +++ trunk/core/descriptors/javax.ext.tools.xml 2008-12-07 11:11:06 UTC (rev 4772) @@ -4,7 +4,7 @@ <fragment id="javax.ext.tools" name="The javax.tools.* and related classes." version="@VERSION@" - plugin-id="org.classpath.core" + plugin-id="rt" plugin-version="@VERSION@" provider-name="Sun Microsystems" provider-url="http://sun.com" Modified: trunk/core/descriptors/mx4j.xml =================================================================== --- trunk/core/descriptors/mx4j.xml 2008-12-07 11:07:18 UTC (rev 4771) +++ trunk/core/descriptors/mx4j.xml 2008-12-07 11:11:06 UTC (rev 4772) @@ -4,7 +4,7 @@ <fragment id="mx4j" name="MX4J Management Extensions" version="3.0.1" - plugin-id="org.classpath.core" + plugin-id="rt" plugin-version="@VERSION@" provider-name="mx4j.org" provider-url="http://mx4j.org" Modified: trunk/core/descriptors/org.classpath.core.xml =================================================================== --- trunk/core/descriptors/org.classpath.core.xml 2008-12-07 11:07:18 UTC (rev 4771) +++ trunk/core/descriptors/org.classpath.core.xml 2008-12-07 11:11:06 UTC (rev 4772) @@ -1,7 +1,7 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plugin SYSTEM "jnode.dtd"> -<plugin id="org.classpath.core" +<plugin id="rt" name="Core java classes" version="@VERSION@" system="true" Modified: trunk/core/descriptors/org.classpath.ext.awt.xml =================================================================== --- trunk/core/descriptors/org.classpath.ext.awt.xml 2008-12-07 11:07:18 UTC (rev 4771) +++ trunk/core/descriptors/org.classpath.ext.awt.xml 2008-12-07 11:11:06 UTC (rev 4772) @@ -4,7 +4,7 @@ <fragment id="org.classpath.ext.awt" name="Classpath AWT classes" version="@VERSION@" - plugin-id="org.classpath.core" + plugin-id="rt" plugin-version="@VERSION@" provider-name="Classpath" provider-url="http://classpath.org" Modified: trunk/core/descriptors/org.classpath.ext.corba.xml =================================================================== --- trunk/core/descriptors/org.classpath.ext.corba.xml 2008-12-07 11:07:18 UTC (rev 4771) +++ trunk/core/descriptors/org.classpath.ext.corba.xml 2008-12-07 11:11:06 UTC (rev 4772) @@ -4,7 +4,7 @@ <fragment id="org.classpath.ext.corba" name="Classpath org.omg.CORBA classes" version="@VERSION@" - plugin-id="org.classpath.core" + plugin-id="rt" plugin-version="@VERSION@" provider-name="Classpath" provider-url="http://classpath.org" Modified: trunk/core/descriptors/org.classpath.ext.core.xml =================================================================== --- trunk/core/descriptors/org.classpath.ext.core.xml 2008-12-07 11:07:18 UTC (rev 4771) +++ trunk/core/descriptors/org.classpath.ext.core.xml 2008-12-07 11:11:06 UTC (rev 4772) @@ -4,7 +4,7 @@ <fragment id="org.classpath.ext.core" name="Classpath core classes" version="@VERSION@" - plugin-id="org.classpath.core" + plugin-id="rt" plugin-version="@VERSION@" provider-name="Classpath" provider-url="http://classpath.org" Modified: trunk/core/descriptors/org.classpath.ext.imageio.xml =================================================================== --- trunk/core/descriptors/org.classpath.ext.imageio.xml 2008-12-07 11:07:18 UTC (rev 4771) +++ trunk/core/descriptors/org.classpath.ext.imageio.xml 2008-12-07 11:11:06 UTC (rev 4772) @@ -4,7 +4,7 @@ <fragment id="org.classpath.ext.imageio" name="Classpath javax.imageio classes" version="@VERSION@" - plugin-id="org.classpath.core" + plugin-id="rt" plugin-version="@VERSION@" provider-name="Classpath" provider-url="http://classpath.org" Modified: trunk/core/descriptors/org.classpath.ext.jdwp.xml =================================================================== --- trunk/core/descriptors/org.classpath.ext.jdwp.xml 2008-12-07 11:07:18 UTC (rev 4771) +++ trunk/core/descriptors/org.classpath.ext.jdwp.xml 2008-12-07 11:11:06 UTC (rev 4772) @@ -4,7 +4,7 @@ <fragment id="org.classpath.ext.jdwp" name="Classpath JDWP classes" version="@VERSION@" - plugin-id="org.classpath.core" + plugin-id="rt" plugin-version="@VERSION@" provider-name="Classpath" provider-url="http://classpath.org" Modified: trunk/core/descriptors/org.classpath.ext.management.xml =================================================================== --- trunk/core/descriptors/org.classpath.ext.management.xml 2008-12-07 11:07:18 UTC (rev 4771) +++ trunk/core/descriptors/org.classpath.ext.management.xml 2008-12-07 11:11:06 UTC (rev 4772) @@ -4,7 +4,7 @@ <fragment id="org.classpath.ext.management" name="Classpath javax.management classes" version="@VERSION@" - plugin-id="org.classpath.core" + plugin-id="rt" plugin-version="@VERSION@" provider-name="Classpath" provider-url="http://classpath.org" Modified: trunk/core/descriptors/org.classpath.ext.print.xml =================================================================== --- trunk/core/descriptors/org.classpath.ext.print.xml 2008-12-07 11:07:18 UTC (rev 4771) +++ trunk/core/descriptors/org.classpath.ext.print.xml 2008-12-07 11:11:06 UTC (rev 4772) @@ -4,7 +4,7 @@ <fragment id="org.classpath.ext.print" name="Classpath javax.print classes" version="@VERSION@" - plugin-id="org.classpath.core" + plugin-id="rt" plugin-version="@VERSION@" provider-name="Classpath" provider-url="http://classpath.org" Modified: trunk/core/descriptors/org.classpath.ext.sql.xml =================================================================== --- trunk/core/descriptors/org.classpath.ext.sql.xml 2008-12-07 11:07:18 UTC (rev 4771) +++ trunk/core/descriptors/org.classpath.ext.sql.xml 2008-12-07 11:11:06 UTC (rev 4772) @@ -4,7 +4,7 @@ <fragment id="org.classpath.ext.sql" name="Classpath javax.sql classes" version="@VERSION@" - plugin-id="org.classpath.core" + plugin-id="rt" plugin-version="@VERSION@" provider-name="Classpath" provider-url="http://classpath.org" Modified: trunk/core/descriptors/org.classpath.ext.xml =================================================================== --- trunk/core/descriptors/org.classpath.ext.xml 2008-12-07 11:07:18 UTC (rev 4771) +++ trunk/core/descriptors/org.classpath.ext.xml 2008-12-07 11:11:06 UTC (rev 4772) @@ -4,7 +4,7 @@ <fragment id="org.classpath.ext" name="Core java classes" version="@VERSION@" - plugin-id="org.classpath.core" + plugin-id="rt" plugin-version="@VERSION@" provider-name="Classpath" provider-url="http://classpath.org" Modified: trunk/core/descriptors/org.classpath.ext.xml.xml =================================================================== --- trunk/core/descriptors/org.classpath.ext.xml.xml 2008-12-07 11:07:18 UTC (rev 4771) +++ trunk/core/descriptors/org.classpath.ext.xml.xml 2008-12-07 11:11:06 UTC (rev 4772) @@ -4,7 +4,7 @@ <fragment id="org.classpath.ext.xml" name="Classpath javax.xml classes" version="@VERSION@" - plugin-id="org.classpath.core" + plugin-id="rt" plugin-version="@VERSION@" provider-name="Classpath" provider-url="http://classpath.org" Modified: trunk/core/descriptors/org.classpath.tools.xml =================================================================== --- trunk/core/descriptors/org.classpath.tools.xml 2008-12-07 11:07:18 UTC (rev 4771) +++ trunk/core/descriptors/org.classpath.tools.xml 2008-12-07 11:11:06 UTC (rev 4772) @@ -4,7 +4,7 @@ <fragment id="org.classpath.tools" name="Core java tools" version="@VERSION@" - plugin-id="org.classpath.core" + plugin-id="rt" plugin-version="@VERSION@" provider-name="Classpath" provider-url="http://classpath.org" Modified: trunk/core/descriptors/org.jnode.vm.core.xml =================================================================== --- trunk/core/descriptors/org.jnode.vm.core.xml 2008-12-07 11:07:18 UTC (rev 4771) +++ trunk/core/descriptors/org.jnode.vm.core.xml 2008-12-07 11:11:06 UTC (rev 4772) @@ -9,7 +9,7 @@ provider-name="JNode.org"> <requires> - <import plugin="org.classpath.core"/> + <import plugin="rt"/> <!-- import plugin="org.apache.jakarta.log4j"/ --> <!-- import plugin="org.jnode.fs.service"/ --> </requires> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2008-12-07 14:18:26
|
Revision: 4777 http://jnode.svn.sourceforge.net/jnode/?rev=4777&view=rev Author: lsantha Date: 2008-12-07 14:18:22 +0000 (Sun, 07 Dec 2008) Log Message: ----------- Fixed code style. Modified Paths: -------------- trunk/core/src/core/org/jnode/naming/AbstractNameSpace.java trunk/core/src/core/org/jnode/vm/scheduler/Monitor.java trunk/fs/src/fs/org/jnode/fs/jfat/FatTable.java trunk/gui/src/test/org/jnode/test/gui/Emu.java trunk/shell/src/shell/org/jnode/shell/CommandLine.java Modified: trunk/core/src/core/org/jnode/naming/AbstractNameSpace.java =================================================================== --- trunk/core/src/core/org/jnode/naming/AbstractNameSpace.java 2008-12-07 14:03:10 UTC (rev 4776) +++ trunk/core/src/core/org/jnode/naming/AbstractNameSpace.java 2008-12-07 14:18:22 UTC (rev 4777) @@ -28,8 +28,6 @@ import javax.naming.NameNotFoundException; -import org.jnode.vm.Unsafe; - /** * Partial implementation of {@link NameSpace} interface : * only listener stuff has been implemented. @@ -42,7 +40,6 @@ private final Map<Class<?>, List<NameSpaceListener<?>>> listeners = new HashMap<Class<?>, List<NameSpaceListener<?>>>(); - @Override public final <T> void addNameSpaceListener(Class<T> name, NameSpaceListener<T> l) { List<NameSpaceListener<?>> list = listeners.get(name); if (list == null) { @@ -64,7 +61,6 @@ } } - @Override public final <T> void removeNameSpaceListener(Class<T> name, NameSpaceListener<T> l) { List<NameSpaceListener<?>> list = listeners.get(name); if (list != null) { @@ -73,7 +69,6 @@ if (list.isEmpty()) { // no more listeners for that name => remove the empty list listeners.remove(name); - list = null; } } } Modified: trunk/core/src/core/org/jnode/vm/scheduler/Monitor.java =================================================================== --- trunk/core/src/core/org/jnode/vm/scheduler/Monitor.java 2008-12-07 14:03:10 UTC (rev 4776) +++ trunk/core/src/core/org/jnode/vm/scheduler/Monitor.java 2008-12-07 14:18:22 UTC (rev 4777) @@ -91,7 +91,7 @@ Monitor(VmThread owner, int lockCount) { this.monitorLock = 0; this.owner = owner; - if(owner != null) + if (owner != null) addToOwner(); this.lockCount = lockCount; if (lockCount < 1) { @@ -110,7 +110,7 @@ final void initialize(VmThread owner, int lockcount) { dropFromOwner(); this.owner = owner; - if(owner != null) + if (owner != null) addToOwner(); this.lockCount = lockcount; } Modified: trunk/fs/src/fs/org/jnode/fs/jfat/FatTable.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/jfat/FatTable.java 2008-12-07 14:03:10 UTC (rev 4776) +++ trunk/fs/src/fs/org/jnode/fs/jfat/FatTable.java 2008-12-07 14:18:22 UTC (rev 4777) @@ -18,8 +18,8 @@ } public FatEntry put(FatEntry entry) { - FatKey key = new FatKey(entry.getName()); - if (table.containsKey(key)){ + FatKey key = new FatKey(entry.getName()); + if (table.containsKey(key)) { throw new IllegalArgumentException("shouldn't happen"); } table.put(key, entry); @@ -63,21 +63,21 @@ * Print FAT table content. */ public String toString() { - StrWriter out = null; - try{ - out = new StrWriter(); + StrWriter out = null; + try { + out = new StrWriter(); - Iterator<FatKey> i = table.keySet().iterator(); + Iterator<FatKey> i = table.keySet().iterator(); - out.println("Entries ["); - while (i.hasNext()) - out.println("\t\t " + i.next()); - out.print("\t\t]"); + out.println("Entries ["); + while (i.hasNext()) + out.println("\t\t " + i.next()); + out.print("\t\t]"); - return out.toString(); - } finally { - out.close(); - } + return out.toString(); + } finally { + out.close(); + } } private class FatKey { Modified: trunk/gui/src/test/org/jnode/test/gui/Emu.java =================================================================== --- trunk/gui/src/test/org/jnode/test/gui/Emu.java 2008-12-07 14:03:10 UTC (rev 4776) +++ trunk/gui/src/test/org/jnode/test/gui/Emu.java 2008-12-07 14:18:22 UTC (rev 4777) @@ -15,10 +15,6 @@ import org.jnode.emu.naming.BasicNameSpace; import org.jnode.emu.plugin.model.DummyExtensionPoint; import org.jnode.naming.InitialNaming; -import org.jnode.plugin.Extension; -import org.jnode.plugin.ExtensionPoint; -import org.jnode.plugin.ExtensionPointListener; -import org.jnode.plugin.PluginDescriptor; import org.jnode.shell.ShellManager; import org.jnode.shell.alias.AliasManager; import org.jnode.shell.alias.def.DefaultAliasManager; Modified: trunk/shell/src/shell/org/jnode/shell/CommandLine.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/CommandLine.java 2008-12-07 14:03:10 UTC (rev 4776) +++ trunk/shell/src/shell/org/jnode/shell/CommandLine.java 2008-12-07 14:18:22 UTC (rev 4777) @@ -41,10 +41,10 @@ * 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. - * + * <p/> * 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... */ @SuppressWarnings("deprecation") @@ -107,16 +107,16 @@ /** * Create a new instance using Tokens instead of Strings. - * - * @param commandToken the command name token or <code>null</code>. + * + * @param commandToken the command name token or <code>null</code>. * @param argumentTokens the argument token list or <code>null</code>. - * @param ios the io stream array or <code>null</code>. + * @param ios the io stream array or <code>null</code>. */ public CommandLine(Token commandToken, Token[] argumentTokens, - CommandIO[] ios) { + CommandIO[] ios) { this.commandToken = commandToken; this.argumentTokens = (argumentTokens == null || argumentTokens.length == 0) ? NO_TOKENS - : argumentTokens.clone(); + : argumentTokens.clone(); this.ios = setupStreams(ios); } @@ -126,10 +126,10 @@ * String array is substituted. If 'streams' is <code>null</code> , an * array of length 4 is substituted. A non-null 'streams' argument must have * a length of at least 4. - * + * * @param commandName the command name or <code>null</code>. - * @param arguments the argument list or <code>null</code>. - * @param ios the io stream array or <code>null</code>. + * @param arguments the argument list or <code>null</code>. + * @param ios the io stream array or <code>null</code>. */ public CommandLine(String commandName, String[] arguments, CommandIO[] ios) { this.commandToken = commandName == null ? null : new Token(commandName); @@ -148,9 +148,9 @@ /** * Create a new instance. Equivalent to CommandLine(commandName, arguments, * null); - * + * * @param commandName the command name or <code>null</code>. - * @param arguments the argument list or <code>null</code>. + * @param arguments the argument list or <code>null</code>. */ public CommandLine(String commandName, String[] arguments) { this(commandName, arguments, null); @@ -158,7 +158,7 @@ /** * Create a new instance. Equivalent to CommandLine(null, arguments, null); - * + * * @param arguments the argument list or <code>null</code>. * @deprecated It is a bad idea to leave out the command name. */ @@ -183,7 +183,7 @@ /** * This method returns an Iterator for the arguments represented as Strings. - * + * * @deprecated */ public SymbolSource<String> iterator() { @@ -303,7 +303,7 @@ /** * Get the command name - * + * * @return the command name */ public String getCommandName() { @@ -312,7 +312,7 @@ /** * Get the command name in token form - * + * * @return the command token */ public Token getCommandToken() { @@ -321,7 +321,7 @@ /** * Get the arguments as String[]. - * + * * @return the arguments as String[] */ public String[] getArguments() { @@ -338,7 +338,7 @@ /** * Get the arguments as String[]. - * + * * @return the arguments as String[] * @deprecated this method name is wrong. */ @@ -348,7 +348,7 @@ /** * Returns the entire command line as a string. - * + * * @return the entire command line */ public String toString() { @@ -362,7 +362,7 @@ /** * Gets the remaining number of parts - * + * * @return the remaining number of parts */ public int getLength() { @@ -386,13 +386,13 @@ * 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. The value -1 indicates that no token type is + * interpreter specific. The value -1 indicates that no token type is * available. */ public final int tokenType; @@ -400,7 +400,7 @@ /** * This field denotes the character offset of the first character of * this token in the source character sequence passed to the - * interpreter. The value -1 indicates that no source start position is + * interpreter. The value -1 indicates that no source start position is * available. */ public final int start; @@ -408,7 +408,7 @@ /** * This field denotes the character offset + 1 for the last character of * this token in the source character sequence passed to the - * interpreter. The value -1 indicates that no source end position is + * interpreter. The value -1 indicates that no source end position is * available. */ public final int end; @@ -456,7 +456,7 @@ if (tokenType != other.tokenType) return false; return true; - } + } public String toString() { return "Token{'" + token + "'," + start + "," + end + "," + tokenType + "}"; @@ -470,12 +470,12 @@ new Escape(ESCAPE_CHAR, ESCAPE_CHAR), new Escape(ESCAPE_B, B), new Escape(ESCAPE_N, N), new Escape(ESCAPE_R, R), new Escape(ESCAPE_T, T), - new Escape(FULL_ESCAPE_CHAR, FULL_ESCAPE_CHAR) }; + new Escape(FULL_ESCAPE_CHAR, FULL_ESCAPE_CHAR)}; /** * Escape a single command line argument for the Shell. Same as calling * escape(arg, <code>false</code>) - * + * * @param arg the unescaped argument * @return the escaped argument */ @@ -485,10 +485,10 @@ /** * Escape a single command line argument for the Shell. - * - * @param arg the unescaped argument + * + * @param arg the unescaped argument * @param forceQuote if <code>true</code>, forces the argument to be - * returned in quotes even if not necessary + * returned in quotes even if not necessary * @return the escaped argument * @deprecated This method does not belong here. Escaping is an interpreter * concern, and this class needs to be interpreter specific. @@ -539,7 +539,7 @@ /** * Get the IO stream context for executing the command. The result is * guaranteed to be non-null and to have at least 4 entries. - * + * * @return the stream context as described above. */ public CommandIO[] getStreams() { @@ -548,7 +548,7 @@ /** * Set the IO stream context for executing the command. - * + * * @param ios the command's new stream context. */ public void setStreams(CommandIO[] ios) { @@ -563,11 +563,11 @@ * 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 a CompandInfo which includes the command instance to which the arguments have been bound * @throws CommandSyntaxException if the chosen syntax doesn't match the command - * line arguments. + * line arguments. */ public CommandInfo parseCommandLine(CommandShell shell) throws ShellException { String cmd = (commandToken == null) ? "" : commandToken.token.trim(); @@ -620,7 +620,7 @@ // Get the command's argument bundle and syntax ArgumentBundle bundle = (command == null) ? null : command.getArgumentBundle(); SyntaxBundle syntaxes = shell.getSyntaxManager().getSyntaxBundle(cmd); - + if (bundle == null) { // We're missing the argument bundle. We assume this is a 'classic' Java application // that does its own argument parsing and completion like a UNIX shell; i.e. @@ -628,14 +628,14 @@ Syntax syntax = new RepeatSyntax(new ArgumentSyntax("argument")); syntaxes = new SyntaxBundle(cmd, syntax); bundle = new ArgumentBundle( - new FileArgument("argument", Argument.MULTIPLE)); + new FileArgument("argument", Argument.MULTIPLE)); } else if (syntaxes == null) { // We're missing the syntax, but we do have an argument bundle. Generate // a default syntax from the bundle. syntaxes = new SyntaxBundle(cmd, bundle.createDefaultSyntax()); } try { - bundle.complete(this, syntaxes, completion); + bundle.complete(this, syntaxes, completion); } catch (CommandSyntaxException ex) { throw new CompletionException("Command syntax problem", ex); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2008-12-13 21:12:01
|
Revision: 4787 http://jnode.svn.sourceforge.net/jnode/?rev=4787&view=rev Author: lsantha Date: 2008-12-13 21:11:59 +0000 (Sat, 13 Dec 2008) Log Message: ----------- Intgerated java.lang.reflect.Field from OpenJDK. Modified Paths: -------------- trunk/builder/src/builder/org/jnode/build/AbstractBootImageBuilder.java trunk/core/descriptors/org.classpath.core.xml Modified: trunk/builder/src/builder/org/jnode/build/AbstractBootImageBuilder.java =================================================================== --- trunk/builder/src/builder/org/jnode/build/AbstractBootImageBuilder.java 2008-12-13 21:11:12 UTC (rev 4786) +++ trunk/builder/src/builder/org/jnode/build/AbstractBootImageBuilder.java 2008-12-13 21:11:59 UTC (rev 4787) @@ -1331,6 +1331,21 @@ addCompileHighOptLevel("org.jnode.vm.memmgr.mmtk.nogc"); addCompileHighOptLevel("org.jnode.vm.memmgr.mmtk.ms"); + //todo review for boot image size reduction + addCompileHighOptLevel("sun.misc"); +// addCompileHighOptLevel("sun.reflect"); <-- // this kills jnode while booting, maybe Reflection static{...} + addCompileHighOptLevel("sun.reflect.annotation"); + addCompileHighOptLevel("sun.reflect.generics"); + addCompileHighOptLevel("sun.reflect.generics.factory"); + addCompileHighOptLevel("sun.reflect.generics.parser"); + addCompileHighOptLevel("sun.reflect.generics.reflectiveObjects"); + addCompileHighOptLevel("sun.reflect.generics.repository"); + addCompileHighOptLevel("sun.reflect.generics.scope"); + addCompileHighOptLevel("sun.reflect.generics.tree"); + addCompileHighOptLevel("sun.reflect.generics.visitor"); + addCompileHighOptLevel("sun.reflect.misc"); + addCompileHighOptLevel("sun.nio"); + if (false) { addCompileHighOptLevel("org.mmtk.plan"); addCompileHighOptLevel("org.mmtk.policy"); Modified: trunk/core/descriptors/org.classpath.core.xml =================================================================== --- trunk/core/descriptors/org.classpath.core.xml 2008-12-13 21:11:12 UTC (rev 4786) +++ trunk/core/descriptors/org.classpath.core.xml 2008-12-13 21:11:59 UTC (rev 4787) @@ -37,6 +37,7 @@ <export name="sun.net.www.protocol.http.InMemoryCookieStore"/> <export name="sun.net.spi.nameservice.NameService"/> <export name="sun.net.spi.nameservice.NameServiceDescriptor"/> + <export name="sun.nio.ByteBuffered"/> <export name="sun.nio.ch.Interruptible"/> <export name="sun.security.acl.GroupImpl"/> <export name="sun.security.util.Debug"/> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2008-12-18 18:35:03
|
Revision: 4794 http://jnode.svn.sourceforge.net/jnode/?rev=4794&view=rev Author: lsantha Date: 2008-12-18 18:34:56 +0000 (Thu, 18 Dec 2008) Log Message: ----------- Integrated java.lang.reflect.Method from OpenJDK. Modified Paths: -------------- trunk/builder/src/builder/org/jnode/build/AbstractBootImageBuilder.java trunk/core/src/core/org/jnode/vm/classmgr/VmMethod.java trunk/core/src/core/org/jnode/vm/isolate/VmIsolate.java trunk/core/src/openjdk/vm/sun/reflect/NativeNativeMethodAccessorImpl.java trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingToolkit.java Added Paths: ----------- trunk/core/src/openjdk/java/java/lang/reflect/Method.java Removed Paths: ------------- trunk/core/src/classpath/vm/java/lang/reflect/Method.java Modified: trunk/builder/src/builder/org/jnode/build/AbstractBootImageBuilder.java =================================================================== --- trunk/builder/src/builder/org/jnode/build/AbstractBootImageBuilder.java 2008-12-17 13:58:56 UTC (rev 4793) +++ trunk/builder/src/builder/org/jnode/build/AbstractBootImageBuilder.java 2008-12-18 18:34:56 UTC (rev 4794) @@ -1281,7 +1281,7 @@ addCompileHighOptLevel("java.io"); addCompileHighOptLevel("java.lang"); addCompileHighOptLevel("java.lang.ref"); - addCompileHighOptLevel("java.lang.reflect"); +// addCompileHighOptLevel("java.lang.reflect"); //<- produces inconsistent bootimage addCompileHighOptLevel("java.net"); addCompileHighOptLevel("java.nio"); addCompileHighOptLevel("java.security"); @@ -1332,18 +1332,18 @@ addCompileHighOptLevel("org.jnode.vm.memmgr.mmtk.ms"); //todo review for boot image size reduction - addCompileHighOptLevel("sun.misc"); +// addCompileHighOptLevel("sun.misc"); // addCompileHighOptLevel("sun.reflect"); <-- // this kills jnode while booting, maybe Reflection static{...} - addCompileHighOptLevel("sun.reflect.annotation"); - addCompileHighOptLevel("sun.reflect.generics"); - addCompileHighOptLevel("sun.reflect.generics.factory"); - addCompileHighOptLevel("sun.reflect.generics.parser"); - addCompileHighOptLevel("sun.reflect.generics.reflectiveObjects"); - addCompileHighOptLevel("sun.reflect.generics.repository"); - addCompileHighOptLevel("sun.reflect.generics.scope"); - addCompileHighOptLevel("sun.reflect.generics.tree"); - addCompileHighOptLevel("sun.reflect.generics.visitor"); - addCompileHighOptLevel("sun.reflect.misc"); +// addCompileHighOptLevel("sun.reflect.annotation"); +// addCompileHighOptLevel("sun.reflect.generics"); +// addCompileHighOptLevel("sun.reflect.generics.factory"); +// addCompileHighOptLevel("sun.reflect.generics.parser"); +// addCompileHighOptLevel("sun.reflect.generics.reflectiveObjects"); +// addCompileHighOptLevel("sun.reflect.generics.repository"); +// addCompileHighOptLevel("sun.reflect.generics.scope"); +// addCompileHighOptLevel("sun.reflect.generics.tree"); +// addCompileHighOptLevel("sun.reflect.generics.visitor"); +// addCompileHighOptLevel("sun.reflect.misc"); addCompileHighOptLevel("sun.nio"); if (false) { Deleted: trunk/core/src/classpath/vm/java/lang/reflect/Method.java =================================================================== --- trunk/core/src/classpath/vm/java/lang/reflect/Method.java 2008-12-17 13:58:56 UTC (rev 4793) +++ trunk/core/src/classpath/vm/java/lang/reflect/Method.java 2008-12-18 18:34:56 UTC (rev 4794) @@ -1,613 +0,0 @@ -/* java.lang.reflect.Method - reflection of Java methods - Copyright (C) 1998, 2001, 2002, 2005 Free Software Foundation, Inc. - -This file is part of GNU Classpath. - -GNU Classpath is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2, or (at your option) -any later version. - -GNU Classpath 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 -General Public License for more details. - -You should have received a copy of the GNU General Public License -along with GNU Classpath; see the file COPYING. If not, write to the -Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -02110-1301 USA. - -Linking this library statically or dynamically with other modules is -making a combined work based on this library. Thus, the terms and -conditions of the GNU General Public License cover the whole -combination. - -As a special exception, the copyright holders of this library give you -permission to link this library with independent modules to produce an -executable, regardless of the license terms of these independent -modules, and to copy and distribute the resulting executable under -terms of your choice, provided that you also meet, for each linked -independent module, the terms and conditions of the license of that -module. An independent module is a module which is not derived from -or based on this library. If you modify this library, you may extend -this exception to your version of the library, but you are not -obligated to do so. If you do not wish to do so, delete this -exception statement from your version. */ - - -package java.lang.reflect; - -import gnu.java.lang.ClassHelper; -import java.lang.annotation.Annotation; -import java.lang.annotation.AnnotationFormatError; -import java.util.ArrayList; - -import org.jnode.vm.VmReflection; -import org.jnode.vm.classmgr.VmExceptions; -import org.jnode.vm.classmgr.VmMethod; -import gnu.java.lang.reflect.MethodSignatureParser; - -import java.util.Arrays; -import java.util.Map; -import java.nio.ByteBuffer; -import sun.reflect.MethodAccessor; -import sun.reflect.annotation.AnnotationParser; -import sun.reflect.annotation.AnnotationType; -import sun.misc.SharedSecrets; - -/** - * The Method class represents a member method of a class. It also allows - * dynamic invocation, via reflection. This works for both static and - * instance methods. Invocation on Method objects knows how to do - * widening conversions, but throws {@link IllegalArgumentException} if - * a narrowing conversion would be necessary. You can query for information - * on this Method regardless of location, but invocation access may be limited - * by Java language access controls. If you can't do it in the compiler, you - * can't normally do it here either.<p> - * - * <B>Note:</B> This class returns and accepts types as Classes, even - * primitive types; there are Class types defined that represent each - * different primitive type. They are <code>java.lang.Boolean.TYPE, - * java.lang.Byte.TYPE,</code>, also available as <code>boolean.class, - * byte.class</code>, etc. These are not to be confused with the - * classes <code>java.lang.Boolean, java.lang.Byte</code>, etc., which are - * real classes.<p> - * - * Also note that this is not a serializable class. It is entirely feasible - * to make it serializable using the Externalizable interface, but this is - * on Sun, not me. - * - * @author John Keiser - * @author Eric Blake <eb...@em...> - * @see Member - * @see Class - * @see java.lang.Class#getMethod(String,Class[]) - * @see java.lang.Class#getDeclaredMethod(String,Class[]) - * @see java.lang.Class#getMethods() - * @see java.lang.Class#getDeclaredMethods() - * @since 1.1 - * @status updated to 1.4 - */ -public final class Method extends AccessibleObject implements Member, AnnotatedElement, GenericDeclaration { - - private VmMethod vmMethod; - private ArrayList<Class> parameterTypes; - private ArrayList<Class> exceptionTypes; - - private static final int METHOD_MODIFIERS - = Modifier.ABSTRACT | Modifier.FINAL | Modifier.NATIVE - | Modifier.PRIVATE | Modifier.PROTECTED | Modifier.PUBLIC - | Modifier.STATIC | Modifier.STRICT | Modifier.SYNCHRONIZED; - - /** - * - */ - public Method(VmMethod vmMethod) { - this.vmMethod = vmMethod; - this.annotationDefault = vmMethod.getRawAnnotationDefault(); - this.annotations = vmMethod.getRawAnnotations(); - this.parameterAnnotations = vmMethod.getRawParameterAnnotations(); - } - - public Method(Class declaringClass, String name, Class[] parameterTypes, Class returnType, Class[] checkedExceptions, int modifiers, int slot, String signature, byte[] annotations, byte[] parameterAnnotations, byte[] annotationDefault) { - - throw new UnsupportedOperationException(); - } - - /** - * Gets the class that declared this method, or the class where this method - * is a non-inherited member. - * @return the class that declared this member - */ - public Class<?> getDeclaringClass() - { - return vmMethod.getDeclaringClass().asClass(); - } - - /** - * Gets the name of this method. - * @return the name of this method - */ - public String getName() - { - return vmMethod.getName(); - } - - /** - * Return the raw modifiers for this method. - * @return the method's modifiers - */ - private int getModifiersInternal() - { - return vmMethod.getModifiers(); - } - - /** - * Gets the modifiers this method uses. Use the <code>Modifier</code> - * class to interpret the values. A method can only have a subset of the - * following modifiers: public, private, protected, abstract, static, - * final, synchronized, native, and strictfp. - * - * @return an integer representing the modifiers to this Member - * @see Modifier - */ - public int getModifiers() - { - return getModifiersInternal() & METHOD_MODIFIERS; - } - - /** - * Return true if this method is a bridge method. A bridge method - * is generated by the compiler in some situations involving - * generics and inheritance. - * @since 1.5 - */ - public boolean isBridge() - { - return (getModifiersInternal() & Modifier.BRIDGE) != 0; - } - - /** - * Return true if this method is synthetic, false otherwise. - * @since 1.5 - */ - public boolean isSynthetic() - { - return (getModifiersInternal() & Modifier.SYNTHETIC) != 0; - } - - /** - * Return true if this is a varargs method, that is if - * the method takes a variable number of arguments. - * @since 1.5 - */ - public boolean isVarArgs() - { - return (getModifiersInternal() & Modifier.VARARGS) != 0; - } - - /** - * Gets the return type of this method. - * @return the type of this method - */ - public Class<?> getReturnType() - { - return vmMethod.getReturnType().asClass(); - } - - /** - * Get the parameter list for this method, in declaration order. If the - * method takes no parameters, returns a 0-length array (not null). - * - * @return a list of the types of the method's parameters - */ - public Class<?>[] getParameterTypes() - { - if (parameterTypes == null) { - int cnt = vmMethod.getNoArguments(); - ArrayList<Class> list = new ArrayList<Class>(cnt); - for (int i = 0; i < cnt; i++) { - list.add(vmMethod.getArgumentType(i).asClass()); - } - parameterTypes = list; - } - return (Class[])parameterTypes.toArray(new Class[parameterTypes.size()]); - } - - /** - * Get the exception types this method says it throws, in no particular - * order. If the method has no throws clause, returns a 0-length array - * (not null). - * - * @return a list of the types in the method's throws clause - */ - public Class<?>[] getExceptionTypes() - { - if (exceptionTypes == null) { - final VmExceptions exceptions = vmMethod.getExceptions(); - final int cnt = exceptions.getLength(); - final ArrayList<Class> list = new ArrayList<Class>(cnt); - for (int i = 0; i < cnt; i++) { - try - { - list.add(exceptions.getException(i).getResolvedVmClass().asClass()); - } - catch (Exception e) - { - // there is some missing getException(i).getResolvedVmClass() - // if one makes a system.out on the methods it fails, looks "java.lang.Exception" is missing - // I think I'll look into it, if I can. - // 10/03/2005 Martin Husted Hartvig - } - } - exceptionTypes = list; - } - return (Class[])exceptionTypes.toArray(new Class[exceptionTypes.size()]); - } - - /** - * Compare two objects to see if they are semantically equivalent. - * Two Methods are semantically equivalent if they have the same declaring - * class, name, and parameter list. This ignores different exception - * clauses or return types. - * - * @param o the object to compare to - * @return <code>true</code> if they are equal; <code>false</code> if not - */ - public boolean equals(Object o) { - if (!(o instanceof Method)) - return false; - Method that = (Method)o; - if (this.getDeclaringClass() != that.getDeclaringClass()) - return false; - if (!this.getName().equals(that.getName())) - return false; - if (this.getReturnType() != that.getReturnType()) - return false; - if (!Arrays.equals(this.getParameterTypes(), that.getParameterTypes())) - return false; - return true; - } - - /** - * Get the hash code for the Method. The Method hash code is the hash code - * of its name XOR'd with the hash code of its class name. - * - * @return the hash code for the object - */ - public int hashCode() - { - return getDeclaringClass().getName().hashCode() ^ getName().hashCode(); - } - - /** - * Get a String representation of the Method. A Method's String - * representation is "<modifiers> <returntype> - * <methodname>(<paramtypes>) throws <exceptions>", where - * everything after ')' is omitted if there are no exceptions.<br> Example: - * <code>public static int run(java.lang.Runnable,int)</code> - * - * @return the String representation of the Method - */ - public String toString() { - // 128 is a reasonable buffer initial size for constructor - StringBuilder sb = new StringBuilder(128); - sb.append(Modifier.toString(getModifiers())).append(' '); - sb.append(ClassHelper.getUserName(getReturnType())).append(' '); - sb.append(getDeclaringClass().getName()).append('.'); - sb.append(getName()).append('('); - Class[] c = getParameterTypes(); - if (c.length > 0) - { - sb.append(ClassHelper.getUserName(c[0])); - for (int i = 1; i < c.length; i++) - sb.append(',').append(ClassHelper.getUserName(c[i])); - } - sb.append(')'); - c = getExceptionTypes(); - if (c.length > 0) { - sb.append(" throws ").append(c[0].getName()); - for (int i = 1; i < c.length; i++) - sb.append(',').append(c[i].getName()); - } - return sb.toString(); - } - - public String toGenericString() - { - // 128 is a reasonable buffer initial size for constructor - StringBuilder sb = new StringBuilder(128); - sb.append(Modifier.toString(getModifiers())).append(' '); - addTypeParameters(sb, getTypeParameters()); - sb.append(getGenericReturnType()).append(' '); - sb.append(getDeclaringClass().getName()).append('.'); - sb.append(getName()).append('('); - Type[] types = getGenericParameterTypes(); - if (types.length > 0) - { - sb.append(types[0]); - for (int i = 1; i < types.length; i++) - sb.append(',').append(types[i]); - } - sb.append(')'); - types = getGenericExceptionTypes(); - if (types.length > 0) - { - sb.append(" throws ").append(types[0]); - for (int i = 1; i < types.length; i++) - sb.append(',').append(types[i]); - } - return sb.toString(); - } - - /** - * Invoke the method. Arguments are automatically unwrapped and widened, - * and the result is automatically wrapped, if needed.<p> - * - * If the method is static, <code>o</code> will be ignored. Otherwise, - * the method uses dynamic lookup as described in JLS 15.12.4.4. You cannot - * mimic the behavior of nonvirtual lookup (as in super.foo()). This means - * you will get a <code>NullPointerException</code> if <code>o</code> is - * null, and an <code>IllegalArgumentException</code> if it is incompatible - * with the declaring class of the method. If the method takes 0 arguments, - * you may use null or a 0-length array for <code>args</code>.<p> - * - * Next, if this Method enforces access control, your runtime context is - * evaluated, and you may have an <code>IllegalAccessException</code> if - * you could not acces this method in similar compiled code. If the method - * is static, and its class is uninitialized, you trigger class - * initialization, which may end in a - * <code>ExceptionInInitializerError</code>.<p> - * - * Finally, the method is invoked. If it completes normally, the return value - * will be null for a void method, a wrapped object for a primitive return - * method, or the actual return of an Object method. If it completes - * abruptly, the exception is wrapped in an - * <code>InvocationTargetException</code>. - * - * @param o the object to invoke the method on - * @param args the arguments to the method - * @return the return value of the method, wrapped in the appropriate - * wrapper if it is primitive - * @throws IllegalAccessException if the method could not normally be called - * by the Java code (i.e. it is not public) - * @throws IllegalArgumentException if the number of arguments is incorrect; - * if the arguments types are wrong even with a widening conversion; - * or if <code>o</code> is not an instance of the class or interface - * declaring this method - * @throws InvocationTargetException if the method throws an exception - * @throws NullPointerException if <code>o</code> is null and this field - * requires an instance - * @throws ExceptionInInitializerError if accessing a static method triggered - * class initialization, which then failed - */ - public Object invoke(Object o, Object... args) - throws IllegalAccessException, InvocationTargetException { - return VmReflection.invoke(vmMethod, o, args); - } - - /** - * Returns an array of <code>TypeVariable</code> objects that represents - * the type variables declared by this constructor, in declaration order. - * An array of size zero is returned if this class has no type - * variables. - * - * @return the type variables associated with this class. - * @throws GenericSignatureFormatError if the generic signature does - * not conform to the format specified in the Virtual Machine - * specification, version 3. - * @since 1.5 - */ - public TypeVariable<Method>[] getTypeParameters() - { - String sig = getSignature(); - if (sig == null) - return new TypeVariable[0]; - MethodSignatureParser p = new MethodSignatureParser(this, sig); - return p.getTypeParameters(); - } - - /** - * Return the String in the Signature attribute for this method. If there - * is no Signature attribute, return null. - */ - private String getSignature() - { - return vmMethod.getSignature(); - } - - /** - * Returns an array of <code>Type</code> objects that represents - * the exception types declared by this method, in declaration order. - * An array of size zero is returned if this method declares no - * exceptions. - * - * @return the exception types declared by this method. - * @throws GenericSignatureFormatError if the generic signature does - * not conform to the format specified in the Virtual Machine - * specification, version 3. - * @since 1.5 - */ - public Type[] getGenericExceptionTypes() - { - String sig = getSignature(); - if (sig == null) - return getExceptionTypes(); - MethodSignatureParser p = new MethodSignatureParser(this, sig); - return p.getGenericExceptionTypes(); - } - - /** - * Returns an array of <code>Type</code> objects that represents - * the parameter list for this method, in declaration order. - * An array of size zero is returned if this method takes no - * parameters. - * - * @return a list of the types of the method's parameters - * @throws GenericSignatureFormatError if the generic signature does - * not conform to the format specified in the Virtual Machine - * specification, version 3. - * @since 1.5 - */ - public Type[] getGenericParameterTypes() - { - String sig = getSignature(); - if (sig == null) - return getParameterTypes(); - MethodSignatureParser p = new MethodSignatureParser(this, sig); - return p.getGenericParameterTypes(); - } - - /** - * Returns the return type of this method. - * - * @return the return type of this method - * @throws GenericSignatureFormatError if the generic signature does - * not conform to the format specified in the Virtual Machine - * specification, version 3. - * @since 1.5 - */ - public Type getGenericReturnType() - { - String sig = getSignature(); - if (sig == null) - return getReturnType(); - MethodSignatureParser p = new MethodSignatureParser(this, sig); - return p.getGenericReturnType(); - } - /** - * @see java.lang.reflect.AnnotatedElement#getAnnotation(java.lang.Class) - */ - public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { - if(annotationClass.getName().equals(org.jnode.vm.annotation.AllowedPackages.class.getName())) { - return vmMethod.getAnnotation(annotationClass); - } else { - return _getAnnotation(annotationClass); - } - } - - //jnode openjdk - public MethodAccessor getMethodAccessor() { - //todo implement it - throw new UnsupportedOperationException(); - } - - public void setMethodAccessor(MethodAccessor accessor) { - //todo implement it - throw new UnsupportedOperationException(); - } - - public Method copy() { - //todo implement it - throw new UnsupportedOperationException(); - } - - private transient Map<Class, Annotation> declaredAnnotations; - private byte[] annotations; - private byte[] parameterAnnotations; - private byte[] annotationDefault; - - private synchronized Map<Class, Annotation> declaredAnnotations() { - - if (declaredAnnotations == null) { - declaredAnnotations = AnnotationParser.parseAnnotations(annotations, - SharedSecrets.getJavaLangAccess().getConstantPool(getDeclaringClass()), getDeclaringClass()); - } - - return declaredAnnotations; - } - - /** - * If this method is an annotation method, returns the default - * value for the method. If there is no default value, or if the - * method is not a member of an annotation type, returns null. - * Primitive types are wrapped. - * - * @throws TypeNotPresentException if the method returns a Class, - * and the class cannot be found - * - * @since 1.5 - */ - public Object getDefaultValue() { - if (annotationDefault == null) - return null; - - Class memberType = AnnotationType.invocationHandlerReturnType(getReturnType()); - - Object result = AnnotationParser.parseMemberValue(memberType, ByteBuffer.wrap(annotationDefault), - SharedSecrets.getJavaLangAccess().getConstantPool(getDeclaringClass()), getDeclaringClass()); - - if (result instanceof sun.reflect.annotation.ExceptionProxy) - throw new AnnotationFormatError("Invalid default: " + this); - - return result; - } - - /** - * @throws NullPointerException {@inheritDoc} - * @since 1.5 - */ - public <T extends Annotation> T _getAnnotation(Class<T> annotationClass) { - if (annotationClass == null) - throw new NullPointerException(); - - return (T) declaredAnnotations().get(annotationClass); - } - - /** - * @since 1.5 - */ - public Annotation[] getDeclaredAnnotations() { - return declaredAnnotations().values().toArray(EMPTY_ANNOTATION_ARRAY); - } - - private static final Annotation[] EMPTY_ANNOTATION_ARRAY=new Annotation[0]; - - /** - * Returns an array of arrays that represent the annotations on the formal - * parameters, in declaration order, of the method represented by - * this <tt>Method</tt> object. (Returns an array of length zero if the - * underlying method is parameterless. If the method has one or more - * parameters, a nested array of length zero is returned for each parameter - * with no annotations.) The annotation objects contained in the returned - * arrays are serializable. The caller of this method is free to modify - * the returned arrays; it will have no effect on the arrays returned to - * other callers. - * - * @return an array of arrays that represent the annotations on the formal - * parameters, in declaration order, of the method represented by this - * Method object - * @since 1.5 - */ - public Annotation[][] getParameterAnnotations() { - - int numParameters = vmMethod.getNoArguments(); - - if (parameterAnnotations == null) - return new Annotation[numParameters][0]; - - Annotation[][] result = AnnotationParser.parseParameterAnnotations(parameterAnnotations, - SharedSecrets.getJavaLangAccess().getConstantPool(getDeclaringClass()), getDeclaringClass()); - - if (result.length != numParameters) - throw new AnnotationFormatError("Parameter annotations don't match number of parameters"); - - return result; - } - - static <X extends GenericDeclaration> - void addTypeParameters(StringBuilder sb, TypeVariable<X>[] typeArgs) - { - if (typeArgs.length == 0) - return; - sb.append('<'); - for (int i = 0; i < typeArgs.length; ++i) - { - if (i > 0) - sb.append(','); - sb.append(typeArgs[i]); - } - sb.append("> "); - } -} Modified: trunk/core/src/core/org/jnode/vm/classmgr/VmMethod.java =================================================================== --- trunk/core/src/core/org/jnode/vm/classmgr/VmMethod.java 2008-12-17 13:58:56 UTC (rev 4793) +++ trunk/core/src/core/org/jnode/vm/classmgr/VmMethod.java 2008-12-18 18:34:56 UTC (rev 4794) @@ -193,44 +193,46 @@ } Member javaMember = javaMemberHolder.get(); if (javaMember == null) { - if (isConstructor()) { - //parameter types - int arg_count = getNoArguments(); - Class[] args = new Class[arg_count]; - for (int i = 0; i < arg_count; i++) { - args[i] = getArgumentType(i).asClass(); + //parameter types + int arg_count = getNoArguments(); + Class[] args = new Class[arg_count]; + for (int i = 0; i < arg_count; i++) { + args[i] = getArgumentType(i).asClass(); + } + //checked exceptions + final VmExceptions exceptions = getExceptions(); + int ce_count = exceptions.getLength(); + final Class[] ces = new Class[ce_count]; + for (int i = 0; i < ce_count; i++) { + VmConstClass vmConstClass = exceptions.getException(i); + if (!vmConstClass.isResolved()) { + vmConstClass.doResolve(getDeclaringClass().getLoader()); } - - //checked exceptions - final VmExceptions exceptions = getExceptions(); - int ce_count = exceptions.getLength(); - final Class[] ces = new Class[ce_count]; - for (int i = 0; i < ce_count; i++) { - VmConstClass vmConstClass = exceptions.getException(i); - if (!vmConstClass.isResolved()) { - vmConstClass.doResolve(getDeclaringClass().getLoader()); - } - ces[i] = vmConstClass.getResolvedVmClass().asClass(); + ces[i] = vmConstClass.getResolvedVmClass().asClass(); + } + //slot + VmType decl_type = getDeclaringClass(); + int slot = -1; + for (int i = 0; i < decl_type.getNoDeclaredMethods(); i++) { + if (this == decl_type.getDeclaredMethod(i)) { + slot = i; + break; } + } - //slot - VmType decl_type = getDeclaringClass(); - int slot = -1; - for (int i = 0; i < decl_type.getNoDeclaredMethods(); i++) { - if (this == decl_type.getDeclaredMethod(i)) { - slot = i; - break; - } - } - + if (isConstructor()) { if (slot == -1) { throw new ClassFormatError("Invalid constructor"); } - javaMember = new Constructor(getDeclaringClass().asClass(), args, ces, getModifiers(), slot, getSignature(), getRawAnnotations(), getRawParameterAnnotations()); } else { - javaMember = new Method(this); + if (slot == -1) { + throw new ClassFormatError("Invalid method"); + } + javaMember = new Method(getDeclaringClass().asClass(), getName(), args, getReturnType().asClass(), ces, + getModifiers(), slot, getSignature(), getRawAnnotations(), getRawParameterAnnotations(), + getRawAnnotationDefault()); } javaMemberHolder.set(javaMember); } Modified: trunk/core/src/core/org/jnode/vm/isolate/VmIsolate.java =================================================================== --- trunk/core/src/core/org/jnode/vm/isolate/VmIsolate.java 2008-12-17 13:58:56 UTC (rev 4793) +++ trunk/core/src/core/org/jnode/vm/isolate/VmIsolate.java 2008-12-18 18:34:56 UTC (rev 4794) @@ -981,6 +981,7 @@ //add to parent this.creator.addChild(this); + mainMethod.setAccessible(true); // Run main method. mainMethod.invoke(null, new Object[]{args}); } catch (Throwable ex) { Added: trunk/core/src/openjdk/java/java/lang/reflect/Method.java =================================================================== --- trunk/core/src/openjdk/java/java/lang/reflect/Method.java (rev 0) +++ trunk/core/src/openjdk/java/java/lang/reflect/Method.java 2008-12-18 18:34:56 UTC (rev 4794) @@ -0,0 +1,788 @@ +/* + * Copyright 1996-2006 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code 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 General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package java.lang.reflect; + +import sun.reflect.MethodAccessor; +import sun.reflect.Reflection; +import sun.reflect.generics.repository.MethodRepository; +import sun.reflect.generics.factory.CoreReflectionFactory; +import sun.reflect.generics.factory.GenericsFactory; +import sun.reflect.generics.scope.MethodScope; +import sun.reflect.annotation.AnnotationType; +import sun.reflect.annotation.AnnotationParser; +import java.lang.annotation.Annotation; +import java.lang.annotation.AnnotationFormatError; +import java.nio.ByteBuffer; +import java.util.Map; + +/** + * A {@code Method} provides information about, and access to, a single method + * on a class or interface. The reflected method may be a class method + * or an instance method (including an abstract method). + * + * <p>A {@code Method} permits widening conversions to occur when matching the + * actual parameters to invoke with the underlying method's formal + * parameters, but it throws an {@code IllegalArgumentException} if a + * narrowing conversion would occur. + * + * @see Member + * @see java.lang.Class + * @see java.lang.Class#getMethods() + * @see java.lang.Class#getMethod(String, Class[]) + * @see java.lang.Class#getDeclaredMethods() + * @see java.lang.Class#getDeclaredMethod(String, Class[]) + * + * @author Kenneth Russell + * @author Nakul Saraiya + */ +public final + class Method extends AccessibleObject implements GenericDeclaration, + Member { + private Class clazz; + private int slot; + // This is guaranteed to be interned by the VM in the 1.4 + // reflection implementation + private String name; + private Class returnType; + private Class[] parameterTypes; + private Class[] exceptionTypes; + private int modifiers; + // Generics and annotations support + private transient String signature; + // generic info repository; lazily initialized + private transient MethodRepository genericInfo; + private byte[] annotations; + private byte[] parameterAnnotations; + private byte[] annotationDefault; + private volatile MethodAccessor methodAccessor; + // For sharing of MethodAccessors. This branching structure is + // currently only two levels deep (i.e., one root Method and + // potentially many Method objects pointing to it.) + private Method root; + + // More complicated security check cache needed here than for + // Class.newInstance() and Constructor.newInstance() + private Class securityCheckCache; + private Class securityCheckTargetClassCache; + + // Modifiers that can be applied to a method in source code + private static final int LANGUAGE_MODIFIERS = + Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE | + Modifier.ABSTRACT | Modifier.STATIC | Modifier.FINAL | + Modifier.SYNCHRONIZED | Modifier.NATIVE; + + // Generics infrastructure + + private String getGenericSignature() {return signature;} + + // Accessor for factory + private GenericsFactory getFactory() { + // create scope and factory + return CoreReflectionFactory.make(this, MethodScope.make(this)); + } + + // Accessor for generic info repository + private MethodRepository getGenericInfo() { + // lazily initialize repository if necessary + if (genericInfo == null) { + // create and cache generic info repository + genericInfo = MethodRepository.make(getGenericSignature(), + getFactory()); + } + return genericInfo; //return cached repository + } + + //jnode + /** + * Package-private constructor used by ReflectAccess to enable + * instantiation of these objects in Java code from the java.lang + * package via sun.reflect.LangReflectAccess. + */ + public Method(Class declaringClass, + String name, + Class[] parameterTypes, + Class returnType, + Class[] checkedExceptions, + int modifiers, + int slot, + String signature, + byte[] annotations, + byte[] parameterAnnotations, + byte[] annotationDefault) + { + this.clazz = declaringClass; + this.name = name; + this.parameterTypes = parameterTypes; + this.returnType = returnType; + this.exceptionTypes = checkedExceptions; + this.modifiers = modifiers; + this.slot = slot; + this.signature = signature; + this.annotations = annotations; + this.parameterAnnotations = parameterAnnotations; + this.annotationDefault = annotationDefault; + } + + /** + * Package-private routine (exposed to java.lang.Class via + * ReflectAccess) which returns a copy of this Method. The copy's + * "root" field points to this Method. + */ + Method copy() { + // This routine enables sharing of MethodAccessor objects + // among Method objects which refer to the same underlying + // method in the VM. (All of this contortion is only necessary + // because of the "accessibility" bit in AccessibleObject, + // which implicitly requires that new java.lang.reflect + // objects be fabricated for each reflective call on Class + // objects.) + Method res = new Method(clazz, name, parameterTypes, returnType, + exceptionTypes, modifiers, slot, signature, + annotations, parameterAnnotations, annotationDefault); + res.root = this; + // Might as well eagerly propagate this if already present + res.methodAccessor = methodAccessor; + return res; + } + + /** + * Returns the {@code Class} object representing the class or interface + * that declares the method represented by this {@code Method} object. + */ + public Class<?> getDeclaringClass() { + return clazz; + } + + /** + * Returns the name of the method represented by this {@code Method} + * object, as a {@code String}. + */ + public String getName() { + return name; + } + + /** + * Returns the Java language modifiers for the method represented + * by this {@code Method} object, as an integer. The {@code Modifier} class should + * be used to decode the modifiers. + * + * @see Modifier + */ + public int getModifiers() { + return modifiers; + } + + /** + * Returns an array of {@code TypeVariable} objects that represent the + * type variables declared by the generic declaration represented by this + * {@code GenericDeclaration} object, in declaration order. Returns an + * array of length 0 if the underlying generic declaration declares no type + * variables. + * + * @return an array of {@code TypeVariable} objects that represent + * the type variables declared by this generic declaration + * @throws GenericSignatureFormatError if the generic + * signature of this generic declaration does not conform to + * the format specified in the Java Virtual Machine Specification, + * 3rd edition + * @since 1.5 + */ + public TypeVariable<Method>[] getTypeParameters() { + if (getGenericSignature() != null) + return (TypeVariable<Method>[])getGenericInfo().getTypeParameters(); + else + return (TypeVariable<Method>[])new TypeVariable[0]; + } + + /** + * Returns a {@code Class} object that represents the formal return type + * of the method represented by this {@code Method} object. + * + * @return the return type for the method this object represents + */ + public Class<?> getReturnType() { + return returnType; + } + + /** + * Returns a {@code Type} object that represents the formal return + * type of the method represented by this {@code Method} object. + * + * <p>If the return type is a parameterized type, + * the {@code Type} object returned must accurately reflect + * the actual type parameters used in the source code. + * + * <p>If the return type is a type variable or a parameterized type, it + * is created. Otherwise, it is resolved. + * + * @return a {@code Type} object that represents the formal return + * type of the underlying method + * @throws GenericSignatureFormatError + * if the generic method signature does not conform to the format + * specified in the Java Virtual Machine Specification, 3rd edition + * @throws TypeNotPresentException if the underlying method's + * return type refers to a non-existent type declaration + * @throws MalformedParameterizedTypeException if the + * underlying method's return typed refers to a parameterized + * type that cannot be instantiated for any reason + * @since 1.5 + */ + public Type getGenericReturnType() { + if (getGenericSignature() != null) { + return getGenericInfo().getReturnType(); + } else { return getReturnType();} + } + + + /** + * Returns an array of {@code Class} objects that represent the formal + * parameter types, in declaration order, of the method + * represented by this {@code Method} object. Returns an array of length + * 0 if the underlying method takes no parameters. + * + * @return the parameter types for the method this object + * represents + */ + public Class<?>[] getParameterTypes() { + return (Class<?>[]) parameterTypes.clone(); + } + + /** + * Returns an array of {@code Type} objects that represent the formal + * parameter types, in declaration order, of the method represented by + * this {@code Method} object. Returns an array of length 0 if the + * underlying method takes no parameters. + * + * <p>If a formal parameter type is a parameterized type, + * the {@code Type} object returned for it must accurately reflect + * the actual type parameters used in the source code. + * + * <p>If a formal parameter type is a type variable or a parameterized + * type, it is created. Otherwise, it is resolved. + * + * @return an array of Types that represent the formal + * parameter types of the underlying method, in declaration order + * @throws GenericSignatureFormatError + * if the generic method signature does not conform to the format + * specified in the Java Virtual Machine Specification, 3rd edition + * @throws TypeNotPresentException if any of the parameter + * types of the underlying method refers to a non-existent type + * declaration + * @throws MalformedParameterizedTypeException if any of + * the underlying method's parameter types refer to a parameterized + * type that cannot be instantiated for any reason + * @since 1.5 + */ + public Type[] getGenericParameterTypes() { + if (getGenericSignature() != null) + return getGenericInfo().getParameterTypes(); + else + return getParameterTypes(); + } + + + /** + * Returns an array of {@code Class} objects that represent + * the types of the exceptions declared to be thrown + * by the underlying method + * represented by this {@code Method} object. Returns an array of length + * 0 if the method declares no exceptions in its {@code throws} clause. + * + * @return the exception types declared as being thrown by the + * method this object represents + */ + public Class<?>[] getExceptionTypes() { + return (Class<?>[]) exceptionTypes.clone(); + } + + /** + * Returns an array of {@code Type} objects that represent the + * exceptions declared to be thrown by this {@code Method} object. + * Returns an array of length 0 if the underlying method declares + * no exceptions in its {@code throws} clause. + * + * <p>If an exception type is a parameterized type, the {@code Type} + * object returned for it must accurately reflect the actual type + * parameters used in the source code. + * + * <p>If an exception type is a type variable or a parameterized + * type, it is created. Otherwise, it is resolved. + * + * @return an array of Types that represent the exception types + * thrown by the underlying method + * @throws GenericSignatureFormatError + * if the generic method signature does not conform to the format + * specified in the Java Virtual Machine Specification, 3rd edition + * @throws TypeNotPresentException if the underlying method's + * {@code throws} clause refers to a non-existent type declaration + * @throws MalformedParameterizedTypeException if + * the underlying method's {@code throws} clause refers to a + * parameterized type that cannot be instantiated for any reason + * @since 1.5 + */ + public Type[] getGenericExceptionTypes() { + Type[] result; + if (getGenericSignature() != null && + ((result = getGenericInfo().getExceptionTypes()).length > 0)) + return result; + else + return getExceptionTypes(); + } + + /** + * Compares this {@code Method} against the specified object. Returns + * true if the objects are the same. Two {@code Methods} are the same if + * they were declared by the same class and have the same name + * and formal parameter types and return type. + */ + public boolean equals(Object obj) { + if (obj != null && obj instanceof Method) { + Method other = (Method)obj; + if ((getDeclaringClass() == other.getDeclaringClass()) + && (getName() == other.getName())) { + if (!returnType.equals(other.getReturnType())) + return false; + /* Avoid unnecessary cloning */ + Class[] params1 = parameterTypes; + Class[] params2 = other.parameterTypes; + if (params1.length == params2.length) { + for (int i = 0; i < params1.length; i++) { + if (params1[i] != params2[i]) + return false; + } + return true; + } + } + } + return false; + } + + /** + * Returns a hashcode for this {@code Method}. The hashcode is computed + * as the exclusive-or of the hashcodes for the underlying + * method's declaring class name and the method's name. + */ + public int hashCode() { + return getDeclaringClass().getName().hashCode() ^ getName().hashCode(); + } + + /** + * Returns a string describing this {@code Method}. The string is + * formatted as the method access modifiers, if any, followed by + * the method return type, followed by a space, followed by the + * class declaring the method, followed by a period, followed by + * the method name, followed by a parenthesized, comma-separated + * list of the method's formal parameter types. If the method + * throws checked exceptions, the parameter list is followed by a + * space, followed by the word throws followed by a + * comma-separated list of the thrown exception types. + * For example: + * <pre> + * public boolean java.lang.Object.equals(java.lang.Object) + * </pre> + * + * <p>The access modifiers are placed in canonical order as + * specified by "The Java Language Specification". This is + * {@code public}, {@code protected} or {@code private} first, + * and then other modifiers in the following order: + * {@code abstract}, {@code static}, {@code final}, + * {@code synchronized}, {@code native}. + */ + public String toString() { + try { + StringBuffer sb = new StringBuffer(); + int mod = getModifiers() & LANGUAGE_MODIFIERS; + if (mod != 0) { + sb.append(Modifier.toString(mod) + " "); + } + sb.append(Field.getTypeName(getReturnType()) + " "); + sb.append(Field.getTypeName(getDeclaringClass()) + "."); + sb.append(getName() + "("); + Class[] params = parameterTypes; // avoid clone + for (int j = 0; j < params.length; j++) { + sb.append(Field.getTypeName(params[j])); + if (j < (params.length - 1)) + sb.append(","); + } + sb.append(")"); + Class[] exceptions = exceptionTypes; // avoid clone + if (exceptions.length > 0) { + sb.append(" throws "); + for (int k = 0; k < exceptions.length; k++) { + sb.append(exceptions[k].getName()); + if (k < (exceptions.length - 1)) + sb.append(","); + } + } + return sb.toString(); + } catch (Exception e) { + return "<" + e + ">"; + } + } + + /** + * Returns a string describing this {@code Method}, including + * type parameters. The string is formatted as the method access + * modifiers, if any, followed by an angle-bracketed + * comma-separated list of the method's type parameters, if any, + * followed by the method's generic return type, followed by a + * space, followed by the class declaring the method, followed by + * a period, followed by the method name, followed by a + * parenthesized, comma-separated list of the method's generic + * formal parameter types. + * + * A space is used to separate access modifiers from one another + * and from the type parameters or return type. If there are no + * type parameters, the type parameter list is elided; if the type + * parameter list is present, a space separates the list from the + * class name. If the method is declared to throw exceptions, the + * parameter list is followed by a space, followed by the word + * throws followed by a comma-separated list of the generic thrown + * exception types. If there are no type parameters, the type + * parameter list is elided. + * + * <p>The access modifiers are placed in canonical order as + * specified by "The Java Language Specification". This is + * {@code public}, {@code protected} or {@code private} first, + * and then other modifiers in the following order: + * {@code abstract}, {@code static}, {@code final}, + * {@code synchronized} {@code native}. + * + * @return a string describing this {@code Method}, + * include type parameters + * + * @since 1.5 + */ + public String toGenericString() { + try { + StringBuilder sb = new StringBuilder(); + int mod = getModifiers() & LANGUAGE_MODIFIERS; + if (mod != 0) { + sb.append(Modifier.toString(mod) + " "); + } + TypeVariable<?>[] typeparms = getTypeParameters(); + if (typeparms.length > 0) { + boolean first = true; + sb.append("<"); + for(TypeVariable<?> typeparm: typeparms) { + if (!first) + sb.append(","); + // Class objects can't occur here; no need to test + // and call Class.getName(). + sb.append(typeparm.toString()); + first = false; + } + sb.append("> "); + } + + Type genRetType = getGenericReturnType(); + sb.append( ((genRetType instanceof Class<?>)? + Field.getTypeName((Class<?>)genRetType):genRetType.toString()) + " "); + + sb.append(Field.getTypeName(getDeclaringClass()) + "."); + sb.append(getName() + "("); + Type[] params = getGenericParameterTypes(); + for (int j = 0; j < params.length; j++) { + String param = (params[j] instanceof Class)? + Field.getTypeName((Class)params[j]): + (params[j].toString()); + sb.append(param); + if (j < (params.length - 1)) + sb.append(","); + } + sb.append(")"); + Type[] exceptions = getGenericExceptionTypes(); + if (exceptions.length > 0) { + sb.append(" throws "); + for (int k = 0; k < exceptions.length; k++) { + sb.append((exceptions[k] instanceof Class)? + ((Class)exceptions[k]).getName(): + exceptions[k].toString()); + if (k < (exceptions.length - 1)) + sb.append(","); + } + } + return sb.toString(); + } catch (Exception e) { + return "<" + e + ">"; + } + } + + /** + * Invokes the underlying method represented by this {@code Method} + * object, on the specified object with the specified parameters. + * Individual parameters are automatically unwrapped to match + * primitive formal parameters, and both primitive and reference + * parameters are subject to method invocation conversions as + * necessary. + * + * <p>If the underlying method is static, then the specified {@code obj} + * argument is ignored. It may be null. + * + * <p>If the number of formal parameters required by the underlying method is + * 0, the supplied {@code args} array may be of length 0 or null. + * + * <p>If the underlying method is an instance method, it is invoked + * using dynamic method lookup as documented in The Java Language + * Specification, Second Edition, section 15.12.4.4; in particular, + * overriding based on the runtime type of the target object will occur. + * + * <p>If the underlying method is static, the class that declared + * the method is initialized if it has not already been initialized. + * + * <p>If the method completes normally, the value it returns is + * returned to the caller of invoke; if the value has a primitive + * type, it is first appropriately wrapped in an object. However, + * if the value has the type of an array of a primitive type, the + * elements of the array are <i>not</i> wrapped in objects; in + * other words, an array of primitive type is returned. If the + * underlying method return type is void, the invocation returns + * null. + * + * @param obj the object the underlying method is invoked from + * @param args the arguments used for the method call + * @return the result of dispatching the method represented by + * this object on {@code obj} with parameters + * {@code args} + * + * @exception IllegalAccessException if this {@code Method} object + * enforces Java language access control and the underlying + * method is inaccessible. + * @exception IllegalArgumentException if the method is an + * instance method and the specified object argument + * is not an instance of the class or interface + * declaring the underlying method (or of a subclass + * or implementor thereof); if the number of actual + * and formal parameters differ; if an unwrapping + * conversion for primitive arguments fails; or if, + * after possible unwrapping, a parameter value + * cannot be converted to the corresponding formal + * parameter type by a method invocation conversion. + * @exception InvocationTargetException if the underlying method + * throws an exception. + * @exception NullPointerException if the specified object is null + * and the method is an instance method. + * @exception ExceptionInInitializerError if the initialization + * provoked by this method fails. + */ + public Object invoke(Object obj, Object... args) + throws IllegalAccessException, IllegalArgumentException, + InvocationTargetException + { + if (!override) { + if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) { + Class caller = Reflection.getCallerClass(1); + Class targetClass = ((obj == null || !Modifier.isProtected(modifiers)) + ? clazz + : obj.getClass()); + + boolean cached; + synchronized (this) { + cached = (securityCheckCache == caller) + && (securityCheckTargetClassCache == targetClass); + } + if (!cached) { + Reflection.ensureMemberAccess(caller, clazz, obj, modifiers); + synchronized (this) { + securityCheckCache = caller; + securityCheckTargetClassCache = targetClass; + } + } + } + } + if (methodAccessor == null) acquireMethodAccessor(); + return methodAccessor.invoke(obj, args); + } + + /** + * Returns {@code true} if this method is a bridge + * method; returns {@code false} otherwise. + * + * @return true if and only if this method is a bridge + * method as defined by the Java Language Specification. + * @since 1.5 + */ + public boolean isBridge() { + return (getModifiers() & Modifier.BRIDGE) != 0; + } + + /** + * Returns {@code true} if this method was declared to take + * a variable number of arguments; returns {@code false} + * otherwise. + * + * @return {@code true} if an only if this method was declared to + * take a variable number of arguments. + * @since 1.5 + */ + public boolean isVarArgs() { + return (getModifiers() & Modifier.VARARGS) != 0; + } + + /** + * Returns {@code true} if this method is a synthetic + * method; returns {@code false} otherwise. + * + * @return true if and only if this method is a synthetic + * method as defined by the Java Language Specification. + * @since 1.5 + */ + public boolean isSynthetic() { + return Modifier.isSynthetic(getModifiers()); + } + + // NOTE that there is no synchronization used here. It is correct + // (though not efficient) to generate more than one MethodAccessor + // for a given Method. However, avoiding synchronization will + // probably make the implementation more scalable. + private void acquireMethodAccessor() { + // First check to see if one has been created yet, and take it + // if so + MethodAccessor tmp = null; + if (root != null) tmp = root.getMethodAccessor(); + if (tmp != null) { + methodAccessor = tmp; + return; + } + // Otherwise fabricate one and propagate it up to the root + tmp = reflectionFactory.newMethodAccessor(this); + setMethodAccessor(tmp); + } + + // Returns MethodAccessor for this Method object, not looking up + // the chain to the root + MethodAccessor getMethodAccessor() { + return methodAccessor; + } + + // Sets the MethodAcce... [truncated message content] |
From: <ls...@us...> - 2008-12-21 13:21:52
|
Revision: 4802 http://jnode.svn.sourceforge.net/jnode/?rev=4802&view=rev Author: lsantha Date: 2008-12-21 13:21:42 +0000 (Sun, 21 Dec 2008) Log Message: ----------- Class.getVmClass() refactored to VmType.fromClass(). Modified Paths: -------------- trunk/core/src/classpath/vm/gnu/classpath/jdwp/NativeVMVirtualMachine.java trunk/core/src/classpath/vm/java/lang/Class.java trunk/core/src/classpath/vm/java/lang/reflect/VMArray.java trunk/core/src/core/org/jnode/naming/DefaultNameSpace.java trunk/core/src/core/org/jnode/vm/SoftByteCodes.java trunk/core/src/core/org/jnode/vm/VmJavaClassLoader.java trunk/core/src/core/org/jnode/vm/VmReflection.java trunk/core/src/core/org/jnode/vm/VmSystem.java trunk/core/src/core/org/jnode/vm/VmSystemClassLoader.java trunk/core/src/core/org/jnode/vm/classmgr/ClassDecoder.java trunk/core/src/core/org/jnode/vm/classmgr/VmAnnotatedElement.java trunk/core/src/core/org/jnode/vm/classmgr/VmType.java trunk/core/src/core/org/jnode/vm/memmgr/def/HeapStatisticsVisitor.java trunk/core/src/openjdk/vm/java/io/NativeObjectStreamClass.java trunk/core/src/openjdk/vm/java/lang/NativeThrowable.java trunk/core/src/openjdk/vm/sun/misc/NativeUnsafe.java trunk/core/src/openjdk/vm/sun/reflect/NativeNativeConstructorAccessorImpl.java trunk/core/src/openjdk/vm/sun/reflect/NativeNativeMethodAccessorImpl.java trunk/core/src/openjdk/vm/sun/reflect/NativeReflection.java trunk/core/src/test/org/jnode/test/ViewMethodTest.java trunk/shell/src/shell/org/jnode/shell/command/ClassCommand.java trunk/shell/src/shell/org/jnode/shell/command/CompileCommand.java trunk/shell/src/shell/org/jnode/shell/command/DisassembleCommand.java Modified: trunk/core/src/classpath/vm/gnu/classpath/jdwp/NativeVMVirtualMachine.java =================================================================== --- trunk/core/src/classpath/vm/gnu/classpath/jdwp/NativeVMVirtualMachine.java 2008-12-21 12:27:12 UTC (rev 4801) +++ trunk/core/src/classpath/vm/gnu/classpath/jdwp/NativeVMVirtualMachine.java 2008-12-21 13:21:42 UTC (rev 4802) @@ -4,11 +4,8 @@ import java.util.ArrayList; import java.nio.ByteBuffer; import java.lang.reflect.Method; -import java.io.DataOutputStream; import gnu.classpath.jdwp.util.MethodResult; import gnu.classpath.jdwp.event.EventRequest; -import gnu.classpath.jdwp.exception.JdwpException; -import gnu.classpath.jdwp.id.ReferenceTypeId; import org.jnode.vm.Vm; import org.jnode.vm.isolate.VmIsolate; import org.jnode.vm.classmgr.VmIsolatedStatics; @@ -167,10 +164,10 @@ } public static void redefineClass(Class oldClass, byte[] classData){ - VmType old_type = oldClass.getVmClass(); + VmType old_type = VmType.fromClass(oldClass); VmType new_type = ClassDecoder.defineClass(oldClass.getName(), ByteBuffer.wrap(classData), false, - oldClass.getVmClass().getLoader(), + VmType.fromClass(oldClass).getLoader(), oldClass.getProtectionDomain()); for(int i = 0; i < old_type.getNoDeclaredMethods(); i++){ VmMethod old_method = old_type.getDeclaredMethod(i); Modified: trunk/core/src/classpath/vm/java/lang/Class.java =================================================================== --- trunk/core/src/classpath/vm/java/lang/Class.java 2008-12-21 12:27:12 UTC (rev 4801) +++ trunk/core/src/classpath/vm/java/lang/Class.java 2008-12-21 13:21:42 UTC (rev 4802) @@ -114,12 +114,6 @@ */ private static final long serialVersionUID = 3206093459760846163L; - /** - * Permission used in {@link #getVmClass()} - */ - private static final JNodePermission GETVMCLASS = new JNodePermission( - "getVmClass"); - private final VmType<T> vmClass; private Constructor[] declaredConstructors; @@ -1050,22 +1044,6 @@ } /** - * Gets the JNode VmType (internal) representation of this class. If there - * is a security manager installed, this method first calls the security - * manager's checkPermission method with a RuntimePermission("getVmClass") - * permission to ensure it's ok to get the internal representation. - * - * @return the JNode internal representation of this class. - */ - public final VmType<T> getVmClass() { - final SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(GETVMCLASS); - } - return vmClass; - } - - /** * Gets a primitive class of a given type. * * @param type Modified: trunk/core/src/classpath/vm/java/lang/reflect/VMArray.java =================================================================== --- trunk/core/src/classpath/vm/java/lang/reflect/VMArray.java 2008-12-21 12:27:12 UTC (rev 4801) +++ trunk/core/src/classpath/vm/java/lang/reflect/VMArray.java 2008-12-21 13:21:42 UTC (rev 4802) @@ -70,7 +70,7 @@ final VmType vmClass = AccessController.doPrivileged( new PrivilegedAction<VmType>() { public VmType run() { - return type.getVmClass(); + return VmType.fromClass(type); } }); Modified: trunk/core/src/core/org/jnode/naming/DefaultNameSpace.java =================================================================== --- trunk/core/src/core/org/jnode/naming/DefaultNameSpace.java 2008-12-21 12:27:12 UTC (rev 4801) +++ trunk/core/src/core/org/jnode/naming/DefaultNameSpace.java 2008-12-21 13:21:42 UTC (rev 4802) @@ -54,10 +54,10 @@ throw new IllegalArgumentException("name == null"); } synchronized (namespace) { - if (namespace.containsKey(name.getVmClass())) { + if (namespace.containsKey(VmType.fromClass(name))) { throw new NameAlreadyBoundException(name.getName()); } - namespace.put(name.getVmClass(), service); + namespace.put(VmType.fromClass(name), service); } // notify listeners @@ -74,7 +74,7 @@ public void unbind(Class<?> name) { final Object service; synchronized (namespace) { - service = namespace.remove(name.getVmClass()); + service = namespace.remove(VmType.fromClass((Class<?>) name)); } // notify listeners @@ -89,7 +89,7 @@ */ @PrivilegedActionPragma public <T> T lookup(Class<T> name) throws NameNotFoundException { - final Object result = namespace.get(name.getVmClass()); + final Object result = namespace.get(VmType.fromClass(name)); if (result == null) { // if (!VmIsolate.isRoot()) { // System.out.println("Looking for " + name.getVmClass().hashCode()); Modified: trunk/core/src/core/org/jnode/vm/SoftByteCodes.java =================================================================== --- trunk/core/src/core/org/jnode/vm/SoftByteCodes.java 2008-12-21 12:27:12 UTC (rev 4801) +++ trunk/core/src/core/org/jnode/vm/SoftByteCodes.java 2008-12-21 13:21:42 UTC (rev 4802) @@ -160,7 +160,7 @@ String cname = classRef.getClassName(); try { Class<?> cls = curLoader.asClassLoader().loadClass(cname); - VmType<?> vmClass = cls.getVmClass(); + VmType<?> vmClass = VmType.fromClass(cls); /* * VmClass vmClass = curLoader.loadClass(cname, true); //VmClass Modified: trunk/core/src/core/org/jnode/vm/VmJavaClassLoader.java =================================================================== --- trunk/core/src/core/org/jnode/vm/VmJavaClassLoader.java 2008-12-21 12:27:12 UTC (rev 4801) +++ trunk/core/src/core/org/jnode/vm/VmJavaClassLoader.java 2008-12-21 13:21:42 UTC (rev 4802) @@ -126,7 +126,7 @@ addLoadedClass(className, cls); } else { final Class<?> javaType = loader.loadClass(className); - cls = javaType.getVmClass(); + cls = VmType.fromClass((Class<?>) javaType); } if (resolve) { cls.link(); Modified: trunk/core/src/core/org/jnode/vm/VmReflection.java =================================================================== --- trunk/core/src/core/org/jnode/vm/VmReflection.java 2008-12-21 12:27:12 UTC (rev 4801) +++ trunk/core/src/core/org/jnode/vm/VmReflection.java 2008-12-21 13:21:42 UTC (rev 4802) @@ -343,7 +343,7 @@ Unsafe.pushObject(o); if (!method.isConstructor()) { - method = o.getClass().getVmClass().getMethod(method.getName(), method.getSignature()); + method = VmType.fromClass(o.getClass()).getMethod(method.getName(), method.getSignature()); } } else { method.getDeclaringClass().initialize(); Modified: trunk/core/src/core/org/jnode/vm/VmSystem.java =================================================================== --- trunk/core/src/core/org/jnode/vm/VmSystem.java 2008-12-21 12:27:12 UTC (rev 4801) +++ trunk/core/src/core/org/jnode/vm/VmSystem.java 2008-12-21 13:21:42 UTC (rev 4802) @@ -180,7 +180,7 @@ //todo this will be moved to java.lang.System during openjdk integration sun.misc.SharedSecrets.setJavaLangAccess(new sun.misc.JavaLangAccess() { public sun.reflect.ConstantPool getConstantPool(Class klass) { - return new VmConstantPool(klass.getVmClass()); + return new VmConstantPool(VmType.fromClass(klass)); } public void setAnnotationType(Class klass, AnnotationType type) { @@ -212,9 +212,15 @@ * @return the system output stream */ public static PrintStream getSystemOut() { + SystemOutputStream sout = null; + if (bootOut == null) { + // initialization trick to avoid circularity and setting bootOut twice + //todo review when migrating java.lang.System to OpenJDK + sout = new SystemOutputStream(); + } if (bootOut == null) { - bootOut = new SystemOutputStream(); + bootOut = sout; bootOutStream = new PrintStream(bootOut, true); IOContext ioContext = getIOContext(); ioContext.setGlobalOutStream(bootOutStream); @@ -1066,7 +1072,7 @@ @PrivilegedActionPragma public static void setStaticField(Class<?> clazz, String fieldName, Object value) { - final VmStaticField f = (VmStaticField) clazz.getVmClass().getField( + final VmStaticField f = (VmStaticField) VmType.fromClass((Class<?>) clazz).getField( fieldName); final Object staticsTable; final Offset offset; Modified: trunk/core/src/core/org/jnode/vm/VmSystemClassLoader.java =================================================================== --- trunk/core/src/core/org/jnode/vm/VmSystemClassLoader.java 2008-12-21 12:27:12 UTC (rev 4801) +++ trunk/core/src/core/org/jnode/vm/VmSystemClassLoader.java 2008-12-21 13:21:42 UTC (rev 4802) @@ -299,7 +299,7 @@ if ((parent != null) && !parent.skipParentLoader(name)) { try { final Class<?> cls = parent.loadClass(name); - return cls.getVmClass(); + return VmType.fromClass((Class<?>) cls); } catch (ClassNotFoundException ex) { // Don't care, try it ourselves. } Modified: trunk/core/src/core/org/jnode/vm/classmgr/ClassDecoder.java =================================================================== --- trunk/core/src/core/org/jnode/vm/classmgr/ClassDecoder.java 2008-12-21 12:27:12 UTC (rev 4801) +++ trunk/core/src/core/org/jnode/vm/classmgr/ClassDecoder.java 2008-12-21 13:21:42 UTC (rev 4802) @@ -991,28 +991,28 @@ if (vtm.isPrimitive()) { switch (vtm.getJvmType()) { case JvmType.BOOLEAN: - vtm = Boolean.class.getVmClass(); + vtm = VmType.fromClass(Boolean.class); break; case JvmType.BYTE: - vtm = Byte.class.getVmClass(); + vtm = VmType.fromClass(Byte.class); break; case JvmType.SHORT: - vtm = Short.class.getVmClass(); + vtm = VmType.fromClass(Short.class); break; case JvmType.CHAR: - vtm = Character.class.getVmClass(); + vtm = VmType.fromClass(Character.class); break; case JvmType.INT: - vtm = Integer.class.getVmClass(); + vtm = VmType.fromClass(Integer.class); break; case JvmType.FLOAT: - vtm = Float.class.getVmClass(); + vtm = VmType.fromClass(Float.class); break; case JvmType.LONG: - vtm = Long.class.getVmClass(); + vtm = VmType.fromClass(Long.class); break; case JvmType.DOUBLE: - vtm = Double.class.getVmClass(); + vtm = VmType.fromClass(Double.class); break; } @@ -1239,28 +1239,28 @@ if (vtm.isPrimitive()) { switch (vtm.getJvmType()) { case JvmType.BOOLEAN: - vtm = Boolean.class.getVmClass(); + vtm = VmType.fromClass(Boolean.class); break; case JvmType.BYTE: - vtm = Byte.class.getVmClass(); + vtm = VmType.fromClass(Byte.class); break; case JvmType.SHORT: - vtm = Short.class.getVmClass(); + vtm = VmType.fromClass(Short.class); break; case JvmType.CHAR: - vtm = Character.class.getVmClass(); + vtm = VmType.fromClass(Character.class); break; case JvmType.INT: - vtm = Integer.class.getVmClass(); + vtm = VmType.fromClass(Integer.class); break; case JvmType.FLOAT: - vtm = Float.class.getVmClass(); + vtm = VmType.fromClass(Float.class); break; case JvmType.LONG: - vtm = Long.class.getVmClass(); + vtm = VmType.fromClass(Long.class); break; case JvmType.DOUBLE: - vtm = Double.class.getVmClass(); + vtm = VmType.fromClass(Double.class); break; } Modified: trunk/core/src/core/org/jnode/vm/classmgr/VmAnnotatedElement.java =================================================================== --- trunk/core/src/core/org/jnode/vm/classmgr/VmAnnotatedElement.java 2008-12-21 12:27:12 UTC (rev 4801) +++ trunk/core/src/core/org/jnode/vm/classmgr/VmAnnotatedElement.java 2008-12-21 13:21:42 UTC (rev 4802) @@ -62,7 +62,7 @@ public final <T extends Annotation> T getAnnotation(Class<T> annotationClass) { if (runtimeAnnotations.length > 0) { final VmClassLoader loader = getLoader(); - final VmType<T> reqType = annotationClass.getVmClass(); + final VmType<T> reqType = VmType.fromClass(annotationClass); for (VmAnnotation ann : runtimeAnnotations) { if (ann.annotationType(loader) == reqType) { try { @@ -133,7 +133,7 @@ Class<? extends Annotation> annotationClass) { if (runtimeAnnotations.length > 0) { final VmClassLoader loader = getLoader(); - final VmType<?> reqType = annotationClass.getVmClass(); + final VmType<?> reqType = VmType.fromClass((Class<? extends Annotation>) annotationClass); for (VmAnnotation ann : runtimeAnnotations) { if (ann.annotationType(loader) == reqType) { return true; Modified: trunk/core/src/core/org/jnode/vm/classmgr/VmType.java =================================================================== --- trunk/core/src/core/org/jnode/vm/classmgr/VmType.java 2008-12-21 12:27:12 UTC (rev 4801) +++ trunk/core/src/core/org/jnode/vm/classmgr/VmType.java 2008-12-21 13:21:42 UTC (rev 4802) @@ -50,7 +50,9 @@ import org.jnode.vm.compiler.CompiledIMT; import org.jnode.vm.compiler.NativeCodeCompiler; import org.jnode.vm.isolate.VmIsolateLocal; +import org.jnode.security.JNodePermission; import org.vmmagic.unboxed.Address; +import org.vmmagic.unboxed.ObjectReference; @SharedStatics @Uninterruptible @@ -223,6 +225,8 @@ private static VmNormalClass VoidClass; + private static VmNormalClass ClassClass; + private static VmArrayClass<boolean[]> BooleanArrayClass; private static VmArrayClass<byte[]> ByteArrayClass; @@ -344,12 +348,14 @@ public static VmType[] initializeForBootImage(VmSystemClassLoader clc) throws ClassNotFoundException { ObjectClass = (VmNormalClass) clc.loadClass("java.lang.Object", false); + ClassClass = (VmNormalClass) clc.loadClass("java.lang.Class", false); CloneableClass = (VmInterfaceClass) clc.loadClass( "java.lang.Cloneable", false); SerializableClass = (VmInterfaceClass) clc.loadClass( "java.io.Serializable", false); ObjectClass.link(); + ClassClass.link(); CloneableClass.link(); SerializableClass.link(); @@ -403,7 +409,7 @@ DoubleArrayClass.link(); ObjectArrayClass.link(); - return new VmType[]{ObjectClass, CloneableClass, SerializableClass, + return new VmType[]{ObjectClass, ClassClass, CloneableClass, SerializableClass, BooleanClass, ByteClass, CharClass, ShortClass, IntClass, FloatClass, LongClass, DoubleClass, VoidClass, BooleanArrayClass, ByteArrayClass, CharArrayClass, @@ -466,6 +472,8 @@ } else { if (name.equals("java.lang.Object")) { ObjectClass = (VmNormalClass) vmClass; + } else if (name.equals("java.lang.Class")) { + ClassClass = (VmNormalClass) vmClass; } else if (name.equals("java.lang.Cloneable")) { CloneableClass = (VmInterfaceClass) vmClass; } else if (name.equals("java.io.Serializable")) { @@ -2418,4 +2426,23 @@ public final int getIsolatedStaticsIndex() { return isolatedStaticsIndex; } + + /** + * Permission used in {@link #fromClass(Class)} + */ + private static final JNodePermission GETVMCLASS = new JNodePermission("getVmClass"); + private static int FIELD_OFFSET = -1; + public static <V> VmType<V> fromClass(Class<V> clazz) { + if (FIELD_OFFSET == -1) { + FIELD_OFFSET = ((VmInstanceField) ClassClass.getDeclaredField("vmClass")).getOffset(); + } + + final SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(GETVMCLASS); + } + + return (VmType<V>) ObjectReference.fromObject(clazz).toAddress().add(FIELD_OFFSET). + loadObjectReference().toObject(); + } } Modified: trunk/core/src/core/org/jnode/vm/memmgr/def/HeapStatisticsVisitor.java =================================================================== --- trunk/core/src/core/org/jnode/vm/memmgr/def/HeapStatisticsVisitor.java 2008-12-21 12:27:12 UTC (rev 4801) +++ trunk/core/src/core/org/jnode/vm/memmgr/def/HeapStatisticsVisitor.java 2008-12-21 13:21:42 UTC (rev 4802) @@ -48,7 +48,7 @@ public final boolean visit(Object object) { int size = 0; if (!heapStatistics.contains(object.getClass().getName())) { - final VmType<?> type = object.getClass().getVmClass(); + final VmType<?> type = VmType.fromClass(object.getClass()); size = (type instanceof VmNormalClass ? ((VmNormalClass<?>) type) .getObjectSize() : 0); } Modified: trunk/core/src/openjdk/vm/java/io/NativeObjectStreamClass.java =================================================================== --- trunk/core/src/openjdk/vm/java/io/NativeObjectStreamClass.java 2008-12-21 12:27:12 UTC (rev 4801) +++ trunk/core/src/openjdk/vm/java/io/NativeObjectStreamClass.java 2008-12-21 13:21:42 UTC (rev 4802) @@ -18,7 +18,7 @@ * @see java.io.ObjectStreamClass#hasStaticInitializer(java.lang.Class) */ private static boolean hasStaticInitializer(Class clazz) { - VmType vmt = clazz.getVmClass(); + VmType vmt = VmType.fromClass(clazz); VmMethod met = vmt.getDeclaredMethod("<clinit>", "()V"); return met != null && met.isStatic(); } Modified: trunk/core/src/openjdk/vm/java/lang/NativeThrowable.java =================================================================== --- trunk/core/src/openjdk/vm/java/lang/NativeThrowable.java 2008-12-21 12:27:12 UTC (rev 4801) +++ trunk/core/src/openjdk/vm/java/lang/NativeThrowable.java 2008-12-21 13:21:42 UTC (rev 4802) @@ -18,7 +18,9 @@ */ @MagicPermission class NativeThrowable { - private static int BACKTRACE_OFFSET = ((VmInstanceField)Throwable.class.getVmClass().getField("backtrace")).getOffset(); + private static int BACKTRACE_OFFSET = ((VmInstanceField) VmType.fromClass(Throwable.class). + getField("backtrace")).getOffset(); + private static synchronized Throwable fillInStackTrace(Throwable instance){ ObjectReference.fromObject(instance).toAddress().add(BACKTRACE_OFFSET). store(ObjectReference.fromObject(VmThread.getStackTrace(VmProcessor.current().getCurrentThread()))); Modified: trunk/core/src/openjdk/vm/sun/misc/NativeUnsafe.java =================================================================== --- trunk/core/src/openjdk/vm/sun/misc/NativeUnsafe.java 2008-12-21 12:27:12 UTC (rev 4801) +++ trunk/core/src/openjdk/vm/sun/misc/NativeUnsafe.java 2008-12-21 13:21:42 UTC (rev 4802) @@ -11,7 +11,6 @@ import java.security.Policy; import java.security.cert.Certificate; import java.util.Map; -import java.util.Hashtable; import java.util.HashMap; import org.vmmagic.unboxed.ObjectReference; import org.vmmagic.unboxed.Address; @@ -416,13 +415,13 @@ } private static VmField getVmField(Field f) { - VmType<?> vmClass = f.getDeclaringClass().getVmClass(); + VmType<?> vmClass = VmType.fromClass((Class<?>) f.getDeclaringClass()); vmClass.link(); return vmClass.getField(f.getName()); } public static void ensureClassInitialized(Unsafe instance, Class c) { - c.getVmClass().initialize(); + VmType.fromClass(c).initialize(); } public static int arrayBaseOffset(Unsafe instance, Class arrayClass) { Modified: trunk/core/src/openjdk/vm/sun/reflect/NativeNativeConstructorAccessorImpl.java =================================================================== --- trunk/core/src/openjdk/vm/sun/reflect/NativeNativeConstructorAccessorImpl.java 2008-12-21 12:27:12 UTC (rev 4801) +++ trunk/core/src/openjdk/vm/sun/reflect/NativeNativeConstructorAccessorImpl.java 2008-12-21 13:21:42 UTC (rev 4802) @@ -16,7 +16,7 @@ private static Object newInstance0(Constructor arg1, Object[] arg2) throws InstantiationException, IllegalArgumentException, InvocationTargetException{ - VmType vmt = arg1.getDeclaringClass().getVmClass(); + VmType vmt = VmType.fromClass(arg1.getDeclaringClass()); VmMethod vmm = vmt.getDeclaredMethod(arg1.getSlot()); try { return VmReflection.newInstance(vmm, arg2); Modified: trunk/core/src/openjdk/vm/sun/reflect/NativeNativeMethodAccessorImpl.java =================================================================== --- trunk/core/src/openjdk/vm/sun/reflect/NativeNativeMethodAccessorImpl.java 2008-12-21 12:27:12 UTC (rev 4801) +++ trunk/core/src/openjdk/vm/sun/reflect/NativeNativeMethodAccessorImpl.java 2008-12-21 13:21:42 UTC (rev 4802) @@ -15,7 +15,7 @@ */ private static Object invoke0(Method arg1, Object arg2, Object[] arg3) throws IllegalArgumentException, InvocationTargetException { - VmType vmt = arg1.getDeclaringClass().getVmClass(); + VmType vmt = VmType.fromClass((Class<?>) arg1.getDeclaringClass()); VmMethod vmm = vmt.getDeclaredMethod(arg1.getSlot()); return VmReflection.invoke(vmm, arg2, arg3); } Modified: trunk/core/src/openjdk/vm/sun/reflect/NativeReflection.java =================================================================== --- trunk/core/src/openjdk/vm/sun/reflect/NativeReflection.java 2008-12-21 12:27:12 UTC (rev 4801) +++ trunk/core/src/openjdk/vm/sun/reflect/NativeReflection.java 2008-12-21 13:21:42 UTC (rev 4802) @@ -4,6 +4,7 @@ package sun.reflect; import org.jnode.vm.VmSystem; +import org.jnode.vm.classmgr.VmType; /** * @see sun.reflect.Reflection @@ -28,7 +29,7 @@ * @see Reflection#getClassAccessFlags(Class) */ static int getClassAccessFlags(Class c) { - return c.getVmClass().getAccessFlags(); + return VmType.fromClass(c).getAccessFlags(); } } Modified: trunk/core/src/test/org/jnode/test/ViewMethodTest.java =================================================================== --- trunk/core/src/test/org/jnode/test/ViewMethodTest.java 2008-12-21 12:27:12 UTC (rev 4801) +++ trunk/core/src/test/org/jnode/test/ViewMethodTest.java 2008-12-21 13:21:42 UTC (rev 4802) @@ -34,7 +34,7 @@ final String mname = (args.length > 1) ? args[1] : null; ClassLoader cl = Thread.currentThread().getContextClassLoader(); - final VmType cls = cl.loadClass(className).getVmClass(); + final VmType cls = VmType.fromClass(cl.loadClass(className)); final int cnt = cls.getNoDeclaredMethods(); for (int i = 0; i < cnt; i++) { Modified: trunk/shell/src/shell/org/jnode/shell/command/ClassCommand.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/command/ClassCommand.java 2008-12-21 12:27:12 UTC (rev 4801) +++ trunk/shell/src/shell/org/jnode/shell/command/ClassCommand.java 2008-12-21 13:21:42 UTC (rev 4802) @@ -67,7 +67,7 @@ final VmType<?> vmType = AccessController.doPrivileged( new PrivilegedAction<VmType<?>>() { public VmType<?> run() { - return type.getVmClass(); + return VmType.fromClass((Class<?>) type); } }); out.println("Name : " + type.getName()); Modified: trunk/shell/src/shell/org/jnode/shell/command/CompileCommand.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/command/CompileCommand.java 2008-12-21 12:27:12 UTC (rev 4801) +++ trunk/shell/src/shell/org/jnode/shell/command/CompileCommand.java 2008-12-21 13:21:42 UTC (rev 4802) @@ -82,7 +82,7 @@ final Class<?> cls; try { cls = cl.loadClass(className); - final VmType<?> type = cls.getVmClass(); + final VmType<?> type = VmType.fromClass((Class<?>) cls); final long start = System.currentTimeMillis(); final int count = type.compileRuntime(level, test); final long end = System.currentTimeMillis(); Modified: trunk/shell/src/shell/org/jnode/shell/command/DisassembleCommand.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/command/DisassembleCommand.java 2008-12-21 12:27:12 UTC (rev 4801) +++ trunk/shell/src/shell/org/jnode/shell/command/DisassembleCommand.java 2008-12-21 13:21:42 UTC (rev 4802) @@ -80,7 +80,7 @@ // not reached return; } - final VmType<?> type = cls.getVmClass(); + final VmType<?> type = VmType.fromClass((Class<?>) cls); if (test) { if (maxTestLevel == -1) { err.println("No test compilers are currently registered"); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2008-12-27 09:17:08
|
Revision: 4808 http://jnode.svn.sourceforge.net/jnode/?rev=4808&view=rev Author: lsantha Date: 2008-12-27 09:16:49 +0000 (Sat, 27 Dec 2008) Log Message: ----------- Integrated java.lang.Class from OpenJDK. Modified Paths: -------------- trunk/builder/src/builder/org/jnode/build/ObjectEmitter.java trunk/core/src/classpath/vm/gnu/classpath/jdwp/NativeVMVirtualMachine.java trunk/core/src/classpath/vm/java/lang/ClassLoader.java trunk/core/src/core/org/jnode/vm/classmgr/ClassDecoder.java trunk/core/src/core/org/jnode/vm/classmgr/VmMember.java trunk/core/src/core/org/jnode/vm/classmgr/VmType.java trunk/core/src/core/org/jnode/vm/isolate/VmIsolate.java trunk/core/src/openjdk/vm/sun/misc/NativeUnsafe.java trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingToolkit.java Added Paths: ----------- trunk/core/src/openjdk/java/java/lang/Class.java trunk/core/src/openjdk/vm/java/lang/NativeClass.java Removed Paths: ------------- trunk/core/src/classpath/vm/java/lang/Class.java Modified: trunk/builder/src/builder/org/jnode/build/ObjectEmitter.java =================================================================== --- trunk/builder/src/builder/org/jnode/build/ObjectEmitter.java 2008-12-27 07:30:02 UTC (rev 4807) +++ trunk/builder/src/builder/org/jnode/build/ObjectEmitter.java 2008-12-27 09:16:49 UTC (rev 4808) @@ -245,6 +245,15 @@ bis.writeObjectRef(null); // annotationType bis.writeObjectRef(null); + + //see the fields of java.lang.Class + bis.writeObjectRef(null); + bis.writeObjectRef(null); + bis.writeObjectRef(null); + bis.writeObjectRef(null); + bis.writeObjectRef(null); + bis.writeObjectRef(null); + bis.writeObjectRef(null); } } catch (ClassNotFoundException ex) { throw new BuildException("emitting object: [" + c + "]", ex); Modified: trunk/core/src/classpath/vm/gnu/classpath/jdwp/NativeVMVirtualMachine.java =================================================================== --- trunk/core/src/classpath/vm/gnu/classpath/jdwp/NativeVMVirtualMachine.java 2008-12-27 07:30:02 UTC (rev 4807) +++ trunk/core/src/classpath/vm/gnu/classpath/jdwp/NativeVMVirtualMachine.java 2008-12-27 09:16:49 UTC (rev 4808) @@ -16,6 +16,8 @@ /** * @see gnu.classpath.jdwp.VMVirtualMachine + * + * @author Levente S\u00e1ntha */ class NativeVMVirtualMachine { /** @@ -66,7 +68,7 @@ } public Object next() { - return new Class(iter.next()); + return iter.next().newClass(); } public void remove() { Deleted: trunk/core/src/classpath/vm/java/lang/Class.java =================================================================== --- trunk/core/src/classpath/vm/java/lang/Class.java 2008-12-27 07:30:02 UTC (rev 4807) +++ trunk/core/src/classpath/vm/java/lang/Class.java 2008-12-27 09:16:49 UTC (rev 4808) @@ -1,1605 +0,0 @@ -/* Class.java -- Representation of a Java class. - Copyright (C) 1998, 1999, 2000, 2002, 2003, 2004, 2005, 2006 - Free Software Foundation - -This file is part of GNU Classpath. - -GNU Classpath is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2, or (at your option) -any later version. - -GNU Classpath 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 -General Public License for more details. - -You should have received a copy of the GNU General Public License -along with GNU Classpath; see the file COPYING. If not, write to the -Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -02110-1301 USA. - -Linking this library statically or dynamically with other modules is -making a combined work based on this library. Thus, the terms and -conditions of the GNU General Public License cover the whole -combination. - -As a special exception, the copyright holders of this library give you -permission to link this library with independent modules to produce an -executable, regardless of the license terms of these independent -modules, and to copy and distribute the resulting executable under -terms of your choice, provided that you also meet, for each linked -independent module, the terms and conditions of the license of that -module. An independent module is a module which is not derived from -or based on this library. If you modify this library, you may extend -this exception to your version of the library, but you are not -obligated to do so. If you do not wish to do so, delete this -exception statement from your version. */ - -package java.lang; - -import gnu.java.lang.VMClassHelper; -import gnu.java.lang.reflect.ClassSignatureParser; - -import java.io.InputStream; -import java.io.Serializable; -import java.lang.annotation.Annotation; -import java.lang.reflect.AnnotatedElement; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.GenericDeclaration; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Member; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.lang.reflect.Type; -import java.lang.reflect.TypeVariable; -import java.net.URL; -import java.security.AllPermission; -import java.security.Permissions; -import java.security.ProtectionDomain; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Enumeration; - -import org.jnode.security.JNodePermission; -import org.jnode.vm.SoftByteCodes; -import org.jnode.vm.VmReflection; -import org.jnode.vm.VmSystem; -import org.jnode.vm.classmgr.Signature; -import org.jnode.vm.classmgr.VmArrayClass; -import org.jnode.vm.classmgr.VmField; -import org.jnode.vm.classmgr.VmMethod; -import org.jnode.vm.classmgr.VmType; -import org.jnode.vm.classmgr.VmClassLoader; -import sun.reflect.annotation.AnnotationType; - -/** - * A Class represents a Java type. There will never be multiple Class - * objects with identical names and ClassLoaders. Primitive types, array - * types, and void also have a Class object. - * - * <p>Arrays with identical type and number of dimensions share the same class. - * The array class ClassLoader is the same as the ClassLoader of the element - * type of the array (which can be null to indicate the bootstrap classloader). - * The name of an array class is <code>[<signature format>;</code>. - * <p> For example, - * String[]'s class is <code>[Ljava.lang.String;</code>. boolean, byte, - * short, char, int, long, float and double have the "type name" of - * Z,B,S,C,I,J,F,D for the purposes of array classes. If it's a - * multidimensioned array, the same principle applies: - * <code>int[][][]</code> == <code>[[[I</code>. - * - * <p>There is no public constructor - Class objects are obtained only through - * the virtual machine, as defined in ClassLoaders. - * - * @serialData Class objects serialize specially: - * <code>TC_CLASS ClassDescriptor</code>. For more serialization information, - * see {@link java.io.ObjectStreamClass}. - * - * @author John Keiser - * @author Eric Blake (eb...@em...) - * @author Tom Tromey (tr...@re...) - * @author Andrew John Hughes (gnu...@me...) - * @since 1.0 - * @see ClassLoader - */ -public final class Class<T> implements AnnotatedElement, Serializable, Type, - GenericDeclaration { - - /** - * Compatible with JDK 1.0+. - */ - private static final long serialVersionUID = 3206093459760846163L; - - private final VmType<T> vmClass; - - private Constructor[] declaredConstructors; - - private Field[] declaredFields; - - private Method[] declaredMethods; - - private ArrayList<Field> fields; - - private ArrayList<Method> methods; - - private ArrayList<Class> interfaces; - - private ArrayList<Constructor> constructors; - - private VmMethod defaultConstructor; - - private String name; - - /** The unknown protection domain. */ - private static ProtectionDomain unknownProtectionDomain; - - /** - * Create a new instance. This constructor can be public, because the - * creation of VmClass instances of already protected. - * - * @param vmClass - */ - public Class(VmType<T> vmClass) { - if (vmClass == null) { - throw new IllegalArgumentException("vmClass cannot be null"); - } - this.vmClass = vmClass; - } - - public static Class forName(String className) throws ClassNotFoundException { - // System.out.println("Class.forName [" + className + "]"); - - return VmSystem.forName(className); - } - - public static Class forName(String className, boolean initialize, - ClassLoader loader) throws ClassNotFoundException { - return (loader == null) ? VmSystem.forName(className) : loader.loadClass(className, initialize); - } - - /** - * Converts this object to its String representation - * - * @see java.lang.Object#toString() - */ - public String toString() { - return (isInterface() ? "interface " : "class ") + getName(); - } - - /** - * Returns the desired assertion status of this class, if it were to be - * initialized at this moment. The class assertion status, if set, is - * returned; the backup is the default package status; then if there is a - * class loader, that default is returned; and finally the system default is - * returned. This method seldom needs calling in user code, but exists for - * compilers to implement the assert statement. Note that there is no - * guarantee that the result of this method matches the class's actual - * assertion status. - * - * @return the desired assertion status - * @see ClassLoader#setClassAssertionStatus(String, boolean) - * @see ClassLoader#setPackageAssertionStatus(String, boolean) - * @see ClassLoader#setDefaultAssertionStatus(boolean) - * @since 1.4 - */ - public boolean desiredAssertionStatus() { - ClassLoader c = getClassLoader(); - Object status; - if (c == null) - return VMClassLoader.defaultAssertionStatus(); - if (c.classAssertionStatus != null) - synchronized (c) { - status = c.classAssertionStatus.get(getName()); - if (status != null) { - return status.equals(Boolean.TRUE); - } - } - else { - if (ClassLoader.StaticData.systemClassAssertionStatus == null) { - throw new Error("systClassAssertionStatus == null"); - } - status = ClassLoader.StaticData.systemClassAssertionStatus - .get(getName()); - if (status != null) { - return status.equals(Boolean.TRUE); - } - } - if (c.packageAssertionStatus != null) - synchronized (c) { - String name = getPackagePortion(getName()); - if ("".equals(name)) - status = c.packageAssertionStatus.get(null); - else - do { - status = c.packageAssertionStatus.get(name); - name = getPackagePortion(name); - } while (!"".equals(name) && status == null); - if (status != null) - return status.equals(Boolean.TRUE); - } - else { - String name = getPackagePortion(getName()); - if ("".equals(name)) - status = ClassLoader.StaticData.systemPackageAssertionStatus - .get(null); - else - do { - status = ClassLoader.StaticData.systemPackageAssertionStatus - .get(name); - name = getPackagePortion(name); - } while (!"".equals(name) && status == null); - if (status != null) - return status.equals(Boolean.TRUE); - } - return c.defaultAssertionStatus; - } - - /** - * Gets the name of this class - * - * @return String - */ - public String getName() { - if (name == null) { - name = vmClass.getName().replace('/', '.'); - } - return name; - } - - /** - * Is this class an interface? - * - * @return boolean - */ - public boolean isInterface() { - return vmClass.isInterface(); - } - - /** - * Gets the Class this class extends, or null if this class is - * <code>java.lang. Object</code> - * - * @return Class - */ - public final Class< ? super T> getSuperclass() { - VmType<T> vmType = getLinkedVmClass(); - - if(vmType.isPrimitive() || vmType.isInterface()) - return null; - - VmType< ? super T> superCls = vmType.getSuperClass(); - if (superCls != null) { - return superCls.asClass(); - } else { - return null; - } - } - - /** - * Gets the signers of this class. - * - * @return - */ - public Object[] getSigners() { - // TODO implement me - return null; - } - - /** - * Determines the interfaces implemented by the class or interface - * represented by this object. - * - * @return Class[] - */ - public final Class[] getInterfaces() { - if (interfaces == null) { - final ArrayList<Class> list = new ArrayList<Class>(); - final VmType<T> vmClass = getLinkedVmClass(); - final int cnt = vmClass.getNoInterfaces(); - for (int i = 0; i < cnt; i++) { - list.add(vmClass.getInterface(i).asClass()); - } - interfaces = list; - } - return (Class[]) interfaces.toArray(new Class[interfaces.size()]); - } - - /** - * Is the given object instanceof this class. - * - * @param object - * @return boolean - */ - public boolean isInstance(Object object) { - return SoftByteCodes.isInstanceof(object, getLinkedVmClass()); - } - - /** - * Discover whether an instance of the Class parameter would be an instance - * of this Class as well. Think of doing - * <code>isInstance(c.newInstance())</code> or even - * <code>c.newInstance() instanceof (this class)</code>. While this - * checks widening conversions for objects, it must be exact for primitive - * types. - * - * @param c - * the class to check - * @return whether an instance of c would be an instance of this class as - * well - * @throws NullPointerException - * if c is null - * @since 1.1 - */ - public boolean isAssignableFrom(Class< ? > c) { - return getLinkedVmClass().isAssignableFrom(c.getLinkedVmClass()); - } - - /** - * Returns the simple name for this class, as used in the source - * code. For normal classes, this is the content returned by - * <code>getName()</code> which follows the last ".". Anonymous - * classes have no name, and so the result of calling this method is - * "". The simple name of an array consists of the simple name of - * its component type, followed by "[]". Thus, an array with the - * component type of an anonymous class has a simple name of simply - * "[]". - * - * @return the simple name for this class. - * @since 1.5 - */ - public String getSimpleName() - { - return getSimpleName(this); - } - - static String getSimpleName(Class klass) { -// if (klass.getVmClass().isArray()){ - // The above involves a security check that is not appropriate in this context. - if (klass.vmClass.isArray()){ - return klass.getComponentType().getSimpleName() + "[]"; - } - String fullName = klass.getName(); - return fullName.substring(fullName.lastIndexOf(".") + 1); - } - /** - * Gets the runtime visible annotations of this class. - */ - public Annotation[] getAnnotations() { - return vmClass.getAnnotations(); - } - - /** - * @see java.lang.reflect.AnnotatedElement#getAnnotation(java.lang.Class) - */ - public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { - return vmClass.getAnnotation(annotationClass); - } - - /** - * @see java.lang.reflect.AnnotatedElement#getDeclaredAnnotations() - */ - public Annotation[] getDeclaredAnnotations() { - return vmClass.getDeclaredAnnotations(); - } - - /** - * @see java.lang.reflect.AnnotatedElement#isAnnotationPresent(java.lang.Class) - */ - public boolean isAnnotationPresent( - Class< ? extends Annotation> annotationClass) { - return vmClass.isAnnotationPresent(annotationClass); - } - - /** - * Gets the classloader used to load this class. - * - * @return ClassLoader - */ - public final ClassLoader getClassLoader() { - VmClassLoader loader = vmClass.getLoader(); - return loader.isSystemClassLoader() ? null : loader.asClassLoader(); - } - - /** - * Create a new instance of this class, using the default constructor - * - * @return Object - * @throws InstantiationException - * @throws IllegalAccessException - */ - public final T newInstance() throws InstantiationException, - IllegalAccessException { - if (defaultConstructor == null) { - defaultConstructor = getLinkedVmClass().getDeclaredMethod("<init>", - "()V"); - } - if (defaultConstructor == null) { - throw new InstantiationException("No default constructor"); - } - try { - return (T)VmReflection.newInstance(defaultConstructor); - } catch (InvocationTargetException ex) { - final InstantiationException ie = new InstantiationException(); - ie.initCause(ex); - throw ie; - } - } - - /** - * Gets the modifiers of this class - * - * @return int - */ - public final int getModifiers() { - return vmClass.getAccessFlags(); - } - - /** - * Gets the field with the given name that is declared in this class or any - * of my super-classes. - * - * @param name - * @return Field - * @throws NoSuchFieldException - * @throws SecurityException - */ - public Field getField(String name) throws NoSuchFieldException, - SecurityException { - VmField f = getLinkedVmClass().getField(name); - if (f != null) { - return f.asField(); - } else { - throw new NoSuchFieldException(name); - } - } - /** - * Gets all fields declared in this class and all of its super-classes. - * - * @return Field[] - */ - public Field[] getFields() - { - //todo enable this: memberAccessCheck(Member.PUBLIC); - return internalGetFields(); - } - - /** - * Like <code>getFields()</code> but without the security checks. - */ - private Field[] internalGetFields() - { - HashSet<Field> set = new HashSet<Field>(); - set.addAll(Arrays.asList(getDeclaredFields(true))); - Class[] interfaces = getInterfaces(); - for (int i = 0; i < interfaces.length; i++) - set.addAll(Arrays.asList(interfaces[i].internalGetFields())); - Class superClass = getSuperclass(); - if (superClass != null) - set.addAll(Arrays.asList(superClass.internalGetFields())); - return set.toArray(new Field[set.size()]); - } - /** - * Gets the field with the given name that is declared in this class. - * - * @param name - * @return Field - * @throws NoSuchFieldException - * @throws SecurityException - */ - public Field getDeclaredField(String name) throws NoSuchFieldException, - SecurityException { - VmField f = getLinkedVmClass().getDeclaredField(name); - if (f != null) { - return f.asField(); - } else { - throw new NoSuchFieldException(name); - } - } - /** - * Gets all fields declared in this class - * - * @return Field[] - */ - public Field[] getDeclaredFields() - { - //todo enable this memberAccessCheck(Member.DECLARED); - return getDeclaredFields(false); - } - - Field[] getDeclaredFields (boolean publicOnly) - { - if (declaredFields == null) { - final VmType<T> vmClass = getLinkedVmClass(); - final int cnt = vmClass.getNoDeclaredFields(); - final ArrayList<Field> fields = new ArrayList<Field>(); - for (int i = 0; i < cnt; i++) { - Field field = vmClass.getDeclaredField(i).asField(); - if(field.getDeclaringClass() == this) {//todo we need this check? - fields.add(field); - } - } - declaredFields = fields.toArray(new Field[fields.size()]); - } - if(publicOnly){ - final ArrayList<Field> fields = new ArrayList<Field>(); - for (Field field : declaredFields) { - if((field.getModifiers() & Modifier.PUBLIC) != 0) { - fields.add(field); - } - } - return fields.toArray(new Field[fields.size()]); - } else { - //todo fials! return Arrays.copyOf(declaredFields, declaredFields.length); - return declaredFields; - } - } - - /** - * Is this class a primitive class? - * - * @return boolean - */ - public boolean isPrimitive() { - return vmClass.isPrimitive(); - } - - /** - * Return the class of my components (if this class is an array) - * - * @return Class - */ - public Class getComponentType() { - final VmType<T> vmClass = getLinkedVmClass(); - if (vmClass instanceof VmArrayClass) { - final VmType< ? > vmCompType = ((VmArrayClass<T>) vmClass) - .getComponentType(); - if (vmCompType != null) { - return vmCompType.asClass(); - } - } - return null; - } - - private static final class MethodKey - { - private String name; - private Class[] params; - private Class returnType; - private int hash; - - MethodKey(Method m) - { - name = m.getName(); - params = m.getParameterTypes(); - returnType = m.getReturnType(); - hash = name.hashCode() ^ returnType.hashCode(); - for(int i = 0; i < params.length; i++) - { - hash ^= params[i].hashCode(); - } - } - - public boolean equals(Object o) - { - if (o instanceof MethodKey) - { - MethodKey m = (MethodKey) o; - if (m.name.equals(name) && m.params.length == params.length - && m.returnType == returnType) - { - for (int i = 0; i < params.length; i++) - { - if (m.params[i] != params[i]) - return false; - } - return true; - } - } - return false; - } - - public int hashCode() - { - return hash; - } - } - - /** - * Gets the method with the given name and argument types declared in this - * class or any of its super-classes. - * - * @param name - * @param argTypes - * @return Method - * @throws NoSuchMethodException - * @throws SecurityException - */ - public Method getMethod(String name, Class<?>... argTypes) - throws NoSuchMethodException, SecurityException { - VmType< ? >[] vmArgTypes; - if (argTypes == null) { - vmArgTypes = null; - } else { - final int cnt = argTypes.length; - vmArgTypes = new VmType[cnt]; - for (int i = 0; i < cnt; i++) { - vmArgTypes[i] = argTypes[i].getLinkedVmClass(); - } - } - VmMethod method = getLinkedVmClass().getMethod(name, vmArgTypes); - if (method != null) { - return (Method) method.asMember(); - } else { - throw new NoSuchMethodException(name); - } - } - - /** - * Gets all methods declared in this class and its super-classes - * - * @return Method[] - */ - - public Method[] getMethods() { - if (methods == null) { - Method[] a = internalGetMethods(); - ArrayList<Method> list = new ArrayList<Method>(); - for(int i = 0; i < a.length; i++){ - list.add(a[i]); - } - methods = list; - } - return methods.toArray(new Method[methods.size()]); - } - /* - public Method[] getMethods() { - if (methods == null) { - final ArrayList<Method> list = new ArrayList<Method>(); - Class< ? > cls = this; - while (cls != null) { - final Method[] dlist = cls.getDeclaredMethods(); - for (int i = 0; i < dlist.length; i++) { - list.add(dlist[i]); - } - cls = cls.getSuperclass(); - } - methods = list; - } - return (Method[]) methods.toArray(new Method[methods.size()]); - }*/ - - /** - * Like <code>getMethods()</code> but without the security checks. - */ - private Method[] internalGetMethods() - { - HashMap map = new HashMap(); - Method[] methods; - Class[] interfaces = getInterfaces(); - for(int i = 0; i < interfaces.length; i++) - { - methods = interfaces[i].internalGetMethods(); - for(int j = 0; j < methods.length; j++) - { - map.put(new MethodKey(methods[j]), methods[j]); - } - } - Class superClass = getSuperclass(); - if(superClass != null) - { - methods = superClass.internalGetMethods(); - for(int i = 0; i < methods.length; i++) - { - map.put(new MethodKey(methods[i]), methods[i]); - } - } - methods = getDeclaredMethods(true); - for(int i = 0; i < methods.length; i++) - { - map.put(new MethodKey(methods[i]), methods[i]); - } - return (Method[])map.values().toArray(new Method[map.size()]); - } - - /** - * Gets the method with the given name and argument types declared in this - * class. - * - * @param name - * @param argTypes - * @return Method - * @throws NoSuchMethodException - * @throws SecurityException - */ - public Method getDeclaredMethod(String name, Class< ? >... argTypes) - throws NoSuchMethodException, SecurityException { - VmType< ? >[] vmArgTypes; - if (argTypes == null) { - vmArgTypes = null; - } else { - final int cnt = argTypes.length; - vmArgTypes = new VmType[cnt]; - for (int i = 0; i < cnt; i++) { - vmArgTypes[i] = argTypes[i].getLinkedVmClass(); - } - } - VmMethod method = getLinkedVmClass() - .getDeclaredMethod(name, vmArgTypes); - if (method != null) { - return (Method) method.asMember(); - } else { - throw new NoSuchMethodException(name); - } - } - - /** - * Gets all methods declared in this class. - * - * @return Method[] - */ - public Method[] getDeclaredMethods() { - if (declaredMethods == null) { - declaredMethods = getDeclaredMethods(false); - } - return declaredMethods; - } - - /** - * Gets all methods declared in this class. - * - * @return Method[] - */ - private Method[] getDeclaredMethods(boolean publicOnly) { - final VmType<T> vmClass = getLinkedVmClass(); - final int cnt = vmClass.getNoDeclaredMethods(); - int max = 0; - for (int i = 0; i < cnt; i++) { - VmMethod method = vmClass.getDeclaredMethod(i); - if (!method.isConstructor() && - (!publicOnly || method.isPublic())) { - max++; - } - } - final Method[] list = new Method[max]; - max = 0; - for (int i = 0; i < cnt; i++) { - VmMethod vmMethod = vmClass.getDeclaredMethod(i); - if (!vmMethod.isConstructor() && - (!publicOnly || vmMethod.isPublic())) { - list[max++] = (Method) vmMethod.asMember(); - } - } - return list; - } - - /** - * Returns an array of all public classes and interfaces that are members of - * this class and declared in this class. - * - * @return - */ - public Class[] getDeclaredClasses() throws SecurityException { - // TODO implement me - return new Class[0]; - } - - /** - * If the class or interface represented by this Class object is a member of - * another class, returns the Class object representing the class in which - * it was declared. This method returns null if this class or interface is - * not a member of any other class. If this Class object represents an array - * class, a primitive type, or void,then this method returns null. - * - * @return - */ - public Class getDeclaringClass() { - // TODO implement me - return null; - } - - public Constructor<T> getDeclaredConstructor(Class<?>... argTypes) - throws NoSuchMethodException { - String signature = Signature.toSignature(null, argTypes); - final VmMethod vmMethod = getLinkedVmClass().getDeclaredMethod( - "<init>", signature); - if (vmMethod != null) { - return (Constructor) vmMethod.asMember(); - } else { - throw new NoSuchMethodException("<init> " + signature); - } - } - - /** - * Gets all constructors declared in this class - * - * @return Constructor[] - */ - public Constructor[] getDeclaredConstructors() { - if (declaredConstructors == null) { - final VmType<T> vmClass = getLinkedVmClass(); - int cnt = vmClass.getNoDeclaredMethods(); - int max = 0; - for (int i = 0; i < cnt; i++) { - if (vmClass.getDeclaredMethod(i).isConstructor()) { - max++; - } - } - Constructor[] list = new Constructor[max]; - max = 0; - for (int i = 0; i < cnt; i++) { - VmMethod vmMethod = vmClass.getDeclaredMethod(i); - if (vmMethod.isConstructor()) { - list[max++] = (Constructor) vmMethod.asMember(); - } - } - declaredConstructors = list; - } - return declaredConstructors; - } - - /** - * Returns the <code>Package</code> in which this class is defined Returns - * null when this information is not available from the classloader of this - * class or when the classloader of this class is null. - * - * @return the package for this class, if it is available - * @since 1.2 - */ - public Package getPackage() { - ClassLoader cl = getClassLoader(); - if (cl != null) { - return cl.getPackage(getPackagePortion(getName())); - } - return null; - } - - /** - * Returns the ProtectionDomain of this class. If there is a security - * manager installed, this method first calls the security manager's - * checkPermission method with a RuntimePermission("getProtectionDomain") - * permission to ensure it's ok to get the ProtectionDomain. - * - * @return the ProtectionDomain of this class - * @throws SecurityException - * if a security manager exists and its checkPermission method - * doesn't allow getting the ProtectionDomain. - * @since 1.2 - */ - public ProtectionDomain getProtectionDomain() { - final SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(new RuntimePermission("getProtectionDomain")); - } - final ProtectionDomain pd = getLinkedVmClass().getProtectionDomain(); - if (pd != null) { - return pd; - } else { - return getUnknownProtectionDomain(); - } - } - - /** - * Gets the unknown protection domain. Create on demand. - * - * @return - */ - private static final ProtectionDomain getUnknownProtectionDomain() { - if (unknownProtectionDomain == null) { - Permissions permissions = new Permissions(); - permissions.add(new AllPermission()); - unknownProtectionDomain = new ProtectionDomain(null, permissions); - } - return unknownProtectionDomain; - } - - /** - * Is this class an array class? - * - * @return boolean - */ - public boolean isArray() { - return vmClass.isArray(); - } - - /** - * Returns an array of all public classes and interfaces that are members of - * this class. - * - * @return - */ - public Class[] getClasses() throws SecurityException { - // TODO implement me - return new Class[0]; - } - - /** - * Gets the constructor with the given argument types. - * - * @param argTypes - * @return Constructor - * @throws NoSuchMethodException - */ - public Constructor<T> getConstructor(Class<?>... argTypes) - throws NoSuchMethodException { - // Check security - memberAccessCheck(Member.PUBLIC); - - // Create signature - String signature = Signature.toSignature(null, argTypes); - final VmMethod vmMethod = getLinkedVmClass().getDeclaredMethod( - "<init>", signature); - if (vmMethod != null) { - return (Constructor) vmMethod.asMember(); - } else { - throw new NoSuchMethodException("<init> " + signature); - } - } - - /** - * Returns an array containing Constructor objects reflecting all the public - * constructors of the class represented by this Class object. An array of - * length 0 is returned if the class has no public constructors, or if the - * class is an array class, or if the class reflects a primitive type or - * void. If there is a security manager, this method first calls the - * security manager's checkMemberAccess method with this and Member.PUBLIC - * as its arguments. If the class is in a package, then this method also - * calls the security manager's checkPackageAccess method with the package - * name as its argument. Either of these calls could result in a - * SecurityException. - * - * @return Constructor[] - */ - public Constructor[] getConstructors() { - if (constructors == null) { - ArrayList<Constructor> list = new ArrayList<Constructor>(); - final Constructor[] dlist = getDeclaredConstructors(); - for (int i = 0; i < dlist.length; i++) { - final Constructor c = dlist[i]; - if ((c.getModifiers() & Modifier.PUBLIC) != 0) { - list.add(dlist[i]); - } - } - constructors = list; - } - return (Constructor[]) constructors - .toArray(new Constructor[constructors.size()]); - } - - /** - * Get a resource URL using this class's package using the - * getClassLoader().getResource() method. If this class was loaded using the - * system classloader, ClassLoader.getSystemResource() is used instead. - * <p> - * If the name you supply is absolute (it starts with a <code>/</code>), - * then it is passed on to getResource() as is. If it is relative, the - * package name is prepended, and <code>.</code>'s are replaced with - * <code>/</code>. - * <p> - * The URL returned is system- and classloader-dependent, and could change - * across implementations. - * - * @param name - * the name of the resource, generally a path - * @return the URL to the resource - * @throws NullPointerException - * if name is null - * @since 1.1 - */ - public URL getResource(String name) { - if (name.length() > 0 && name.charAt(0) != '/') { - name = VMClassHelper.getPackagePortion(getName()).replace('.', '/') - + "/" + name; - } - final ClassLoader ld = getClassLoader(); - if (ld != null) { - return ld.getResource(name); - } else { - try { - Enumeration resources = vmClass.getLoader().asClassLoader().getResources(name); - - return resources.hasMoreElements() ? (URL) resources.nextElement() : null; - } catch (Exception x) { - return null; - } - //return ClassLoader.getSystemResource(name); - } - } - - /** - * Get a resource using this class's package using the - * getClassLoader().getResourceAsStream() method. If this class was loaded - * using the system classloader, ClassLoader.getSystemResource() is used - * instead. - * <p> - * If the name you supply is absolute (it starts with a <code>/</code>), - * then it is passed on to getResource() as is. If it is relative, the - * package name is prepended, and <code>.</code>'s are replaced with - * <code>/</code>. - * <p> - * The URL returned is system- and classloader-dependent, and could change - * across implementations. - * - * @param name - * the name of the resource, generally a path - * @return an InputStream with the contents of the resource in it, or null - * @throws NullPointerException - * if name is null - * @since 1.1 - */ - public InputStream getResourceAsStream(String name) { - if (name.length() > 0 && name.charAt(0) != '/') { - name = VMClassHelper.getPackagePortion(getName()).replace('.', '/') - + "/" + name; - } - final ClassLoader ld = getClassLoader(); - if (ld != null) { - return ld.getResourceAsStream(name); - } else { - return ClassLoader.getSystemResourceAsStream(name); - } - } - - /** - * Gets a primitive class of a given type. - * - * @param type - * @return - * @see VmType#getPrimitiveClass(char) - */ - static Class getPrimitiveClass(char type) { - return VmType.getPrimitiveClass(type).asClass(); - } - - /** - * Gets a primitive class of a given type. - * - * @param type - * @return - * @see VmType#getPrimitiveClass(char) - */ - static Class getPrimitiveClass(String type) { - if(type.equals("double")) - return getPrimitiveClass('D'); - else if(type.equals("float")) - return getPrimitiveClass('F'); - else if(type.equals("boolean")) - return getPrimitiveClass('Z'); - else if(type.equals("byte")) - return getPrimitiveClass('B'); - else if(type.equals("char")) - return getPrimitiveClass('C'); - else if(type.equals("short")) - return getPrimitiveClass('S'); - else if(type.equals("int")) - return getPrimitiveClass('I'); - else if(type.equals("long")) - return getPrimitiveClass('J'); - else if(type.equals("void")) - return getPrimitiveClass('V'); - else - throw new IllegalArgumentException("Unknown type " + type); - } - - /** - * Returns the enumeration constants of this class, or null if this class is - * not an <code>Enum</code>. - * - * @return an array of <code>Enum</code> constants associated with this - * class, or null if this class is not an <code>enum</code>. - */ - @SuppressWarnings("unchecked") - public T[] getEnumConstants() { - if (isEnum()) { - try { - return (T[]) getMethod("values", null).invoke(null, null); - } catch (NoSuchMethodException exception) { - throw new Error("Enum lacks values() method"); - } catch (IllegalAccessException exception) { - throw new Error("Unable to access Enum class"); - } catch (InvocationTargetException exception) { - throw new RuntimeException( - "The values method threw an exception", exception); - } - } else { - return null; - } - } - - /** - * Returns true if this class is an <code>Enum</code>. - * - * @return true if this is an enumeration class. - */ - public boolean isEnum() { - return vmClass.isEnum(); - } - - /** - * Return object, cast to this Class' type. - * - * @param obj - * the object to cast - * @throws ClassCastException - * if obj is not an instance of this class - * @since 1.5 - */ - @SuppressWarnings("unchecked") - public T cast(Object obj) { - if ((obj != null) && !isInstance(obj)) { - throw new ClassCastException(); - } - return (T) obj; - } - - /** - * Gets the VmType and make sure it is linked. - * - * @return - */ - private final VmType<T> getLinkedVmClass() { - vmClass.link(); - return vmClass; - } - - /** - * @see java.lang.reflect.GenericDeclaration#getTypeParameters() - */ - public TypeVariable< ? >[] getTypeParameters() { - String sig = vmClass.getSignature(); - if (sig == null) - return new TypeVariable[0]; - - ClassSignatureParser p = new ClassSignatureParser(this, sig); - return p.getTypeParameters(); - } - - /** - * <p> - * Casts this class to represent a subclass of the specified class. This - * method is useful for `narrowing' the type of a class so that the class - * object, and instances of that class, can match the contract of a more - * restrictive method. For example, if this class has the static type of - * <code>Class<Object></code>, and a dynamic type of - * <code>Class<Rectangle></code>, then, assuming <code>Shape</code> - * is a superclass of <code>Rectangle</code>, this method can be used on - * this class with the parameter, <code>Class<Shape></code>, to - * retain the same instance but with the type - * <code>Class<? extends Shape></code>. - * </p> - * <p> - * If this class can be converted to an instance which is parameterised over - * a subtype of the supplied type, <code>U</code>, then this method - * returns an appropriately cast reference to this object. Otherwise, a - * <code>ClassCastException</code> is thrown. - * </p> - * - * @param klass - * the class object, the parameterized type (<code>U</code>) - * of which should be a superclass of the parameterized type of - * this instance. - * @return a reference to this object, appropriately cast. - * @throws ClassCastException - * if this class can not be converted to one which represents a - * subclass of the specified type, <code>U</code>. - * @since 1.5 - */ - @SuppressWarnings("unchecked") - public <U> Class< ? extends U> asSubclass(Class<U> klass) { - if (!klass.isAssignableFrom(this)) - throw new ClassCastException(); - return (Class< ? extends U>) this; - } - - /** - * Returns the class which immediately encloses this class. If this class - * is a top-level class, this method returns <code>null</code>. - * - * @return the immediate enclosing class, or <code>null</code> if this is - * a top-level class. - * @since 1.5 - */ - public Class<?> getEnclosingClass() - { - //return VMClass.getEnclosingClass(this); - //todo implement it - return null; - } - - /** - * Returns the constructor which immediately encloses this class. If - * this class is a top-level class, or a local or anonymous class - * immediately enclosed by a type definition, instance initializer - * or static initializer, then <code>null</code> is returned. - * - * @return the immediate enclosing constructor if this class is - * declared within a constructor. Otherwise, <code>null</code> - * is returned. - * @since 1.5 - */ - public Constructor getEnclosingConstructor() - { - //return VMClass.getEnclosingConstructor(this); - //todo implement it - return null; - } - - /** - * Returns the method which immediately encloses this class. If - * this class is a top-level class, or a local or anonymous class - * immediately enclosed by a type definition, instance initializer - * or static initializer, then <code>null</code> is returned. - * - * @return the immediate enclosing method if this class is - * declared within a method. Otherwise, <code>null</code> - * is returned. - * @since 1.5 - */ - public Method getEnclosingMethod() - { - //return VMClass.getEnclosingMethod(this); - //todo implement it - return null; - } - - /** - * Perform security checks common to all of the methods that get members of - * this Class. - */ - private void memberAccessCheck(int which) { - SecurityManager sm = SecurityManager.current; - if (sm != null) { - sm.checkMemberAccess(this, which); - Package pkg = getPackage(); - if (pkg != null) { - sm.checkPackageAccess(pkg.getName()); - } - } - } - - /** - * Strip the last portion of the name (after the last dot). - * - * @param name - * the name to get package of - * @return the package name, or "" if no package - */ - private static String getPackagePortion(String name) { - int lastInd = name.lastIndexOf('.'); - if (lastInd == -1) - return ""; - return name.substring(0, lastInd); - } - - /** - * Returns true if this class is an <code>Annotation</code>. - * - * @return true if this is an annotation class. - * @since 1.5 - */ - public boolean isAnnotation() - { - return vmClass.isAnnotation(); - } - - public String getCanonicalName() { - if (isArray()) { - String canonicalName = getComponentType().getCanonicalName(); - if (canonicalName != null) - return canonicalName + "[]"; - else - return null; - } - if (isLocalOrAnonymousClass()) - return null; - Class<?> enclosingClass = getEnclosingClass(); - if (enclosingClass == null) { // top level class - return getName(); - } else { - String enclosingName = enclosingClass.getCanonicalName(); - if (enclosingName == null) - return null; - return enclosingName + "." + getSimpleName(); - } - - } - - /** - * <p> - * Returns a <code>Type</code> object representing the direct superclass, - * whether class, interface, primitive type or void, of this class. - * If this class is an array class, then a class instance representing - * the <code>Object</code> class is returned. If this class is primitive, - * an interface, or a representation of either the <code>Object</code> - * class or void, then <code>null</code> is returned. - * </p> - * <p> - * If the superclass is a parameterized type, then the - * object returned for this interface reflects the actual type - * parameters used in the source code. Type parameters are created - * using the semantics specified by the <code>ParameterizedType</code> - * interface, and only if an instance has not already been created. - * </p> - * - * @return the superclass of this class. - * @throws GenericSignatureFormatError if the generic signature of the - * class does not comply with that specified by the Java - * Virtual Machine specification, 3rd edition. - * @throws TypeNotPresentException if the superclass refers - * to a non-existant type. - * @throws MalformedParameterizedTypeException if the superclass - * refers to a parameterized type that can not be instantiated for - * some reason. - * @since 1.5 - * @see java.lang.reflect.ParameterizedType - */ - public Type getGenericSuperclass() - { - if (isArray()) - return Object.class; - - if (isPrimitive() || isInterface() || this == Object.class) - return null; - - String sig = vmClass.getSignature(); - if (sig == null) - return getSuperclass(); - - ClassSignatureParser p = new ClassSignatureParser(this, sig); - return p.getSuperclassType(); - } - - /** - * <p> - * Returns an array of <code>Type</code> objects which represent the - * interfaces directly implemented by this class or extended by this - * interface. - * </p> - * <p> - * If one of the superinterfaces is a parameterized type, then the - * object returned for this interface reflects the actual type - * parameters used in the source code. Type parameters are created - * using the semantics specified by the <code>ParameterizedType</code> - * interface, and only if an instance has not already been created. - * </p> - * <p> - * The order of the interfaces in the array matches the order in which - * the interfaces are declared. For classes which represent an array, - * an array of two interfaces, <code>Cloneable</code> and - * <code>Serializable</code>, is always returned, with the objects in - * that order. A class representing a primitive type or void always - * returns an array of zero size. - * </p> - * - * @return an array of interfaces implemented or extended by this class. - * @throws GenericSignatureFormatError if the generic signature of one - * of the interfaces does not comply with that specified by the Java - * Virtual Machine specification, 3rd edition. - * @throws TypeNotPresentException if any of the superinterfaces refers - * to a non-existant type. - * @throws MalformedParameterizedTypeException if any of the interfaces - * refer to a parameterized type that can not be instantiated for - * some reason. - * @since 1.5 - * @see java.lang.reflect.ParameterizedType - */ - public Type[] getGenericInterfaces() - { - if (isPrimitive()) - return new Type[0]; - - String sig = vmClass.getSignature(); - if (sig == null) - return getInterfaces(); - - ClassSignatureParser p = new ClassSignatureParser(this, sig); - return p.getInterfaceTypes(); - } - - //jnode openjdk - /** - * Returns the elements of this enum class or null if this - * Class object does not represent an enum type; - * identical to getEnumConstantsShared except that - * the result is uncloned, cached, and shared by all callers. - */ - //todo make it package private - public T[] getEnumConstantsShared() { - if (enumConstants == null) { - if (!isEnum()) return null; - try { - final Method values = getMethod("values"); - java.security.AccessController.doPrivileged - (new java.security.PrivilegedAction<Void>() { - public Void run() { - values.setAccessible(true); - return null; - } - }); - enumConstants = (T[]) values.invoke(null); - } - // These can happen when users concoct enum-like classes - // that don't comply with the enum spec. - catch (InvocationTargetException ex) { - return null; - } - catch (NoSuchMethodException ex) { - return null; - } - catch (IllegalAccessException ex) { - return null; - } - } - return enumConstants; - } - private volatile transient T[] enumConstants; - - - /** - * Returns a map from simple name to enum constant. This package-private - * method is used internally by Enum to implement - * public static <T extends Enum<T>> T valueOf(Class<T>, String) - * efficiently. Note that the map is returned by this method is - * created lazily on first use. Typically it won't ever get created. - */ - HashMap<String, T> enumConstantDirectory() { - if (enumConstantDirectory == null) { - T[] universe = getEnumConstantsShared(); - if (universe == null) - throw new IllegalArgumentException( - getName() + " is not an enum type"); - HashMap<String, T> m = new HashMap<String, T>(2 * universe.length); - for (T constant : universe) - m.put(((Enum) constant).name(), constant); - enumConstantDirectory = m; - } - return enumConstantDirectory; - } - private volatile transient HashMap enumConstantDirectory; - - ClassLoader getClassLoader0(){ - return getClassLoader(); - } - - /** - * Returns <tt>true</tt> if and only if the underlying class - * is an anonymous class. - * - * @return <tt>true</tt> if and only if this class is an anonymous class. - * @since 1.5 - */ - public boolean isAnonymousClass() { - return "".equals(getSimpleName()); - } - - /** - * Returns <tt>true</tt> if and only if the underlying class - * is a local class. - * - * @return <tt>true</tt> if and only if this class is a local class. - * @since 1.5 - */ - public boolean isLocalClass() { - return isLocalOrAnonymousClass() && !isAnonymousClass(); - } - - /** - * Returns <tt>true</tt> if this is a local class or an anonymous - * class. Returns <tt>false</tt> otherwise. - */ - private boolean isLocalOrAnonymousClass() { - // JVM Spec 4.8.6: A class must have an EnclosingMethod - // attribute if and only if it is a local class or an - // anonymous class. - return getEnclosingMethodInfo() != null; - } - - /* - private EnclosingMethodInfo getEnclosingMethodInfo() { - Object[] enclosingInfo = getEnclosingMethod0(); - if (enclosingInfo == null) - return null; - else { - return new EnclosingMethodInfo(enclosingInfo); - } - } */ - - private EnclosingMethodInfo getEnclosingMethodInfo() { - //todo implement it - return null; - } - - public boolean isMemberClass() { - return getSimpleBinaryName() != null && !isLocalOrAnonymousClass(); - } - - /** - * Returns the "simple binary name" of the underlying class, i.e., - * the binary name without the leading enclosing class name. - * Returns <tt>null</tt> if the underlying class is a top level - * class. - */ - private String getSimpleBinaryName() { - Class<?> enclosingClass = getEnclosingClass(); - if (enclosingClass == null) // top level class - return null; - // Otherwise, strip the enclosing class' name - try { - return getName().substring(enclosingClass.getName().length()); - } catch (IndexOutOfBoundsException ex) { - throw new InternalError("Malformed class name"); - } - } - - private final static class EnclosingMethodInfo { - private Class<?> enclosingClass; - private String name; - private String descriptor; - - private EnclosingMethodInfo(Object[] enclosingInfo) { - if (enclosingInfo.length != 3) - throw new InternalError("Malformed enclosing method information"); - try { - // The array is expected to have three elements: - - // the immediately enclosing class - enclosingClass = (Class<?>) enclosingInfo[0]; - assert(enclosingClass != null); - - // the immediately enclosing method or constructor's - // name (can be null). - name = (String) enclosingInfo[1]; - - // the immediately enclosing method or constructor's - // descriptor (null iff name is). - descriptor = (String) enclosingInfo[2]; - assert((name != null && descriptor != null) || name == descriptor); - } catch (ClassCastException cce) { - throw new InternalError("Invalid type in enclosing method information"); - } - } - - boolean isPartial() { - return enclosingClass == null || name == null || descriptor == null; - } - - boolean isConstructor() { return !isPartial() && "<init>".equals(name); } - - boolean isMethod() { return !isPartial() && !isConstructor() && !"<clinit>".equals(name); } - - Class<?> getEnclosingClass() { return enclosingClass; } - - String getName() { return name; } - - String getDescriptor() { return descriptor; } - - } - - //jnode + openjdk - /** - * Returns <tt>true</tt> if this class is a synthetic class; - * returns <tt>false</tt> otherwise. - * @return <tt>true</tt> if and only if this class is a synthetic class as - * defined by the Java Language Specification. - * @since 1.5 - */ - public boolean isSynthetic() { - return vmClass.isSynthetic(); - } - - // Annotation types cache their internal (AnnotationType) form - private AnnotationType annotationType; - - //todo change this to package private - public void setAnnotationType(AnnotationType type) { - annotationType = type; - } - - //todo change this to package private - public AnnotationType getAnnotationType() { - return annotationType; - } -} Modified: trunk/core/src/classpath/vm/java/lang/ClassLoader.java =================================================================== --- trunk/core/src/classpath/vm/java/lang/ClassLoader.java 2008-12-27 07:30:02 UTC (rev 4807) +++ trunk/core/src/classpath/vm/java/lang/ClassLoader.java 2008-12-27 09:16:49 UTC (rev 4808) @@ -894,4 +894,74 @@ // Circumvent security check since this is package-private return caller.getClassLoader0(); } + + // Returns true if the specified class loader can be found in this class + // loader's delegation chain. + boolean isAncestor(ClassLoader cl) { + ClassLoader acl = this; + do { + acl = acl.parent; + if (cl == acl) { + return true; + } + } while (acl != null); + return false; + } + +/** + * Returns the assertion status that would be assigned to the specified + * class if it were to be initialized at the time this method is invoked. + * If the named class has had its assertion status set, the most recent + * setting will be returned; otherwise, if any package default assertion + * status pertains to this class, the most recent setting for the most + * specific pertinent package default assertion status is returned; + * otherwise, this class loader's default assertion status is returned. + * </p> + * + * @param className + * The fully qualified class name of the class whose desired + * assertion status is being queried. + * + * @return The desired assertion status of the specified class. + * + * @see #setClassAssertionStatus(String, boolean) + * @see #setPackageAssertionStatus(String, boolean) + * @see #setDefaultAssertionStatus(boolean) + * + * @since 1.4 + */ + synchronized boolean desiredAssertionStatus(String className) { + Boolean result; + + // assert classAssertionStatus != null; + // assert packageAssertionStatus != null; + + // Check for a class entry + result = (Boolean)classAssertionStatus.get(className); + if (result != null) + return result.boolean... [truncated message content] |
From: <ls...@us...> - 2009-01-02 22:42:57
|
Revision: 4816 http://jnode.svn.sourceforge.net/jnode/?rev=4816&view=rev Author: lsantha Date: 2009-01-02 22:42:52 +0000 (Fri, 02 Jan 2009) Log Message: ----------- Fixed more security exceptions. Modified Paths: -------------- trunk/core/src/core/org/jnode/vm/isolate/VmIsolate.java trunk/gui/descriptors/org.jnode.desktop.xml trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingToolkit.java Modified: trunk/core/src/core/org/jnode/vm/isolate/VmIsolate.java =================================================================== --- trunk/core/src/core/org/jnode/vm/isolate/VmIsolate.java 2009-01-02 22:17:19 UTC (rev 4815) +++ trunk/core/src/core/org/jnode/vm/isolate/VmIsolate.java 2009-01-02 22:42:52 UTC (rev 4816) @@ -32,6 +32,8 @@ import java.util.LinkedList; import java.util.List; import java.util.Properties; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; import javax.isolate.Isolate; import javax.isolate.IsolateStartupException; import javax.isolate.IsolateStatus; @@ -772,7 +774,7 @@ */ - private java.util.concurrent.ExecutorService executor; + private ExecutorService executor; /** * Execute a task within this isolate and wait for completion. @@ -781,7 +783,11 @@ */ public synchronized void invokeAndWait(final Runnable task) { if (executor == null) { - executor = java.util.concurrent.Executors.newSingleThreadExecutor(new IsolateThreadFactory2(this)); + executor = AccessController.doPrivileged(new PrivilegedAction<ExecutorService>(){ + public ExecutorService run() { + return Executors.newSingleThreadExecutor(new IsolateThreadFactory2(VmIsolate.this)); + } + }); } if (task == null) return; Modified: trunk/gui/descriptors/org.jnode.desktop.xml =================================================================== --- trunk/gui/descriptors/org.jnode.desktop.xml 2009-01-02 22:17:19 UTC (rev 4815) +++ trunk/gui/descriptors/org.jnode.desktop.xml 2009-01-02 22:42:52 UTC (rev 4816) @@ -31,6 +31,7 @@ <permission class="java.util.PropertyPermission" name="jnode.desktop" actions="read,write"/> <permission class="java.lang.RuntimePermission" name="getClassLoader" /> + <permission class="java.lang.RuntimePermission" name="accessDeclaredMembers" /> <permission class="java.util.PropertyPermission" name="java.util.logging.manager" actions="read"/> <permission class="java.util.logging.LoggingPermission" name="control" actions="" /> <permission class="java.util.PropertyPermission" name="java.util.logging.config.class" actions="read" /> Modified: trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingToolkit.java =================================================================== --- trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingToolkit.java 2009-01-02 22:17:19 UTC (rev 4815) +++ trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingToolkit.java 2009-01-02 22:42:52 UTC (rev 4816) @@ -84,6 +84,8 @@ import java.util.WeakHashMap; import java.lang.reflect.Method; import java.lang.reflect.Field; +import java.security.AccessController; +import java.security.PrivilegedAction; import javax.swing.JComponent; import javax.swing.JInternalFrame; import javax.swing.JMenuBar; @@ -253,7 +255,7 @@ protected FramePeer createFrame(final Frame target) { final FramePeer[] ret = new FramePeer[1]; - Runnable run = new Runnable() { + final Runnable run = new Runnable() { public void run() { if (!isGuiActive()) { @@ -296,68 +298,78 @@ } */ } }; + AccessController.doPrivileged(new PrivilegedAction<Object>(){ + public Object run() { - //peer frames should be created in the same app context where the desktop is - //todo refactor this into a generic inter-appcontext invoke and wait - AppContext ac = SunToolkit.targetToAppContext(target); - if (ac != null) { - EventQueue eq = (EventQueue) ac.get(sun.awt.AppContext.EVENT_QUEUE_KEY); - if (eq != null) { + + //peer frames should be created in the same app context where the desktop is + //todo refactor this into a generic inter-appcontext invoke and wait + AppContext ac = SunToolkit.targetToAppContext(target); + if (ac != null) { + EventQueue eq = (EventQueue) ac.get(sun.awt.AppContext.EVENT_QUEUE_KEY); + if (eq != null) { + try { + Method met = EventQueue.class.getDeclaredMethod("initDispatchThread"); + met.setAccessible(true); + met.invoke(eq); + } catch (Exception x) { + x.printStackTrace(); + } + } + } + + // invoke and wait -- + EventQueue eq = getMainEventQueue(); + + if (eq == getSystemEventQueueImpl()) { + run.run(); + synchronized (ret) { + return ret[0]; + } + } + try { - Method met = EventQueue.class.getDeclaredMethod("initDispatchThread"); - met.setAccessible(true); - met.invoke(eq); + Field field = EventQueue.class.getField("dispatchThread"); + field.setAccessible(true); + Thread edt = (Thread) field.get(eq); + if (Thread.currentThread() == edt) { + run.run(); + synchronized (ret) { + return ret[0]; + } + } } catch (Exception x) { - x.printStackTrace(); + throw new RuntimeException(x); } - } - } - // invoke and wait -- - EventQueue eq = getMainEventQueue(); + class AWTInvocationLock { + } + Object lock = new AWTInvocationLock(); - if (eq == getSystemEventQueueImpl()) { - run.run(); - synchronized (ret) { - return ret[0]; - } - } + InvocationEvent event = new InvocationEvent(Toolkit.getDefaultToolkit(), run, lock, true); - try { - Field field = EventQueue.class.getField("dispatchThread"); - field.setAccessible(true); - Thread edt = (Thread) field.get(eq); - if (Thread.currentThread() == edt) { - run.run(); - synchronized (ret) { - return ret[0]; + try { + synchronized (lock) { + eq.postEvent(event); + lock.wait(); + } + } catch (Exception x) { + throw new RuntimeException(x); } - } - } catch (Exception x) { - throw new RuntimeException(x); - } - class AWTInvocationLock { - } - Object lock = new AWTInvocationLock(); + Throwable eventThrowable = event.getThrowable(); + if (eventThrowable != null) { + throw new RuntimeException(eventThrowable); + } - InvocationEvent event = new InvocationEvent(Toolkit.getDefaultToolkit(), run, lock, true); + // --invoke and wait - try { - synchronized (lock) { - eq.postEvent(event); - lock.wait(); + + return null; } - } catch (Exception x) { - throw new RuntimeException(x); - } + }); - Throwable eventThrowable = event.getThrowable(); - if (eventThrowable != null) { - throw new RuntimeException(eventThrowable); - } - // --invoke and wait synchronized (ret) { return ret[0]; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2009-01-03 21:16:55
|
Revision: 4822 http://jnode.svn.sourceforge.net/jnode/?rev=4822&view=rev Author: lsantha Date: 2009-01-03 21:16:46 +0000 (Sat, 03 Jan 2009) Log Message: ----------- OpenJDK integration. Modified Paths: -------------- trunk/core/src/classpath/java/java/io/FileOutputStream.java trunk/core/src/classpath/vm/java/lang/ClassLoader.java trunk/core/src/classpath/vm/java/lang/Thread.java trunk/core/src/core/org/jnode/log4j/config/UnsafeDebugAppender.java trunk/core/src/core/org/jnode/vm/isolate/VmIsolate.java trunk/core/src/openjdk/vm/java/lang/NativeShutdown.java trunk/core/src/openjdk/vm/java/lang/NativeSystem.java trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingToolkit.java Added Paths: ----------- trunk/core/src/openjdk/java/java/lang/ProcessBuilder.java trunk/core/src/openjdk/java/java/lang/Runtime.java trunk/core/src/openjdk/java/java/lang/System.java trunk/core/src/openjdk/vm/java/lang/NativeProcessEnvironment.java trunk/core/src/openjdk/vm/java/lang/NativeUNIXProcess.java trunk/core/src/openjdk/vm/java/lang/ProcessEnvironment.java trunk/core/src/openjdk/vm/java/lang/ProcessImpl.java trunk/core/src/openjdk/vm/java/lang/Terminator.java trunk/core/src/openjdk/vm/java/lang/UNIXProcess.java Removed Paths: ------------- trunk/core/src/classpath/java/java/lang/ProcessBuilder.java trunk/core/src/classpath/java/java/lang/Runtime.java trunk/core/src/classpath/java/java/lang/System.java Modified: trunk/core/src/classpath/java/java/io/FileOutputStream.java =================================================================== --- trunk/core/src/classpath/java/java/io/FileOutputStream.java 2009-01-03 21:05:14 UTC (rev 4821) +++ trunk/core/src/classpath/java/java/io/FileOutputStream.java 2009-01-03 21:16:46 UTC (rev 4822) @@ -194,10 +194,9 @@ public FileOutputStream (FileDescriptor fdObj) throws SecurityException { - // Hmm, no other exception but this one to throw, but if the descriptor - // isn't valid, we surely don't have "permission" to write to it. - if (!fdObj.valid()) - throw new SecurityException("Invalid FileDescriptor"); + if (fdObj == null) { + throw new NullPointerException(); + } SecurityManager s = System.getSecurityManager(); if (s != null) Deleted: trunk/core/src/classpath/java/java/lang/ProcessBuilder.java =================================================================== --- trunk/core/src/classpath/java/java/lang/ProcessBuilder.java 2009-01-03 21:05:14 UTC (rev 4821) +++ trunk/core/src/classpath/java/java/lang/ProcessBuilder.java 2009-01-03 21:16:46 UTC (rev 4822) @@ -1,337 +0,0 @@ -/* ProcessBuilder.java - Represent spawned system process - Copyright (C) 2005 Free Software Foundation, Inc. - -This file is part of GNU Classpath. - -GNU Classpath is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2, or (at your option) -any later version. - -GNU Classpath 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 -General Public License for more details. - -You should have received a copy of the GNU General Public License -along with GNU Classpath; see the file COPYING. If not, write to the -Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -02110-1301 USA. - -Linking this library statically or dynamically with other modules is -making a combined work based on this library. Thus, the terms and -conditions of the GNU General Public License cover the whole -combination. - -As a special exception, the copyright holders of this library give you -permission to link this library with independent modules to produce an -executable, regardless of the license terms of these independent -modules, and to copy and distribute the resulting executable under -terms of your choice, provided that you also meet, for each linked -independent module, the terms and conditions of the license of that -module. An independent module is a module which is not derived from -or based on this library. If you modify this library, you may extend -this exception to your version of the library, but you are not -obligated to do so. If you do not wish to do so, delete this -exception statement from your version. */ - - -package java.lang; - -import java.io.File; -import java.io.IOException; - -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -/** - * <p> - * This class is used to construct new operating system processes. - * A <code>ProcessBuilder</code> instance basically represent a - * template for a new process. Actual processes are generated from - * this template via use of the <code>start()</code> method, which - * may be invoked multiple times, with each invocation spawning a - * new process with the current attributes of the - * <code>ProcessBuilder</code> object. Each spawned process is - * independent of the <code>ProcessBuilder</code> object, and is - * unaffected by changes in its attributes. - * </p> - * <p> - * The following attributes define a process: - * </p> - * <ul> - * <li>The <emphasis>working directory</emphasis>; the activities of a - * process begin with the current directory set to this. By default, - * this is the working directory of the current process, as defined - * by the <code>user.dir</code> property.</li> - * <li>The <emphasis>command</emphasis> which invokes the process. This - * usually consists of the name of the program binary followed by an - * arbitrary number of arguments. For example, <code>find -type f</code> - * invokes the <code>find</code> binary with the arguments "-type" and "f". - * The command is provided a list, the elements of which are defined in a - * system dependent manner; the layout is affected by expected operating - * system conventions. A common method is to split the command on each - * space within the string. Thus, <code>find -type f</code> forms a - * three element list. However, in some cases, the expectation is that - * this split is performed by the program itself; thus, the list consists - * of only two elements (the program name and its arguments).</li> - * <li>The <emphasis>environment map</emphasis>, which links environment - * variables to their corresponding values. The initial contents of the map - * are the current environment values i.e. it contains the contents of the - * map returned by <code>System.getenv()</code>.</li> - * <li>The <emphasis>redirection flag</emphasis>, which specifies whether - * or not the contents of the error stream should be redirected to standard - * output. By default, this is false, and there are two output streams, one - * for normal data ({@link Process#getOutputStream()}) and one for error data - * ({@link Process#getErrorStream()}). When set to true, the two are merged, - * which simplifies the interleaving of the two streams. Data is read using - * the stream returned by {@link Process#getOutputStream()}, and the - * stream returned by {@link Process#getErrorStream()} throws an immediate - * end-of-file exception.</li> - * </ul> - * <p> - * All checks on attribute validity are delayed until <code>start()</code> - * is called. <code>ProcessBuilder</code> objects are <strong>not - * synchronized</strong>; the user must provide external synchronization - * where multiple threads may interact with the same - * <code>ProcessBuilder</code> object. - * </p> - * - * @author Tom Tromey (tr...@re...) - * @author Andrew John Hughes (gnu...@me...) - * @see Process - * @see System#getenv() - * @since 1.5 - */ -public final class ProcessBuilder -{ - - /** - * The working directory of the process. - */ - private File directory = new File(System.getProperty("user.dir")); - - /** - * The command line syntax for invoking the process. - */ - private List<String> command; - - /** - * The mapping of environment variables to values. - */ - private Map<String, String> environment = - new System.EnvironmentMap(System.getenv()); - - /** - * A flag indicating whether to redirect the error stream to standard - * output. - */ - private boolean redirect = false; - - /** - * Constructs a new <code>ProcessBuilder</code> with the specified - * command being used to invoke the process. The list is used directly; - * external changes are reflected in the <code>ProcessBuilder</code>. - * - * @param command the name of the program followed by its arguments. - */ - public ProcessBuilder(List<String> command) - { - this.command = command; - } - - /** - * Constructs a new <code>ProcessBuilder</code> with the specified - * command being used to invoke the process. This constructor - * simplifies creating a new <code>ProcessBuilder</code> by - * converting the provided series of constructor arguments into a - * list of command-line arguments. - * - * @param command the name of the program followed by its arguments. - */ - public ProcessBuilder(String... command) - { - this.command = Arrays.asList(command); - } - - /** - * Returns the current command line, used to invoke the process. - * The return value is simply a reference to the list of command - * line arguments used by the <code>ProcessBuilder</code> object; - * any changes made to it will be reflected in the operation of - * the <code>ProcessBuilder</code>. - * - * @return the list of command-line arguments. - */ - public List<String> command() - { - return command; - } - - /** - * Sets the command-line arguments to those specified. The list is - * used directly; external changes are reflected in the - * <code>ProcessBuilder</code>. - * - * @param command the name of the program followed by its arguments. - * @return a reference to this process builder. - */ - public ProcessBuilder command(List<String> command) - { - this.command = command; - return this; - } - - /** - * Sets the command-line arguments to those specified. - * This simplifies modifying the arguments by converting - * the provided series of constructor arguments into a - * list of command-line arguments. - * - * @param command the name of the program followed by its arguments. - * @return a reference to this process builder. - */ - public ProcessBuilder command(String... command) - { - this.command = Arrays.asList(command); - return this; - } - - /** - * Returns the working directory of the process. The - * returned value may be <code>null</code>; this - * indicates that the default behaviour of using the - * working directory of the current process should - * be adopted. - * - * @return the working directory. - */ - public File directory() - { - return directory; - } - - /** - * Sets the working directory to that specified. - * The supplied argument may be <code>null</code>, - * which indicates the default value should be used. - * The default is the working directory of the current - * process. - * - * @param directory the new working directory. - * @return a reference to this process builder. - */ - public ProcessBuilder directory(File directory) - { - this.directory = directory; - return this; - } - - /** - * <p> - * Returns the system environment variables of the process. - * If the underlying system does not support environment variables, - * an empty map is returned. - * </p> - * <p> - * The returned map does not accept queries using - * null keys or values, or those of a type other than - * <code>String</code>. Attempts to pass in a null value will - * throw a <code>NullPointerException</code>. Types other than - * <code>String</code> throw a <code>ClassCastException</code>. - * </p> - * <p> - * As the returned map is generated using data from the underlying - * platform, it may not comply with the <code>equals()</code> - * and <code>hashCode()</code> contracts. It is also likely that - * the keys of this map will be case-sensitive. - * </p> - * <p> - * Modification of the map is reliant on the underlying platform; - * some may not allow any changes to the environment variables or - * may prevent certain values being used. Attempts to do so will - * throw an <code>UnsupportedOperationException</code> or - * <code>IllegalArgumentException</code>, respectively. - * </p> - * <p> - * Use of this method may require a security check for the - * RuntimePermission "getenv.*". - * </p> - * - * @return a map of the system environment variables for the process. - * @throws SecurityException if the checkPermission method of - * an installed security manager prevents access to - * the system environment variables. - * @since 1.5 - */ - public Map<String, String> environment() - { - return environment; - } - - /** - * Returns true if the output stream and error stream of the - * process will be merged to form one composite stream. The - * default return value is <code>false</code>. - * - * @return true if the output stream and error stream are to - * be merged. - */ - public boolean redirectErrorStream() - { - return redirect; - } - - /** - * Sets the error stream redirection flag. If set, the output - * and error streams are merged to form one composite stream. - * - * @param redirect the new value of the redirection flag. - * @return a reference to this process builder. - */ - public ProcessBuilder redirectErrorStream(boolean redirect) - { - this.redirect = redirect; - return this; - } - - /** - * <p> - * Starts execution of a new process, based on the attributes of - * this <code>ProcessBuilder</code> object. This is the point - * at which the command-line arguments are checked. The list - * must be non-empty and contain only non-null string objects. - * The other attributes have default values which are used in - * cases where their values are not explicitly specified. - * </p> - * <p> - * If a security manager is in place, then the - * {@link SecurityManager#checkExec()} method is called to - * ensure that permission is given to execute the process. - * </p> - * <p> - * The execution of the process is system-dependent. Various - * exceptions may result, due to problems at the operating system - * level. These are all returned as a form of {@link IOException}. - * </p> - * - * @return a <code>Process</code> object, representing the spawned - * subprocess. - * @throws IOException if a problem occurs with executing the process - * at the operating system level. - * @throws IndexOutOfBoundsException if the command to execute is - * actually an empty list. - * @throws NullPointerException if the command to execute is null - * or the list contains null elements. - * @throws SecurityException if a security manager exists and prevents - * execution of the subprocess. - */ - public Process start() throws IOException - { - SecurityManager sm = SecurityManager.current; // Be thread-safe! - if (sm != null) - sm.checkExec(command.get(0)); - return VMProcess.exec(command, environment, directory, redirect); - } -} Deleted: trunk/core/src/classpath/java/java/lang/Runtime.java =================================================================== --- trunk/core/src/classpath/java/java/lang/Runtime.java 2009-01-03 21:05:14 UTC (rev 4821) +++ trunk/core/src/classpath/java/java/lang/Runtime.java 2009-01-03 21:16:46 UTC (rev 4822) @@ -1,813 +0,0 @@ -/* Runtime.java -- access to the VM process - Copyright (C) 1998, 2002, 2003, 2004, 2005 Free Software Foundation - -This file is part of GNU Classpath. - -GNU Classpath is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2, or (at your option) -any later version. - -GNU Classpath 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 -General Public License for more details. - -You should have received a copy of the GNU General Public License -along with GNU Classpath; see the file COPYING. If not, write to the -Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -02110-1301 USA. - -Linking this library statically or dynamically with other modules is -making a combined work based on this library. Thus, the terms and -conditions of the GNU General Public License cover the whole -combination. - -As a special exception, the copyright holders of this library give you -permission to link this library with independent modules to produce an -executable, regardless of the license terms of these independent -modules, and to copy and distribute the resulting executable under -terms of your choice, provided that you also meet, for each linked -independent module, the terms and conditions of the license of that -module. An independent module is a module which is not derived from -or based on this library. If you modify this library, you may extend -this exception to your version of the library, but you are not -obligated to do so. If you do not wish to do so, delete this -exception statement from your version. */ - - -package java.lang; - -import gnu.classpath.SystemProperties; -import gnu.classpath.VMStackWalker; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; -import java.util.StringTokenizer; - -/** - * Runtime represents the Virtual Machine. - * - * @author John Keiser - * @author Eric Blake (eb...@em...) - * @author Jeroen Frijters - */ -// No idea why this class isn't final, since you can't build a subclass! -public class Runtime -{ - /** - * The library path, to search when loading libraries. We can also safely use - * this as a lock for synchronization. - */ - private final String[] libpath; - - /** - * The thread that started the exit sequence. Access to this field must - * be thread-safe; lock on libpath to avoid deadlock with user code. - * <code>runFinalization()</code> may want to look at this to see if ALL - * finalizers should be run, because the virtual machine is about to halt. - */ - private Thread exitSequence; - - /** - * All shutdown hooks. This is initialized lazily, and set to null once all - * shutdown hooks have run. Access to this field must be thread-safe; lock - * on libpath to avoid deadlock with user code. - */ - private Set shutdownHooks; - - /** - * The one and only runtime instance. - */ - private static final Runtime current = new Runtime(); - - /** - * Not instantiable by a user, this should only create one instance. - */ - private Runtime() - { - if (current != null) - throw new InternalError("Attempt to recreate Runtime"); - - // If used by underlying VM this contains the directories where Classpath's own - // native libraries are located. - String bootPath = SystemProperties.getProperty("gnu.classpath.boot.library.path", ""); - - // If properly set by the user this contains the directories where the application's - // native libraries are located. On operating systems where a LD_LIBRARY_PATH environment - // variable is available a VM should preset java.library.path with value of this - // variable. - String path = SystemProperties.getProperty("java.library.path", "."); - String pathSep = SystemProperties.getProperty("path.separator", ":"); - String fileSep = SystemProperties.getProperty("file.separator", "/"); - - StringTokenizer t1 = new StringTokenizer(bootPath, pathSep); - StringTokenizer t2 = new StringTokenizer(path, pathSep); - libpath = new String[t1.countTokens() + t2.countTokens()]; - - int i = 0; - while(t1.hasMoreTokens()) { - String prefix = t1.nextToken(); - if (! prefix.endsWith(fileSep)) - prefix += fileSep; - - libpath[i] = prefix; - i++; - } - - while(t2.hasMoreTokens()) { - String prefix = t2.nextToken(); - if (! prefix.endsWith(fileSep)) - prefix += fileSep; - - libpath[i] = prefix; - i++; - } - } - - /** - * Get the current Runtime object for this JVM. This is necessary to access - * the many instance methods of this class. - * - * @return the current Runtime object - */ - public static Runtime getRuntime() - { - return current; - } - - /** - * Exit the Java runtime. This method will either throw a SecurityException - * or it will never return. The status code is returned to the system; often - * a non-zero status code indicates an abnormal exit. Of course, there is a - * security check, <code>checkExit(status)</code>. - * - * <p>First, all shutdown hooks are run, in unspecified order, and - * concurrently. Next, if finalization on exit has been enabled, all pending - * finalizers are run. Finally, the system calls <code>halt</code>.</p> - * - * <p>If this is run a second time after shutdown has already started, there - * are two actions. If shutdown hooks are still executing, it blocks - * indefinitely. Otherwise, if the status is nonzero it halts immediately; - * if it is zero, it blocks indefinitely. This is typically called by - * <code>System.exit</code>.</p> - * - * @param status the status to exit with - * @throws SecurityException if permission is denied - * @see #addShutdownHook(Thread) - * @see #runFinalizersOnExit(boolean) - * @see #runFinalization() - * @see #halt(int) - */ - public void exit(int status) - { - SecurityManager sm = SecurityManager.current; // Be thread-safe! - if (sm != null) - sm.checkExit(status); - - if (runShutdownHooks()) - VMRuntime.exit(status); - - // Someone else already called runShutdownHooks(). - // Make sure we are not/no longer in the shutdownHooks set. - // And wait till the thread that is calling runShutdownHooks() finishes. - synchronized (libpath) - { - if (shutdownHooks != null) - { - shutdownHooks.remove(Thread.currentThread()); - // Interrupt the exit sequence thread, in case it was waiting - // inside a join on our thread. - exitSequence.interrupt(); - // Shutdown hooks are still running, so we clear status to - // make sure we don't halt. - status = 0; - } - } - - // If exit() is called again after the shutdown hooks have run, but - // while finalization for exit is going on and the status is non-zero - // we halt immediately. - if (status != 0) - VMRuntime.exit(status); - -// @classpath-bugfix 27213 19/4/2006 Martin Husted Hartvig (ha...@jn...) : - while (shutdownHooks != null) - { - try - { - exitSequence.join(); - } - catch (InterruptedException e) - { - // Ignore, we've suspended indefinitely to let all shutdown - // hooks complete, and to let any non-zero exits through, because - // this is a duplicate call to exit(0). - } - } - - VMRuntime.exit(status); -// @classpath-bugfix-end - } - - /** - * On first invocation, run all the shutdown hooks and return true. - * Any subsequent invocations will simply return false. - * Note that it is package accessible so that VMRuntime can call it - * when VM exit is not triggered by a call to Runtime.exit(). - * - * @return was the current thread the first one to call this method? - */ - boolean runShutdownHooks() - { - boolean first = false; - synchronized (libpath) // Synch on libpath, not this, to avoid deadlock. - { - if (exitSequence == null) - { - first = true; - exitSequence = Thread.currentThread(); - if (shutdownHooks != null) - { - Iterator i = shutdownHooks.iterator(); - while (i.hasNext()) // Start all shutdown hooks. - try - { - ((Thread) i.next()).start(); - } - catch (IllegalThreadStateException e) - { - i.remove(); - } - } - } - } - if (first) - { - if (shutdownHooks != null) - { - // Check progress of all shutdown hooks. As a hook completes, - // remove it from the set. If a hook calls exit, it removes - // itself from the set, then waits indefinitely on the - // exitSequence thread. Once the set is empty, set it to null to - // signal all finalizer threads that halt may be called. - while (true) - { - Thread[] hooks; - synchronized (libpath) - { - hooks = new Thread[shutdownHooks.size()]; - shutdownHooks.toArray(hooks); - } - if (hooks.length == 0) - break; - for (int i = 0; i < hooks.length; i++) - { - try - { - synchronized (libpath) - { - if (!shutdownHooks.contains(hooks[i])) - continue; - } - hooks[i].join(); - synchronized (libpath) - { - shutdownHooks.remove(hooks[i]); - } - } - catch (InterruptedException x) - { - // continue waiting on the next thread - } - } - } - synchronized (libpath) - { - shutdownHooks = null; - } - } - // Run finalization on all finalizable objects (even if they are - // still reachable). - VMRuntime.runFinalizationForExit(); - -// @classpath-bugfix 27213 19/4/2006 Martin Husted Hartvig (ha...@jn...) : - synchronized (libpath) - { - exitSequence = null; - } -// @classpath-bugfix-end - } - return first; - } - - /** - * Register a new shutdown hook. This is invoked when the program exits - * normally (because all non-daemon threads ended, or because - * <code>System.exit</code> was invoked), or when the user terminates - * the virtual machine (such as by typing ^C, or logging off). There is - * a security check to add hooks, - * <code>RuntimePermission("shutdownHooks")</code>. - * - * <p>The hook must be an initialized, but unstarted Thread. The threads - * are run concurrently, and started in an arbitrary order; and user - * threads or daemons may still be running. Once shutdown hooks have - * started, they must all complete, or else you must use <code>halt</code>, - * to actually finish the shutdown sequence. Attempts to modify hooks - * after shutdown has started result in IllegalStateExceptions.</p> - * - * <p>It is imperative that you code shutdown hooks defensively, as you - * do not want to deadlock, and have no idea what other hooks will be - * running concurrently. It is also a good idea to finish quickly, as the - * virtual machine really wants to shut down!</p> - * - * <p>There are no guarantees that such hooks will run, as there are ways - * to forcibly kill a process. But in such a drastic case, shutdown hooks - * would do little for you in the first place.</p> - * - * @param hook an initialized, unstarted Thread - * @throws IllegalArgumentException if the hook is already registered or run - * @throws IllegalStateException if the virtual machine is already in - * the shutdown sequence - * @throws SecurityException if permission is denied - * @since 1.3 - * @see #removeShutdownHook(Thread) - * @see #exit(int) - * @see #halt(int) - */ - public void addShutdownHook(Thread hook) - { - SecurityManager sm = SecurityManager.current; // Be thread-safe! - if (sm != null) - sm.checkPermission(new RuntimePermission("shutdownHooks")); - - //jnode - //todo investigate the reson of this chek failing - //if (hook.isAlive() || hook.getThreadGroup() == null) - // throw new IllegalArgumentException("The hook thread " + hook + " must not have been already run or started"); - - synchronized (libpath) - { - if (exitSequence != null) - throw new IllegalStateException("The Virtual Machine is exiting. It is not possible anymore to add any hooks"); - if (shutdownHooks == null) - { - VMRuntime.enableShutdownHooks(); - shutdownHooks = new HashSet(); // Lazy initialization. - } - if (! shutdownHooks.add(hook)) - throw new IllegalArgumentException(hook.toString() + " had already been inserted"); - } - } - - /** - * De-register a shutdown hook. As when you registered it, there is a - * security check to remove hooks, - * <code>RuntimePermission("shutdownHooks")</code>. - * - * @param hook the hook to remove - * @return true if the hook was successfully removed, false if it was not - * registered in the first place - * @throws IllegalStateException if the virtual machine is already in - * the shutdown sequence - * @throws SecurityException if permission is denied - * @since 1.3 - * @see #addShutdownHook(Thread) - * @see #exit(int) - * @see #halt(int) - */ - public boolean removeShutdownHook(Thread hook) - { - SecurityManager sm = SecurityManager.current; // Be thread-safe! - if (sm != null) - sm.checkPermission(new RuntimePermission("shutdownHooks")); - synchronized (libpath) - { - if (exitSequence != null) - throw new IllegalStateException(); - if (shutdownHooks != null) - return shutdownHooks.remove(hook); - } - return false; - } - - /** - * Forcibly terminate the virtual machine. This call never returns. It is - * much more severe than <code>exit</code>, as it bypasses all shutdown - * hooks and initializers. Use caution in calling this! Of course, there is - * a security check, <code>checkExit(status)</code>. - * - * @param status the status to exit with - * @throws SecurityException if permission is denied - * @since 1.3 - * @see #exit(int) - * @see #addShutdownHook(Thread) - */ - public void halt(int status) - { - SecurityManager sm = SecurityManager.current; // Be thread-safe! - if (sm != null) - sm.checkExit(status); - VMRuntime.halt(status); - } - - /** - * Tell the VM to run the finalize() method on every single Object before - * it exits. Note that the JVM may still exit abnormally and not perform - * this, so you still don't have a guarantee. And besides that, this is - * inherently unsafe in multi-threaded code, as it may result in deadlock - * as multiple threads compete to manipulate objects. This value defaults to - * <code>false</code>. There is a security check, <code>checkExit(0)</code>. - * - * @param finalizeOnExit whether to finalize all Objects on exit - * @throws SecurityException if permission is denied - * @see #exit(int) - * @see #gc() - * @since 1.1 - * @deprecated never rely on finalizers to do a clean, thread-safe, - * mop-up from your code - */ - public static void runFinalizersOnExit(boolean finalizeOnExit) - { - SecurityManager sm = SecurityManager.current; // Be thread-safe! - if (sm != null) - sm.checkExit(0); - VMRuntime.runFinalizersOnExit(finalizeOnExit); - } - - /** - * Create a new subprocess with the specified command line. Calls - * <code>exec(cmdline, null, null)</code>. A security check is performed, - * <code>checkExec</code>. - * - * @param cmdline the command to call - * @return the Process object - * @throws SecurityException if permission is denied - * @throws IOException if an I/O error occurs - * @throws NullPointerException if cmdline is null - * @throws IndexOutOfBoundsException if cmdline is "" - */ - public Process exec(String cmdline) throws IOException - { - return exec(cmdline, null, null); - } - - /** - * Create a new subprocess with the specified command line and environment. - * If the environment is null, the process inherits the environment of - * this process. Calls <code>exec(cmdline, env, null)</code>. A security - * check is performed, <code>checkExec</code>. - * - * @param cmdline the command to call - * @param env the environment to use, in the format name=value - * @return the Process object - * @throws SecurityException if permission is denied - * @throws IOException if an I/O error occurs - * @throws NullPointerException if cmdline is null, or env has null entries - * @throws IndexOutOfBoundsException if cmdline is "" - */ - public Process exec(String cmdline, String[] env) throws IOException - { - return exec(cmdline, env, null); - } - - /** - * Create a new subprocess with the specified command line, environment, and - * working directory. If the environment is null, the process inherits the - * environment of this process. If the directory is null, the process uses - * the current working directory. This splits cmdline into an array, using - * the default StringTokenizer, then calls - * <code>exec(cmdArray, env, dir)</code>. A security check is performed, - * <code>checkExec</code>. - * - * @param cmdline the command to call - * @param env the environment to use, in the format name=value - * @param dir the working directory to use - * @return the Process object - * @throws SecurityException if permission is denied - * @throws IOException if an I/O error occurs - * @throws NullPointerException if cmdline is null, or env has null entries - * @throws IndexOutOfBoundsException if cmdline is "" - * @since 1.3 - */ - public Process exec(String cmdline, String[] env, File dir) - throws IOException - { - StringTokenizer t = new StringTokenizer(cmdline); - String[] cmd = new String[t.countTokens()]; - for (int i = 0; i < cmd.length; i++) - cmd[i] = t.nextToken(); - return exec(cmd, env, dir); - } - - /** - * Create a new subprocess with the specified command line, already - * tokenized. Calls <code>exec(cmd, null, null)</code>. A security check - * is performed, <code>checkExec</code>. - * - * @param cmd the command to call - * @return the Process object - * @throws SecurityException if permission is denied - * @throws IOException if an I/O error occurs - * @throws NullPointerException if cmd is null, or has null entries - * @throws IndexOutOfBoundsException if cmd is length 0 - */ - public Process exec(String[] cmd) throws IOException - { - return exec(cmd, null, null); - } - - /** - * Create a new subprocess with the specified command line, already - * tokenized, and specified environment. If the environment is null, the - * process inherits the environment of this process. Calls - * <code>exec(cmd, env, null)</code>. A security check is performed, - * <code>checkExec</code>. - * - * @param cmd the command to call - * @param env the environment to use, in the format name=value - * @return the Process object - * @throws SecurityException if permission is denied - * @throws IOException if an I/O error occurs - * @throws NullPointerException if cmd is null, or cmd or env has null - * entries - * @throws IndexOutOfBoundsException if cmd is length 0 - */ - public Process exec(String[] cmd, String[] env) throws IOException - { - return exec(cmd, env, null); - } - - /** - * Create a new subprocess with the specified command line, already - * tokenized, and the specified environment and working directory. If the - * environment is null, the process inherits the environment of this - * process. If the directory is null, the process uses the current working - * directory. A security check is performed, <code>checkExec</code>. - * - * @param cmd the command to call - * @param env the environment to use, in the format name=value - * @param dir the working directory to use - * @return the Process object - * @throws SecurityException if permission is denied - * @throws IOException if an I/O error occurs - * @throws NullPointerException if cmd is null, or cmd or env has null - * entries - * @throws IndexOutOfBoundsException if cmd is length 0 - * @since 1.3 - */ - public Process exec(String[] cmd, String[] env, File dir) - throws IOException - { - SecurityManager sm = SecurityManager.current; // Be thread-safe! - if (sm != null) - sm.checkExec(cmd[0]); - return VMRuntime.exec(cmd, env, dir); - } - - /** - * Returns the number of available processors currently available to the - * virtual machine. This number may change over time; so a multi-processor - * program want to poll this to determine maximal resource usage. - * - * @return the number of processors available, at least 1 - */ - public int availableProcessors() - { - return VMRuntime.availableProcessors(); - } - - /** - * Find out how much memory is still free for allocating Objects on the heap. - * - * @return the number of bytes of free memory for more Objects - */ - public long freeMemory() - { - return VMRuntime.freeMemory(); - } - - /** - * Find out how much memory total is available on the heap for allocating - * Objects. - * - * @return the total number of bytes of memory for Objects - */ - public long totalMemory() - { - return VMRuntime.totalMemory(); - } - - /** - * Returns the maximum amount of memory the virtual machine can attempt to - * use. This may be <code>Long.MAX_VALUE</code> if there is no inherent - * limit (or if you really do have a 8 exabyte memory!). - * - * @return the maximum number of bytes the virtual machine will attempt - * to allocate - */ - public long maxMemory() - { - return VMRuntime.maxMemory(); - } - - /** - * Run the garbage collector. This method is more of a suggestion than - * anything. All this method guarantees is that the garbage collector will - * have "done its best" by the time it returns. Notice that garbage - * collection takes place even without calling this method. - */ - public void gc() - { - VMRuntime.gc(); - } - - /** - * Run finalization on all Objects that are waiting to be finalized. Again, - * a suggestion, though a stronger one than {@link #gc()}. This calls the - * <code>finalize</code> method of all objects waiting to be collected. - * - * @see #finalize() - */ - public void runFinalization() - { - VMRuntime.runFinalization(); - } - - /** - * Tell the VM to trace every bytecode instruction that executes (print out - * a trace of it). No guarantees are made as to where it will be printed, - * and the VM is allowed to ignore this request. - * - * @param on whether to turn instruction tracing on - */ - public void traceInstructions(boolean on) - { - VMRuntime.traceInstructions(on); - } - - /** - * Tell the VM to trace every method call that executes (print out a trace - * of it). No guarantees are made as to where it will be printed, and the - * VM is allowed to ignore this request. - * - * @param on whether to turn method tracing on - */ - public void traceMethodCalls(boolean on) - { - VMRuntime.traceMethodCalls(on); - } - - /** - * Load a native library using the system-dependent filename. This is similar - * to loadLibrary, except the only name mangling done is inserting "_g" - * before the final ".so" if the VM was invoked by the name "java_g". There - * may be a security check, of <code>checkLink</code>. - * - * <p> - * The library is loaded using the class loader associated with the - * class associated with the invoking method. - * - * @param filename the file to load - * @throws SecurityException if permission is denied - * @throws UnsatisfiedLinkError if the library is not found - */ - public void load(String filename) - { - load(filename, VMStackWalker.getCallingClassLoader()); - } - - /** - * Same as <code>load(String)</code> but using the given loader. - * - * @param filename the file to load - * @param loader class loader, or <code>null</code> for the boot loader - * @throws SecurityException if permission is denied - * @throws UnsatisfiedLinkError if the library is not found - */ - void load(String filename, ClassLoader loader) - { - SecurityManager sm = SecurityManager.current; // Be thread-safe! - if (sm != null) - sm.checkLink(filename); - if (loadLib(filename, loader) == 0) - throw new UnsatisfiedLinkError("Could not load library " + filename); - } - - /** - * Do a security check on the filename and then load the native library. - * - * @param filename the file to load - * @param loader class loader, or <code>null</code> for the boot loader - * @return 0 on failure, nonzero on success - * @throws SecurityException if file read permission is denied - */ - private static int loadLib(String filename, ClassLoader loader) - { - SecurityManager sm = SecurityManager.current; // Be thread-safe! - if (sm != null) - sm.checkRead(filename); - return VMRuntime.nativeLoad(filename, loader); - } - - /** - * Load a native library using a system-independent "short name" for the - * library. It will be transformed to a correct filename in a - * system-dependent manner (for example, in Windows, "mylib" will be turned - * into "mylib.dll"). This is done as follows: if the context that called - * load has a ClassLoader cl, then <code>cl.findLibrary(libpath)</code> is - * used to convert the name. If that result was null, or there was no class - * loader, this searches each directory of the system property - * <code>java.library.path</code> for a file named - * <code>System.mapLibraryName(libname)</code>. There may be a security - * check, of <code>checkLink</code>. - * - * <p>Note: Besides <code>java.library.path</code> a VM may chose to search - * for native libraries in a path that is specified by the - * <code>gnu.classpath.boot.library.path</code> system property. However - * this is for internal usage or development of GNU Classpath only. - * <b>A Java application must not load a non-system library by changing - * this property otherwise it will break compatibility.</b></p> - * - * <p> - * The library is loaded using the class loader associated with the - * class associated with the invoking method. - * - * @param libname the library to load - * - * @throws SecurityException if permission is denied - * @throws UnsatisfiedLinkError if the library is not found - * - * @see System#mapLibraryName(String) - * @see ClassLoader#findLibrary(String) - */ - public void loadLibrary(String libname) - { - loadLibrary(libname, VMStackWalker.getCallingClassLoader()); - } - - /** - * Same as <code>loadLibrary(String)</code> but using the given loader. - * - * @param libname the library to load - * @param loader class loader, or <code>null</code> for the boot loader - * @throws SecurityException if permission is denied - * @throws UnsatisfiedLinkError if the library is not found - */ - void loadLibrary(String libname, ClassLoader loader) - { - SecurityManager sm = SecurityManager.current; // Be thread-safe! - if (sm != null) - sm.checkLink(libname); - String filename; - if (loader != null && (filename = loader.findLibrary(libname)) != null) - { - if (loadLib(filename, loader) != 0) - return; - } - else - { - filename = VMRuntime.mapLibraryName(libname); - for (int i = 0; i < libpath.length; i++) - if (loadLib(libpath[i] + filename, loader) != 0) - return; - } - throw new UnsatisfiedLinkError("Native library `" + libname - + "' not found (as file `" + filename + "') in gnu.classpath.boot.library.path and java.library.path"); - } - - /** - * Return a localized version of this InputStream, meaning all characters - * are localized before they come out the other end. - * - * @param in the stream to localize - * @return the localized stream - * @deprecated <code>InputStreamReader</code> is the preferred way to read - * local encodings - * @XXX This implementation does not localize, yet. - */ - public InputStream getLocalizedInputStream(InputStream in) - { - return in; - } - - /** - * Return a localized version of this OutputStream, meaning all characters - * are localized before they are sent to the other end. - * - * @param out the stream to localize - * @return the localized stream - * @deprecated <code>OutputStreamWriter</code> is the preferred way to write - * local encodings - * @XXX This implementation does not localize, yet. - */ - public OutputStream getLocalizedOutputStream(OutputStream out) - { - return out; - } -} // class Runtime Deleted: trunk/core/src/classpath/java/java/lang/System.java =================================================================== --- trunk/core/src/classpath/java/java/lang/System.java 2009-01-03 21:05:14 UTC (rev 4821) +++ trunk/core/src/classpath/java/java/lang/System.java 2009-01-03 21:16:46 UTC (rev 4822) @@ -1,1141 +0,0 @@ -/* System.java -- useful methods to interface with the system - Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005 - Free Software Foundation, Inc. - -This file is part of GNU Classpath. - -GNU Classpath is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2, or (at your option) -any later version. - -GNU Classpath 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 -General Public License for more details. - -You should have received a copy of the GNU General Public License -along with GNU Classpath; see the file COPYING. If not, write to the -Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -02110-1301 USA. - -Linking this library statically or dynamically with other modules is -making a combined work based on this library. Thus, the terms and -conditions of the GNU General Public License cover the whole -combination. - -As a special exception, the copyright holders of this library give you -permission to link this library with independent modules to produce an -executable, regardless of the license terms of these independent -modules, and to copy and distribute the resulting executable under -terms of your choice, provided that you also meet, for each linked -independent module, the terms and conditions of the license of that -module. An independent module is a module which is not derived from -or based on this library. If you modify this library, you may extend -this exception to your version of the library, but you are not -obligated to do so. If you do not wish to do so, delete this -exception statement from your version. */ - - -package java.lang; - -import gnu.classpath.SystemProperties; -import gnu.classpath.VMStackWalker; - -import java.io.InputStream; -import java.io.PrintStream; -import java.io.Console; -import java.io.IOException; -import java.util.AbstractCollection; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Properties; -import java.util.PropertyPermission; -import java.nio.channels.Channel; -import java.nio.channels.spi.SelectorProvider; - -/** - * System represents system-wide resources; things that represent the - * general environment. As such, all methods are static. - * - * @author John Keiser - * @author Eric Blake (eb...@em...) - * @since 1.0 - * @status still missing 1.4 functionality - */ -public final class System -{ - // WARNING: System is a CORE class in the bootstrap cycle. See the comments - // in vm/reference/java/lang/Runtime for implications of this fact. - - /** - * The standard InputStream. This is assigned at startup and starts its - * life perfectly valid. Although it is marked final, you can change it - * using {@link #setIn(InputStream)} through some hefty VM magic. - * - * <p>This corresponds to the C stdin and C++ cin variables, which - * typically input from the keyboard, but may be used to pipe input from - * other processes or files. That should all be transparent to you, - * however. - */ - public static final InputStream in = VMSystem.makeStandardInputStream(); - - /** - * The standard output PrintStream. This is assigned at startup and - * starts its life perfectly valid. Although it is marked final, you can - * change it using {@link #setOut(PrintStream)} through some hefty VM magic. - * - * <p>This corresponds to the C stdout and C++ cout variables, which - * typically output normal messages to the screen, but may be used to pipe - * output to other processes or files. That should all be transparent to - * you, however. - */ - public static final PrintStream out = VMSystem.makeStandardOutputStream(); - - /** - * The standard output PrintStream. This is assigned at startup and - * starts its life perfectly valid. Although it is marked final, you can - * change it using {@link #setErr(PrintStream)} through some hefty VM magic. - * - * <p>This corresponds to the C stderr and C++ cerr variables, which - * typically output error messages to the screen, but may be used to pipe - * output to other processes or files. That should all be transparent to - * you, however. - */ - public static final PrintStream err = VMSystem.makeStandardErrorStream(); - - /** - * A cached copy of the environment variable map. - */ - private static Map<String,String> environmentMap; - - /** - * This class is uninstantiable. - */ - private System() - { - } - - /** - * Set {@link #in} to a new InputStream. This uses some VM magic to change - * a "final" variable, so naturally there is a security check, - * <code>RuntimePermission("setIO")</code>. - * - * @param in the new InputStream - * @throws SecurityException if permission is denied - * @since 1.1 - */ - public static void setIn(InputStream in) - { - SecurityManager sm = SecurityManager.current; // Be thread-safe. - if (sm != null) - sm.checkPermission(new RuntimePermission("setIO")); - - VMSystem.setIn(in); - } - - /** - * Set {@link #out} to a new PrintStream. This uses some VM magic to change - * a "final" variable, so naturally there is a security check, - * <code>RuntimePermission("setIO")</code>. - * - * @param out the new PrintStream - * @throws SecurityException if permission is denied - * @since 1.1 - */ - public static void setOut(PrintStream out) - { - SecurityManager sm = SecurityManager.current; // Be thread-safe. - if (sm != null) - sm.checkPermission(new RuntimePermission("setIO")); - VMSystem.setOut(out); - } - - /** - * Set {@link #err} to a new PrintStream. This uses some VM magic to change - * a "final" variable, so naturally there is a security check, - * <code>RuntimePermission("setIO")</code>. - * - * @param err the new PrintStream - * @throws SecurityException if permission is denied - * @since 1.1 - */ - public static void setErr(PrintStream err) - { - SecurityManager sm = SecurityManager.current; // Be thread-safe. - if (sm != null) - sm.checkPermission(new RuntimePermission("setIO")); - VMSystem.setErr(err); - } - - /** - * Set the current SecurityManager. If a security manager already exists, - * then <code>RuntimePermission("setSecurityManager")</code> is checked - * first. Since this permission is denied by the default security manager, - * setting the security manager is often an irreversible action. - * - * <STRONG>Spec Note:</STRONG> Don't ask me, I didn't write it. It looks - * pretty vulnerable; whoever gets to the gate first gets to set the policy. - * There is probably some way to set the original security manager as a - * command line argument to the VM, but I don't know it. - * - * @param sm the new SecurityManager - * @throws SecurityException if permission is denied - */ - public static synchronized void setSecurityManager(SecurityManager sm) - { - // Implementation note: the field lives in SecurityManager because of - // bootstrap initialization issues. This method is synchronized so that - // no other thread changes it to null before this thread makes the change. - if (SecurityManager.current != null) - SecurityManager.current.checkPermission - (new RuntimePermission("setSecurityManager")); - - // java.security.Security's class initialiser loads and parses the - // policy files. If it hasn't been run already it will be run - // during the first permission check. That initialisation will - // fail if a very restrictive security manager is in force, so we - // preload it here. - if (SecurityManager.current == null) - { - try - { - Class.forName("java.security.Security"); - } - catch (ClassNotFoundException e) - { - } - } - - SecurityManager.current = sm; - } - - /** - * Get the current SecurityManager. If the SecurityManager has not been - * set yet, then this method returns null. - * - * @return the current SecurityManager, or null - */ - public static SecurityManager getSecurityManager() - { - return SecurityManager.current; - } - - /** - * Get the current time, measured in the number of milliseconds from the - * beginning of Jan. 1, 1970. This is gathered from the system clock, with - * any attendant incorrectness (it may be timezone dependent). - * - * @return the current time - * @see java.util.Date - */ - public static long currentTimeMillis() - { - return VMSystem.currentTimeMillis(); - } - - /** - * <p> - * Returns the current value of a nanosecond-precise system timer. - * The value of the timer is an offset relative to some arbitrary fixed - * time, which may be in the future (making the value negative). This - * method is useful for timing events where nanosecond precision is - * required. This is achieved by calling this method before and after the - * event, and taking the difference betweent the two times: - * </p> - * <p> - * <code>long startTime = System.nanoTime();</code><br /> - * <code>... <emph>event code</emph> ...</code><br /> - * <code>long endTime = System.nanoTime();</code><br /> - * <code>long duration = endTime - startTime;</code><br /> - * </p> - * <p> - * Note that the value is only nanosecond-precise, and not accurate; there - * is no guarantee that the difference between two values is really a - * nanosecond. Also, the value is prone to overflow if the offset - * exceeds 2^63. - * </p> - * - * @return the time of a system timer in nanoseconds. - * @since 1.5 - */ - public static long nanoTime() - { - return VMSystem.nanoTime(); - } - - /** - * Copy one array onto another from <code>src[srcStart]</code> ... - * <code>src[srcStart+len-1]</code> to <code>dest[destStart]</code> ... - * <code>dest[destStart+len-1]</code>. First, the arguments are validated: - * neither array may be null, they must be of compatible types, and the - * start and length must fit within both arrays. Then the copying starts, - * and proceeds through increasing slots. If src and dest are the same - * array, this will appear to copy the data to a temporary location first. - * An ArrayStoreException in the middle of copying will leave earlier - * elements copied, but later elements unchanged. - * - * @param src the array to copy elements from - * @param srcStart the starting position in src - * @param dest the array to copy elements to - * @param destStart the starting position in dest - * @param len the number of elements to copy - * @throws NullPointerException if src or dest is null - * @throws ArrayStoreException if src or dest is not an array, if they are - * not compatible array types, or if an incompatible runtime type - * is stored in dest - * @throws IndexOutOfBoundsException if len is negative, or if the start or - * end copy position in either array is out of bounds - */ - public static void arraycopy(Object src, int srcStart, - Object dest, int destStart, int len) - { - VMSystem.arraycopy(src, srcStart, dest, destStart, len); - } - - /** - * Get a hash code computed by the VM for the Object. This hash code will - * be the same as Object's hashCode() method. It is usually some - * convolution of the pointer to the Object internal to the VM. It - * follows standard hash code rules, in that it will remain the same for a - * given Object for the lifetime of that Object. - * - * @param o the Object to get the hash code for - * @return the VM-dependent hash code for this Object - * @since 1.1 - */ - public static int identityHashCode(Object o) - { - return VMSystem.identityHashCode(o); - } - - /** - * Get all the system properties at once. A security check may be performed, - * <code>checkPropertiesAccess</code>. Note that a security manager may - * allow getting a single property, but not the entire group. - * - * <p>The required properties include: - * <dl> - * <dt>java.version</dt> <dd>Java version number</dd> - * <dt>java.vendor</dt> <dd>Java vendor specific string</dd> - * <dt>java.vendor.url</dt> <dd>Java vendor URL</dd> - * <dt>java.home</dt> <dd>Java installation directory</dd> - * <dt>java.vm.specification.version</dt> <dd>VM Spec version</dd> - * <dt>java.vm.specification.vendor</dt> <dd>VM Spec vendor</dd> - * <dt>java.vm.specification.name</dt> <dd>VM Spec name</dd> - * <dt>java.vm.version</dt> <dd>VM implementation version</dd> - * <dt>java.vm.vendor</dt> <dd>VM implementation vendor</dd> - * <dt>java.vm.name</dt> <dd>VM implementation name</dd> - * <dt>java.specification.version</dt> <dd>Java Runtime Environment version</dd> - * <dt>java.specification.vendor</dt> <dd>Java Runtime Environment vendor</dd> - * <dt>java.specification.name</dt> <dd>Java Runtime Environment name</dd> - * <dt>java.class.version</dt> <dd>Java class version number</dd> - * <dt>java.class.path</dt> <dd>Java classpath</dd> - * <dt>java.library.path</dt> <dd>Path for finding Java libraries</dd> - * <dt>java.io.tmpdir</dt> <dd>Default temp file path</dd> - * <dt>java.compiler</dt> <dd>Name of JIT to use</dd> - * <dt>java.ext.dirs</dt> <dd>Java extension path</dd> - * <dt>os.name</dt> <dd>Operating System Name</dd> - * <dt>os.arch</dt> <dd>Operating System Architecture</dd> - * <dt>os.version</dt> <dd>Operating System Version</dd> - * <dt>file.separator</dt> <dd>File separator ("/" on Unix)</dd> - * <dt>path.separator</dt> <dd>Path separator (":" on Unix)</dd> - * <dt>line.separator</dt> <dd>Line separator ("\n" on Unix)</dd> - * <dt>user.name</dt> <dd>User account name</dd> - * <dt>user.home</dt> <dd>User home directory</dd> - * <dt>user.dir</dt> <dd>User's current working directory</dd> - * </dl> - * ... [truncated message content] |
From: <cr...@us...> - 2009-01-04 14:07:59
|
Revision: 4827 http://jnode.svn.sourceforge.net/jnode/?rev=4827&view=rev Author: crawley Date: 2009-01-04 14:07:46 +0000 (Sun, 04 Jan 2009) Log Message: ----------- Bjorne shell command argument completion is now working for simple cases. I'm moving the bjorne shell plugin to the default plugin list to encourage testers to try it out. Modified Paths: -------------- trunk/all/conf/default-plugin-list.xml trunk/all/conf/full-plugin-list.xml trunk/shell/src/shell/org/jnode/shell/ArgumentCompleter.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 Modified: trunk/all/conf/default-plugin-list.xml =================================================================== --- trunk/all/conf/default-plugin-list.xml 2009-01-04 12:43:05 UTC (rev 4826) +++ trunk/all/conf/default-plugin-list.xml 2009-01-04 14:07:46 UTC (rev 4827) @@ -156,6 +156,7 @@ <plugin id="org.acplt.oncrpc"/> <plugin id="org.jnode.shell"/> + <plugin id="org.jnode.shell.bjorne"/> <plugin id="org.jnode.shell.help"/> <plugin id="org.jnode.shell.syntax"/> <plugin id="org.jnode.shell.command"/> Modified: trunk/all/conf/full-plugin-list.xml =================================================================== --- trunk/all/conf/full-plugin-list.xml 2009-01-04 12:43:05 UTC (rev 4826) +++ trunk/all/conf/full-plugin-list.xml 2009-01-04 14:07:46 UTC (rev 4827) @@ -31,7 +31,6 @@ <plugin id="thinlet"/> - <plugin id="org.jnode.shell.bjorne"/> <plugin id="org.jnode.shell.command.unix"/> <plugin id="org.jnode.apps.jpartition"/> Modified: trunk/shell/src/shell/org/jnode/shell/ArgumentCompleter.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/ArgumentCompleter.java 2009-01-04 12:43:05 UTC (rev 4826) +++ trunk/shell/src/shell/org/jnode/shell/ArgumentCompleter.java 2009-01-04 14:07:46 UTC (rev 4827) @@ -25,7 +25,7 @@ import org.jnode.shell.syntax.Argument; /** - * This class wraps an old-style Argument as a Completable for use in a default syntax. + * This class wraps an Argument as a Completable for use in a default syntax. * * @author cr...@jn... */ Modified: trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneContext.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneContext.java 2009-01-04 12:43:05 UTC (rev 4826) +++ trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneContext.java 2009-01-04 14:07:46 UTC (rev 4827) @@ -199,7 +199,7 @@ } /** - * Crreat a copy of a context with the same initial variable bindings and + * Create 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. @@ -305,111 +305,123 @@ } /** - * Perform expand-and-split processing on an array of word/name tokens. + * Perform expand-and-split processing on an array of word tokens. The resulting + * wordTokens are assembled into a CommandLine. * * @param tokens the tokens to be expanded and split into words - * @return the resulting words + * @return the command line * @throws ShellException */ public CommandLine expandAndSplit(BjorneToken[] tokens) throws ShellException { - LinkedList<String> words = new LinkedList<String>(); + LinkedList<BjorneToken> wordTokens = new LinkedList<BjorneToken>(); for (BjorneToken token : tokens) { - splitAndAppend(expand(token.getText()), words); + splitAndAppend(token, wordTokens); } - return makeCommandLine(words); + return makeCommandLine(wordTokens); } /** - * Perform expand-and-split processing on sequence of characters + * Perform expand-and-split processing on a sequence of characters. The resulting + * wordTokens are assembled into a CommandLine. This method is only used in tests + * at the moment, and probably should be removed. (It does not set token attributes + * properly ...) * * @param text the characters to be split - * @return the resulting words + * @return the command line * @throws ShellException */ public CommandLine expandAndSplit(CharSequence text) throws ShellException { - LinkedList<String> words = split(expand(text)); + LinkedList<BjorneToken> words = split(expand(text)); return makeCommandLine(words); } - private CommandLine makeCommandLine(LinkedList<String> words) { + private CommandLine makeCommandLine(LinkedList<BjorneToken> wordTokens) { if (globbing || tildes) { - LinkedList<String> globbedWords = new LinkedList<String>(); - for (String word : words) { + LinkedList<BjorneToken> globbedWordTokens = new LinkedList<BjorneToken>(); + for (BjorneToken wordToken : wordTokens) { if (tildes) { - word = tildeExpand(word); + wordToken = tildeExpand(wordToken); } if (globbing) { - globAndAppend(word, globbedWords); + globAndAppend(wordToken, globbedWordTokens); } else { - globbedWords.add(word); + globbedWordTokens.add(wordToken); } } - words = globbedWords; + wordTokens = globbedWordTokens; } - int nosWords = words.size(); + int nosWords = wordTokens.size(); if (nosWords == 0) { return new CommandLine(null, null); - } else if (nosWords == 1) { - return new CommandLine(words.get(0), null); } else { - String alias = words.removeFirst(); - String[] args = words.toArray(new String[nosWords - 1]); - return new CommandLine(alias, args); + BjorneToken alias = wordTokens.removeFirst(); + BjorneToken[] args = wordTokens.toArray(new BjorneToken[nosWords - 1]); + return new CommandLine(alias, args, null); } } - private String tildeExpand(String word) { + private BjorneToken tildeExpand(BjorneToken wordToken) { + String word = wordToken.getText(); if (word.startsWith("~")) { int slashPos = word.indexOf(File.separatorChar); String name = (slashPos >= 0) ? word.substring(1, slashPos) : ""; - // FIXME ... support "~username" when we have kind of user info / management. + // FIXME ... support "~username" when we have some kind of user info / management. String home = (name.length() == 0) ? System.getProperty("user.home", "") : ""; if (home.length() == 0) { - return word; - } else if (slashPos == -1) { - return home; - } else { - return home + word.substring(slashPos); - } + return wordToken; + } + String expansion = (slashPos == -1) ? + home : (home + word.substring(slashPos)); + return wordToken.remake(expansion); } else { - return word; + return wordToken; } } - private void globAndAppend(String word, LinkedList<String> globbedWords) { + private void globAndAppend(BjorneToken wordToken, LinkedList<BjorneToken> globbedWordTokens) { // Try to deal with the 'not-a-pattern' case quickly and cheaply. + String word = wordToken.getText(); if (!PathnamePattern.isPattern(word)) { - globbedWords.add(word); + globbedWordTokens.add(wordToken); return; } PathnamePattern pattern = PathnamePattern.compile(word); LinkedList<String> paths = pattern.expand(new File(".")); // If it doesn't match anything, a pattern 'expands' to itself. if (paths.isEmpty()) { - globbedWords.add(word); + globbedWordTokens.add(wordToken); } else { - globbedWords.addAll(paths); + for (String path : paths) { + globbedWordTokens.add(wordToken.remake(path)); + } } } /** - * Split a character sequence into words, dealing with and removing any - * non-literal quotes. + * Split a character sequence into word tokens, dealing with and removing any + * non-literal * * @param text the characters to be split - * @return the resulting list of words. + * @return the destination for the tokens. * @throws ShellException */ - public LinkedList<String> split(CharSequence text) throws ShellException { - LinkedList<String> words = new LinkedList<String>(); - splitAndAppend(text, words); - return words; + public LinkedList<BjorneToken> split(CharSequence text) throws ShellException { + LinkedList<BjorneToken> wordTokens = new LinkedList<BjorneToken>(); + splitAndAppend(new BjorneToken(-1, text.toString(), -1, -1), wordTokens); + return wordTokens; } /** - * This method does the work of 'split'; see above. + * Split a token into a series of word tokens, dealing with and removing any + * non-literal quotes. The resulting tokens are appended to a supplied list. + * + * @param token the token to be split + * @param wordTokens the destination for the tokens. + * @throws ShellException */ - private void splitAndAppend(CharSequence text, LinkedList<String> words) throws ShellException { + private void splitAndAppend(BjorneToken token, LinkedList<BjorneToken> wordTokens) + throws ShellException { + String text = token.getText(); StringBuffer sb = null; int len = text.length(); int quote = 0; @@ -433,7 +445,7 @@ case '\t': if (quote == 0) { if (sb != null) { - words.add(sb.toString()); + wordTokens.add(token.remake(sb.toString())); sb = null; } } else { @@ -452,7 +464,7 @@ } } if (sb != null) { - words.add(sb.toString()); + wordTokens.add(token.remake(sb.toString())); } } Modified: trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneInterpreter.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneInterpreter.java 2009-01-04 12:43:05 UTC (rev 4826) +++ trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneInterpreter.java 2009-01-04 14:07:46 UTC (rev 4827) @@ -51,10 +51,10 @@ import org.jnode.shell.syntax.CommandSyntaxException; /** - * This is a Java implementation of the Bourne Shell language. + * This is the JNode implementation of the Bourne Shell language. The long term + * goal is to faithfully implement the POSIX Shell specification. * * @author cr...@jn... - * */ public class BjorneInterpreter implements CommandInterpreter { @@ -141,6 +141,7 @@ private BjorneContext context; public BjorneInterpreter() { + this.context = new BjorneContext(this); } @Override @@ -155,15 +156,15 @@ @Override public Completable parsePartial(CommandShell shell, String partial) throws ShellSyntaxException { - init(shell); + bindShell(shell); BjorneTokenizer tokens = new BjorneTokenizer(partial); final CommandNode tree = new BjorneParser(tokens).parse(); if (tree instanceof BjorneCompletable) { return new Completable() { @Override - public void complete(CompletionInfo completion, + public void complete(CompletionInfo completions, CommandShell shell) throws CompletionException { - ((BjorneCompletable) tree).complete(completion, context, shell); + ((BjorneCompletable) tree).complete(completions, context, shell); } }; @@ -187,8 +188,10 @@ int interpret(CommandShell shell, String command, OutputStream capture, boolean source) throws ShellException { BjorneContext myContext; + // FIXME ... I think there is something wrong / incomplete with the way I'm handling + // the contexts here ... if (capture == null) { - init(shell); + bindShell(shell); myContext = this.context; } else { myContext = new BjorneContext(this); @@ -215,13 +218,12 @@ } } - private void init(CommandShell shell) { + private void bindShell(CommandShell shell) { if (this.shell != shell) { if (this.shell != null) { throw new ShellFailureException("my shell changed"); } this.shell = shell; - this.context = new BjorneContext(this); } } Modified: trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneToken.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneToken.java 2009-01-04 12:43:05 UTC (rev 4826) +++ trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneToken.java 2009-01-04 14:07:46 UTC (rev 4827) @@ -129,6 +129,10 @@ super(text == null ? "" : text, tokenType, start, end); validate(); } + + public BjorneToken remake(String newText) { + return new BjorneToken(this.tokenType, newText, this.start, this.end); + } private void validate() { switch (tokenType) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cr...@us...> - 2009-01-09 12:34:42
|
Revision: 4836 http://jnode.svn.sourceforge.net/jnode/?rev=4836&view=rev Author: crawley Date: 2009-01-09 12:26:02 +0000 (Fri, 09 Jan 2009) Log Message: ----------- Fix for the proclet stream cycle bug Modified Paths: -------------- trunk/core/src/core/org/jnode/util/ProxyStream.java trunk/shell/src/shell/org/jnode/shell/proclet/ProcletContext.java trunk/shell/src/shell/org/jnode/shell/proclet/ProcletIOContext.java trunk/shell/src/shell/org/jnode/shell/proclet/ProcletProxyInputStream.java trunk/shell/src/shell/org/jnode/shell/proclet/ProcletProxyPrintStream.java Modified: trunk/core/src/core/org/jnode/util/ProxyStream.java =================================================================== --- trunk/core/src/core/org/jnode/util/ProxyStream.java 2009-01-07 11:45:52 UTC (rev 4835) +++ trunk/core/src/core/org/jnode/util/ProxyStream.java 2009-01-09 12:26:02 UTC (rev 4836) @@ -46,16 +46,4 @@ * @return the wrapped stream for this proxy. */ public T getProxiedStream() throws ProxyStreamException; - - /** - * Determine if this proxy refers to the same underlying stream as another - * stream object. - * - * @param other - * @return <code>true</code> if this object and <code>other</code> - * resolve to the same underlying stream, otherwise false. Note: the - * 'otherwise' covers cases where <code>other</code> is - * <code>null</code>. - */ - public boolean sameStream(T other) throws ProxyStreamException; } Modified: trunk/shell/src/shell/org/jnode/shell/proclet/ProcletContext.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/proclet/ProcletContext.java 2009-01-07 11:45:52 UTC (rev 4835) +++ trunk/shell/src/shell/org/jnode/shell/proclet/ProcletContext.java 2009-01-09 12:26:02 UTC (rev 4836) @@ -34,6 +34,7 @@ import org.jnode.util.ProxyStreamException; import org.jnode.vm.VmExit; import org.jnode.vm.VmSystem; +import org.jnode.vm.isolate.VmIsolate; /** * This class implements the proclet-specific state used in the JNode proclet @@ -46,8 +47,9 @@ * @author cr...@jn... */ public class ProcletContext extends ThreadGroup { + public static final int NO_SUCH_PID = 0; + private Properties properties; - private Object[] streams; private Map<String, String> environment; private int threadCount; private final int pid; @@ -66,8 +68,8 @@ properties = parentContext.properties; } if (properties == null) { - properties = AccessController - .doPrivileged(new PrivilegedAction<Properties>() { + properties = AccessController.doPrivileged( + new PrivilegedAction<Properties>() { public Properties run() { return System.getProperties(); } @@ -76,19 +78,13 @@ properties = (Properties) properties.clone(); } if (streams == null) { - if (parentContext != null) { - streams = parentContext.streams; - } - if (streams == null) { - try { - streams = new Object[] { - resolve(System.in), resolve(System.out), resolve(System.err)}; - } catch (ProxyStreamException ex) { - throw new ProcletException("Broken streams", ex); - } - } else { - streams = (Object[]) streams.clone(); - } + try { + streams = new Object[] { + resolve(System.in), resolve(System.out), resolve(System.err) + }; + } catch (ProxyStreamException ex) { + throw new ProcletException("Broken streams", ex); + } } if (environment == null) { if (parentContext != null) { @@ -100,14 +96,17 @@ } this.environment = environment; this.properties = properties; - this.streams = streams; this.pid = extractPid(getName()); + ((ProcletIOContext) VmIsolate.getRoot().getIOContext()).setStreamsForNewProclet(pid, streams); setDaemon(true); } private Closeable resolve(Closeable stream) throws ProxyStreamException { - return (stream instanceof ProxyStream) ? ((ProxyStream<?>) stream) - .getProxiedStream() : stream; + if (stream instanceof ProxyStream) { + return ((ProxyStream<?>) stream).getProxiedStream(); + } else { + return stream; + } } /** @@ -127,44 +126,6 @@ return properties; } - /** - * Set the stream object that corresponds to a given 'fd'. - * - * @param fd a non-negative index into the streams vector. - * @param stream the stream object to set. - */ - synchronized void setStream(int fd, Object stream) { - if (stream instanceof ProcletProxyStream) { - throw new IllegalArgumentException( - "stream is a proclet proxy stream"); - } - if (fd < 0) { - throw new IllegalArgumentException("fd is negative"); - } - if (fd >= streams.length) { - Object[] tmp = new Object[fd + 1]; - System.arraycopy(streams, 0, tmp, 0, streams.length); - streams = tmp; - } - streams[fd] = stream; - } - - /** - * Get the stream object that corresponds to a given 'fd'. - * - * @param fd a non-negative index into the streams vector. - * @return the stream object, or <code>null</code> - */ - public synchronized Object getStream(int fd) { - if (fd < 0) { - throw new IllegalArgumentException("fd is negative"); - } else if (fd > streams.length) { - return null; - } else { - return streams[fd]; - } - } - public synchronized void setProperties(Properties properties) { this.properties = properties; } Modified: trunk/shell/src/shell/org/jnode/shell/proclet/ProcletIOContext.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/proclet/ProcletIOContext.java 2009-01-07 11:45:52 UTC (rev 4835) +++ trunk/shell/src/shell/org/jnode/shell/proclet/ProcletIOContext.java 2009-01-09 12:26:02 UTC (rev 4836) @@ -24,118 +24,105 @@ import java.io.InputStream; import java.io.PrintStream; -import org.jnode.util.ProxyStreamException; import org.jnode.vm.IOContext; import org.jnode.vm.VmSystem; /** + * The ProcletIOContext is an IOContext implementation that uses Proxy streams to + * direct System.in/out/err traffic to different places depending on the current + * proclet. + * * @author Levente S\u00e1ntha * @author cr...@jn... */ public class ProcletIOContext implements IOContext { - private static InputStream globalInStream; - private static PrintStream globalOutStream; - private static PrintStream globalErrStream; - private static boolean initialized; + public static final int GLOBAL_STREAM_ID = ProcletContext.NO_SUCH_PID; + public ProcletIOContext() { - initGlobals(); } - private static synchronized void initGlobals() { - if (!initialized) { - globalInStream = System.in; - globalOutStream = System.out; - globalErrStream = System.err; - initialized = true; - } + public synchronized void setGlobalInStream(InputStream is) { + doSetIn(is, GLOBAL_STREAM_ID); } - public void setGlobalInStream(InputStream in) { - globalInStream = in; + public synchronized void setGlobalOutStream(PrintStream ps) { + doSetOut(ps, GLOBAL_STREAM_ID); } - public void setGlobalOutStream(PrintStream out) { - globalOutStream = out; + public synchronized void setGlobalErrStream(PrintStream is) { + doSetErr(is, GLOBAL_STREAM_ID); } - public PrintStream getGlobalOutStream() { - return globalOutStream; + public synchronized InputStream getGlobalInStream() { + return ((ProcletProxyInputStream) System.in).getProxiedStream(GLOBAL_STREAM_ID); } - public void setGlobalErrStream(PrintStream err) { - globalErrStream = err; + public synchronized PrintStream getGlobalOutStream() { + return ((ProcletProxyPrintStream) System.out).getProxiedStream(GLOBAL_STREAM_ID); } - public PrintStream getGlobalErrStream() { - return globalErrStream; + public synchronized PrintStream getGlobalErrStream() { + return ((ProcletProxyPrintStream) System.err).getProxiedStream(GLOBAL_STREAM_ID); } - public InputStream getGlobalInStream() { - return globalInStream; + public synchronized void setSystemIn(InputStream is) { + doSetIn(is, getCurrentPid()); } - public void setSystemIn(InputStream in) { - if (in instanceof ProcletProxyInputStream) { - try { - in = ((ProcletProxyInputStream) in).getProxiedStream(); - } catch (ProxyStreamException ex) { - throw new ProcletException("Cannot resolve 'in'", ex); - } - } + public synchronized void setSystemOut(PrintStream ps) { + doSetOut(ps, getCurrentPid()); + } + + public synchronized void setSystemErr(PrintStream ps) { + doSetErr(ps, getCurrentPid()); + } + + private int getCurrentPid() { ProcletContext procletContext = ProcletContext.currentProcletContext(); - if (procletContext != null) { - procletContext.setStream(0, in); - } else { - globalInStream = in; + return (procletContext == null) ? GLOBAL_STREAM_ID : procletContext.getPid(); + } + + private void doSetIn(InputStream is, int pid) { + if (is instanceof ProcletProxyInputStream) { + is = ((ProcletProxyInputStream) is).getProxiedStream(pid); } + ProcletProxyInputStream newProxyStream = new ProcletProxyInputStream( + (ProcletProxyInputStream) System.in, is, pid); + VmSystem.setStaticField(System.class, "in", newProxyStream); } - public void setSystemOut(PrintStream out) { - if (out instanceof ProcletProxyPrintStream) { - try { - out = ((ProcletProxyPrintStream) out).getProxiedStream(); - } catch (ProxyStreamException ex) { - throw new ProcletException("Cannot resolve 'out'", ex); - } + private void doSetOut(PrintStream ps, int pid) { + if (ps instanceof ProcletProxyPrintStream) { + ps = ((ProcletProxyPrintStream) ps).getProxiedStream(pid); } - ProcletContext procletContext = ProcletContext.currentProcletContext(); - if (procletContext != null) { - procletContext.setStream(1, out); - } else { - globalOutStream = out; - } + ProcletProxyPrintStream newProxyStream = new ProcletProxyPrintStream( + (ProcletProxyPrintStream) System.out, ps, pid); + VmSystem.setStaticField(System.class, "out", newProxyStream); } - public void setSystemErr(PrintStream err) { - if (err instanceof ProcletProxyPrintStream) { - try { - err = ((ProcletProxyPrintStream) err).getProxiedStream(); - } catch (ProxyStreamException ex) { - throw new ProcletException("Cannot resolve 'err'", ex); - } + private void doSetErr(PrintStream ps, int pid) { + if (ps instanceof ProcletProxyPrintStream) { + ps = ((ProcletProxyPrintStream) ps).getProxiedStream(pid); } - ProcletContext procletContext = ProcletContext.currentProcletContext(); - if (procletContext != null) { - procletContext.setStream(2, err); - } else { - globalErrStream = err; - } + ProcletProxyPrintStream newProxyStream = new ProcletProxyPrintStream( + (ProcletProxyPrintStream) System.err, ps, pid); + VmSystem.setStaticField(System.class, "err", newProxyStream); } - public void enterContext() { + public synchronized void enterContext() { VmSystem.setStaticField(System.class, "in", - new ProcletProxyInputStream()); + new ProcletProxyInputStream(System.in, 0)); VmSystem.setStaticField(System.class, "out", - new ProcletProxyPrintStream(1)); + new ProcletProxyPrintStream(System.out, 1)); VmSystem.setStaticField(System.class, "err", - new ProcletProxyPrintStream(2)); + new ProcletProxyPrintStream(System.err, 2)); } - public void exitContext() { - InputStream in = globalInStream; - PrintStream out = globalOutStream; - PrintStream err = globalErrStream; + public synchronized void exitContext() { + InputStream in = getGlobalInStream(); + PrintStream out = getGlobalOutStream(); + PrintStream err = getGlobalErrStream(); if (in instanceof ProcletProxyStream) { throw new ProcletException( @@ -154,30 +141,27 @@ VmSystem.setStaticField(System.class, "err", err); } - public PrintStream getRealSystemErr() { - ProcletContext procletContext = ProcletContext.currentProcletContext(); - if (procletContext != null) { - return (PrintStream) procletContext.getStream(2); - } else { - return globalErrStream; - } + public synchronized PrintStream getRealSystemErr() { + return ((ProcletProxyPrintStream) System.err).getProxiedStream(getCurrentPid()); } - public InputStream getRealSystemIn() { - ProcletContext procletContext = ProcletContext.currentProcletContext(); - if (procletContext != null) { - return (InputStream) procletContext.getStream(0); - } else { - return globalInStream; - } + public synchronized InputStream getRealSystemIn() { + return ((ProcletProxyInputStream) System.in).getProxiedStream(getCurrentPid()); } - public PrintStream getRealSystemOut() { - ProcletContext procletContext = ProcletContext.currentProcletContext(); - if (procletContext != null) { - return (PrintStream) procletContext.getStream(1); - } else { - return globalOutStream; - } + public synchronized PrintStream getRealSystemOut() { + return ((ProcletProxyPrintStream) System.out).getProxiedStream(getCurrentPid()); } + + synchronized void setStreamsForNewProclet(int pid, Object[] streams) { + ProcletProxyInputStream in = new ProcletProxyInputStream( + (ProcletProxyInputStream) System.in, (InputStream) streams[0], pid); + ProcletProxyPrintStream out = new ProcletProxyPrintStream( + (ProcletProxyPrintStream) System.out, (PrintStream) streams[1], pid); + ProcletProxyPrintStream err = new ProcletProxyPrintStream( + (ProcletProxyPrintStream) System.err, (PrintStream) streams[2], pid); + VmSystem.setStaticField(System.class, "in", in); + VmSystem.setStaticField(System.class, "out", out); + VmSystem.setStaticField(System.class, "err", err); + } } Modified: trunk/shell/src/shell/org/jnode/shell/proclet/ProcletProxyInputStream.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/proclet/ProcletProxyInputStream.java 2009-01-07 11:45:52 UTC (rev 4835) +++ trunk/shell/src/shell/org/jnode/shell/proclet/ProcletProxyInputStream.java 2009-01-09 12:26:02 UTC (rev 4836) @@ -23,10 +23,11 @@ import java.io.IOException; import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; import org.jnode.util.ProxyStream; import org.jnode.util.ProxyStreamException; -import org.jnode.vm.VmSystem; /** * This class provides a proxy mechanism for System.in. If the current thread is @@ -38,28 +39,48 @@ */ public class ProcletProxyInputStream extends InputStream implements ProcletProxyStream<InputStream> { + + private Map<Integer, InputStream> streamMap; private int fd; /** - * Construct a proxy input stream for 'standard input'; i.e. fd = 0; - */ - public ProcletProxyInputStream() { - this(0); - } - - /** * Construct a proxy input stream for a designated fd. Note that if the fd * is non-zero, the proxy will not work in a non-ProcletContext context, and * not work in the ProcletContext context if the fd doesn't correspond to an * InputStream. * + * @param is the initial value for globalInput. * @param fd */ - public ProcletProxyInputStream(int fd) { + public ProcletProxyInputStream(InputStream is, int fd) { this.fd = fd; + streamMap = new HashMap<Integer, InputStream>(); + if (is == null) { + throw new IllegalArgumentException("null stream"); + } + streamMap.put(ProcletIOContext.GLOBAL_STREAM_ID, is); } + /** + * Construct a proxy input stream based on the state of the supplied proxy. + * The new proxy has all entries of the existing one except that the entry + * for pid is set / reset to in. + * + * @param proxy + * @param is + * @param pid + */ + public ProcletProxyInputStream(ProcletProxyInputStream proxy, InputStream is, + int pid) { + if (is == null) { + throw new IllegalArgumentException("null stream"); + } + streamMap = new HashMap<Integer, InputStream>(proxy.streamMap); + streamMap.put(pid, is); + fd = proxy.fd; + } + @Override public int read() throws IOException { return getRealStream().read(); @@ -124,43 +145,25 @@ } public InputStream getProxiedStream() throws ProxyStreamException { - ThreadGroup threadGroup = Thread.currentThread().getThreadGroup(); - if (threadGroup instanceof ProcletContext) { - try { - Object stream = ((ProcletContext) threadGroup).getStream(fd); - if (stream instanceof ProcletProxyStream) { - throw new ProxyStreamException( - "Proclet stream points to another proclet stream"); - } - if (stream instanceof ProxyStream) { - stream = ((ProxyStream<?>) stream).getRealStream(); - } - return (InputStream) stream; - } catch (Exception ex) { - throw new ProxyStreamException("Proclet input broken for fd = " - + fd, ex); - } - } else { - if (fd != 0) { - throw new ProxyStreamException( - "Proclet input broken: wrong fd = " + fd); - } - return VmSystem.getGlobalInStream(); + ProcletContext procletContext = ProcletContext.currentProcletContext(); + int pid = (procletContext == null) ? ProcletIOContext.GLOBAL_STREAM_ID : procletContext.getPid(); + InputStream is = streamMap.get(pid); + if (is == null) { + throw new ProxyStreamException( + "Proclet stream not set (fd = " + fd + ")"); + } else if (is instanceof ProcletProxyStream) { + throw new ProxyStreamException( + "Proclet stream points to another proclet stream (fd = " + fd + ")"); } + return is; } - @SuppressWarnings("unchecked") - public boolean sameStream(InputStream obj) throws ProxyStreamException { - InputStream rs = getRealStream(); - if (obj == rs) { - return true; - } else if (rs instanceof ProxyStream) { - return ((ProxyStream<InputStream>) rs).sameStream(obj); - } else if (obj instanceof ProxyStream) { - return ((ProxyStream<InputStream>) obj).sameStream(rs); - } else { - return false; + InputStream getProxiedStream(int pid) { + InputStream is = streamMap.get(pid); + if (is == null && pid != ProcletIOContext.GLOBAL_STREAM_ID) { + is = streamMap.get(ProcletIOContext.GLOBAL_STREAM_ID); } + return is; } } Modified: trunk/shell/src/shell/org/jnode/shell/proclet/ProcletProxyPrintStream.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/proclet/ProcletProxyPrintStream.java 2009-01-07 11:45:52 UTC (rev 4835) +++ trunk/shell/src/shell/org/jnode/shell/proclet/ProcletProxyPrintStream.java 2009-01-09 12:26:02 UTC (rev 4836) @@ -22,10 +22,11 @@ package org.jnode.shell.proclet; import java.io.PrintStream; +import java.util.HashMap; +import java.util.Map; import org.jnode.util.ProxyStream; import org.jnode.util.ProxyStreamException; -import org.jnode.vm.VmSystem; /** * This class provides a proxy mechanism for System.out,err. If the current @@ -37,46 +38,64 @@ */ public class ProcletProxyPrintStream extends AbstractProxyPrintStream implements ProcletProxyStream<PrintStream> { + + private Map<Integer, PrintStream> streamMap; + private final int fd; - public ProcletProxyPrintStream(int fd) { + /** + * Construct a proxy print stream with 'out' as the initial global stream. + * + * @param proxy + * @param ps + * @param pid + */ + public ProcletProxyPrintStream(PrintStream ps, int fd) { super(); + if (ps == null) { + throw new IllegalArgumentException("null stream"); + } this.fd = fd; + streamMap = new HashMap<Integer, PrintStream>(); + streamMap.put(ProcletIOContext.GLOBAL_STREAM_ID, ps); } - + /** + * Construct a proxy print stream based on the state of the supplied proxy. + * The new proxy has all entries of the existing one except that the entry + * for pid is set / reset to in. + * + * @param proxy + * @param ps + * @param pid + */ + public ProcletProxyPrintStream(ProcletProxyPrintStream proxy, PrintStream ps, + int pid) { + if (ps == null) { + throw new IllegalArgumentException("null stream"); + } + streamMap = new HashMap<Integer, PrintStream>(proxy.streamMap); + streamMap.put(pid, ps); + fd = proxy.fd; + } + + /** * This method does the work of deciding which printstream to delegate to. * * @return the PrintStream we are currently delegating to. */ private PrintStream proxiedPrintStream() throws ProxyStreamException { - ThreadGroup threadGroup = Thread.currentThread().getThreadGroup(); - if (threadGroup instanceof ProcletContext) { - try { - Object stream = ((ProcletContext) threadGroup).getStream(fd); - if (stream instanceof ProcletProxyStream) { - throw new ProxyStreamException( - "Proclet stream points to another proclet stream"); - } - if (stream instanceof ProxyStream) { - stream = ((ProxyStream<?>) stream).getRealStream(); - } - return (PrintStream) stream; - } catch (Exception ex) { - throw new ProxyStreamException("Proclet print broken for fd = " - + fd, ex); - } - } else { - switch (fd) { - case 1: - return VmSystem.getGlobalOutStream(); - case 2: - return VmSystem.getGlobalErrStream(); - default: - throw new ProxyStreamException( - "Proclet print stream broken: wrong fd = " + fd); - } + ProcletContext procletContext = ProcletContext.currentProcletContext(); + int pid = (procletContext == null) ? ProcletIOContext.GLOBAL_STREAM_ID : procletContext.getPid(); + PrintStream ps = getProxiedStream(pid); + if (ps == null) { + throw new ProxyStreamException( + "Proclet stream not set (fd = " + fd + ")"); + } else if (ps instanceof ProcletProxyStream) { + throw new ProxyStreamException( + "Proclet stream points to another proclet stream (fd = " + fd + ")"); } + return ps; } @SuppressWarnings("unchecked") @@ -101,18 +120,12 @@ return proxiedPrintStream(); } - @SuppressWarnings("unchecked") - public boolean sameStream(PrintStream obj) throws ProxyStreamException { - PrintStream rs = getRealStream(); - if (obj == rs) { - return true; - } else if (rs instanceof ProxyStream) { - return ((ProxyStream<PrintStream>) rs).sameStream(obj); - } else if (obj instanceof ProxyStream) { - return ((ProxyStream<PrintStream>) obj).sameStream(rs); - } else { - return false; + PrintStream getProxiedStream(int pid) { + PrintStream ps = streamMap.get(pid); + if (ps == null && pid != ProcletIOContext.GLOBAL_STREAM_ID) { + ps = streamMap.get(ProcletIOContext.GLOBAL_STREAM_ID); } + return ps; } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cr...@us...> - 2009-01-11 06:29:00
|
Revision: 4847 http://jnode.svn.sourceforge.net/jnode/?rev=4847&view=rev Author: crawley Date: 2009-01-11 06:28:56 +0000 (Sun, 11 Jan 2009) Log Message: ----------- Rename the 'token' field of the CommandToken type to 'text'. Fix a couple of Bjorne bugs that prevented backtick redirection from working. Modified Paths: -------------- trunk/fs/src/fs/org/jnode/fs/nfs/command/NFSHostNameArgument.java trunk/fs/src/fs/org/jnode/partitions/command/IBMPartitionTypeArgument.java trunk/net/src/net/org/jnode/net/syntax/IPv4AddressArgument.java trunk/net/src/net/org/jnode/net/syntax/IPv4HostArgument.java trunk/shell/src/shell/org/jnode/shell/ArgumentCompleter.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/bjorne/BjorneContext.java trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneToken.java trunk/shell/src/shell/org/jnode/shell/bjorne/CaseCommandNode.java trunk/shell/src/shell/org/jnode/shell/command/BindKeysCommand.java trunk/shell/src/shell/org/jnode/shell/syntax/AliasArgument.java trunk/shell/src/shell/org/jnode/shell/syntax/ClassNameArgument.java trunk/shell/src/shell/org/jnode/shell/syntax/CountryArgument.java trunk/shell/src/shell/org/jnode/shell/syntax/DeviceArgument.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/HostNameArgument.java trunk/shell/src/shell/org/jnode/shell/syntax/IntegerArgument.java trunk/shell/src/shell/org/jnode/shell/syntax/KeyboardLayoutArgument.java trunk/shell/src/shell/org/jnode/shell/syntax/LanguageArgument.java trunk/shell/src/shell/org/jnode/shell/syntax/Log4jLoggerArgument.java trunk/shell/src/shell/org/jnode/shell/syntax/LongArgument.java trunk/shell/src/shell/org/jnode/shell/syntax/MappedArgument.java trunk/shell/src/shell/org/jnode/shell/syntax/MuParser.java trunk/shell/src/shell/org/jnode/shell/syntax/OptionSetSyntax.java trunk/shell/src/shell/org/jnode/shell/syntax/PropertyNameArgument.java trunk/shell/src/shell/org/jnode/shell/syntax/SizeArgument.java trunk/shell/src/shell/org/jnode/shell/syntax/StringArgument.java trunk/shell/src/shell/org/jnode/shell/syntax/URLArgument.java trunk/shell/src/test/org/jnode/test/shell/syntax/CommandLineTest.java trunk/shell/src/test/org/jnode/test/shell/syntax/DefaultTokenizerTest.java Modified: trunk/fs/src/fs/org/jnode/fs/nfs/command/NFSHostNameArgument.java =================================================================== --- trunk/fs/src/fs/org/jnode/fs/nfs/command/NFSHostNameArgument.java 2009-01-10 13:42:03 UTC (rev 4846) +++ trunk/fs/src/fs/org/jnode/fs/nfs/command/NFSHostNameArgument.java 2009-01-11 06:28:56 UTC (rev 4847) @@ -98,15 +98,15 @@ @Override protected String doAccept(Token value) throws CommandSyntaxException { - int index = value.token.indexOf(':'); + int index = value.text.indexOf(':'); if (index == -1) { throw new CommandSyntaxException("missing ':'"); } else if (index == 0) { throw new CommandSyntaxException("no hostname before ':'"); - } else if (index == value.token.length() - 1) { + } else if (index == value.text.length() - 1) { throw new CommandSyntaxException("no directory after ':'"); } else { - return value.token; + return value.text; } } } Modified: trunk/fs/src/fs/org/jnode/partitions/command/IBMPartitionTypeArgument.java =================================================================== --- trunk/fs/src/fs/org/jnode/partitions/command/IBMPartitionTypeArgument.java 2009-01-10 13:42:03 UTC (rev 4846) +++ trunk/fs/src/fs/org/jnode/partitions/command/IBMPartitionTypeArgument.java 2009-01-11 06:28:56 UTC (rev 4847) @@ -40,7 +40,7 @@ @Override protected IBMPartitionTypes doAccept(Token value) throws CommandSyntaxException { try { - int code = Integer.parseInt(value.token, 16); + int code = Integer.parseInt(value.text, 16); return IBMPartitionTypes.valueOf(code); } catch (NumberFormatException ex) { throw new CommandSyntaxException("not a valid hexadecimal number"); Modified: trunk/net/src/net/org/jnode/net/syntax/IPv4AddressArgument.java =================================================================== --- trunk/net/src/net/org/jnode/net/syntax/IPv4AddressArgument.java 2009-01-10 13:42:03 UTC (rev 4846) +++ trunk/net/src/net/org/jnode/net/syntax/IPv4AddressArgument.java 2009-01-11 06:28:56 UTC (rev 4847) @@ -26,10 +26,10 @@ @Override protected IPv4Address doAccept(Token value) throws CommandSyntaxException { - if (value.token.equals("default")) { + if (value.text.equals("default")) { return new IPv4Address(new byte[]{0, 0, 0, 0}, 0); } - final StringTokenizer tok = new StringTokenizer(value.token, "."); + final StringTokenizer tok = new StringTokenizer(value.text, "."); if (tok.countTokens() != 4) { throw new CommandSyntaxException("wrong number of components for an IPv4 address"); } Modified: trunk/net/src/net/org/jnode/net/syntax/IPv4HostArgument.java =================================================================== --- trunk/net/src/net/org/jnode/net/syntax/IPv4HostArgument.java 2009-01-10 13:42:03 UTC (rev 4846) +++ trunk/net/src/net/org/jnode/net/syntax/IPv4HostArgument.java 2009-01-11 06:28:56 UTC (rev 4847) @@ -25,7 +25,7 @@ @Override protected IPv4Address doAccept(Token value) throws CommandSyntaxException { try { - return new IPv4Address(value.token); + return new IPv4Address(value.text); } catch (IllegalArgumentException ex) { throw new CommandSyntaxException("invalid hostname or IPv4 address"); } Modified: trunk/shell/src/shell/org/jnode/shell/ArgumentCompleter.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/ArgumentCompleter.java 2009-01-10 13:42:03 UTC (rev 4846) +++ trunk/shell/src/shell/org/jnode/shell/ArgumentCompleter.java 2009-01-11 06:28:56 UTC (rev 4847) @@ -47,7 +47,7 @@ } public void complete(CompletionInfo completion, CommandShell shell) { - argument.complete(completion, token == null ? "" : token.token); + argument.complete(completion, token == null ? "" : token.text); if (token != null) { completion.setCompletionStart(token.start); } Modified: trunk/shell/src/shell/org/jnode/shell/CommandLine.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/CommandLine.java 2009-01-10 13:42:03 UTC (rev 4846) +++ trunk/shell/src/shell/org/jnode/shell/CommandLine.java 2009-01-11 06:28:56 UTC (rev 4847) @@ -200,21 +200,21 @@ if (!hasNext()) { throw new NoSuchElementException(); } - return argumentTokens[pos++].token; + return argumentTokens[pos++].text; } public String peek() throws NoSuchElementException { if (!hasNext()) { throw new NoSuchElementException(); } - return argumentTokens[pos].token; + return argumentTokens[pos].text; } public String last() throws NoSuchElementException { if (pos <= 0) { throw new NoSuchElementException(); } - return argumentTokens[pos - 1].token; + return argumentTokens[pos - 1].text; } public void remove() { @@ -307,7 +307,7 @@ * @return the command name */ public String getCommandName() { - return commandToken == null ? null : commandToken.token; + return commandToken == null ? null : commandToken.text; } /** @@ -331,7 +331,7 @@ } String[] arguments = new String[len]; for (int i = 0; i < len; i++) { - arguments[i] = argumentTokens[i].token; + arguments[i] = argumentTokens[i].text; } return arguments; } @@ -352,10 +352,10 @@ * @return the entire command line */ public String toString() { - StringBuilder sb = new StringBuilder(escape(commandToken.token)); + StringBuilder sb = new StringBuilder(escape(commandToken.text)); for (Token arg : argumentTokens) { sb.append(' '); - sb.append(escape(arg.token)); + sb.append(escape(arg.text)); } return sb.toString(); } @@ -388,7 +388,7 @@ * should have been processed so that the value of the field represents * a command name or argument. */ - public final String token; + public final String text; /** * This field represents the type of the token. The meaning is @@ -414,7 +414,7 @@ public final int end; public Token(String value, int type, int start, int end) { - this.token = value; + this.text = value; this.tokenType = type; this.start = start; this.end = end; @@ -430,7 +430,7 @@ int result = 1; result = prime * result + end; result = prime * result + start; - result = prime * result + ((token == null) ? 0 : token.hashCode()); + result = prime * result + ((text == null) ? 0 : text.hashCode()); result = prime * result + tokenType; return result; } @@ -448,10 +448,10 @@ return false; if (start != other.start) return false; - if (token == null) { - if (other.token != null) + if (text == null) { + if (other.text != null) return false; - } else if (!token.equals(other.token)) + } else if (!text.equals(other.text)) return false; if (tokenType != other.tokenType) return false; @@ -459,7 +459,7 @@ } public String toString() { - return "Token{'" + token + "'," + start + "," + end + "," + tokenType + "}"; + return "Token{'" + text + "'," + start + "," + end + "," + tokenType + "}"; } } @@ -570,7 +570,7 @@ * line arguments. */ public CommandInfo parseCommandLine(CommandShell shell) throws ShellException { - String cmd = (commandToken == null) ? "" : commandToken.token.trim(); + String cmd = (commandToken == null) ? "" : commandToken.text.trim(); if (cmd.equals("")) { throw new ShellFailureException("no command name"); } @@ -601,7 +601,7 @@ } public void complete(CompletionInfo completion, CommandShell shell) throws CompletionException { - String cmd = (commandToken == null) ? "" : commandToken.token.trim(); + String cmd = (commandToken == null) ? "" : commandToken.text.trim(); if (!cmd.equals("") && (argumentTokens.length > 0 || argumentAnticipated)) { CommandInfo cmdClass; try { @@ -649,7 +649,7 @@ } public CommandInfo getCommandInfo(CommandShell shell) { - String cmd = (commandToken == null) ? "" : commandToken.token.trim(); + String cmd = (commandToken == null) ? "" : commandToken.text.trim(); if (cmd.equals("")) { return null; } Modified: trunk/shell/src/shell/org/jnode/shell/CommandShell.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/CommandShell.java 2009-01-10 13:42:03 UTC (rev 4846) +++ trunk/shell/src/shell/org/jnode/shell/CommandShell.java 2009-01-11 06:28:56 UTC (rev 4847) @@ -487,7 +487,7 @@ } if (context.token != null) { errPW.println(" " + context.exception.getMessage() + ": " + - context.token.token); + context.token.text); } else { errPW.println(" " + context.exception.getMessage() + ": " + context.syntax.format()); Modified: trunk/shell/src/shell/org/jnode/shell/RedirectingInterpreter.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/RedirectingInterpreter.java 2009-01-10 13:42:03 UTC (rev 4846) +++ trunk/shell/src/shell/org/jnode/shell/RedirectingInterpreter.java 2009-01-11 06:28:56 UTC (rev 4847) @@ -147,7 +147,7 @@ CommandLine.Token commandToken = tokenizer.next(); if (commandToken.tokenType == SPECIAL) { throw new ShellSyntaxException("Misplaced '" + - commandToken.token + "': expected a command name"); + commandToken.text + "': expected a command name"); } CommandLine.Token from = null; @@ -157,7 +157,7 @@ while (tokenizer.hasNext()) { CommandLine.Token token = tokenizer.next(); if (token.tokenType == SPECIAL) { - if (token.token.equals("<")) { + if (token.text.equals("<")) { from = parseFileName(tokenizer, "<"); if (from == null && !completing) { throw new ShellSyntaxException("no filename after '<'"); @@ -167,7 +167,7 @@ new FileArgument("?", Argument.MANDATORY, null), from); } continue; - } else if (token.token.equals(">")) { + } else if (token.text.equals(">")) { to = parseFileName(tokenizer, ">"); if (to == null && !completing) { throw new ShellSyntaxException("no filename after '>'"); @@ -177,7 +177,7 @@ new FileArgument("?", Argument.MANDATORY, null), to); } continue; - } else if (token.token.equals("|")) { + } else if (token.text.equals("|")) { pipeTo = true; break; } else { @@ -219,7 +219,7 @@ if (token.tokenType == SPECIAL) { throw new ShellSyntaxException("misplaced '" + token + "'"); } - if (token.token.isEmpty()) { + if (token.text.isEmpty()) { throw new ShellSyntaxException("empty '" + special + "' file name"); } return token; @@ -233,19 +233,19 @@ try { try { if (desc.fromFileName != null) { - in = new CommandInput(new FileInputStream(desc.fromFileName.token)); + in = new CommandInput(new FileInputStream(desc.fromFileName.text)); } } catch (IOException ex) { throw new ShellInvocationException("cannot open '" + - desc.fromFileName.token + "': " + ex.getMessage()); + desc.fromFileName.text + "': " + ex.getMessage()); } try { if (desc.toFileName != null) { - out = new CommandOutput(new FileOutputStream(desc.toFileName.token)); + out = new CommandOutput(new FileOutputStream(desc.toFileName.text)); } } catch (IOException ex) { throw new ShellInvocationException("cannot open '" + - desc.toFileName.token + "': " + ex.getMessage()); + desc.toFileName.text + "': " + ex.getMessage()); } desc.commandLine.setStreams(new CommandIO[] {in, out, err, CommandLine.DEFAULT_STDERR}); try { @@ -289,17 +289,17 @@ try { // redirect from if (desc.fromFileName != null) { - in = new CommandInput(new FileInputStream(desc.fromFileName.token)); + in = new CommandInput(new FileInputStream(desc.fromFileName.text)); desc.openedStreams.add(in); } } catch (IOException ex) { throw new ShellInvocationException("cannot open '" + - desc.fromFileName.token + "': " + ex.getMessage()); + desc.fromFileName.text + "': " + ex.getMessage()); } try { // redirect to if (desc.toFileName != null) { - out = new CommandOutput(new FileOutputStream(desc.toFileName.token)); + out = new CommandOutput(new FileOutputStream(desc.toFileName.text)); desc.openedStreams.add(out); } } catch (IOException ex) { Modified: trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneContext.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneContext.java 2009-01-10 13:42:03 UTC (rev 4846) +++ trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneContext.java 2009-01-11 06:28:56 UTC (rev 4847) @@ -43,6 +43,7 @@ import java.util.List; import java.util.Map; +import org.apache.log4j.Logger; import org.jnode.shell.CommandLine; import org.jnode.shell.CommandThread; import org.jnode.shell.PathnamePattern; @@ -241,7 +242,10 @@ if (expanded == word) { splitAndAppend(token, wordTokens); } else { - splitAndAppend(token.remake(expanded), wordTokens); + BjorneToken newToken = token.remake(expanded); + if (newToken != null) { + splitAndAppend(newToken, wordTokens); + } } } return makeCommandLine(wordTokens); @@ -397,9 +401,9 @@ private String runBacktickCommand(String commandLine) throws ShellException { ByteArrayOutputStream capture = new ByteArrayOutputStream(); - interpreter.interpret(interpreter.getShell(), commandLine, capture, - false); + interpreter.interpret(interpreter.getShell(), commandLine, capture, false); String output = capture.toString(); + // Trim trailing newlines int i; for (i = output.length(); i > 0 && output.charAt(i - 1) == '\n'; i--) { /**/ } @@ -415,19 +419,13 @@ } /** - * Perform '$' expansions. Any quotes and escapes should be preserved. + * Perform '$' expansion and backtick substitution. 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; Modified: trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneToken.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneToken.java 2009-01-10 13:42:03 UTC (rev 4846) +++ trunk/shell/src/shell/org/jnode/shell/bjorne/BjorneToken.java 2009-01-11 06:28:56 UTC (rev 4847) @@ -21,7 +21,6 @@ package org.jnode.shell.bjorne; import org.jnode.shell.CommandLine; -import org.jnode.shell.ShellException; public class BjorneToken extends CommandLine.Token { @@ -131,7 +130,11 @@ } public BjorneToken remake(CharSequence newText) { - return new BjorneToken(this.tokenType, newText.toString(), this.start, this.end); + if (newText.length() == 0) { + return null; + } else { + return new BjorneToken(this.tokenType, newText.toString(), this.start, this.end); + } } private void validate() { @@ -140,28 +143,20 @@ case TOK_IO_NUMBER: case TOK_NAME: case TOK_ASSIGNMENT: - if (token.length() == 0) { + if (text == null || text.length() == 0) { throw new IllegalArgumentException("null or empty text"); } break; default: - if (token.length() > 0) { + if (text != null && text.length() > 0) { throw new IllegalArgumentException("non-empty text"); } } } - public String getInterpolatedText(BjorneContext context) throws ShellException { - switch (tokenType) { - case TOK_WORD: - default: - return toString(); - } - } - public String getText() { - return token; + return text; } public int getTokenType() { @@ -169,7 +164,7 @@ } public boolean isName() { - return token != null && isName(token); + return text != null && isName(text); } public static boolean isName(String str) { @@ -255,13 +250,13 @@ public String toString() { switch (tokenType) { case TOK_WORD: - return "WORD{" + token + "}"; + return "WORD{" + text + "}"; case TOK_NAME: - return "NAME{" + token + "}"; + return "NAME{" + text + "}"; case TOK_ASSIGNMENT: - return "ASSIGNMENT{" + token + "}"; + return "ASSIGNMENT{" + text + "}"; case TOK_IO_NUMBER: - return "IO_NUMBER{" + token + "}"; + return "IO_NUMBER{" + text + "}"; case TOK_SEMI: case TOK_AMP: case TOK_BAR: Modified: trunk/shell/src/shell/org/jnode/shell/bjorne/CaseCommandNode.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/bjorne/CaseCommandNode.java 2009-01-10 13:42:03 UTC (rev 4846) +++ trunk/shell/src/shell/org/jnode/shell/bjorne/CaseCommandNode.java 2009-01-11 06:28:56 UTC (rev 4847) @@ -58,10 +58,10 @@ public int execute(BjorneContext context) throws ShellException { int rc = -1; - CharSequence expandedWord = context.expand(word.token); + CharSequence expandedWord = context.expand(word.text); for (CaseItemNode caseItem : caseItems) { for (BjorneToken pattern : caseItem.getPattern()) { - CharSequence pat = context.expand(pattern.token); + CharSequence pat = context.expand(pattern.text); if (context.patternMatch(expandedWord, pat)) { throw new ShellException("not implemented yet"); } Modified: trunk/shell/src/shell/org/jnode/shell/command/BindKeysCommand.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/command/BindKeysCommand.java 2009-01-10 13:42:03 UTC (rev 4846) +++ trunk/shell/src/shell/org/jnode/shell/command/BindKeysCommand.java 2009-01-11 06:28:56 UTC (rev 4847) @@ -126,7 +126,7 @@ @Override protected VirtualKey doAccept(Token value) throws CommandSyntaxException { - String str = value.token; + String str = value.text; String[] parts = str.split("\\+"); int modifiers = 0; for (int i = 0; i < parts.length - 1; i++) { @@ -157,7 +157,7 @@ @Override protected Character doAccept(Token value) throws CommandSyntaxException { - String str = value.token; + String str = value.text; String upper = str.toUpperCase(); for (int i = 0; i < ASCII_NAMES.length; i++) { if (ASCII_NAMES[i].equals(upper)) { Modified: trunk/shell/src/shell/org/jnode/shell/syntax/AliasArgument.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/syntax/AliasArgument.java 2009-01-10 13:42:03 UTC (rev 4846) +++ trunk/shell/src/shell/org/jnode/shell/syntax/AliasArgument.java 2009-01-11 06:28:56 UTC (rev 4847) @@ -51,10 +51,10 @@ @Override public String doAccept(Token value) throws CommandSyntaxException { - if (value.token.length() == 0) { + if (value.text.length() == 0) { throw new CommandSyntaxException("empty alias name"); } - return value.token; + return value.text; } public void complete(CompletionInfo completion, String partial) { Modified: trunk/shell/src/shell/org/jnode/shell/syntax/ClassNameArgument.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/syntax/ClassNameArgument.java 2009-01-10 13:42:03 UTC (rev 4846) +++ trunk/shell/src/shell/org/jnode/shell/syntax/ClassNameArgument.java 2009-01-11 06:28:56 UTC (rev 4847) @@ -41,7 +41,7 @@ @Override protected String doAccept(Token token) throws CommandSyntaxException { - return token.token; + return token.text; } @Override Modified: trunk/shell/src/shell/org/jnode/shell/syntax/CountryArgument.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/syntax/CountryArgument.java 2009-01-10 13:42:03 UTC (rev 4846) +++ trunk/shell/src/shell/org/jnode/shell/syntax/CountryArgument.java 2009-01-11 06:28:56 UTC (rev 4847) @@ -43,8 +43,8 @@ @Override protected String doAccept(Token token) throws CommandSyntaxException { - if (validCountries.contains(token.token)) { - return token.token; + if (validCountries.contains(token.text)) { + return token.text; } else { throw new CommandSyntaxException("invalid country code"); } Modified: trunk/shell/src/shell/org/jnode/shell/syntax/DeviceArgument.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/syntax/DeviceArgument.java 2009-01-10 13:42:03 UTC (rev 4846) +++ trunk/shell/src/shell/org/jnode/shell/syntax/DeviceArgument.java 2009-01-11 06:28:56 UTC (rev 4847) @@ -58,7 +58,7 @@ protected Device doAccept(Token token) throws CommandSyntaxException { try { final DeviceManager devMgr = getDeviceManager(); - final Device device = devMgr.getDevice(token.token); + final Device device = devMgr.getDevice(token.text); if (apiClass == null || device.implementsAPI(apiClass)) { return device; } else { Modified: trunk/shell/src/shell/org/jnode/shell/syntax/EnumArgument.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/syntax/EnumArgument.java 2009-01-10 13:42:03 UTC (rev 4846) +++ trunk/shell/src/shell/org/jnode/shell/syntax/EnumArgument.java 2009-01-11 06:28:56 UTC (rev 4847) @@ -63,7 +63,7 @@ @Override protected E doAccept(Token token) throws CommandSyntaxException { try { - return E.valueOf(clazz, token.token); + return E.valueOf(clazz, token.text); } catch (IllegalArgumentException ex) { throw new CommandSyntaxException("not a valid <" + argumentKind() + ">"); } Modified: trunk/shell/src/shell/org/jnode/shell/syntax/FileArgument.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/syntax/FileArgument.java 2009-01-10 13:42:03 UTC (rev 4846) +++ trunk/shell/src/shell/org/jnode/shell/syntax/FileArgument.java 2009-01-11 06:28:56 UTC (rev 4847) @@ -47,8 +47,8 @@ @Override protected File doAccept(Token token) throws CommandSyntaxException { - if (token.token.length() > 0) { - File file = new File(token.token); + if (token.text.length() > 0) { + File file = new File(token.text); if (isExisting() && !file.exists()) { throw new CommandSyntaxException("this file or directory does not exist"); } Modified: trunk/shell/src/shell/org/jnode/shell/syntax/HostNameArgument.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/syntax/HostNameArgument.java 2009-01-10 13:42:03 UTC (rev 4846) +++ trunk/shell/src/shell/org/jnode/shell/syntax/HostNameArgument.java 2009-01-11 06:28:56 UTC (rev 4847) @@ -50,7 +50,7 @@ @Override protected String doAccept(Token token) throws CommandSyntaxException { - return token.token; + return token.text; } @Override Modified: trunk/shell/src/shell/org/jnode/shell/syntax/IntegerArgument.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/syntax/IntegerArgument.java 2009-01-10 13:42:03 UTC (rev 4846) +++ trunk/shell/src/shell/org/jnode/shell/syntax/IntegerArgument.java 2009-01-11 06:28:56 UTC (rev 4847) @@ -58,11 +58,11 @@ @Override protected Integer doAccept(Token token) throws CommandSyntaxException { try { - int tmp = Integer.parseInt(token.token); + int tmp = Integer.parseInt(token.text); if (tmp < min || tmp > max) { throw new CommandSyntaxException("number is out of range"); } - return new Integer(token.token); + return new Integer(token.text); } catch (NumberFormatException ex) { throw new CommandSyntaxException("invalid number"); } Modified: trunk/shell/src/shell/org/jnode/shell/syntax/KeyboardLayoutArgument.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/syntax/KeyboardLayoutArgument.java 2009-01-10 13:42:03 UTC (rev 4846) +++ trunk/shell/src/shell/org/jnode/shell/syntax/KeyboardLayoutArgument.java 2009-01-11 06:28:56 UTC (rev 4847) @@ -47,7 +47,7 @@ @Override protected String doAccept(Token token) throws CommandSyntaxException { - return token.token; + return token.text; } @Override Modified: trunk/shell/src/shell/org/jnode/shell/syntax/LanguageArgument.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/syntax/LanguageArgument.java 2009-01-10 13:42:03 UTC (rev 4846) +++ trunk/shell/src/shell/org/jnode/shell/syntax/LanguageArgument.java 2009-01-11 06:28:56 UTC (rev 4847) @@ -43,8 +43,8 @@ @Override protected String doAccept(Token token) throws CommandSyntaxException { - if (validLanguages.contains(token.token)) { - return token.token; + if (validLanguages.contains(token.text)) { + return token.text; } else { throw new CommandSyntaxException("invalid language code"); } Modified: trunk/shell/src/shell/org/jnode/shell/syntax/Log4jLoggerArgument.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/syntax/Log4jLoggerArgument.java 2009-01-10 13:42:03 UTC (rev 4846) +++ trunk/shell/src/shell/org/jnode/shell/syntax/Log4jLoggerArgument.java 2009-01-11 06:28:56 UTC (rev 4847) @@ -29,7 +29,7 @@ */ @Override protected Logger doAccept(Token value) throws CommandSyntaxException { - return Logger.getLogger(value.token); + return Logger.getLogger(value.text); } /** Modified: trunk/shell/src/shell/org/jnode/shell/syntax/LongArgument.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/syntax/LongArgument.java 2009-01-10 13:42:03 UTC (rev 4846) +++ trunk/shell/src/shell/org/jnode/shell/syntax/LongArgument.java 2009-01-11 06:28:56 UTC (rev 4847) @@ -59,11 +59,11 @@ @Override protected Long doAccept(Token token) throws CommandSyntaxException { try { - long tmp = Long.parseLong(token.token); + long tmp = Long.parseLong(token.text); if (tmp < min || tmp > max) { throw new CommandSyntaxException("number is out of range"); } - return new Long(token.token); + return new Long(token.text); } catch (NumberFormatException ex) { throw new CommandSyntaxException("invalid number"); } Modified: trunk/shell/src/shell/org/jnode/shell/syntax/MappedArgument.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/syntax/MappedArgument.java 2009-01-10 13:42:03 UTC (rev 4846) +++ trunk/shell/src/shell/org/jnode/shell/syntax/MappedArgument.java 2009-01-11 06:28:56 UTC (rev 4847) @@ -78,7 +78,7 @@ */ @Override protected V doAccept(Token token) throws CommandSyntaxException { - String t = caseInsensitive ? token.token.toLowerCase() : token.token; + String t = caseInsensitive ? token.text.toLowerCase() : token.text; V value = valueMap.get(t); if (value == null) { throw new CommandSyntaxException("not an acceptable <" + argumentKind() + ">"); Modified: trunk/shell/src/shell/org/jnode/shell/syntax/MuParser.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/syntax/MuParser.java 2009-01-10 13:42:03 UTC (rev 4846) +++ trunk/shell/src/shell/org/jnode/shell/syntax/MuParser.java 2009-01-11 06:28:56 UTC (rev 4847) @@ -157,7 +157,7 @@ if (DEBUG) { log.debug("Trying kind = " + syntax.getKind() + ", syntax = " + syntax.format()); if (source.hasNext()) { - log.debug("source -> " + source.peek().token); + log.debug("source -> " + source.peek().text); } else { log.debug("source at end"); } @@ -169,17 +169,17 @@ token = source.hasNext() ? source.next() : null; if (completion == null || source.hasNext()) { - backtrack = token == null || !token.token.equals(symbol); + backtrack = token == null || !token.text.equals(symbol); } else { if (token == null) { completion.addCompletion(symbol); backtrack = true; } else if (source.whitespaceAfterLast()) { - if (!token.token.equals(symbol)) { + if (!token.text.equals(symbol)) { backtrack = true; } } else { - if (symbol.startsWith(token.token)) { + if (symbol.startsWith(token.text)) { completion.addCompletion(symbol); completion.setCompletionStart(token.start); } @@ -202,7 +202,7 @@ } } } else { - arg.complete(completion, token.token); + arg.complete(completion, token.text); completion.setCompletionStart(token.start); backtrack = true; } Modified: trunk/shell/src/shell/org/jnode/shell/syntax/OptionSetSyntax.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/syntax/OptionSetSyntax.java 2009-01-10 13:42:03 UTC (rev 4846) +++ trunk/shell/src/shell/org/jnode/shell/syntax/OptionSetSyntax.java 2009-01-11 06:28:56 UTC (rev 4847) @@ -54,7 +54,7 @@ @Override protected Boolean doAccept(Token token) throws CommandSyntaxException { - String value = token.token; + String value = token.text; int len = value.length(); if (len < 2 || value.charAt(0) != '-') { throw new CommandSyntaxException("not a flag set"); Modified: trunk/shell/src/shell/org/jnode/shell/syntax/PropertyNameArgument.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/syntax/PropertyNameArgument.java 2009-01-10 13:42:03 UTC (rev 4846) +++ trunk/shell/src/shell/org/jnode/shell/syntax/PropertyNameArgument.java 2009-01-11 06:28:56 UTC (rev 4847) @@ -26,7 +26,7 @@ @Override protected String doAccept(Token token) throws CommandSyntaxException { - return token.token; + return token.text; } @Override Modified: trunk/shell/src/shell/org/jnode/shell/syntax/SizeArgument.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/syntax/SizeArgument.java 2009-01-10 13:42:03 UTC (rev 4846) +++ trunk/shell/src/shell/org/jnode/shell/syntax/SizeArgument.java 2009-01-11 06:28:56 UTC (rev 4847) @@ -47,7 +47,7 @@ @Override protected Long doAccept(Token token) throws CommandSyntaxException { - String str = token.token; + String str = token.text; ScaleFactor factor = scaleFactor(str); if (factor != null) { str = str.substring(0, str.length() - factor.getUnit().length()); Modified: trunk/shell/src/shell/org/jnode/shell/syntax/StringArgument.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/syntax/StringArgument.java 2009-01-10 13:42:03 UTC (rev 4846) +++ trunk/shell/src/shell/org/jnode/shell/syntax/StringArgument.java 2009-01-11 06:28:56 UTC (rev 4847) @@ -44,7 +44,7 @@ @Override protected String doAccept(Token token) throws CommandSyntaxException { - return token.token; + return token.text; } @Override Modified: trunk/shell/src/shell/org/jnode/shell/syntax/URLArgument.java =================================================================== --- trunk/shell/src/shell/org/jnode/shell/syntax/URLArgument.java 2009-01-10 13:42:03 UTC (rev 4846) +++ trunk/shell/src/shell/org/jnode/shell/syntax/URLArgument.java 2009-01-11 06:28:56 UTC (rev 4847) @@ -55,7 +55,7 @@ @Override protected URL doAccept(Token value) throws CommandSyntaxException { try { - return new URL(value.token); + return new URL(value.text); } catch (MalformedURLException ex) { throw new CommandSyntaxException(ex.getMessage()); } Modified: trunk/shell/src/test/org/jnode/test/shell/syntax/CommandLineTest.java =================================================================== --- trunk/shell/src/test/org/jnode/test/shell/syntax/CommandLineTest.java 2009-01-10 13:42:03 UTC (rev 4846) +++ trunk/shell/src/test/org/jnode/test/shell/syntax/CommandLineTest.java 2009-01-11 06:28:56 UTC (rev 4847) @@ -53,16 +53,16 @@ SymbolSource<Token> ts = c1.tokenIterator(); assertEquals(true, ts.hasNext()); - assertEquals("1", ts.next().token); + assertEquals("1", ts.next().text); assertEquals(true, ts.hasNext()); - assertEquals("2", ts.next().token); + assertEquals("2", ts.next().text); assertEquals(true, ts.hasNext()); - assertEquals("3", ts.next().token); + assertEquals("3", ts.next().text); assertEquals(false, ts.hasNext()); CommandLine c2 = new CommandLine("foo", args); assertEquals("foo", c2.getCommandName()); - assertEquals("foo", c2.getCommandToken().token); + assertEquals("foo", c2.getCommandToken().text); } @SuppressWarnings("deprecation") Modified: trunk/shell/src/test/org/jnode/test/shell/syntax/DefaultTokenizerTest.java =================================================================== --- trunk/shell/src/test/org/jnode/test/shell/syntax/DefaultTokenizerTest.java 2009-01-10 13:42:03 UTC (rev 4846) +++ trunk/shell/src/test/org/jnode/test/shell/syntax/DefaultTokenizerTest.java 2009-01-11 06:28:56 UTC (rev 4847) @@ -60,15 +60,15 @@ assertEquals(true, t.hasNext()); assertEquals(false, t.whitespaceAfterLast()); CommandLine.Token s = t.next(); - assertEquals("a", s.token); + assertEquals("a", s.text); assertEquals(0, s.start); assertEquals(1, s.end); s = t.next(); - assertEquals("b", s.token); + assertEquals("b", s.text); assertEquals(2, s.start); assertEquals(3, s.end); s = t.next(); - assertEquals("c", s.token); + assertEquals("c", s.text); assertEquals(4, s.start); assertEquals(5, s.end); assertEquals(false, t.hasNext()); @@ -82,7 +82,7 @@ t.seek(0); assertEquals(true, t.hasNext()); s = t.next(); - assertEquals("a", s.token); + assertEquals("a", s.text); assertEquals(0, s.start); assertEquals(1, s.end); assertEquals(1, t.tell()); @@ -105,11 +105,11 @@ assertEquals(true, t.hasNext()); assertEquals(false, t.whitespaceAfterLast()); CommandLine.Token s = t.next(); - assertEquals("a", s.token); + assertEquals("a", s.text); assertEquals(0, s.start); assertEquals(3, s.end); s = t.next(); - assertEquals("b c", s.token); + assertEquals("b c", s.text); assertEquals(4, s.start); assertEquals(9, s.end); assertEquals(false, t.hasNext()); @@ -120,11 +120,11 @@ assertEquals(true, t.hasNext()); assertEquals(false, t.whitespaceAfterLast()); CommandLine.Token s = t.next(); - assertEquals("'a", s.token); + assertEquals("'a", s.text); assertEquals(0, s.start); assertEquals(3, s.end); s = t.next(); - assertEquals("b c\"", s.token); + assertEquals("b c\"", s.text); assertEquals(5, s.start); assertEquals(11, s.end); assertEquals(false, t.hasNext()); @@ -135,7 +135,7 @@ assertEquals(true, t.hasNext()); assertEquals(true, t.whitespaceAfterLast()); CommandLine.Token s = t.next(); - assertEquals("\\\n\r\t\b", s.token); + assertEquals("\\\n\r\t\b", s.text); assertEquals(0, s.start); assertEquals(10, s.end); assertEquals(false, t.hasNext()); @@ -147,21 +147,21 @@ MyDefaultInterpreter.REDIRECTS_FLAG); assertEquals(true, t.hasNext()); assertEquals(false, t.whitespaceAfterLast()); - assertEquals("a", t.next().token); - assertEquals("<", t.next().token); + assertEquals("a", t.next().text); + assertEquals("<", t.next().text); assertEquals(MyDefaultInterpreter.SPECIAL, t.last().tokenType); - assertEquals(">", t.next().token); + assertEquals(">", t.next().text); assertEquals(MyDefaultInterpreter.SPECIAL, t.last().tokenType); - assertEquals("b", t.next().token); - assertEquals("c", t.next().token); - assertEquals("|", t.next().token); + assertEquals("b", t.next().text); + assertEquals("c", t.next().text); + assertEquals("|", t.next().text); assertEquals(MyDefaultInterpreter.SPECIAL, t.last().tokenType); - assertEquals("d", t.next().token); - assertEquals("<", t.next().token); + assertEquals("d", t.next().text); + assertEquals("<", t.next().text); assertEquals(MyDefaultInterpreter.STRING | MyDefaultInterpreter.CLOSED, t.last().tokenType); - assertEquals("<", t.next().token); + assertEquals("<", t.next().text); assertEquals(MyDefaultInterpreter.LITERAL, t.last().tokenType); - assertEquals("<", t.next().token); + assertEquals("<", t.next().text); assertEquals(MyDefaultInterpreter.STRING | MyDefaultInterpreter.CLOSED, t.last().tokenType); assertEquals(false, t.hasNext()); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2009-01-12 08:03:55
|
Revision: 4850 http://jnode.svn.sourceforge.net/jnode/?rev=4850&view=rev Author: lsantha Date: 2009-01-12 08:03:50 +0000 (Mon, 12 Jan 2009) Log Message: ----------- Added findfugs-1.3.7 and initial set of plugins to analyze. Modified Paths: -------------- trunk/all/build.xml Added Paths: ----------- trunk/core/lib/findbugs/ trunk/core/lib/findbugs/lib/ trunk/core/lib/findbugs/lib/annotations.jar trunk/core/lib/findbugs/lib/ant.jar trunk/core/lib/findbugs/lib/asm-3.1.jar trunk/core/lib/findbugs/lib/asm-analysis-3.1.jar trunk/core/lib/findbugs/lib/asm-commons-3.1.jar trunk/core/lib/findbugs/lib/asm-tree-3.1.jar trunk/core/lib/findbugs/lib/asm-util-3.1.jar trunk/core/lib/findbugs/lib/asm-xml-3.1.jar trunk/core/lib/findbugs/lib/bcel.jar trunk/core/lib/findbugs/lib/buggy.icns trunk/core/lib/findbugs/lib/commons-lang-2.4.jar trunk/core/lib/findbugs/lib/dom4j-1.6.1.jar trunk/core/lib/findbugs/lib/findbugs-ant.jar trunk/core/lib/findbugs/lib/findbugs.jar trunk/core/lib/findbugs/lib/jFormatString.jar trunk/core/lib/findbugs/lib/jaxen-1.1.1.jar trunk/core/lib/findbugs/lib/jsr305.jar Modified: trunk/all/build.xml =================================================================== --- trunk/all/build.xml 2009-01-11 09:58:18 UTC (rev 4849) +++ trunk/all/build.xml 2009-01-12 08:03:50 UTC (rev 4850) @@ -748,6 +748,15 @@ <fileset dir="${root.dir}/core/src/openjdk/sun"> <patternset refid="cp-includes-pattern"/> </fileset> + <fileset dir="${root.dir}/core/src/openjdk/jaxws"> + <patternset refid="cp-includes-pattern"/> + </fileset> + <fileset dir="${root.dir}/core/src/openjdk/langtools"> + <patternset refid="cp-includes-pattern"/> + </fileset> + <fileset dir="${root.dir}/core/src/openjdk/corba"> + <patternset refid="cp-includes-pattern"/> + </fileset> </vmsources> <vmspecificsources> <fileset dir="${root.dir}/core/src/openjdk/vm"> @@ -755,10 +764,26 @@ </fileset> </vmspecificsources> <classpathsources> - <fileset dir="${root.dir}/../../openjdk/j2se/src/share/classes/"> + <fileset dir="${root.dir}/../openjdk/jdk/src/share/classes/"> <patternset refid="cp-includes-pattern"/> <patternset refid="cp-sources-pattern"/> </fileset> + <fileset dir="${root.dir}/../openjdk/corba/src/share/classes/"> + <patternset refid="cp-includes-pattern"/> + <patternset refid="cp-sources-pattern"/> + </fileset> + <fileset dir="${root.dir}/../openjdk/jaxp/src/share/classes/"> + <patternset refid="cp-includes-pattern"/> + <patternset refid="cp-sources-pattern"/> + </fileset> + <fileset dir="${root.dir}/../openjdk/jaxws/src/share/classes/"> + <patternset refid="cp-includes-pattern"/> + <patternset refid="cp-sources-pattern"/> + </fileset> + <fileset dir="${root.dir}/../openjdk/langtools/src/share/classes/"> + <patternset refid="cp-includes-pattern"/> + <patternset refid="cp-sources-pattern"/> + </fileset> </classpathsources> </cp-compare> </target> @@ -954,6 +979,32 @@ </checkstyle> </target> + <target name="findbugs" depends="assemble-plugins"> + <taskdef name="findbugs" classpath="../core/lib/findbugs/lib/findbugs-ant.jar" + classname="edu.umd.cs.findbugs.anttask.FindBugsTask"/> + <findbugs home="../core/lib/findbugs/" output="html" outputFile="./build/findbugs.html" > + <auxclasspath> + <pathelement location="./build/plugins/rt_${jnode-ver}.jar" /> + <pathelement location="./build/plugins/org.classpath.ext.core_${jnode-ver}.jar" /> + <pathelement location="./build/plugins/nanoxml_1.4.jar" /> + <pathelement location="${nanoxml-java.jar}" /> + <pathelement location="${log4j.jar}" /> + </auxclasspath> + <sourcepath> + <pathelement path="../core/src/core/"/> + </sourcepath> + <class location="./build/plugins/org.jnode.vm_${jnode-ver}.jar"/> + <class location="./build/plugins/org.jnode.vm.core_${jnode-ver}.jar"/> + <class location="./build/plugins/org.jnode.vm.memmgr.def_${jnode-ver}.jar"/> + <class location="./build/plugins/org.jnode.driver_${jnode-ver}.jar"/> + <class location="./build/plugins/org.jnode.runtime_${jnode-ver}.jar"/> + <class location="./build/plugins/org.jnode.runtime.core_${jnode-ver}.jar"/> + <class location="./build/plugins/org.jnode.util_${jnode-ver}.jar"/> + <class location="./build/plugins/org.jnode.work_${jnode-ver}.jar"/> + <class location="./build/plugins/org.jnode.security_${jnode-ver}.jar"/> + </findbugs> + </target> + <!-- Create a patch --> <!-- TODO create replacement SVN task <target name="create-patch"> Added: trunk/core/lib/findbugs/lib/annotations.jar =================================================================== (Binary files differ) Property changes on: trunk/core/lib/findbugs/lib/annotations.jar ___________________________________________________________________ Added: svn:mime-type + application/octet-stream Added: trunk/core/lib/findbugs/lib/ant.jar =================================================================== (Binary files differ) Property changes on: trunk/core/lib/findbugs/lib/ant.jar ___________________________________________________________________ Added: svn:mime-type + application/octet-stream Added: trunk/core/lib/findbugs/lib/asm-3.1.jar =================================================================== (Binary files differ) Property changes on: trunk/core/lib/findbugs/lib/asm-3.1.jar ___________________________________________________________________ Added: svn:mime-type + application/octet-stream Added: trunk/core/lib/findbugs/lib/asm-analysis-3.1.jar =================================================================== (Binary files differ) Property changes on: trunk/core/lib/findbugs/lib/asm-analysis-3.1.jar ___________________________________________________________________ Added: svn:mime-type + application/octet-stream Added: trunk/core/lib/findbugs/lib/asm-commons-3.1.jar =================================================================== (Binary files differ) Property changes on: trunk/core/lib/findbugs/lib/asm-commons-3.1.jar ___________________________________________________________________ Added: svn:mime-type + application/octet-stream Added: trunk/core/lib/findbugs/lib/asm-tree-3.1.jar =================================================================== (Binary files differ) Property changes on: trunk/core/lib/findbugs/lib/asm-tree-3.1.jar ___________________________________________________________________ Added: svn:mime-type + application/octet-stream Added: trunk/core/lib/findbugs/lib/asm-util-3.1.jar =================================================================== (Binary files differ) Property changes on: trunk/core/lib/findbugs/lib/asm-util-3.1.jar ___________________________________________________________________ Added: svn:mime-type + application/octet-stream Added: trunk/core/lib/findbugs/lib/asm-xml-3.1.jar =================================================================== (Binary files differ) Property changes on: trunk/core/lib/findbugs/lib/asm-xml-3.1.jar ___________________________________________________________________ Added: svn:mime-type + application/octet-stream Added: trunk/core/lib/findbugs/lib/bcel.jar =================================================================== (Binary files differ) Property changes on: trunk/core/lib/findbugs/lib/bcel.jar ___________________________________________________________________ Added: svn:mime-type + application/octet-stream Added: trunk/core/lib/findbugs/lib/buggy.icns =================================================================== (Binary files differ) Property changes on: trunk/core/lib/findbugs/lib/buggy.icns ___________________________________________________________________ Added: svn:mime-type + application/octet-stream Added: trunk/core/lib/findbugs/lib/commons-lang-2.4.jar =================================================================== (Binary files differ) Property changes on: trunk/core/lib/findbugs/lib/commons-lang-2.4.jar ___________________________________________________________________ Added: svn:mime-type + application/octet-stream Added: trunk/core/lib/findbugs/lib/dom4j-1.6.1.jar =================================================================== (Binary files differ) Property changes on: trunk/core/lib/findbugs/lib/dom4j-1.6.1.jar ___________________________________________________________________ Added: svn:mime-type + application/octet-stream Added: trunk/core/lib/findbugs/lib/findbugs-ant.jar =================================================================== (Binary files differ) Property changes on: trunk/core/lib/findbugs/lib/findbugs-ant.jar ___________________________________________________________________ Added: svn:mime-type + application/octet-stream Added: trunk/core/lib/findbugs/lib/findbugs.jar =================================================================== (Binary files differ) Property changes on: trunk/core/lib/findbugs/lib/findbugs.jar ___________________________________________________________________ Added: svn:mime-type + application/octet-stream Added: trunk/core/lib/findbugs/lib/jFormatString.jar =================================================================== (Binary files differ) Property changes on: trunk/core/lib/findbugs/lib/jFormatString.jar ___________________________________________________________________ Added: svn:mime-type + application/octet-stream Added: trunk/core/lib/findbugs/lib/jaxen-1.1.1.jar =================================================================== (Binary files differ) Property changes on: trunk/core/lib/findbugs/lib/jaxen-1.1.1.jar ___________________________________________________________________ Added: svn:mime-type + application/octet-stream Added: trunk/core/lib/findbugs/lib/jsr305.jar =================================================================== (Binary files differ) Property changes on: trunk/core/lib/findbugs/lib/jsr305.jar ___________________________________________________________________ Added: 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: <ls...@us...> - 2009-01-16 21:20:06
|
Revision: 4875 http://jnode.svn.sourceforge.net/jnode/?rev=4875&view=rev Author: lsantha Date: 2009-01-16 21:20:03 +0000 (Fri, 16 Jan 2009) Log Message: ----------- Improved modal dialogs. Modified Paths: -------------- trunk/core/src/openjdk/java/java/awt/Dialog.java trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingToolkit.java Modified: trunk/core/src/openjdk/java/java/awt/Dialog.java =================================================================== --- trunk/core/src/openjdk/java/java/awt/Dialog.java 2009-01-16 15:23:29 UTC (rev 4874) +++ trunk/core/src/openjdk/java/java/awt/Dialog.java 2009-01-16 21:20:03 UTC (rev 4875) @@ -191,7 +191,7 @@ * * @since 1.6 */ - public final static ModalityType DEFAULT_MODALITY_TYPE = ModalityType.APPLICATION_MODAL; + public final static ModalityType DEFAULT_MODALITY_TYPE = ModalityType.DOCUMENT_MODAL; //jnode the default blocks the whole desktop if in root isolate: ModalityType.APPLICATION_MODAL; /** * True if this dialog is modal, false is the dialog is modeless. Modified: trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingToolkit.java =================================================================== --- trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingToolkit.java 2009-01-16 15:23:29 UTC (rev 4874) +++ trunk/gui/src/awt/org/jnode/awt/swingpeers/SwingToolkit.java 2009-01-16 21:20:03 UTC (rev 4875) @@ -613,7 +613,7 @@ */ public boolean isModalityTypeSupported(Dialog.ModalityType modalityType) { //todo implement it - return false; + return true; } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |