You can subscribe to this list here.
2000 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
(1) |
Nov
(107) |
Dec
(67) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2001 |
Jan
(76) |
Feb
(125) |
Mar
(72) |
Apr
(13) |
May
(18) |
Jun
(12) |
Jul
(129) |
Aug
(47) |
Sep
(1) |
Oct
(36) |
Nov
(128) |
Dec
(124) |
2002 |
Jan
(59) |
Feb
|
Mar
(14) |
Apr
(14) |
May
(72) |
Jun
(9) |
Jul
(3) |
Aug
(5) |
Sep
(18) |
Oct
(65) |
Nov
(28) |
Dec
(12) |
2003 |
Jan
(10) |
Feb
(2) |
Mar
(4) |
Apr
(33) |
May
(21) |
Jun
(9) |
Jul
(29) |
Aug
(34) |
Sep
(4) |
Oct
(8) |
Nov
(15) |
Dec
(4) |
2004 |
Jan
(26) |
Feb
(12) |
Mar
(11) |
Apr
(9) |
May
(7) |
Jun
|
Jul
(5) |
Aug
|
Sep
(3) |
Oct
(7) |
Nov
(1) |
Dec
(10) |
2005 |
Jan
(2) |
Feb
(72) |
Mar
(16) |
Apr
(39) |
May
(48) |
Jun
(97) |
Jul
(57) |
Aug
(13) |
Sep
(16) |
Oct
(24) |
Nov
(100) |
Dec
(24) |
2006 |
Jan
(15) |
Feb
(34) |
Mar
(33) |
Apr
(31) |
May
(79) |
Jun
(64) |
Jul
(41) |
Aug
(64) |
Sep
(31) |
Oct
(46) |
Nov
(55) |
Dec
(37) |
2007 |
Jan
(32) |
Feb
(61) |
Mar
(11) |
Apr
(58) |
May
(46) |
Jun
(30) |
Jul
(94) |
Aug
(93) |
Sep
(86) |
Oct
(69) |
Nov
(125) |
Dec
(177) |
2008 |
Jan
(169) |
Feb
(97) |
Mar
(74) |
Apr
(113) |
May
(120) |
Jun
(334) |
Jul
(215) |
Aug
(237) |
Sep
(72) |
Oct
(189) |
Nov
(126) |
Dec
(160) |
2009 |
Jan
(180) |
Feb
(45) |
Mar
(98) |
Apr
(140) |
May
(151) |
Jun
(71) |
Jul
(107) |
Aug
(119) |
Sep
(73) |
Oct
(121) |
Nov
(14) |
Dec
(6) |
2010 |
Jan
(13) |
Feb
(9) |
Mar
(10) |
Apr
(64) |
May
(3) |
Jun
(16) |
Jul
(7) |
Aug
(23) |
Sep
(17) |
Oct
(37) |
Nov
(5) |
Dec
(8) |
2011 |
Jan
(10) |
Feb
(11) |
Mar
(77) |
Apr
(11) |
May
(2) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
From: <pj...@us...> - 2008-11-06 05:20:07
|
Revision: 5548 http://jython.svn.sourceforge.net/jython/?rev=5548&view=rev Author: pjenvey Date: 2008-11-06 05:20:01 +0000 (Thu, 06 Nov 2008) Log Message: ----------- __import__ requires __builtins__ to be initialized, use imp.load Modified Paths: -------------- trunk/jython/src/org/python/core/codecs.java Modified: trunk/jython/src/org/python/core/codecs.java =================================================================== --- trunk/jython/src/org/python/core/codecs.java 2008-11-05 17:51:34 UTC (rev 5547) +++ trunk/jython/src/org/python/core/codecs.java 2008-11-06 05:20:01 UTC (rev 5548) @@ -112,7 +112,7 @@ if (!import_encodings_called) { import_encodings_called = true; try { - __builtin__.__import__("encodings"); + imp.load("encodings"); } catch (PyException exc) { if (exc.type != Py.ImportError) { throw exc; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: Philip J. <pj...@un...> - 2008-11-05 21:16:55
|
On Nov 5, 2008, at 11:11 AM, Frank Wierzbicki wrote: > On Tue, Nov 4, 2008 at 9:39 PM, <le...@us...> > wrote: >> Log Message: >> ----------- >> Fixing mangling of multibyte characters before parsing PyUnicode >> input (as described on <http://www.nabble.com/Parsing-and-non-ASCII-Input-td19007415.html >> >). This doesn't completely solve the parsing problems with unicode >> input because org.python.antlr.GrammarActions#extractStrings is not >> aware of the 'current' input encoding yet. But it is a step >> forward. Refs: #1062 > > Hey Leo, > > If you haven't started on making GrammarActions aware of the current > input encoding, I can take a look at that. Frank - No need, I'm already pretty far along on that. -- Philip Jenvey |
From: Frank W. <fwi...@gm...> - 2008-11-05 19:11:19
|
On Tue, Nov 4, 2008 at 9:39 PM, <le...@us...> wrote: > Log Message: > ----------- > Fixing mangling of multibyte characters before parsing PyUnicode input (as described on <http://www.nabble.com/Parsing-and-non-ASCII-Input-td19007415.html>). This doesn't completely solve the parsing problems with unicode input because org.python.antlr.GrammarActions#extractStrings is not aware of the 'current' input encoding yet. But it is a step forward. Refs: #1062 Hey Leo, If you haven't started on making GrammarActions aware of the current input encoding, I can take a look at that. -Frank |
From: <otm...@us...> - 2008-11-05 17:51:40
|
Revision: 5547 http://jython.svn.sourceforge.net/jython/?rev=5547&view=rev Author: otmarhumbel Date: 2008-11-05 17:51:34 +0000 (Wed, 05 Nov 2008) Log Message: ----------- allow the installer to be started as follows: java -Djava.awt.headless=true -jar jython_installer-2.5b0.jar -A this is necessary if we want to stress-test it on build bots Modified Paths: -------------- trunk/installer/src/java/org/python/util/install/InstallerCommandLine.java trunk/installer/test/java/org/python/util/install/InstallerCommandLineTest.java Modified: trunk/installer/src/java/org/python/util/install/InstallerCommandLine.java =================================================================== --- trunk/installer/src/java/org/python/util/install/InstallerCommandLine.java 2008-11-05 15:32:35 UTC (rev 5546) +++ trunk/installer/src/java/org/python/util/install/InstallerCommandLine.java 2008-11-05 17:51:34 UTC (rev 5547) @@ -134,28 +134,6 @@ } /** - * Pre-scan of the arguments to detect a console flag - * @param args - * @return <code>true</code> if there is a console option - */ - public static final boolean hasConsoleOptionInArgs(String[] args) { - String shortConsole = "-".concat(CONSOLE_SHORT); - String longConsole = "--".concat(CONSOLE_LONG); - return hasOptionInArgs(args, shortConsole, longConsole); - } - - /** - * Pre-scan of the arguments to detect a silent flag - * @param args - * @return <code>true</code> if there is a silent option - */ - public static final boolean hasSilentOptionInArgs(String[] args) { - String shortSilent = "-".concat(SILENT_SHORT); - String longSilent = "--".concat(SILENT_LONG); - return hasOptionInArgs(args, shortSilent, longSilent); - } - - /** * constructor intended for JUnit tests only. */ public InstallerCommandLine() { @@ -170,19 +148,26 @@ * <code>false</code> is returned */ public boolean setArgs(String args[]) { - _args = args; - if (!hasConsoleOptionInArgs(args) && !hasSilentOptionInArgs(args)) { - if (!Installation.isGuiAllowed() || Installation.isGNUJava()) { - // auto switch to console mode - if (hasVerboseOptionInArgs(args)) { - ConsoleInstaller.message("auto-switching to console mode"); + // pre-process args to determine if we can (and should) switch to console mode + try { + CommandLine preCommandLine = _parser.parse(_options, args, false); + if (!hasConsoleOption(preCommandLine) && !hasSilentOption(preCommandLine) + && !hasAutotestOption(preCommandLine)) { + if (!Installation.isGuiAllowed() || Installation.isGNUJava()) { + // auto switch to console mode + if (hasVerboseOption(preCommandLine)) { + ConsoleInstaller.message("auto-switching to console mode"); + } + String[] newArgs = new String[args.length + 1]; + System.arraycopy(args, 0, newArgs, 0, args.length); + newArgs[args.length] = "-" + CONSOLE_SHORT; + args = newArgs; } - String[] newArgs = new String[args.length + 1]; - System.arraycopy(args, 0, newArgs, 0, args.length); - newArgs[args.length] = "-" + CONSOLE_SHORT; - _args = newArgs; } + } catch (Exception e) { + // ignore } + _args = args; try { // throws for missing or unknown options / arguments _commandLine = _parser.parse(_options, _args, false); @@ -245,16 +230,28 @@ } public boolean hasSilentOption() { - return _commandLine.hasOption(SILENT_SHORT) || _commandLine.hasOption(SILENT_LONG); + return hasSilentOption(_commandLine); } + private boolean hasSilentOption(CommandLine commandLine) { + return commandLine.hasOption(SILENT_SHORT) || commandLine.hasOption(SILENT_LONG); + } + public boolean hasConsoleOption() { - return _commandLine.hasOption(CONSOLE_SHORT) || _commandLine.hasOption(CONSOLE_LONG); + return hasConsoleOption(_commandLine); } + + private boolean hasConsoleOption(CommandLine commandLine) { + return commandLine.hasOption(CONSOLE_SHORT) || commandLine.hasOption(CONSOLE_LONG); + } public boolean hasAutotestOption() { - return _commandLine.hasOption(AUTOTEST_SHORT) || _commandLine.hasOption(AUTOTEST_LONG); + return hasAutotestOption(_commandLine); } + + private boolean hasAutotestOption(CommandLine commandLine) { + return commandLine.hasOption(AUTOTEST_SHORT) || commandLine.hasOption(AUTOTEST_LONG); + } public boolean hasDirectoryOption() { return _commandLine.hasOption(DIRECTORY_SHORT) || _commandLine.hasOption(DIRECTORY_LONG); @@ -277,9 +274,13 @@ } public boolean hasVerboseOption() { - return _commandLine.hasOption(VERBOSE_SHORT) || _commandLine.hasOption(VERBOSE_LONG); + return hasVerboseOption(_commandLine); } + private boolean hasVerboseOption(CommandLine commandLine) { + return commandLine.hasOption(VERBOSE_SHORT) || commandLine.hasOption(VERBOSE_LONG); + } + public void printHelp() { HelpFormatter formatter = new HelpFormatter(); formatter.defaultWidth = 76; Modified: trunk/installer/test/java/org/python/util/install/InstallerCommandLineTest.java =================================================================== --- trunk/installer/test/java/org/python/util/install/InstallerCommandLineTest.java 2008-11-05 15:32:35 UTC (rev 5546) +++ trunk/installer/test/java/org/python/util/install/InstallerCommandLineTest.java 2008-11-05 17:51:34 UTC (rev 5547) @@ -269,6 +269,22 @@ File dir = commandLine.getTargetDirectory(); assertNotNull(dir); assertEquals("some_dir", dir.getName()); + + // -A (autotest) should override as well + args = new String[] {"-A"}; + commandLine = new InstallerCommandLine(); + assertTrue(commandLine.setArgs(args)); + assertFalse(commandLine.hasVerboseOption()); + assertFalse(commandLine.hasConsoleOption()); // no auto switch + assertFalse(commandLine.hasSilentOption()); + + // console aready present should be no problem + args = new String[] {"-c", "-v"}; + commandLine = new InstallerCommandLine(); + assertTrue(commandLine.setArgs(args)); + assertTrue(commandLine.hasVerboseOption()); + assertTrue(commandLine.hasConsoleOption()); + assertFalse(commandLine.hasSilentOption()); } finally { if (!originalHeadless) { System.setProperty(Installation.HEADLESS_PROPERTY_NAME, "false"); @@ -607,51 +623,5 @@ args = new String[] {"a", "--" + InstallerCommandLine.VERBOSE_LONG, "c"}; assertTrue(InstallerCommandLine.hasVerboseOptionInArgs(args)); } - - public void testHasConsoleOptionInArgs() { - String[] args = new String[0]; - assertFalse(InstallerCommandLine.hasConsoleOptionInArgs(args)); - - args = new String[] {"a", "b", "c"}; - assertFalse(InstallerCommandLine.hasConsoleOptionInArgs(args)); - - args = new String[] {"a", InstallerCommandLine.CONSOLE_SHORT, "c"}; - assertFalse(InstallerCommandLine.hasConsoleOptionInArgs(args)); - - args = new String[] {"a", "-" + InstallerCommandLine.CONSOLE_SHORT, "c"}; - assertTrue(InstallerCommandLine.hasConsoleOptionInArgs(args)); - - args = new String[] {"a", InstallerCommandLine.CONSOLE_LONG, "c"}; - assertFalse(InstallerCommandLine.hasConsoleOptionInArgs(args)); - - args = new String[] {"a", "-" + InstallerCommandLine.CONSOLE_LONG, "c"}; - assertFalse(InstallerCommandLine.hasConsoleOptionInArgs(args)); - - args = new String[] {"a", "--" + InstallerCommandLine.CONSOLE_LONG, "c"}; - assertTrue(InstallerCommandLine.hasConsoleOptionInArgs(args)); - } - - public void testHasSilentOptionInArgs() { - String[] args = new String[0]; - assertFalse(InstallerCommandLine.hasSilentOptionInArgs(args)); - - args = new String[] {"a", "b", "c"}; - assertFalse(InstallerCommandLine.hasSilentOptionInArgs(args)); - - args = new String[] {"a", InstallerCommandLine.SILENT_SHORT, "c"}; - assertFalse(InstallerCommandLine.hasSilentOptionInArgs(args)); - - args = new String[] {"a", "-" + InstallerCommandLine.SILENT_SHORT, "c"}; - assertTrue(InstallerCommandLine.hasSilentOptionInArgs(args)); - - args = new String[] {"a", InstallerCommandLine.SILENT_LONG, "c"}; - assertFalse(InstallerCommandLine.hasSilentOptionInArgs(args)); - - args = new String[] {"a", "-" + InstallerCommandLine.SILENT_LONG, "c"}; - assertFalse(InstallerCommandLine.hasSilentOptionInArgs(args)); - - args = new String[] {"a", "--" + InstallerCommandLine.SILENT_LONG, "c"}; - assertTrue(InstallerCommandLine.hasSilentOptionInArgs(args)); - } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <otm...@us...> - 2008-11-05 15:32:43
|
Revision: 5546 http://jython.svn.sourceforge.net/jython/?rev=5546&view=rev Author: otmarhumbel Date: 2008-11-05 15:32:35 +0000 (Wed, 05 Nov 2008) Log Message: ----------- correctly quote _JYTHON_HOME this should fix issue #1125 Modified Paths: -------------- trunk/installer/src/java/org/python/util/install/driver/jython_test.bat.template Modified: trunk/installer/src/java/org/python/util/install/driver/jython_test.bat.template =================================================================== --- trunk/installer/src/java/org/python/util/install/driver/jython_test.bat.template 2008-11-05 15:30:32 UTC (rev 5545) +++ trunk/installer/src/java/org/python/util/install/driver/jython_test.bat.template 2008-11-05 15:32:35 UTC (rev 5546) @@ -29,12 +29,11 @@ call jython.bat "%_SCRIPT%" set E=%ERRORLEVEL% -rem this exposes the last part of issue 1125 -rem echo "{3}: both homes UNquoted:" -rem set JAVA_HOME=%_JAVA_HOME% -rem set JYTHON_HOME=%_INSTALL_DIR% -rem call jython.bat "%_SCRIPT%" -rem set E=%ERRORLEVEL% +echo {3}: both homes UNquoted: +set JAVA_HOME=%_JAVA_HOME% +set JYTHON_HOME=%_INSTALL_DIR% +call jython.bat "%_SCRIPT%" +set E=%ERRORLEVEL% rem cleanup: set JAVA_HOME=%_OLD_JAVA_HOME% This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <otm...@us...> - 2008-11-05 15:30:36
|
Revision: 5545 http://jython.svn.sourceforge.net/jython/?rev=5545&view=rev Author: otmarhumbel Date: 2008-11-05 15:30:32 +0000 (Wed, 05 Nov 2008) Log Message: ----------- correctly quote _JYTHON_HOME this should fix issue #1125 Modified Paths: -------------- trunk/jython/src/shell/jython.bat Modified: trunk/jython/src/shell/jython.bat =================================================================== --- trunk/jython/src/shell/jython.bat 2008-11-05 07:30:28 UTC (rev 5544) +++ trunk/jython/src/shell/jython.bat 2008-11-05 15:30:32 UTC (rev 5545) @@ -24,11 +24,13 @@ set _JAVA_CMD="%JAVA_HOME:"=%\bin\java" ) -set _JYTHON_HOME=%JYTHON_HOME% rem remove surrounding quotes from jython home, to be able to safely empty-test it set _TRIMMED_JYTHON_HOME=%JYTHON_HOME% for /f "useback tokens=*" %%a in ('%_TRIMMED_JYTHON_HOME%') do set _TRIMMED_JYTHON_HOME=%%~a -if not "%_TRIMMED_JYTHON_HOME%"=="" goto gotHome +if not "%_TRIMMED_JYTHON_HOME%"=="" ( + set _JYTHON_HOME="%_TRIMMED_JYTHON_HOME%" + goto gotHome +) pushd "%~dp0%\.." set _JYTHON_HOME="%CD%" popd This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <otm...@us...> - 2008-11-05 07:30:33
|
Revision: 5544 http://jython.svn.sourceforge.net/jython/?rev=5544&view=rev Author: otmarhumbel Date: 2008-11-05 07:30:28 +0000 (Wed, 05 Nov 2008) Log Message: ----------- installation autotests now verify the shell scripts more deeply the set of calls is defined in jython_test.template and jython_test.bat.template Modified Paths: -------------- trunk/installer/src/java/org/python/util/install/AbstractWizardPage.java trunk/installer/src/java/org/python/util/install/JarInfo.java trunk/installer/src/java/org/python/util/install/JarInstaller.java trunk/installer/src/java/org/python/util/install/JavaVersionTester.java trunk/installer/src/java/org/python/util/install/StartScriptGenerator.java trunk/installer/src/java/org/python/util/install/driver/Autotest.java trunk/installer/src/java/org/python/util/install/driver/InstallationDriver.java trunk/installer/src/java/org/python/util/install/driver/NormalVerifier.java trunk/installer/src/java/org/python/util/install/driver/StandaloneVerifier.java trunk/installer/test/java/org/python/util/install/StandalonePackagerTest.java trunk/installer/test/java/org/python/util/install/StartScriptGeneratorTest.java trunk/installer/test/java/org/python/util/install/driver/NormalVerifierTest.java trunk/installer/test/java/org/python/util/install/driver/StandaloneVerifierTest.java trunk/jython/build.xml Added Paths: ----------- trunk/installer/src/java/org/python/util/install/FileHelper.java trunk/installer/src/java/org/python/util/install/driver/jython_test.bat.template trunk/installer/src/java/org/python/util/install/driver/jython_test.template trunk/installer/test/java/org/python/util/install/FileHelperTest.java Removed Paths: ------------- trunk/installer/src/java/org/python/util/install/driver/FileHelper.java Modified: trunk/installer/src/java/org/python/util/install/AbstractWizardPage.java =================================================================== --- trunk/installer/src/java/org/python/util/install/AbstractWizardPage.java 2008-11-05 02:56:03 UTC (rev 5543) +++ trunk/installer/src/java/org/python/util/install/AbstractWizardPage.java 2008-11-05 07:30:28 UTC (rev 5544) @@ -9,6 +9,8 @@ import javax.swing.JPanel; public abstract class AbstractWizardPage extends JPanel implements TextKeys { + private static final long serialVersionUID = -5233805023557214279L; + private static final String _ICON_FILE_NAME = "jython_small_c.png"; private static ImageIcon _imageIcon = null; @@ -54,11 +56,7 @@ */ protected ImageIcon getIcon() { if (_imageIcon == null) { - String className = getClass().getName(); - String packageName = className.substring(0, className.lastIndexOf(".")); - String packagePath = packageName.replace('.', '/'); - URL iconURL = Thread.currentThread().getContextClassLoader().getResource( - packagePath + "/" + _ICON_FILE_NAME); + URL iconURL = FileHelper.getRelativeURL(getClass(), _ICON_FILE_NAME); if (iconURL != null) { _imageIcon = new ImageIcon(iconURL); } Added: trunk/installer/src/java/org/python/util/install/FileHelper.java =================================================================== --- trunk/installer/src/java/org/python/util/install/FileHelper.java (rev 0) +++ trunk/installer/src/java/org/python/util/install/FileHelper.java 2008-11-05 07:30:28 UTC (rev 5544) @@ -0,0 +1,208 @@ +package org.python.util.install; + +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; + +/** + * Helper methods for file handling during installation / installation verification + */ +public final class FileHelper { + + private final static String EXECUTABLE_MODE = "755"; + + /** + * create a temporary directory with the same name as the passed in File (which may exist as + * file, not directory) + * + * @param tempDirectory + * @return <code>true</code> only if the the directory was successfully created (or already + * existed) + */ + public static boolean createTempDirectory(File tempDirectory) { + boolean success = true; + if (!tempDirectory.isDirectory()) { + if (tempDirectory.exists()) { + success = carryOnResult(tempDirectory.delete(), success); + } + if (success) { + success = tempDirectory.mkdirs(); + } + } + return success; + } + + /** + * completely remove a directory + * + * @param dir + * @return <code>true</code> if successful, <code>false</code> otherwise. + */ + public static boolean rmdir(File dir) { + boolean success = true; + if (dir.exists()) { + File[] files = dir.listFiles(); + for (int i = 0; i < files.length; i++) { + File file = files[i]; + if (file.isFile()) { + success = carryOnResult(file.delete(), success); + } else { + if (file.isDirectory()) { + success = carryOnResult(rmdir(file), success); + } + } + } + success = carryOnResult(dir.delete(), success); + } + return success; + } + + /** + * read the contents of a file into a String + * + * @param file + * The file has to exist + * @return The contents of the file as String + * @throws IOException + */ + public static String readAll(File file) throws IOException { + FileReader fileReader = new FileReader(file); + try { + StringBuffer sb = new StringBuffer(); + char[] b = new char[8192]; + int n; + while ((n = fileReader.read(b)) > 0) { + sb.append(b, 0, n); + } + return sb.toString(); + } finally { + fileReader.close(); + } + } + + /** + * read the contents of a stream into a String + * <p> + * ATTN: does not handle encodings + * + * @param inputStream + * The input stream + * @return A String representation of the file contents + * @throws IOException + */ + public static String readAll(InputStream inputStream) throws IOException { + try { + StringBuffer sb = new StringBuffer(); + byte[] b = new byte[8192]; + int n; + while ((n = inputStream.read(b)) > 0) { + sb.append(new String(b, 0, n)); + } + return sb.toString(); + } finally { + inputStream.close(); + } + } + + /** + * Write contents to a file. + * <p> + * An existing file would be overwritten. + * + * @param file + * @param contents + * + * @throws IOException + */ + public static void write(File file, String contents) throws IOException { + FileWriter writer = new FileWriter(file); + writer.write(contents); + writer.flush(); + writer.close(); + } + + /** + * determine the url of a file relative to (in the same directory as) the specified .class file<br> + * can also be used if the .class file resides inside a .jar file + * + * @param clazz + * The class next to the file + * @param fileName + * The name of the file + * + * @return The url of the file, can be null + */ + public static URL getRelativeURL(Class<?> clazz, String fileName) { + String filePath = getRelativePackagePath(clazz) + "/" + fileName; + return Thread.currentThread().getContextClassLoader().getResource(filePath); + } + + /** + * get the input stream of a file relative to (in the same directory as) the specified .class + * file<br> + * can also be used if the .class file resides inside a .jar file + * + * @param clazz + * The class next to the file + * @param fileName + * The name of the file + * + * @return The input stream of the file, can be null + */ + public static InputStream getRelativeURLAsStream(Class<?> clazz, String fileName) { + String filePath = getRelativePackagePath(clazz) + "/" + fileName; + return Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath); + } + + /** + * do a chmod on the passed file + * + * @param scriptFile + */ + public static void makeExecutable(File scriptFile) { + try { + String command[] = new String[3]; + command[0] = "chmod"; + command[1] = EXECUTABLE_MODE; + command[2] = scriptFile.getAbsolutePath(); + long timeout = 3000; + ChildProcess childProcess = new ChildProcess(command, timeout); + childProcess.run(); + } catch (Throwable t) { + t.printStackTrace(); + } + } + + /** + * build the package path for the class loader<br> + * the class loader should be able to load a file appended to this path, if it is in the same + * directory. + * + * @param clazz + * The class + * + * @return The package path + */ + private static String getRelativePackagePath(Class<?> clazz) { + String className = clazz.getName(); + String packageName = className.substring(0, className.lastIndexOf(".")); + return packageName.replace('.', '/'); + } + + /** + * @param newResult + * @param existingResult + * @return <code>false</code> if newResult or existingResult are false, <code>true</code> + * otherwise. + */ + private static boolean carryOnResult(boolean newResult, boolean existingResult) { + if (existingResult) { + return newResult; + } else { + return existingResult; + } + } +} Modified: trunk/installer/src/java/org/python/util/install/JarInfo.java =================================================================== --- trunk/installer/src/java/org/python/util/install/JarInfo.java 2008-11-05 02:56:03 UTC (rev 5543) +++ trunk/installer/src/java/org/python/util/install/JarInfo.java 2008-11-05 07:30:28 UTC (rev 5544) @@ -75,8 +75,8 @@ return _numberOfEntries; } - public List getExcludeDirs() throws IOException { - List excludeDirs = new ArrayList(); + public List<String> getExcludeDirs() throws IOException { + List<String> excludeDirs = new ArrayList<String>(); Attributes jythonAttributes = getManifest().getAttributes(JYTHON); if (jythonAttributes != null) { // do not use containsKey @@ -122,7 +122,7 @@ throw new InstallerException(Installation.getText(TextKeys.JAR_NOT_FOUND, _jarFile.getAbsolutePath())); } JarFile jarFile = new JarFile(_jarFile); - Enumeration entries = jarFile.entries(); + Enumeration<JarEntry> entries = jarFile.entries(); _numberOfEntries = 0; while (entries.hasMoreElements()) { JarEntry entry = (JarEntry) entries.nextElement(); Modified: trunk/installer/src/java/org/python/util/install/JarInstaller.java =================================================================== --- trunk/installer/src/java/org/python/util/install/JarInstaller.java 2008-11-05 02:56:03 UTC (rev 5543) +++ trunk/installer/src/java/org/python/util/install/JarInstaller.java 2008-11-05 07:30:28 UTC (rev 5544) @@ -13,25 +13,31 @@ /** * Working horse extracting the contents of the installation .jar to the file system. <br> - * The directory stucture is preserved, but there is the possibility to exclude some entries (directories at the - * moment). + * The directory stucture is preserved, but there is the possibility to exclude some entries + * (directories at the moment). */ public class JarInstaller { + public static final String JYTHON_JAR = "jython-complete.jar"; - + private static final String PATH_SEPARATOR = "/"; + private static final String LIB_NAME_SEP = "Lib" + PATH_SEPARATOR; + private static final String LIB_PAWT_SEP = LIB_NAME_SEP + "pawt" + PATH_SEPARATOR; + private static final int BUFFER_SIZE = 1024; private ProgressListener _progressListener; + private JarInfo _jarInfo; - private List _installationListeners; + private List<InstallationListener> _installationListeners; + public JarInstaller(ProgressListener progressListener, JarInfo jarInfo) { _progressListener = progressListener; _jarInfo = jarInfo; - _installationListeners = new ArrayList(); + _installationListeners = new ArrayList<InstallationListener>(); } /** @@ -48,8 +54,8 @@ try { // has to correspond with build.xml // has to correspond with build.Lib.include.properties - List excludeDirs = _jarInfo.getExcludeDirs(); - List coreLibFiles = new ArrayList(); + List<String> excludeDirs = _jarInfo.getExcludeDirs(); + List<String> coreLibFiles = new ArrayList<String>(); if (!installationType.installSources()) { excludeDirs.add("src"); excludeDirs.add("grammar"); @@ -73,35 +79,36 @@ excludeDirs.add(LIB_NAME_SEP + "email/test"); excludeDirs.add(LIB_NAME_SEP + "test"); } - int count = 0; int percent = 0; int numberOfIntervals = 100 / _progressListener.getInterval(); int numberOfEntries = approximateNumberOfEntries(installationType); int threshold = numberOfEntries / numberOfIntervals + 1; // +1 = pessimistic boolean coreExclusionReported = false; - // unzip - ZipInputStream zipInput = new ZipInputStream(new BufferedInputStream(new FileInputStream(_jarInfo - .getJarFile()), BUFFER_SIZE)); + ZipInputStream zipInput = new ZipInputStream(new BufferedInputStream(new FileInputStream(_jarInfo.getJarFile()), + BUFFER_SIZE)); ZipEntry zipEntry = zipInput.getNextEntry(); while (zipEntry != null) { String zipEntryName = zipEntry.getName(); boolean exclude = false; // handle exclusion of directories - Iterator excludeDirsAsIterator = excludeDirs.iterator(); + Iterator<String> excludeDirsAsIterator = excludeDirs.iterator(); while (excludeDirsAsIterator.hasNext()) { - if (zipEntryName.startsWith((String) excludeDirsAsIterator.next() + PATH_SEPARATOR)) { + if (zipEntryName.startsWith((String)excludeDirsAsIterator.next() + + PATH_SEPARATOR)) { exclude = true; } } // exclude build.xml when not installing source if (!installationType.installSources() && zipEntryName.equals("build.xml")) exclude = true; - // handle exclusion of core Lib files if (!exclude) { - exclude = shouldExcludeFile(installationType, coreLibFiles, zipEntry, zipEntryName); + exclude = shouldExcludeFile(installationType, + coreLibFiles, + zipEntry, + zipEntryName); if (Installation.isVerbose() && !coreExclusionReported && exclude) { ConsoleInstaller.message("excluding some .py files, like " + zipEntryName); coreExclusionReported = true; @@ -125,7 +132,7 @@ byte[] buffer = new byte[BUFFER_SIZE]; int len; while ((len = zipInput.read(buffer)) > 0) { - output.write(buffer, 0, len); + output.write(buffer, 0, len); } output.close(); file.setLastModified(zipEntry.getTime()); @@ -150,13 +157,14 @@ _progressListener.progressChanged(90); // approx packager.addFullDirectory(libDir); packager.close(); + // TODO:Oti move to FileHelper StandalonePackager.emptyDirectory(targetDirectory, jythonJar); } - // end + // finish: inform listeners _progressListener.progressFinished(); - Iterator installationListenersIterator = _installationListeners.iterator(); + Iterator<InstallationListener> installationListenersIterator = _installationListeners.iterator(); while (installationListenersIterator.hasNext()) { - ((InstallationListener) installationListenersIterator.next()).progressFinished(); + installationListenersIterator.next().progressFinished(); } } catch (IOException ioe) { throw new InstallerException(Installation.getText(TextKeys.ERROR_ACCESS_JARFILE), ioe); @@ -194,29 +202,29 @@ int lastSepIndex = zipEntryName.lastIndexOf(PATH_SEPARATOR); if (lastSepIndex > 0) { File directory = new File(targetDirectory, zipEntryName.substring(0, lastSepIndex)); - if (directory.exists() && directory.isDirectory()) { - } else { + if (directory.exists() && directory.isDirectory()) {} else { if (!directory.mkdirs()) { - throw new InstallerException(Installation.getText(TextKeys.UNABLE_CREATE_DIRECTORY, directory - .getAbsolutePath())); + throw new InstallerException(Installation.getText(TextKeys.UNABLE_CREATE_DIRECTORY, + directory.getAbsolutePath())); } } } } - private File createFile(final File targetDirectory, final String zipEntryName) throws IOException { + private File createFile(final File targetDirectory, final String zipEntryName) + throws IOException { File file = new File(targetDirectory, zipEntryName); - if (file.exists() && file.isFile()) { - } else { + if (file.exists() && file.isFile()) {} else { if (!file.createNewFile()) { - throw new InstallerException(Installation.getText(TextKeys.UNABLE_CREATE_FILE, file.getCanonicalPath())); + throw new InstallerException(Installation.getText(TextKeys.UNABLE_CREATE_FILE, + file.getCanonicalPath())); } } return file; } - private List getCoreLibFiles() { - List coreLibFiles = new ArrayList(); + private List<String> getCoreLibFiles() { + List<String> coreLibFiles = new ArrayList<String>(); coreLibFiles.add("__future__.py"); coreLibFiles.add("copy.py"); coreLibFiles.add("dbexts.py"); @@ -247,8 +255,10 @@ return coreLibFiles; } - private boolean shouldExcludeFile(InstallationType installationType, List coreLibFiles, ZipEntry zipEntry, - String zipEntryName) { + private boolean shouldExcludeFile(InstallationType installationType, + List<String> coreLibFiles, + ZipEntry zipEntry, + String zipEntryName) { boolean exclude = false; if (!installationType.installLibraryModules()) { // handle files in Lib @@ -257,9 +267,9 @@ if (!zipEntryName.startsWith(LIB_PAWT_SEP)) { if (zipEntryName.endsWith(".py")) { // only compare *.py files exclude = true; - Iterator coreLibFilesAsIterator = coreLibFiles.iterator(); + Iterator<String> coreLibFilesAsIterator = coreLibFiles.iterator(); while (coreLibFilesAsIterator.hasNext()) { - String coreFileName = (String) coreLibFilesAsIterator.next(); + String coreFileName = (String)coreLibFilesAsIterator.next(); if (zipEntryName.endsWith(PATH_SEPARATOR + coreFileName)) { exclude = false; } @@ -270,5 +280,4 @@ } return exclude; } - } Modified: trunk/installer/src/java/org/python/util/install/JavaVersionTester.java =================================================================== --- trunk/installer/src/java/org/python/util/install/JavaVersionTester.java 2008-11-05 02:56:03 UTC (rev 5543) +++ trunk/installer/src/java/org/python/util/install/JavaVersionTester.java 2008-11-05 07:30:28 UTC (rev 5544) @@ -1,7 +1,6 @@ package org.python.util.install; import java.io.File; -import java.io.FileWriter; /** * Helper class to test a java version @@ -39,10 +38,7 @@ } private static void writeTempFile(File file) throws Exception { - FileWriter writer = new FileWriter(file); - writer.write(createFileContent()); - writer.flush(); - writer.close(); + FileHelper.write(file, createFileContent()); } private static String createFileContent() { Modified: trunk/installer/src/java/org/python/util/install/StartScriptGenerator.java =================================================================== --- trunk/installer/src/java/org/python/util/install/StartScriptGenerator.java 2008-11-05 02:56:03 UTC (rev 5543) +++ trunk/installer/src/java/org/python/util/install/StartScriptGenerator.java 2008-11-05 07:30:28 UTC (rev 5544) @@ -1,8 +1,6 @@ package org.python.util.install; import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; import java.io.IOException; import java.text.MessageFormat; import java.util.Date; @@ -17,8 +15,6 @@ protected final static String WIN_CR_LF; - private final static String EXECUTABLE_MODE = "755"; - private final static String JYTHON = "jython"; private final static String JYTHON_BAT = "jython.bat"; @@ -75,20 +71,26 @@ } protected final void generateStartScripts() throws IOException { - generateJythonScript(); - } - - private final void generateJythonScript() throws IOException { + File bin = new File(getTargetDirectory(), "bin"); + File bin_jython = new File(bin, JYTHON); switch(getFlavour()){ case BOTH_FLAVOUR: - writeToFile(JYTHON_BAT, getJythonScript(WINDOWS_FLAVOUR)); - makeExecutable(writeToFile(JYTHON, getJythonScript(BOTH_FLAVOUR))); + writeToTargetDir(JYTHON_BAT, getJythonScript(WINDOWS_FLAVOUR)); + FileHelper.makeExecutable(writeToTargetDir(JYTHON, getJythonScript(BOTH_FLAVOUR))); + FileHelper.makeExecutable(bin_jython); break; case WINDOWS_FLAVOUR: - writeToFile(JYTHON_BAT, getJythonScript(WINDOWS_FLAVOUR)); + writeToTargetDir(JYTHON_BAT, getJythonScript(WINDOWS_FLAVOUR)); + // delete the *nix script in /bin dir + bin_jython.delete(); break; default: - makeExecutable(writeToFile(JYTHON, getJythonScript(UNIX_FLAVOUR))); + FileHelper.makeExecutable(writeToTargetDir(JYTHON, getJythonScript(UNIX_FLAVOUR))); + FileHelper.makeExecutable(bin_jython); + // delete the windows script in /bin dir + File bin_jython_bat = new File(bin, JYTHON_BAT); + bin_jython_bat.delete(); + break; } } @@ -116,7 +118,7 @@ parameters[0] = new Date().toString(); parameters[1] = System.getProperty("user.name"); parameters[2] = _javaHome.getCanonicalPath(); - parameters[3] = _targetDirectory.getCanonicalPath(); + parameters[3] = getTargetDirectory().getCanonicalPath(); return MessageFormat.format(template, (Object[])parameters); } @@ -183,65 +185,31 @@ */ private String readFromFile(String fileName) throws IOException { // default runtime location - File file = new File(new File(_targetDirectory, "bin"), fileName); + File targetDirectory = getTargetDirectory(); + File file = new File(new File(targetDirectory, "bin"), fileName); if (!file.exists()) { // deviation: test time location - file = new File(_targetDirectory, fileName); + file = new File(targetDirectory, fileName); } - FileReader fileReader = new FileReader(file); - try { - StringBuffer sb = new StringBuffer(); - char[] b = new char[8192]; - int n; - while ((n = fileReader.read(b)) > 0) { - sb.append(b, 0, n); - } - return sb.toString(); - } finally { - fileReader.close(); - } + return FileHelper.readAll(file); } /** + * Create (or overwrite) the specified file in the target directory + * * @param fileName * The short file name, e.g. JYTHON_BAT * @param contents * * @throws IOException */ - private File writeToFile(String fileName, String contents) throws IOException { - File file = new File(_targetDirectory, fileName); - if (file.exists()) { - file.delete(); - } - file.createNewFile(); - if (file.exists()) { - if (file.canWrite()) { - FileWriter fileWriter = new FileWriter(file); - fileWriter.write(contents); - fileWriter.flush(); - fileWriter.close(); - } - } + private File writeToTargetDir(String fileName, String contents) throws IOException { + File file = new File(getTargetDirectory(), fileName); + FileHelper.write(file, contents); return file; } - /** - * do a chmod on the passed file - * - * @param scriptFile - */ - private void makeExecutable(File scriptFile) { - try { - String command[] = new String[3]; - command[0] = "chmod"; - command[1] = EXECUTABLE_MODE; - command[2] = scriptFile.getAbsolutePath(); - long timeout = 3000; - ChildProcess childProcess = new ChildProcess(command, timeout); - childProcess.run(); - } catch (Throwable t) { - t.printStackTrace(); - } + private File getTargetDirectory() { + return _targetDirectory; } } Modified: trunk/installer/src/java/org/python/util/install/driver/Autotest.java =================================================================== --- trunk/installer/src/java/org/python/util/install/driver/Autotest.java 2008-11-05 02:56:03 UTC (rev 5543) +++ trunk/installer/src/java/org/python/util/install/driver/Autotest.java 2008-11-05 07:30:28 UTC (rev 5544) @@ -3,6 +3,7 @@ import java.io.File; import java.io.IOException; +import org.python.util.install.FileHelper; import org.python.util.install.InstallationListener; import org.python.util.install.InstallerCommandLine; Deleted: trunk/installer/src/java/org/python/util/install/driver/FileHelper.java =================================================================== --- trunk/installer/src/java/org/python/util/install/driver/FileHelper.java 2008-11-05 02:56:03 UTC (rev 5543) +++ trunk/installer/src/java/org/python/util/install/driver/FileHelper.java 2008-11-05 07:30:28 UTC (rev 5544) @@ -1,24 +0,0 @@ -package org.python.util.install.driver; - -import java.io.File; - -public class FileHelper { - - /** - * create a temporary directory with the same name as the passed in File (which may exist as file, not directory) - * - * @param tempDirectory - * @return <code>true</code> only if the the directory was successfully created (or already existed) - */ - public static boolean createTempDirectory(File tempDirectory) { - if (!tempDirectory.isDirectory()) { - if (tempDirectory.exists()) { - tempDirectory.delete(); - } - return tempDirectory.mkdir(); - } else { - return true; - } - } - -} Modified: trunk/installer/src/java/org/python/util/install/driver/InstallationDriver.java =================================================================== --- trunk/installer/src/java/org/python/util/install/driver/InstallationDriver.java 2008-11-05 02:56:03 UTC (rev 5543) +++ trunk/installer/src/java/org/python/util/install/driver/InstallationDriver.java 2008-11-05 07:30:28 UTC (rev 5544) @@ -110,7 +110,7 @@ private void validate(Autotest autoTest) throws DriverException { autoTest.assertTargetDirNotEmpty(); if (autoTest.getVerifier() != null) { - System.out.println("verifying installation ..."); + System.out.println("verifying installation - this can take a while ..."); autoTest.getVerifier().verify(); System.out.println("... installation ok.\n"); } Modified: trunk/installer/src/java/org/python/util/install/driver/NormalVerifier.java =================================================================== --- trunk/installer/src/java/org/python/util/install/driver/NormalVerifier.java 2008-11-05 02:56:03 UTC (rev 5543) +++ trunk/installer/src/java/org/python/util/install/driver/NormalVerifier.java 2008-11-05 07:30:28 UTC (rev 5544) @@ -1,139 +1,263 @@ -package org.python.util.install.driver; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.PrintStream; -import java.util.StringTokenizer; - -import org.python.util.install.ChildProcess; -import org.python.util.install.Installation; - -public class NormalVerifier implements Verifier { - - protected static final String AUTOTEST_PY = "autotest.py"; - private static final String JYTHON_UP = "jython up and running"; - private static final String JYTHON = "jython"; - - private File _targetDir; - - public void setTargetDir(File targetDir) { - _targetDir = targetDir; - } - - public File getTargetDir() { - return _targetDir; - } - - public void verify() throws DriverException { - // create the test .py script - createTestScriptFile(); - - // start jython and capture the output - ChildProcess childProcess = new ChildProcess(getCommand()); - childProcess.setDebug(true); - ByteArrayOutputStream redirectedErr = new ByteArrayOutputStream(); - ByteArrayOutputStream redirectedOut = new ByteArrayOutputStream(); - int exitValue = 0; - PrintStream oldErr = System.err; - PrintStream oldOut = System.out; - try { - System.setErr(new PrintStream(redirectedErr)); - System.setOut(new PrintStream(redirectedOut)); - exitValue = childProcess.run(); - } finally { - System.setErr(oldErr); - System.setOut(oldOut); - } - - // verify the output - String output = null; - String error = null; - try { - redirectedErr.flush(); - redirectedOut.flush(); - String encoding = "US-ASCII"; - output = redirectedOut.toString(encoding); - error = redirectedErr.toString(encoding); - } catch (IOException ioe) { - throw new DriverException(ioe); - } - if (exitValue != 0) { - throw new DriverException("start of jython failed, output:\n" + output + "\nerror:\n" + error); - } - verifyError(error); - verifyOutput(output); - } - - /** - * will be overridden in subclass StandaloneVerifier - * - * @return the command array to start jython with - * @throws DriverException if there was a problem getting the target directory path - */ - protected String[] getCommand() throws DriverException { - String parentDirName = null; - try { - parentDirName = getTargetDir().getCanonicalPath() + File.separator; - } catch (IOException ioe) { - throw new DriverException(ioe); - } - String[] command = new String[2]; - if (Installation.isWindows()) { - command[0] = parentDirName + JYTHON + ".bat"; - } else { - command[0] = parentDirName + JYTHON; - } - command[1] = parentDirName + AUTOTEST_PY; - return command; - } - - private void verifyError(String error) throws DriverException { - StringTokenizer tokenizer = new StringTokenizer(error, "\n"); - while (tokenizer.hasMoreTokens()) { - String line = tokenizer.nextToken(); - if (!line.startsWith("*sys-package-mgr*")) { - throw new DriverException(error); - } - } - } - - private void verifyOutput(String output) throws DriverException { - boolean started = false; - StringTokenizer tokenizer = new StringTokenizer(output, "\n"); - while (tokenizer.hasMoreTokens()) { - String line = tokenizer.nextToken(); - if (!line.startsWith("[ChildProcess]")) { - if (line.startsWith(JYTHON_UP)) { - started = true; - } else { - throw new DriverException(output); - } - } - } - if (!started) { - throw new DriverException("start of jython failed:\n" + output); - } - } - - private String getTestScript() { - StringBuffer buf = new StringBuffer(); - buf.append("import sys\n"); - buf.append("print '" + JYTHON_UP + "'\n"); - return buf.toString(); - } - - private void createTestScriptFile() throws DriverException { - File file = new File(getTargetDir(), AUTOTEST_PY); - try { - FileWriter writer = new FileWriter(file); - writer.write(getTestScript()); - writer.flush(); - writer.close(); - } catch (IOException ioe) { - throw new DriverException(ioe); - } - } - -} +package org.python.util.install.driver; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintStream; +import java.text.MessageFormat; +import java.util.StringTokenizer; + +import org.python.util.install.ChildProcess; +import org.python.util.install.FileHelper; +import org.python.util.install.Installation; +import org.python.util.install.JavaVersionTester; + +public class NormalVerifier implements Verifier { + + protected static final String AUTOTEST_PY = "autotest.py"; + + protected static final String JYTHON_TEST = "jython_test"; + + private static final String BIN = "bin"; + + private static final String BAT_EXTENSION = ".bat"; + + private static final String JYTHON_UP = "jython up and running!"; + + private static final String JYTHON = "jython"; + + private static final String TEMPLATE_SUFFIX = ".template"; + + private static final String VERIFYING = "verifying"; + + private File _targetDir; + + public void setTargetDir(File targetDir) { + _targetDir = targetDir; + } + + public File getTargetDir() { + return _targetDir; + } + + public void verify() throws DriverException { + createTestScriptFile(); // create the test .py script + // verify the most simple start of jython works + verifyStart(getSimpleCommand()); + if (doShellScriptTests()) { + // verify more complex versions of starting jython + verifyStart(getShellScriptTestCommand()); + } + } + + /** + * Will be overridden in subclass StandaloneVerifier + * + * @return the command array to start jython with + * @throws DriverException + * if there was a problem getting the target directory path + */ + protected String[] getSimpleCommand() throws DriverException { + String parentDirName = null; + try { + parentDirName = getTargetDir().getCanonicalPath() + File.separator; + } catch (IOException ioe) { + throw new DriverException(ioe); + } + String[] command = new String[2]; + if (Installation.isWindows()) { + command[0] = parentDirName + JYTHON + BAT_EXTENSION; + } else { + command[0] = parentDirName + JYTHON; + } + command[1] = parentDirName + AUTOTEST_PY; + return command; + } + + /** + * @return The command to test the shell script more deeply + * @throws DriverException + */ + protected final String[] getShellScriptTestCommand() throws DriverException { + // first we have to create the shell script + File testCommandDir = getShellScriptTestCommandDir(); + if (!testCommandDir.exists()) { + if (!testCommandDir.mkdirs()) { + throw new DriverException("unable to create directory " + + testCommandDir.getAbsolutePath()); + } + } + String commandName = JYTHON_TEST; + boolean isWindows = Installation.isWindows(); + if (isWindows) { + commandName = commandName.concat(BAT_EXTENSION); + } + File command = new File(testCommandDir, commandName); + try { + if (!command.exists()) { + command.createNewFile(); + } + FileHelper.write(command, getShellScriptTestContents()); + if (!isWindows) { + FileHelper.makeExecutable(command); + } + return new String[] {command.getCanonicalPath()}; + } catch (Exception e) { + throw new DriverException(e); + } + } + + /** + * @return The contents of the shell test script + * @throws DriverException + */ + protected final String getShellScriptTestContents() throws DriverException { + String contents = ""; + String templateName = JYTHON_TEST; + if (Installation.isWindows()) { + templateName = templateName.concat(BAT_EXTENSION); + } + templateName = templateName.concat(TEMPLATE_SUFFIX); + InputStream inputStream = FileHelper.getRelativeURLAsStream(getClass(), templateName); + if (inputStream != null) { + try { + String template = FileHelper.readAll(inputStream); + String targetDirPath = getTargetDir().getCanonicalPath(); + String upScriptPath = getSimpleCommand()[1]; + String javaHomeString = System.getProperty(JavaVersionTester.JAVA_HOME, ""); + contents = MessageFormat.format(template, + targetDirPath, + upScriptPath, + javaHomeString, + VERIFYING); + } catch (Exception e) { + throw new DriverException(e); + } + } + return contents; + } + + /** + * @return The directory where to create the shell script test command in. + * + * @throws DriverException + */ + protected final File getShellScriptTestCommandDir() throws DriverException { + String dirName; + try { + dirName = getTargetDir().getCanonicalPath().concat(File.separator).concat(BIN); + return new File(dirName); + } catch (IOException ioe) { + throw new DriverException(ioe); + } + } + + /** + * Internal method verifying a jython-starting command by capturing the ouptut + * + * @param command + * + * @throws DriverException + */ + private void verifyStart(String[] command) throws DriverException { + ChildProcess childProcess = new ChildProcess(command); + childProcess.setDebug(true); + ByteArrayOutputStream redirectedErr = new ByteArrayOutputStream(); + ByteArrayOutputStream redirectedOut = new ByteArrayOutputStream(); + int exitValue = 0; + PrintStream oldErr = System.err; + PrintStream oldOut = System.out; + try { + System.setErr(new PrintStream(redirectedErr)); + System.setOut(new PrintStream(redirectedOut)); + exitValue = childProcess.run(); + } finally { + System.setErr(oldErr); + System.setOut(oldOut); + } + // verify the output + String output = null; + String error = null; + try { + redirectedErr.flush(); + redirectedOut.flush(); + String encoding = "US-ASCII"; + output = redirectedOut.toString(encoding); + error = redirectedErr.toString(encoding); + } catch (IOException ioe) { + throw new DriverException(ioe); + } + if (exitValue != 0) { + throw new DriverException("start of jython failed, output:\n" + output + "\nerror:\n" + + error); + } + verifyError(error); + verifyOutput(output); + } + + /** + * Will be overridden in subclass StandaloneVerifier + * + * @return <code>true</code> if the jython start shell script should be verified (using + * different options) + */ + protected boolean doShellScriptTests() { + return true; + } + + private void verifyError(String error) throws DriverException { + StringTokenizer tokenizer = new StringTokenizer(error, "\n"); + while (tokenizer.hasMoreTokens()) { + String line = tokenizer.nextToken(); + if (line.startsWith("*sys-package-mgr*")) { + feedback(line); + } else { + throw new DriverException(error); + } + } + } + + private void verifyOutput(String output) throws DriverException { + boolean started = false; + StringTokenizer tokenizer = new StringTokenizer(output, "\n"); + while (tokenizer.hasMoreTokens()) { + String line = tokenizer.nextToken(); + if (line.startsWith("[ChildProcess]") || line.startsWith(VERIFYING)) { + feedback(line); + } else { + if (line.startsWith(JYTHON_UP)) { + started = true; + feedback(line); + } else { + throw new DriverException(output); + } + } + } + if (!started) { + throw new DriverException("start of jython failed:\n" + output); + } + } + + private String getTestScript() { + StringBuilder b = new StringBuilder(80); + b.append("import sys\n"); + b.append("print '"); + b.append(JYTHON_UP); + b.append("'\n"); + return b.toString(); + } + + private void createTestScriptFile() throws DriverException { + File file = new File(getTargetDir(), AUTOTEST_PY); + try { + FileHelper.write(file, getTestScript()); + } catch (IOException ioe) { + throw new DriverException(ioe); + } + } + + private void feedback(String line) { + System.out.println(line); + } +} Modified: trunk/installer/src/java/org/python/util/install/driver/StandaloneVerifier.java =================================================================== --- trunk/installer/src/java/org/python/util/install/driver/StandaloneVerifier.java 2008-11-05 02:56:03 UTC (rev 5543) +++ trunk/installer/src/java/org/python/util/install/driver/StandaloneVerifier.java 2008-11-05 07:30:28 UTC (rev 5544) @@ -1,90 +1,89 @@ -package org.python.util.install.driver; - -import java.io.File; -import java.io.IOException; -import java.util.Enumeration; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; - -import org.python.util.install.JavaVersionTester; - -public class StandaloneVerifier extends NormalVerifier { - - public void verify() throws DriverException { - // make sure only JYTHON_JAR is in the target directory - if (getTargetDir().listFiles().length != 1) { - throw new DriverException("more than " + JYTHON_JAR + " installed"); - } - - // make sure JYTHON_JAR contains a MANIFEST and a /Lib directory - verifyJythonJar(); - - // do the jython startup verification from the superclass - super.verify(); - } - - /** - * overrides superclass method getting the command to start jython - */ - protected String[] getCommand() throws DriverException { - String parentDirName = null; - try { - parentDirName = getTargetDir().getCanonicalPath() + File.separator; - } catch (IOException ioe) { - throw new DriverException(ioe); - } - - String command[] = new String[4]; - command[0] = null; - String javaHomeString = System.getProperty(JavaVersionTester.JAVA_HOME, null); - if (javaHomeString != null) { - File javaHome = new File(javaHomeString); - if (javaHome.exists()) { - try { - command[0] = javaHome.getCanonicalPath() + File.separator + "bin" + File.separator + "java"; - } catch (IOException ioe) { - throw new DriverException(ioe); - } - } - } - if (command[0] == null) { - command[0] = "java"; - } - command[1] = "-jar"; - command[2] = parentDirName + JYTHON_JAR; - command[3] = parentDirName + AUTOTEST_PY; - return command; - } - - private void verifyJythonJar() throws DriverException { - File jythonJar = getTargetDir().listFiles()[0]; - JarFile jar = null; - try { - jar = new JarFile(jythonJar); - if (jar.getManifest() == null) { - throw new DriverException(JYTHON_JAR + " contains no MANIFEST"); - } - boolean hasLibDir = false; - Enumeration entries = jar.entries(); - while (!hasLibDir && entries.hasMoreElements()) { - JarEntry entry = (JarEntry) entries.nextElement(); - if (entry.getName().startsWith("Lib/")) { - hasLibDir = true; - } - } - if (!hasLibDir) { - throw new DriverException(JYTHON_JAR + " contains no /Lib directory"); - } - } catch (IOException e) { - throw new DriverException(e); - } finally { - if (jar != null) { - try { - jar.close(); - } catch (IOException ioe) { - } - } - } - } - -} +package org.python.util.install.driver; + +import java.io.File; +import java.io.IOException; +import java.util.Enumeration; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; + +import org.python.util.install.JavaVersionTester; + +public class StandaloneVerifier extends NormalVerifier { + + public void verify() throws DriverException { + // make sure only JYTHON_JAR is in the target directory + if (getTargetDir().listFiles().length > 1) { + throw new DriverException("more than " + JYTHON_JAR + " installed"); + } + // make sure JYTHON_JAR contains a MANIFEST and a /Lib directory + verifyJythonJar(); + // do the jython startup verification from the superclass + super.verify(); + } + + @Override + protected String[] getSimpleCommand() throws DriverException { + String parentDirName = null; + try { + parentDirName = getTargetDir().getCanonicalPath() + File.separator; + } catch (IOException ioe) { + throw new DriverException(ioe); + } + String command[] = new String[4]; + command[0] = null; + String javaHomeString = System.getProperty(JavaVersionTester.JAVA_HOME, null); + if (javaHomeString != null) { + File javaHome = new File(javaHomeString); + if (javaHome.exists()) { + try { + command[0] = javaHome.getCanonicalPath() + File.separator + "bin" + + File.separator + "java"; + } catch (IOException ioe) { + throw new DriverException(ioe); + } + } + } + if (command[0] == null) { + command[0] = "java"; + } + command[1] = "-jar"; + command[2] = parentDirName + JYTHON_JAR; + command[3] = parentDirName + AUTOTEST_PY; + return command; + } + + @Override + protected boolean doShellScriptTests() { + return false; + } + + private void verifyJythonJar() throws DriverException { + File jythonJar = getTargetDir().listFiles()[0]; + JarFile jar = null; + try { + jar = new JarFile(jythonJar); + if (jar.getManifest() == null) { + throw new DriverException(JYTHON_JAR + " contains no MANIFEST"); + } + boolean hasLibDir = false; + Enumeration<JarEntry> entries = jar.entries(); + while (!hasLibDir && entries.hasMoreElements()) { + JarEntry entry = (JarEntry)entries.nextElement(); + if (entry.getName().startsWith("Lib/")) { + hasLibDir = true; + } + } + if (!hasLibDir) { + throw new DriverException(JYTHON_JAR + " contains no /Lib directory"); + } + } catch (IOException e) { + throw new DriverException(e); + } finally { + if (jar != null) { + try { + jar.close(); + } catch (IOException ioe) {} + } + } + } +} Added: trunk/installer/src/java/org/python/util/install/driver/jython_test.bat.template =================================================================== --- trunk/installer/src/java/org/python/util/install/driver/jython_test.bat.template (rev 0) +++ trunk/installer/src/java/org/python/util/install/driver/jython_test.bat.template 2008-11-05 07:30:28 UTC (rev 5544) @@ -0,0 +1,43 @@ +@echo off + +rem 3 variables to be set from the caller, UNquoted: +set _INSTALL_DIR={0} +set _SCRIPT={1} +set _JAVA_HOME={2} + +rem save old home env vars: +set _OLD_JAVA_HOME=%JAVA_HOME% +set _OLD_JYTHON_HOME=%JYTHON_HOME% + +cd /d "%_INSTALL_DIR%\bin" + +echo {3}: only JAVA_HOME, quoted: +set JAVA_HOME="%_JAVA_HOME%" +set JYTHON_HOME= +call jython.bat "%_SCRIPT%" +set E=%ERRORLEVEL% + +echo {3}: only JAVA_HOME, UNquoted: +set JAVA_HOME=%_JAVA_HOME% +set JYTHON_HOME= +call jython.bat "%_SCRIPT%" +set E=%ERRORLEVEL% + +echo {3}: both homes quoted: +set JAVA_HOME="%_JAVA_HOME%" +set JYTHON_HOME="%_INSTALL_DIR%" +call jython.bat "%_SCRIPT%" +set E=%ERRORLEVEL% + +rem this exposes the last part of issue 1125 +rem echo "{3}: both homes UNquoted:" +rem set JAVA_HOME=%_JAVA_HOME% +rem set JYTHON_HOME=%_INSTALL_DIR% +rem call jython.bat "%_SCRIPT%" +rem set E=%ERRORLEVEL% + +rem cleanup: +set JAVA_HOME=%_OLD_JAVA_HOME% +set JYTHON_HOME=%_OLD_JYTHON_HOME% +cd /d "%~dp0%" +exit /b %E% Added: trunk/installer/src/java/org/python/util/install/driver/jython_test.template =================================================================== --- trunk/installer/src/java/org/python/util/install/driver/jython_test.template (rev 0) +++ trunk/installer/src/java/org/python/util/install/driver/jython_test.template 2008-11-05 07:30:28 UTC (rev 5544) @@ -0,0 +1,30 @@ +# 3 variables to be set from the caller (unquoted) -> quoted in here: +_INSTALL_DIR="{0}" +_SCRIPT="{1}" +_JAVA_HOME="{2}" + +# save old home env vars: +_OLD_JAVA_HOME=$JAVA_HOME +_OLD_JYTHON_HOME=$JYTHON_HOME + +cd "$_INSTALL_DIR/bin" + +# auto detection of JYTHON_HOME does not yet work +#echo "{3}: only JAVA_HOME:" +#export JAVA_HOME="$_JAVA_HOME" +#export JYTHON_HOME= +#./jython "$_SCRIPT" + +echo "{3}: only JYTHON_HOME:" +export JAVA_HOME= +export JYTHON_HOME="$_INSTALL_DIR" +./jython "$_SCRIPT" + +echo "{3}: both homes:" +export JAVA_HOME="$_JAVA_HOME" +export JYTHON_HOME="$_INSTALL_DIR" +./jython "$_SCRIPT" + +# cleanup: +export JAVA_HOME=$_OLD_JAVA_HOME +export JYTHON_HOME=$_OLD_JYTHON_HOME Added: trunk/installer/test/java/org/python/util/install/FileHelperTest.java =================================================================== --- trunk/installer/test/java/org/python/util/install/FileHelperTest.java (rev 0) +++ trunk/installer/test/java/org/python/util/install/FileHelperTest.java 2008-11-05 07:30:28 UTC (rev 5544) @@ -0,0 +1,271 @@ +package org.python.util.install; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URL; + +import junit.framework.TestCase; +import junit.runner.TestSuiteLoader; + +import org.python.util.install.driver.Autotest; + +public class FileHelperTest extends TestCase { + + private static final String JYTHON_TEST_TEMPLATE = "jython_test.template"; + + private static final String LOGO_GIF = "logo.gif"; + + private static final String JYTHON_SMALL_C_PNG = "jython_small_c.png"; + + public void testCreateTempDirectory_WasFile() throws IOException { + File file = File.createTempFile("some_prefix", ""); + assertTrue(file.exists()); + assertTrue(file.isFile()); + assertTrue(FileHelper.createTempDirectory(file)); + assertTrue(file.exists()); + assertTrue(file.isDirectory()); + } + + public void testCreateTempDirectory_AlreadyPresent() throws IOException { + File dir = new File(System.getProperty("user.dir")); + assertTrue(dir.exists()); + assertTrue(dir.isDirectory()); + assertTrue(FileHelper.createTempDirectory(dir)); + assertTrue(dir.exists()); + assertTrue(dir.isDirectory()); + } + + public void testCreateTempDirectory() throws IOException { + File dir = new File(System.getProperty("user.dir")); + assertTrue(dir.exists()); + assertTrue(dir.isDirectory()); + File tmpDir = new File(dir, "tmp"); + assertFalse(tmpDir.exists()); + try { + assertTrue(FileHelper.createTempDirectory(tmpDir)); + assertTrue(tmpDir.exists()); + assertTrue(dir.isDirectory()); + } finally { + if (tmpDir.exists()) { + assertTrue(tmpDir.delete()); + } + } + } + + public void testCreateTempDirectory_Failure() throws Exception { + File dir = new File(System.getProperty("user.dir")); + assertTrue(dir.exists()); + assertTrue(dir.isDirectory()); + File tmpFile = new File(dir, "tmpFailure"); + assertFalse(tmpFile.exists()); + try { + tmpFile.createNewFile(); + assertTrue(tmpFile.exists()); + assertTrue(tmpFile.isFile()); + Lock lock = null; + try { + lock = new Lock(tmpFile); + boolean created = FileHelper.createTempDirectory(tmpFile); + if (Installation.isWindows()) { + // locking currently only effective on windows + assertFalse(created); + } else { + // change if there is a locking mechanism + assertTrue(created); + } + } finally { + if (lock != null) { + lock.release(); + } + } + } finally { + if (tmpFile.exists()) { + assertTrue(tmpFile.delete()); + } + } + } + + public void testRmdir() throws IOException { + File dir = new File(System.getProperty("java.io.tmpdir"), "StartScriptGeneratorTest"); + if (!dir.exists()) { + assertTrue(dir.mkdirs()); + } + File bin = new File(dir, "bin"); + if (!bin.exists()) { + assertTrue(bin.mkdirs()); + } + File jython = new File(bin, "jython"); + if (!jython.exists()) { + assertTrue(jython.createNewFile()); + } + File jython_bat = new File(bin, "jython.bat"); + if (!jython_bat.exists()) { + assertTrue(jython_bat.createNewFile()); + } + assertTrue(FileHelper.rmdir(dir)); + } + + public void testRmdir_Failure() throws Exception { + File dir = new File(System.getProperty("java.io.tmpdir"), "StartScriptGeneratorTest"); + if (!dir.exists()) { + assertTrue(dir.mkdirs()); + } + File bin = new File(dir, "bin"); + if (!bin.exists()) { + assertTrue(bin.mkdirs()); + } + File jython = new File(bin, "jython"); + if (!jython.exists()) { + assertTrue(jython.createNewFile()); + } + File jython_bat = new File(bin, "jython.bat"); + if (!jython_bat.exists()) { + assertTrue(jython_bat.createNewFile()); + } + Lock lock = null; + try { + lock = new Lock(jython_bat); + boolean removed = FileHelper.rmdir(dir); + if (Installation.isWindows()) { + // locking currently only effective on windows + assertFalse(removed); + } else { + // change if there is a locking mechanism + assertTrue(removed); + } + } finally { + if (lock != null) { + lock.release(); + } + assertTrue(FileHelper.rmdir(dir)); + } + } + + public void testReadAll() throws Exception { + File file = File.createTempFile("testReadAll", ""); + final String contents = new String("line1 \n line2 \n"); + FileHelper.write(file, contents); + String readContents = FileHelper.readAll(file); + assertEquals(contents, readContents); + } + + public void testReadAll_InputStream() throws Exception { + URL url = FileHelper.getRelativeURL(Autotest.class, JYTHON_TEST_TEMPLATE); + assertNotNull(url); + URI uri = new URI(url.toString()); + File file = new File(uri); + assertNotNull(file); + assertTrue(file.exists()); + String expectedContents = FileHelper.readAll(file); + InputStream is = FileHelper.getRelativeURLAsStream(Autotest.class, JYTHON_TEST_TEMPLATE); + assertNotNull(is); + String contents = FileHelper.readAll(is); + assertEquals(expectedContents, contents); + // now from a .jar + is = FileHelper.getRelativeURLAsStream(TestSuiteLoader.class, LOGO_GIF); + assertNotNull(is); + contents = FileHelper.readAll(is); + assertNotNull(contents); + assertEquals(964, contents.length()); + assertTrue(contents.startsWith("GIF89a&")); + } + + public void testReadAll_NonExisting() { + String readContents = null; + try { + readContents = FileHelper.readAll(new File("_non_existing")); + fail("FileNotFoundException expected"); + } catch (IOException e) { + assertNull(readContents); + } + } + + public void testGetRelativeURL() { + URL url = FileHelper.getRelativeURL(Installation.class, JYTHON_SMALL_C_PNG); + assertNotNull(url); + assertTrue(url.getPath().endsWith("org/python/util/install/".concat(JYTHON_SMALL_C_PNG))); + // now from a .jar + ... [truncated message content] |
From: <le...@us...> - 2008-11-05 02:56:11
|
Revision: 5543 http://jython.svn.sourceforge.net/jython/?rev=5543&view=rev Author: leosoto Date: 2008-11-05 02:56:03 +0000 (Wed, 05 Nov 2008) Log Message: ----------- ParserFacade#partialParse: Check that the input reader is not null before trying to validate a partial sentence Modified Paths: -------------- trunk/jython/src/org/python/core/ParserFacade.java Modified: trunk/jython/src/org/python/core/ParserFacade.java =================================================================== --- trunk/jython/src/org/python/core/ParserFacade.java 2008-11-05 02:39:25 UTC (rev 5542) +++ trunk/jython/src/org/python/core/ParserFacade.java 2008-11-05 02:56:03 UTC (rev 5543) @@ -165,7 +165,7 @@ return parse(reader, kind, filename, cflags); } catch (Throwable t) { PyException p = fixParseError(reader, t, filename); - if (validPartialSentence(reader, kind, filename)) { + if (reader != null && validPartialSentence(reader, kind, filename)) { return null; } throw p; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <le...@us...> - 2008-11-05 02:39:32
|
Revision: 5542 http://jython.svn.sourceforge.net/jython/?rev=5542&view=rev Author: leosoto Date: 2008-11-05 02:39:25 +0000 (Wed, 05 Nov 2008) Log Message: ----------- Fixing mangling of multibyte characters before parsing PyUnicode input (as described on <http://www.nabble.com/Parsing-and-non-ASCII-Input-td19007415.html>). This doesn't completely solve the parsing problems with unicode input because org.python.antlr.GrammarActions#extractStrings is not aware of the 'current' input encoding yet. But it is a step forward. Refs: #1062 Modified Paths: -------------- trunk/jython/src/org/python/core/ParserFacade.java trunk/jython/src/org/python/core/Py.java trunk/jython/src/org/python/core/__builtin__.java Modified: trunk/jython/src/org/python/core/ParserFacade.java =================================================================== --- trunk/jython/src/org/python/core/ParserFacade.java 2008-10-31 22:06:00 UTC (rev 5541) +++ trunk/jython/src/org/python/core/ParserFacade.java 2008-11-05 02:39:25 UTC (rev 5542) @@ -7,7 +7,9 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; +import java.io.LineNumberReader; import java.io.Reader; +import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -32,14 +34,13 @@ import org.python.core.io.StreamIO; import org.python.core.io.TextIOInputStream; import org.python.core.io.UniversalIOWrapper; -import org.python.core.util.StringUtil; /** * Facade for the classes in the org.python.antlr package. */ public class ParserFacade { - + private static int MARK_LIMIT = 100000; private ParserFacade() {} @@ -70,7 +71,7 @@ reader = null; } } - + if (t instanceof ParseException) { ParseException e = (ParseException)t; PythonTree node = (PythonTree)e.node; @@ -90,76 +91,87 @@ else return Py.JavaError(t); } + /** + * Internal parser entry point. + * + * Users of this method should call fixParseError on any Throwable thrown + * from it, to translate ParserExceptions into PySyntaxErrors or + * PyIndentationErrors. + */ + private static modType parse(BufferedReader reader, + String kind, + String filename, + CompilerFlags cflags) throws Throwable { + reader.mark(MARK_LIMIT); // We need the ability to move back on the + // reader, for the benefit of fixParseError and + // validPartialSentence + if (kind.equals("eval")) { + CharStream cs = new NoCloseReaderStream(reader); + ExpressionParser e = new ExpressionParser(cs, filename); + return e.parse(); + } else if (kind.equals("single")) { + InteractiveParser i = new InteractiveParser(reader, filename); + return i.parse(); + } else if (kind.equals("exec")) { + CharStream cs = new NoCloseReaderStream(reader); + ModuleParser g = new ModuleParser(cs, filename); + return g.file_input(); + } else { + throw Py.ValueError("parse kind must be eval, exec, or single"); + } + } + public static modType parse(InputStream stream, String kind, String filename, CompilerFlags cflags) { - //FIXME: npe? - BufferedReader bufreader = null; - modType node = null; + BufferedReader bufReader = null; try { - if (kind.equals("eval")) { - bufreader = prepBufreader(stream, cflags, filename); - CharStream cs = new NoCloseReaderStream(bufreader); - ExpressionParser e = new ExpressionParser(cs, filename); - node = e.parse(); - } else if (kind.equals("single")) { - bufreader = prepBufreader(stream, cflags, filename); - InteractiveParser i = new InteractiveParser(bufreader, filename); - node = i.parse(); - } else if (kind.equals("exec")) { - bufreader = prepBufreader(stream, cflags, filename); - CharStream cs = new NoCloseReaderStream(bufreader); - ModuleParser g = new ModuleParser(cs, filename); - node = g.file_input(); - } else { - throw Py.ValueError("parse kind must be eval, exec, or single"); - } + // prepBufReader takes care of encoding detection and universal + // newlines: + bufReader = prepBufreader(stream, cflags, filename); + return parse(bufReader, kind, filename, cflags ); } catch (Throwable t) { - throw fixParseError(bufreader, t, filename); + throw fixParseError(bufReader, t, filename); } finally { - try { - if (bufreader != null) { - bufreader.close(); - } - } catch (IOException i) { - //XXX - } + close(bufReader); } - return node; } + public static modType parse(String string, + String kind, + String filename, + CompilerFlags cflags) { + BufferedReader bufReader = null; + try { + bufReader = prepBufReader(string); + return parse(bufReader, kind, filename, cflags); + } catch (Throwable t) { + throw fixParseError(bufReader, t, filename); + } finally { + close(bufReader); + } + } + public static modType partialParse(String string, String kind, String filename, CompilerFlags cflags, boolean stdprompt) { - ByteArrayInputStream istream = new ByteArrayInputStream( - StringUtil.toBytes(string)); - //FIXME: npe? - BufferedReader bufreader = null; - modType node = null; + // XXX: What's the idea of the stdprompt argument? + BufferedReader reader = null; try { - if (kind.equals("single")) { - bufreader = prepBufreader(istream, cflags, filename); - InteractiveParser i = new InteractiveParser(bufreader, filename); - node = i.parse(); - } else if (kind.equals("eval")) { - bufreader = prepBufreader(istream, cflags, filename); - CharStream cs = new NoCloseReaderStream(bufreader); - ExpressionParser e = new ExpressionParser(cs, filename); - node = e.parse(); - } else { - throw Py.ValueError("parse kind must be eval, exec, or single"); - } + reader = prepBufReader(string); + return parse(reader, kind, filename, cflags); } catch (Throwable t) { - PyException p = fixParseError(bufreader, t, filename); - if (validPartialSentence(bufreader, kind, filename)) { + PyException p = fixParseError(reader, t, filename); + if (validPartialSentence(reader, kind, filename)) { return null; } throw p; + } finally { + close(reader); } - return node; } private static boolean validPartialSentence(BufferedReader bufreader, String kind, String filename) { @@ -182,6 +194,7 @@ } } catch (Exception e) { + System.out.println(e); return lexer.eofWhileNested; } return true; @@ -202,8 +215,6 @@ } else if (cflags != null && cflags.encoding != null) { encoding = cflags.encoding; } - } else if (cflags.source_is_utf8) { - throw new ParseException("encoding declaration in Unicode string"); } // Enable universal newlines mode on the input @@ -229,13 +240,29 @@ throw Py.SystemError("Java couldn't find the ISO-8859-1 encoding"); } } - + BufferedReader bufreader = new BufferedReader(reader); - - bufreader.mark(MARK_LIMIT); return bufreader; } + private static BufferedReader prepBufReader(String string) throws IOException { + BufferedReader bufReader; + + // LineNumberReader takes care of universal newlines + bufReader = new LineNumberReader(new StringReader(string)); + + // If the input is a decoded string (implied from the String argument + // for prepBufReader), it can't have an encoding declaration. + bufReader.mark(MARK_LIMIT); + if (findEncoding(bufReader) != null) { + throw new ParseException("encoding declaration in Unicode string"); + } + bufReader.reset(); + + return bufReader; + } + + /** * Check for a BOM mark at the begginning of stream. If there is a BOM * mark, advance the stream passed it. If not, reset() to start at the @@ -262,12 +289,31 @@ } stream.reset(); return false; - } + } private static String readEncoding(InputStream stream) throws IOException { stream.mark(MARK_LIMIT); String encoding = null; BufferedReader br = new BufferedReader(new InputStreamReader(stream), 512); + encoding = findEncoding(br); + // XXX: reset() can still raise an IOException if a line exceeds our large mark + // limit + stream.reset(); + return encodingMap(encoding); + } + + /** + * Reads the first two lines of the reader, searching for an encoding + * declaration. + * + * Note that reseting the reader (if needed) is responsibility of the caller. + * + * @return The declared encoding, or null if no encoding declaration is + * found + */ + private static String findEncoding(BufferedReader br) + throws IOException { + String encoding = null; for (int i = 0; i < 2; i++) { String strLine = br.readLine(); if (strLine == null) { @@ -279,10 +325,7 @@ break; } } - // XXX: reset() can still raise an IOException if a line exceeds our large mark - // limit - stream.reset(); - return encodingMap(encoding); + return encoding; } private static String encodingMap(String encoding) { @@ -308,4 +351,14 @@ return null; } + private static void close(BufferedReader reader) { + try { + if (reader != null) { + reader.close(); + } + } catch (IOException i) { + // XXX: Log the error? + } + } + } Modified: trunk/jython/src/org/python/core/Py.java =================================================================== --- trunk/jython/src/org/python/core/Py.java 2008-10-31 22:06:00 UTC (rev 5541) +++ trunk/jython/src/org/python/core/Py.java 2008-11-05 02:39:25 UTC (rev 5542) @@ -16,6 +16,7 @@ import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; +import java.util.Arrays; import java.util.Calendar; import java.util.HashSet; import java.util.Set; @@ -357,7 +358,7 @@ public static PyObject ImportWarning; public static void ImportWarning(String message) { - warning(ImportWarning, message); + warning(ImportWarning, message); } public static PyObject UnicodeWarning; @@ -1610,34 +1611,31 @@ } // w/o compiler-flags - public static PyObject compile(modType node, String filename) { - return compile(node, getName(), filename); - } - - public static PyObject compile(modType node, String name, - String filename) { - return compile(node, name, filename, true, false); - } - - public static PyObject compile(modType node, String name, - String filename, - boolean linenumbers, - boolean printResults) { - return compile_flags(node, name, filename, linenumbers, - printResults, null); - } - - public static PyObject compile(InputStream istream, String filename, - String kind) { + public static PyObject compile(InputStream istream, String filename, String kind) { return compile_flags(istream, filename, kind, null); } - // with compiler-flags - public static PyObject compile_flags(modType node, String name, - String filename, - boolean linenumbers, - boolean printResults, CompilerFlags cflags) { + /** + * Entry point for compiling modules. + * + * @param node Module node, coming from the parsing process + * @param name Internal name for the compiled code. Typically generated by + * calling {@link #getName()}. + * @param filename Source file name + * @param linenumbers True to track source line numbers on the generated + * code + * @param printResults True to call the sys.displayhook on the result of + * the code + * @param cflags Compiler flags + * @return Code object for the compiled module + */ + public static PyObject compile_flags(modType node, String name, String filename, + boolean linenumbers, boolean printResults, + CompilerFlags cflags) { try { + if (cflags != null && cflags.only_ast) { + return Py.java2py(node); + } ByteArrayOutputStream ostream = new ByteArrayOutputStream(); Module.compile(node, ostream, name, filename, linenumbers, printResults, false, cflags); @@ -1650,62 +1648,75 @@ } } + public static PyObject compile_flags(modType node, String filename, + String kind, CompilerFlags cflags) { + return Py.compile_flags(node, getName(), filename, true, + kind.equals("single"), cflags); + } + + /** + * Compiles python source code coming from a file or another external stream + */ public static PyObject compile_flags(InputStream istream, String filename, - String kind,CompilerFlags cflags) - { + String kind, CompilerFlags cflags) { modType node = ParserFacade.parse(istream, kind, filename, cflags); - if (cflags != null && cflags.only_ast) { - return Py.java2py(node); - } - - boolean printResults = false; - if (kind.equals("single")) { - printResults = true; - } - return Py.compile_flags(node, getName(), filename, true, printResults, cflags); + return Py.compile_flags(node, filename, kind, cflags); } - public static PyObject compile_flags(modType node, String filename, - String kind, CompilerFlags cflags) { - boolean printResults = false; - if (kind.equals("single")) { - printResults = true; + /** + * Compiles python source code coming from decoded Strings. + * + * DO NOT use this for PyString input. Use + * {@link #compile_flags(byte[], String, String, CompilerFlags)} instead. + */ + public static PyObject compile_flags(String data, String filename, + String kind, CompilerFlags cflags) { + if (data.contains("\0")) { + throw Py.TypeError("compile() expected string without null bytes"); } - return Py.compile_flags(node, getName(), filename, true, printResults, cflags); + if (cflags != null && cflags.dont_imply_dedent) { + data += "\n"; + } else { + data += "\n\n"; + } + modType node = ParserFacade.parse(data, kind, filename, cflags); + return Py.compile_flags(node, filename, kind, cflags); } - public static PyObject compile_flags(String data, - String filename, - String kind, - CompilerFlags cflags) { - - if (data.contains("\0")) { - throw Py.TypeError("compile() expected string without null bytes"); + /** + * Compiles python source code coming from bytestrings + */ + public static PyObject compile_flags(byte[] bytes, String filename, + String kind, CompilerFlags cflags) { + for(int i = 0; i < bytes.length; i++) { + if (bytes[i] == 0) { + throw Py.TypeError("compile() expected string without null bytes"); + } } - - byte[] bytes; + byte[] data; if (cflags != null && cflags.dont_imply_dedent) { - bytes = StringUtil.toBytes(data + "\n"); + data = new byte[bytes.length + 1]; + System.arraycopy(bytes, 0, data, 0, bytes.length); + data[data.length - 1] = '\n'; } else { - bytes = StringUtil.toBytes(data + "\n\n"); + data = new byte[bytes.length + 2]; + System.arraycopy(bytes, 0, data, 0, bytes.length); + data[data.length - 1] = data[data.length - 2] = '\n'; } - return Py.compile_flags(new ByteArrayInputStream(bytes), - filename, - kind, - cflags); + modType node = ParserFacade.parse(new ByteArrayInputStream(data), kind, + filename, cflags); + return Py.compile_flags(node, filename, kind, cflags); } - public static PyObject compile_command_flags(String string, - String filename, String kind, CompilerFlags cflags, boolean stdprompt) { + public static PyObject compile_command_flags(String string, String filename, + String kind, CompilerFlags cflags, boolean stdprompt) { modType node = ParserFacade.partialParse(string + "\n", kind, filename, - cflags, stdprompt); - + cflags, stdprompt); if (node == null) { return Py.None; } - return Py.compile_flags(node, Py.getName(), filename, true, true, - cflags); + return Py.compile_flags(node, Py.getName(), filename, true, true, cflags); } public static PyObject[] unpackSequence(PyObject obj, int length) { Modified: trunk/jython/src/org/python/core/__builtin__.java =================================================================== --- trunk/jython/src/org/python/core/__builtin__.java 2008-10-31 22:06:00 UTC (rev 5541) +++ trunk/jython/src/org/python/core/__builtin__.java 2008-11-05 02:39:25 UTC (rev 5542) @@ -1,6 +1,8 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.core; +import java.io.ByteArrayInputStream; +import java.io.InputStream; import java.util.Iterator; import java.util.Map; @@ -281,7 +283,7 @@ if (args[0] instanceof PyUnicode) { flags += PyTableCode.PyCF_SOURCE_IS_UTF8; } - return __builtin__.compile(args[0].toString(), args[1].toString(), args[2].toString(), flags, dont_inherit); + return __builtin__.compile((PyString)args[0], args[1].toString(), args[2].toString(), flags, dont_inherit); case 29: return __builtin__.map(args); case 43: @@ -412,7 +414,7 @@ } public static PyObject apply(PyObject o) { - return o.__call__(); + return o.__call__(); } public static PyObject apply(PyObject o, PyObject args) { @@ -473,19 +475,29 @@ throw Py.TypeError("number coercion failed"); } - public static PyObject compile(String data, String filename, String kind) { - return Py.compile_flags(data, filename, kind, Py.getCompilerFlags()); + public static PyObject compile(PyString data, String filename, String kind) { + if (data instanceof PyUnicode) { + return Py.compile_flags(data.toString(), filename, kind, Py.getCompilerFlags()); + } else { + return Py.compile_flags(data.toBytes(), filename, kind, Py.getCompilerFlags()); + } } public static PyObject compile(modType node, String filename, String kind) { return Py.compile_flags(node, filename, kind, Py.getCompilerFlags()); } - public static PyObject compile(String data, String filename, String kind, int flags, boolean dont_inherit) { + public static PyObject compile(PyString data, String filename, String kind, int flags, boolean dont_inherit) { if ((flags & ~PyTableCode.CO_ALL_FEATURES) != 0) { throw Py.ValueError("compile(): unrecognised flags"); } - return Py.compile_flags(data, filename, kind, Py.getCompilerFlags(flags, dont_inherit)); + if (data instanceof PyUnicode) { + return Py.compile_flags(data.toString(), filename, kind, + Py.getCompilerFlags(flags, dont_inherit)); + } else { + return Py.compile_flags(data.toBytes(), filename, kind, + Py.getCompilerFlags(flags, dont_inherit)); + } } public static PyObject compile(modType node, String filename, String kind, int flags, boolean dont_inherit) { @@ -550,7 +562,7 @@ code = (PyCode) o; } else { if (o instanceof PyString) { - code = (PyCode)compile(o.toString(), "<string>", "eval"); + code = (PyCode)compile((PyString)o, "<string>", "eval"); } else { throw Py.TypeError("eval: argument 1 must be string or code object"); } @@ -1164,7 +1176,7 @@ } public static PyObject reload(PySystemState o) { - // reinitialize methods + // reinitialize methods o.reload(); return o; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-10-31 22:06:02
|
Revision: 5541 http://jython.svn.sourceforge.net/jython/?rev=5541&view=rev Author: fwierzbicki Date: 2008-10-31 22:06:00 +0000 (Fri, 31 Oct 2008) Log Message: ----------- tag beta0 Added Paths: ----------- tags/Release_2_5beta0/ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-10-31 17:43:57
|
Revision: 5540 http://jython.svn.sourceforge.net/jython/?rev=5540&view=rev Author: pjenvey Date: 2008-10-31 17:43:52 +0000 (Fri, 31 Oct 2008) Log Message: ----------- bump bytecode magic for all the compiler changes since alpha3 Modified Paths: -------------- trunk/jython/src/org/python/core/imp.java Modified: trunk/jython/src/org/python/core/imp.java =================================================================== --- trunk/jython/src/org/python/core/imp.java 2008-10-31 17:23:18 UTC (rev 5539) +++ trunk/jython/src/org/python/core/imp.java 2008-10-31 17:43:52 UTC (rev 5540) @@ -22,7 +22,7 @@ private static final String UNKNOWN_SOURCEFILE = "<unknown>"; - public static final int APIVersion = 15; + public static final int APIVersion = 16; //This should change to 0 for Python 2.7 and 3.0 see PEP 328 public static final int DEFAULT_LEVEL = -1; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <otm...@us...> - 2008-10-31 17:23:29
|
Revision: 5539 http://jython.svn.sourceforge.net/jython/?rev=5539&view=rev Author: otmarhumbel Date: 2008-10-31 17:23:18 +0000 (Fri, 31 Oct 2008) Log Message: ----------- UserDict.py is also needed for a mimimum start of jython (on Windows) Modified Paths: -------------- trunk/installer/src/java/org/python/util/install/JarInstaller.java Modified: trunk/installer/src/java/org/python/util/install/JarInstaller.java =================================================================== --- trunk/installer/src/java/org/python/util/install/JarInstaller.java 2008-10-31 17:07:03 UTC (rev 5538) +++ trunk/installer/src/java/org/python/util/install/JarInstaller.java 2008-10-31 17:23:18 UTC (rev 5539) @@ -241,6 +241,7 @@ coreLibFiles.add("stat.py"); coreLibFiles.add("string.py"); coreLibFiles.add("threading.py"); + coreLibFiles.add("UserDict.py"); coreLibFiles.add("zipfile.py"); coreLibFiles.add("zlib.py"); return coreLibFiles; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <otm...@us...> - 2008-10-31 17:07:07
|
Revision: 5538 http://jython.svn.sourceforge.net/jython/?rev=5538&view=rev Author: otmarhumbel Date: 2008-10-31 17:07:03 +0000 (Fri, 31 Oct 2008) Log Message: ----------- first guess what os.py needs for a mimimum start of jython Modified Paths: -------------- trunk/installer/src/java/org/python/util/install/JarInstaller.java Modified: trunk/installer/src/java/org/python/util/install/JarInstaller.java =================================================================== --- trunk/installer/src/java/org/python/util/install/JarInstaller.java 2008-10-31 16:33:46 UTC (rev 5537) +++ trunk/installer/src/java/org/python/util/install/JarInstaller.java 2008-10-31 17:07:03 UTC (rev 5538) @@ -226,7 +226,9 @@ coreLibFiles.add("javapath.py"); coreLibFiles.add("jreload.py"); coreLibFiles.add("marshal.py"); + coreLibFiles.add("ntpath.py"); coreLibFiles.add("os.py"); + coreLibFiles.add("popen2.py"); coreLibFiles.add("posixpath.py"); coreLibFiles.add("random.py"); coreLibFiles.add("re.py"); @@ -238,6 +240,7 @@ coreLibFiles.add("sre_parse.py"); coreLibFiles.add("stat.py"); coreLibFiles.add("string.py"); + coreLibFiles.add("threading.py"); coreLibFiles.add("zipfile.py"); coreLibFiles.add("zlib.py"); return coreLibFiles; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-10-31 16:33:50
|
Revision: 5537 http://jython.svn.sourceforge.net/jython/?rev=5537&view=rev Author: fwierzbicki Date: 2008-10-31 16:33:46 +0000 (Fri, 31 Oct 2008) Log Message: ----------- Change build labels to beta. Modified Paths: -------------- trunk/jython/README.txt trunk/jython/build.xml Modified: trunk/jython/README.txt =================================================================== --- trunk/jython/README.txt 2008-10-31 16:26:45 UTC (rev 5536) +++ trunk/jython/README.txt 2008-10-31 16:33:46 UTC (rev 5537) @@ -1,13 +1,10 @@ -Welcome to Jython 2.5a3 +Welcome to Jython 2.5b0 ======================= -This is the third alpha of the 2.5 version of Jython. It +This is the first beta of the 2.5 version of Jython. It contains most of the new features for the 2.5 release. -This release fixes an installation bug on windows and restores standalone -mode. - The release was compiled on Mac OS X with JDK 5 and requires JDK 5 to run. -As an alpha release, this release is incomplete and contains bugs. Do not +As a beta release, this release is incomplete and contains bugs. Do not use in a production environment. Modified: trunk/jython/build.xml =================================================================== --- trunk/jython/build.xml 2008-10-31 16:26:45 UTC (rev 5536) +++ trunk/jython/build.xml 2008-10-31 16:33:46 UTC (rev 5537) @@ -187,12 +187,12 @@ <property name="PY_RELEASE_LEVEL_SNAPSHOT" value="170"/> <!-- 0xAA --> <!-- The current version info --> - <property name="jython.version" value="2.5a3+"/> - <property name="jython.version.noplus" value="2.5a3"/> + <property name="jython.version" value="2.5b0+"/> + <property name="jython.version.noplus" value="2.5b0"/> <property name="jython.major_version" value="2"/> <property name="jython.minor_version" value="5"/> - <property name="jython.micro_version" value="3"/> - <property name="jython.release_level" value="${PY_RELEASE_LEVEL_ALPHA}"/> + <property name="jython.micro_version" value="0"/> + <property name="jython.release_level" value="${PY_RELEASE_LEVEL_BETA}"/> <property name="jython.release_serial" value="0"/> <condition property="do.snapshot.build"> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-10-31 16:26:49
|
Revision: 5536 http://jython.svn.sourceforge.net/jython/?rev=5536&view=rev Author: fwierzbicki Date: 2008-10-31 16:26:45 +0000 (Fri, 31 Oct 2008) Log Message: ----------- Offset fix. Modified Paths: -------------- trunk/jython/grammar/Python.g Modified: trunk/jython/grammar/Python.g =================================================================== --- trunk/jython/grammar/Python.g 2008-10-31 15:59:39 UTC (rev 5535) +++ trunk/jython/grammar/Python.g 2008-10-31 16:26:45 UTC (rev 5536) @@ -1178,6 +1178,7 @@ $etype = c; } else if (o instanceof Attribute) { Attribute c = (Attribute)o; + c.setCharStartIndex($etype.getCharStartIndex()); c.value = $etype; $etype = c; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <am...@us...> - 2008-10-31 15:59:49
|
Revision: 5535 http://jython.svn.sourceforge.net/jython/?rev=5535&view=rev Author: amak Date: 2008-10-31 15:59:39 +0000 (Fri, 31 Oct 2008) Log Message: ----------- Adding modjy to the jython distro. Simply adding the entire zip containing source, jars, docs, etc, for now. version being added is 0.22.3, which matches a label in the modjy repo. Modified Paths: -------------- trunk/jython/build.xml Added Paths: ----------- trunk/jython/extlibs/modjy_0_22_3.zip Modified: trunk/jython/build.xml =================================================================== --- trunk/jython/build.xml 2008-10-31 08:37:16 UTC (rev 5534) +++ trunk/jython/build.xml 2008-10-31 15:59:39 UTC (rev 5535) @@ -626,6 +626,7 @@ <include name="src/org/**/ucnhash.dat" /> <include name="grammar/*.g" /> <include name="extlibs/**/*.jar" /> + <include name="extlibs/**/*.zip" /> <include name="tests/java/**/*.java" /> <include name="CoreExposed.includes" /> </fileset> Added: trunk/jython/extlibs/modjy_0_22_3.zip =================================================================== (Binary files differ) Property changes on: trunk/jython/extlibs/modjy_0_22_3.zip ___________________________________________________________________ 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: <otm...@us...> - 2008-10-31 08:37:25
|
Revision: 5534 http://jython.svn.sourceforge.net/jython/?rev=5534&view=rev Author: otmarhumbel Date: 2008-10-31 08:37:16 +0000 (Fri, 31 Oct 2008) Log Message: ----------- revert that part of revision 5296 which deletes the /bin directory Revision Links: -------------- http://jython.svn.sourceforge.net/jython/?rev=5296&view=rev Modified Paths: -------------- trunk/installer/src/java/org/python/util/install/JarInstaller.java Modified: trunk/installer/src/java/org/python/util/install/JarInstaller.java =================================================================== --- trunk/installer/src/java/org/python/util/install/JarInstaller.java 2008-10-31 02:04:57 UTC (rev 5533) +++ trunk/installer/src/java/org/python/util/install/JarInstaller.java 2008-10-31 08:37:16 UTC (rev 5534) @@ -139,7 +139,6 @@ _progressListener.progressStartScripts(); StartScriptGenerator generator = new StartScriptGenerator(targetDirectory, javaHome); generator.generateStartScripts(); - StandalonePackager.emptyDirectory(new File(targetDirectory, "bin"), null); } else { _progressListener.progressStandalone(); File jythonJar = new File(targetDirectory, JYTHON_JAR); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-10-31 02:05:00
|
Revision: 5533 http://jython.svn.sourceforge.net/jython/?rev=5533&view=rev Author: pjenvey Date: 2008-10-31 02:04:57 +0000 (Fri, 31 Oct 2008) Log Message: ----------- add asDouble (like asInt), fix round conversion Modified Paths: -------------- trunk/jython/Lib/test/test_builtin_jy.py trunk/jython/src/org/python/core/PyFloat.java trunk/jython/src/org/python/core/PyObject.java trunk/jython/src/org/python/core/__builtin__.java Modified: trunk/jython/Lib/test/test_builtin_jy.py =================================================================== --- trunk/jython/Lib/test/test_builtin_jy.py 2008-10-30 22:43:59 UTC (rev 5532) +++ trunk/jython/Lib/test/test_builtin_jy.py 2008-10-31 02:04:57 UTC (rev 5533) @@ -102,11 +102,13 @@ return None self.assert_(not callable(Baz())) -class RangeTest(unittest.TestCase): +class ConversionTest(unittest.TestCase): class Foo(object): def __int__(self): return 3 + def __float__(self): + return 3.14 foo = Foo() def test_range_non_int(self): @@ -115,6 +117,9 @@ def test_xrange_non_int(self): self.assertEqual(list(xrange(self.foo)), [0, 1, 2]) + def test_round_non_float(self): + self.assertEqual(round(self.Foo(), 1), 3.1) + def test_main(): test.test_support.run_unittest(BuiltinTest, LoopTest, @@ -124,7 +129,7 @@ ReturnTest, ReprTest, CallableTest, - RangeTest) + ConversionTest) if __name__ == "__main__": test_main() Modified: trunk/jython/src/org/python/core/PyFloat.java =================================================================== --- trunk/jython/src/org/python/core/PyFloat.java 2008-10-30 22:43:59 UTC (rev 5532) +++ trunk/jython/src/org/python/core/PyFloat.java 2008-10-31 02:04:57 UTC (rev 5533) @@ -620,6 +620,10 @@ return float___getnewargs__(); } + public double asDouble() { + return value; + } + // standard singleton issues apply here to __getformat__/__setformat__, // but this is what Python demands Modified: trunk/jython/src/org/python/core/PyObject.java =================================================================== --- trunk/jython/src/org/python/core/PyObject.java 2008-10-30 22:43:59 UTC (rev 5532) +++ trunk/jython/src/org/python/core/PyObject.java 2008-10-31 02:04:57 UTC (rev 5533) @@ -3887,8 +3887,26 @@ } /** - * Coerce this object into an index-sized integer. + * Convert this object into a double. Throws a PyException on failure. * + * @return a double value + */ + public double asDouble() { + PyFloat floatObj; + try { + floatObj = __float__(); + } catch (PyException pye) { + if (Py.matchException(pye, Py.AttributeError)) { + throw Py.TypeError("a float is required"); + } + throw pye; + } + return floatObj.asDouble(); + } + + /** + * Convert this object into an index-sized integer. Throws a PyException on failure. + * * @return an index-sized int */ public int asIndex() { @@ -3896,7 +3914,7 @@ } /** - * Coerce this object into an index-sized integer. + * Convert this object into an index-sized integer. * * Throws a Python exception on Overflow if specified an exception type for err. * Modified: trunk/jython/src/org/python/core/__builtin__.java =================================================================== --- trunk/jython/src/org/python/core/__builtin__.java 2008-10-30 22:43:59 UTC (rev 5532) +++ trunk/jython/src/org/python/core/__builtin__.java 2008-10-31 02:04:57 UTC (rev 5533) @@ -1534,7 +1534,7 @@ ArgParser ap = new ArgParser("round", args, kwds, new String[] {"number", "ndigits"}, 0); PyObject number = ap.getPyObject(0); int ndigits = ap.getInt(1, 0); - return round(Py.py2double(number), ndigits); + return round(number.asDouble(), ndigits); } private static PyFloat round(double f, int digits) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <otm...@us...> - 2008-10-30 22:44:05
|
Revision: 5532 http://jython.svn.sourceforge.net/jython/?rev=5532&view=rev Author: otmarhumbel Date: 2008-10-30 22:43:59 +0000 (Thu, 30 Oct 2008) Log Message: ----------- small improvements, and formatting Modified Paths: -------------- trunk/installer/src/java/org/python/util/install/ChildProcess.java Modified: trunk/installer/src/java/org/python/util/install/ChildProcess.java =================================================================== --- trunk/installer/src/java/org/python/util/install/ChildProcess.java 2008-10-30 22:43:27 UTC (rev 5531) +++ trunk/installer/src/java/org/python/util/install/ChildProcess.java 2008-10-30 22:43:59 UTC (rev 5532) @@ -11,8 +11,8 @@ * <ul> * <li>wait for the child process to finish. * <li>kill the child process after a specified timeout. - * <li>get the output of the child process (System.out and System.err) redirected to the calling process, unless in - * silent mode. + * <li>get the output of the child process (System.out and System.err) redirected to the calling + * process, unless in silent mode. * </ul> */ public class ChildProcess { @@ -21,14 +21,15 @@ * Inner class for reading stdout of the child process and printing it onto the caller's stdout. */ private class StdoutMonitor extends Thread { - private StdoutMonitor() { - } + private StdoutMonitor() {} + public void run() { String line = null; BufferedReader stdout = new BufferedReader(new InputStreamReader(_process.getInputStream())); try { - while ((line = stdout.readLine()) != null) { // blocks until input found or process dead + // blocks until input found or process dead + while ((line = stdout.readLine()) != null) { if (!isSilent()) { System.out.println(line); } @@ -41,8 +42,7 @@ if (stdout != null) try { stdout.close(); - } catch (IOException e) { - } + } catch (IOException e) {} } } } @@ -51,14 +51,15 @@ * Inner class for reading stderr of the child process and printing it onto the caller's stderr. */ private class StderrMonitor extends Thread { - private StderrMonitor() { - } + private StderrMonitor() {} + public void run() { String line = null; BufferedReader stderr = new BufferedReader(new InputStreamReader(_process.getErrorStream())); try { - while ((line = stderr.readLine()) != null) { // blocks until input found or process dead + // blocks until input found or process dead + while ((line = stderr.readLine()) != null) { if (!isSilent()) { System.err.println(line); } @@ -71,8 +72,7 @@ if (stderr != null) try { stderr.close(); - } catch (IOException e) { - } + } catch (IOException e) {} } } } @@ -140,13 +140,13 @@ /** * Default constructor */ - public ChildProcess() { - } + public ChildProcess() {} /** * Constructor taking the command as an argument * - * @param command The command to be executed. + * @param command + * The command to be executed. */ public ChildProcess(String command) { setCommand(command); @@ -155,7 +155,8 @@ /** * Constructor taking a command array as an argument * - * @param commandArray The command to be executed, every token as array element. + * @param commandArray + * The command to be executed, every token as array element. */ public ChildProcess(String commandArray[]) { setCommandArray(commandArray); @@ -164,8 +165,11 @@ /** * Constructor taking the command and the timeout as an argument * - * @param command The command to be executed. - * @param timeout in milliseconds. Special value: <code>INFINITE_TIMEOUT</code> indicates no timeout at all. + * @param command + * The command to be executed. + * @param timeout + * in milliseconds. Special value: <code>INFINITE_TIMEOUT</code> indicates no timeout + * at all. */ public ChildProcess(String command, long timeout) { setCommand(command); @@ -175,8 +179,11 @@ /** * Constructor taking a command array and the timeout as an argument * - * @param commandArray The command to be executed, every token as array element. - * @param timeout in milliseconds. Special value: <code>INFINITE_TIMEOUT</code> indicates no timeout at all. + * @param commandArray + * The command to be executed, every token as array element. + * @param timeout + * in milliseconds. Special value: <code>INFINITE_TIMEOUT</code> indicates no timeout + * at all. */ public ChildProcess(String commandArray[], long timeout) { setCommandArray(commandArray); @@ -214,8 +221,9 @@ /** * Set the timeout (how long should the calling process wait for the child). * - * @param timeout in milliseconds. Special value: <code>INFINITE_TIMEOUT</code> indicates no timeout at all. This - * is the default. + * @param timeout + * in milliseconds. Special value: <code>INFINITE_TIMEOUT</code> indicates no timeout + * at all. This is the default. */ public void setTimeout(long timeout) { _timeout = timeout; @@ -231,8 +239,8 @@ /** * Set the debug flag. * <p> - * Setting this to true will print the submitted command and an information if the child process is destroyed after - * the timeout. + * Setting this to true will print the submitted command and an information if the child process + * is destroyed after the timeout. */ public void setDebug(boolean debug) { _debug = debug; @@ -262,15 +270,16 @@ } /** - * Set the interval (in milliseconds) after which the subprocess is checked if it is still alive. Defaults to 1000 - * ms. + * Set the interval (in milliseconds) after which the subprocess is checked if it is still + * alive. Defaults to 1000 ms. */ public void setPollAliveInterval(long pollAliveInterval) { _pollAliveInterval = pollAliveInterval; } /** - * Returns the interval (in milliseconds) after which the subprocess is checked if it is still alive. + * Returns the interval (in milliseconds) after which the subprocess is checked if it is still + * alive. */ public long getPollAliveInterval() { return _pollAliveInterval; @@ -283,10 +292,10 @@ boolean isTimeout = false; long currentTime = System.currentTimeMillis(); long diff = 0; - - if (getTimeout() != INFINITE_TIMEOUT) { + long timeout = getTimeout(); + if (timeout != INFINITE_TIMEOUT) { diff = currentTime - _startTime; - if (diff > getTimeout()) { + if (diff > timeout) { isTimeout = true; } } @@ -300,7 +309,6 @@ try { // determine start time _startTime = System.currentTimeMillis(); - // start the process if (getCommandArray() != null) { _process = Runtime.getRuntime().exec(getCommandArray()); @@ -308,13 +316,11 @@ _process = Runtime.getRuntime().exec(getCommand()); } debugCommand(); - // handle stdout and stderr StdoutMonitor stdoutMonitor = new StdoutMonitor(); stdoutMonitor.start(); StderrMonitor stderrMonitor = new StderrMonitor(); stderrMonitor.start(); - // run the subprocess as long as wanted while (!isTimeout() && isAlive()) { try { @@ -325,7 +331,6 @@ } } } - // end properly if (isAlive()) { // sets the exit value in case process is dead destroy(); @@ -381,20 +386,22 @@ */ private void debugCommand() { if (isDebug()) { - if (getCommandArray() != null) { + String[] commandArray = getCommandArray(); + if (commandArray != null) { System.out.print("[ChildProcess] command '"); - for (int i = 0; i < getCommandArray().length; i++) { + for (int i = 0; i < commandArray.length; i++) { + String commandPart = commandArray[i]; if (i == 0) { - System.out.print(getCommandArray()[i]); + System.out.print(commandPart); } else { - System.out.print(" " + getCommandArray()[i]); + System.out.print(" " + commandPart); } } System.out.println("' is now running..."); } else { - System.out.println("[ChildProcess] command '" + getCommand() + "' is now running..."); + System.out.println("[ChildProcess] command '" + getCommand() + + "' is now running..."); } } } - } \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <otm...@us...> - 2008-10-30 22:43:32
|
Revision: 5531 http://jython.svn.sourceforge.net/jython/?rev=5531&view=rev Author: otmarhumbel Date: 2008-10-30 22:43:27 +0000 (Thu, 30 Oct 2008) Log Message: ----------- fixed javac warnings due to source file encoding problems Modified Paths: -------------- trunk/installer/src/java/org/python/util/install/UnicodeSequences.java Modified: trunk/installer/src/java/org/python/util/install/UnicodeSequences.java =================================================================== --- trunk/installer/src/java/org/python/util/install/UnicodeSequences.java 2008-10-30 06:07:01 UTC (rev 5530) +++ trunk/installer/src/java/org/python/util/install/UnicodeSequences.java 2008-10-30 22:43:27 UTC (rev 5531) @@ -7,13 +7,13 @@ */ public interface UnicodeSequences { - public static final String A2 = "\u00C4"; // \xC4: A with two dots above - public static final String a2 = "\u00E4"; // \xE4: a with two dots above + public static final String A2 = "\u00C4"; // German A umlaut: A with two dots above + public static final String a2 = "\u00E4"; // German a umlaut: a with two dots above - public static final String O2 = "\u00D6"; // \xD6: O with two dots above - public static final String o2 = "\u00F6"; // \xF6: o with two dots above + public static final String O2 = "\u00D6"; // German O umlaut: O with two dots above + public static final String o2 = "\u00F6"; // German o umlaut: o with two dots above - public static final String U2 = "\u00DC"; // \xDC: U with two dots above - public static final String u2 = "\u00FC"; // \xFC: u with two dots above + public static final String U2 = "\u00DC"; // German U umlaut: U with two dots above + public static final String u2 = "\u00FC"; // German u umlaut: u with two dots above } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-10-30 06:07:06
|
Revision: 5530 http://jython.svn.sourceforge.net/jython/?rev=5530&view=rev Author: pjenvey Date: 2008-10-30 06:07:01 +0000 (Thu, 30 Oct 2008) Log Message: ----------- Derived changes for r5529 __cmp__ results Modified Paths: -------------- trunk/jython/src/org/python/core/PyArrayDerived.java trunk/jython/src/org/python/core/PyBaseExceptionDerived.java trunk/jython/src/org/python/core/PyBooleanDerived.java trunk/jython/src/org/python/core/PyClassMethodDerived.java trunk/jython/src/org/python/core/PyComplexDerived.java trunk/jython/src/org/python/core/PyDictionaryDerived.java trunk/jython/src/org/python/core/PyEnumerateDerived.java trunk/jython/src/org/python/core/PyFileDerived.java trunk/jython/src/org/python/core/PyFloatDerived.java trunk/jython/src/org/python/core/PyFrozenSetDerived.java trunk/jython/src/org/python/core/PyIntegerDerived.java trunk/jython/src/org/python/core/PyListDerived.java trunk/jython/src/org/python/core/PyLongDerived.java trunk/jython/src/org/python/core/PyModuleDerived.java trunk/jython/src/org/python/core/PyObjectDerived.java trunk/jython/src/org/python/core/PyPropertyDerived.java trunk/jython/src/org/python/core/PySetDerived.java trunk/jython/src/org/python/core/PySliceDerived.java trunk/jython/src/org/python/core/PyStringDerived.java trunk/jython/src/org/python/core/PySuperDerived.java trunk/jython/src/org/python/core/PyTupleDerived.java trunk/jython/src/org/python/core/PyTypeDerived.java trunk/jython/src/org/python/core/PyUnicodeDerived.java trunk/jython/src/org/python/modules/_collections/PyDefaultDictDerived.java trunk/jython/src/org/python/modules/_collections/PyDequeDerived.java trunk/jython/src/org/python/modules/_csv/PyDialectDerived.java trunk/jython/src/org/python/modules/_functools/PyPartialDerived.java trunk/jython/src/org/python/modules/_weakref/ReferenceTypeDerived.java trunk/jython/src/org/python/modules/random/PyRandomDerived.java trunk/jython/src/org/python/modules/thread/PyLocalDerived.java trunk/jython/src/org/python/modules/zipimport/zipimporterDerived.java Modified: trunk/jython/src/org/python/core/PyArrayDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyArrayDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyArrayDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyBaseExceptionDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyBaseExceptionDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyBaseExceptionDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -752,11 +752,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyBooleanDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyBooleanDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyBooleanDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyClassMethodDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyClassMethodDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyClassMethodDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyComplexDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyComplexDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyComplexDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyDictionaryDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyDictionaryDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyDictionaryDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyEnumerateDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyEnumerateDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyEnumerateDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyFileDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyFileDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyFileDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyFloatDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyFloatDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyFloatDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyFrozenSetDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyFrozenSetDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyFrozenSetDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyIntegerDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyIntegerDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyIntegerDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyListDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyListDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyListDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyLongDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyLongDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyLongDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyModuleDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyModuleDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyModuleDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -752,11 +752,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyObjectDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyObjectDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyObjectDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyPropertyDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyPropertyDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyPropertyDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PySetDerived.java =================================================================== --- trunk/jython/src/org/python/core/PySetDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PySetDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PySliceDerived.java =================================================================== --- trunk/jython/src/org/python/core/PySliceDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PySliceDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyStringDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyStringDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyStringDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PySuperDerived.java =================================================================== --- trunk/jython/src/org/python/core/PySuperDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PySuperDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyTupleDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyTupleDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyTupleDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyTypeDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyTypeDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyTypeDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -752,11 +752,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyUnicodeDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyUnicodeDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyUnicodeDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/modules/_collections/PyDefaultDictDerived.java =================================================================== --- trunk/jython/src/org/python/modules/_collections/PyDefaultDictDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/modules/_collections/PyDefaultDictDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -778,11 +778,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/modules/_collections/PyDequeDerived.java =================================================================== --- trunk/jython/src/org/python/modules/_collections/PyDequeDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/modules/_collections/PyDequeDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -778,11 +778,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/modules/_csv/PyDialectDerived.java =================================================================== --- trunk/jython/src/org/python/modules/_csv/PyDialectDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/modules/_csv/PyDialectDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -754,11 +754,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/modules/_functools/PyPartialDerived.java =================================================================== --- trunk/jython/src/org/python/modules/_functools/PyPartialDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/modules/_functools/PyPartialDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -754,11 +754,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/modules/_weakref/ReferenceTypeDerived.java =================================================================== --- trunk/jython/src/org/python/modules/_weakref/ReferenceTypeDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/modules/_weakref/ReferenceTypeDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -778,11 +778,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/modules/random/PyRandomDerived.java =================================================================== --- trunk/jython/src/org/python/modules/random/PyRandomDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/modules/random/PyRandomDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -778,11 +778,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/modules/thread/PyLocalDerived.java =================================================================== --- trunk/jython/src/org/python/modules/thread/PyLocalDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/modules/thread/PyLocalDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -754,11 +754,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/modules/zipimport/zipimporterDerived.java =================================================================== --- trunk/jython/src/org/python/modules/zipimport/zipimporterDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/modules/zipimport/zipimporterDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -754,11 +754,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-10-30 06:06:04
|
Revision: 5529 http://jython.svn.sourceforge.net/jython/?rev=5529&view=rev Author: pjenvey Date: 2008-10-30 06:06:03 +0000 (Thu, 30 Oct 2008) Log Message: ----------- allow NotImplemented and non ints that can be converted in Derived __cmp__ results Modified Paths: -------------- trunk/jython/Lib/test/test_cmp_jy.py trunk/jython/src/templates/object.derived Modified: trunk/jython/Lib/test/test_cmp_jy.py =================================================================== --- trunk/jython/Lib/test/test_cmp_jy.py 2008-10-30 03:05:31 UTC (rev 5528) +++ trunk/jython/Lib/test/test_cmp_jy.py 2008-10-30 06:06:03 UTC (rev 5529) @@ -31,12 +31,37 @@ assert (-2 < 'a') assert not (-1 == 'a') +class CustomCmp(unittest.TestCase): + def test___cmp___returns(self): + class Foo(object): + def __int__(self): + return 0 + class Bar(object): + def __int__(self): + raise ValueError('doh') + class Baz(object): + def __cmp__(self, other): + return self.cmp(other) + baz = Baz() + baz.cmp = lambda other : Foo() + self.assertEqual(cmp(100, baz), 0) + baz.cmp = lambda other : NotImplemented + self.assertEqual(cmp(100, baz), 1) + baz.cmp = lambda other: Bar() + self.assertRaises(ValueError, cmp, 100, baz) + baz.cmp = lambda other: 1 / 0 + self.assertRaises(ZeroDivisionError, cmp, 100, baz) + del Baz.__cmp__ + # CPython handles numbers differently than other types in + # object.c:default_3way_compare, and gets 1 here. we don't care + self.assert_(cmp(100, baz) in (-1, 1)) def test_main(): test_support.run_unittest( UnicodeDerivedCmp, LongDerivedCmp, IntStrCmp, + CustomCmp ) if __name__ == '__main__': Modified: trunk/jython/src/templates/object.derived =================================================================== --- trunk/jython/src/templates/object.derived 2008-10-30 03:05:31 UTC (rev 5528) +++ trunk/jython/src/templates/object.derived 2008-10-30 06:06:03 UTC (rev 5529) @@ -110,11 +110,11 @@ return super.__cmp__(other); } PyObject res = impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v < 0 ? -1 : v > 0 ? 1 : 0; + if (res == Py.NotImplemented) { + return -2; } - throw Py.TypeError("__cmp__ should return a int"); + int c = res.asInt(); + return c < 0 ? -1 : c > 0 ? 1 : 0; } public boolean __nonzero__() { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-10-30 03:05:36
|
Revision: 5528 http://jython.svn.sourceforge.net/jython/?rev=5528&view=rev Author: pjenvey Date: 2008-10-30 03:05:31 +0000 (Thu, 30 Oct 2008) Log Message: ----------- o make asInt try conversion via custom __int__ methods on non int/longs, as these are valid asInts in most places (like ArgParser.getInt, xrange) o make range use asInt with non long args, which is trickier than it sounds, so rewrote it to work exactly as CPython's -- bonus of being faster for int args Modified Paths: -------------- trunk/jython/Lib/test/test_builtin_jy.py trunk/jython/src/org/python/core/PyObject.java trunk/jython/src/org/python/core/PyString.java trunk/jython/src/org/python/core/PyXRange.java trunk/jython/src/org/python/core/__builtin__.java Modified: trunk/jython/Lib/test/test_builtin_jy.py =================================================================== --- trunk/jython/Lib/test/test_builtin_jy.py 2008-10-30 02:49:44 UTC (rev 5527) +++ trunk/jython/Lib/test/test_builtin_jy.py 2008-10-30 03:05:31 UTC (rev 5528) @@ -102,6 +102,19 @@ return None self.assert_(not callable(Baz())) +class RangeTest(unittest.TestCase): + + class Foo(object): + def __int__(self): + return 3 + foo = Foo() + + def test_range_non_int(self): + self.assertEqual(range(self.foo), [0, 1, 2]) + + def test_xrange_non_int(self): + self.assertEqual(list(xrange(self.foo)), [0, 1, 2]) + def test_main(): test.test_support.run_unittest(BuiltinTest, LoopTest, @@ -110,7 +123,8 @@ ChrTest, ReturnTest, ReprTest, - CallableTest) + CallableTest, + RangeTest) if __name__ == "__main__": test_main() Modified: trunk/jython/src/org/python/core/PyObject.java =================================================================== --- trunk/jython/src/org/python/core/PyObject.java 2008-10-30 02:49:44 UTC (rev 5527) +++ trunk/jython/src/org/python/core/PyObject.java 2008-10-30 03:05:31 UTC (rev 5528) @@ -3866,7 +3866,20 @@ } public int asInt() { - throw Py.TypeError("an integer is required"); + PyObject intObj; + try { + intObj = __int__(); + } catch (PyException pye) { + if (Py.matchException(pye, Py.AttributeError)) { + throw Py.TypeError("an integer is required"); + } + throw pye; + } + if (!(intObj instanceof PyInteger) && !(intObj instanceof PyLong)) { + // Shouldn't happen except with buggy builtin types + throw Py.TypeError("nb_int should return int object"); + } + return intObj.asInt(); } public long asLong(int index) throws ConversionException { Modified: trunk/jython/src/org/python/core/PyString.java =================================================================== --- trunk/jython/src/org/python/core/PyString.java 2008-10-30 02:49:44 UTC (rev 5527) +++ trunk/jython/src/org/python/core/PyString.java 2008-10-30 03:05:31 UTC (rev 5528) @@ -2400,6 +2400,17 @@ return string; } + @Override + public int asInt() { + // We have to override asInt because we override __int__, but generally don't want + // implicit atoi conversions for the base types. blah + PyType type = getType(); + if (type == PyString.TYPE || type == PyUnicode.TYPE || type.lookup("__int__") == null) { + throw Py.TypeError("an integer is required"); + } + return super.asInt(); + } + public String asName(int index) throws PyObject.ConversionException { return internedString(); } Modified: trunk/jython/src/org/python/core/PyXRange.java =================================================================== --- trunk/jython/src/org/python/core/PyXRange.java 2008-10-30 02:49:44 UTC (rev 5527) +++ trunk/jython/src/org/python/core/PyXRange.java 2008-10-30 03:05:31 UTC (rev 5528) @@ -77,7 +77,7 @@ * @param step int value (> 0) * @return int length of range */ - private int getLenOfRange(int lo, int hi, int step) { + static int getLenOfRange(int lo, int hi, int step) { int n = 0; if (lo < hi) { // the base difference may be > Integer.MAX_VALUE Modified: trunk/jython/src/org/python/core/__builtin__.java =================================================================== --- trunk/jython/src/org/python/core/__builtin__.java 2008-10-30 02:49:44 UTC (rev 5527) +++ trunk/jython/src/org/python/core/__builtin__.java 2008-10-30 03:05:31 UTC (rev 5528) @@ -989,48 +989,36 @@ } public static PyObject range(PyObject start, PyObject stop, PyObject step) { - // Check that step is valid. - int stepCmp = step.__cmp__(Py.Zero); - if (stepCmp == -2) { - throw Py.TypeError("non-integer type for step in range()"); - } else if (stepCmp == 0) { - throw Py.ValueError("zero step for range()"); + int ilow = 0; + int ihigh = 0; + int istep = 1; + int n; + + try { + ilow = start.asInt(); + ihigh = stop.asInt(); + istep = step.asInt(); + } catch (PyException pye) { + return handleRangeLongs(start, stop, step); } - // Calculate the number of values in the range. - PyObject n = stop.__sub__(start); - if (n == null) { - throw Py.TypeError("non-integer type for start or stop in range()"); + if (istep == 0) { + throw Py.ValueError("range() step argument must not be zero"); } - n = n.__add__(step); - if (stepCmp == 1) { // step is positive - n = n.__sub__(Py.One).__div__(step); - } else { // step is negative - n = n.__add__(Py.One).__div__(step); + if (istep > 0) { + n = PyXRange.getLenOfRange(ilow, ihigh, istep); + } else { + n = PyXRange.getLenOfRange(ihigh, ilow, -istep); } - - // Check that the number of values is valid. - if (n.__cmp__(Py.Zero) <= 0) { - return new PyList(); + if (n < 0) { + throw Py.OverflowError("range() result has too many items"); } - Object nAsInteger = n.__tojava__(Integer.TYPE); - if (nAsInteger == Py.NoConversion) { - if (n instanceof PyLong) { - throw Py.OverflowError("Can't use range for more than " + Integer.MAX_VALUE + " items. Try xrange instead."); - } else { - throw Py.TypeError("non-integer type for start or stop in range()"); - } - } - // Fill in the range. - int nAsInt = ((Integer) nAsInteger).intValue(); - PyObject j = start; - PyObject[] objs = new PyObject[nAsInt]; - for (int i = 0; i < nAsInt; i++) { - objs[i] = j; - j = j.__add__(step); + PyObject[] range = new PyObject[n]; + for (int i = 0; i < n; i++, ilow += istep) { + range[i] = Py.newInteger(ilow); } - return new PyList(objs); + return new PyList(range); } public static PyObject range(PyObject n) { @@ -1041,6 +1029,70 @@ return range(start, stop, Py.One); } + /** + * Handle range() when PyLong arguments (that OverFlow ints) are given. + */ + private static PyObject handleRangeLongs(PyObject ilow, PyObject ihigh, PyObject istep) { + if (!(ilow instanceof PyInteger) && !(ilow instanceof PyLong)) { + throw Py.TypeError(String.format("range() integer start argument expected, got %s.", + ilow.getType().fastGetName())); + } + if (!(ihigh instanceof PyInteger) && !(ihigh instanceof PyLong)) { + throw Py.TypeError(String.format("range() integer end argument expected, got %s.", + ihigh.getType().fastGetName())); + } + if (!(istep instanceof PyInteger) && !(istep instanceof PyLong)) { + throw Py.TypeError(String.format("range() integer step argument expected, got %s.", + istep.getType().fastGetName())); + } + + int n; + int cmpResult = istep._cmp(Py.Zero); + if (cmpResult == 0) { + throw Py.ValueError("range() step argument must not be zero"); + } + if (cmpResult > 0) { + n = getLenOfRangeLongs(ilow, ihigh, istep); + } else { + n = getLenOfRangeLongs(ihigh, ilow, istep.__neg__()); + } + if (n < 0) { + throw Py.OverflowError("range() result has too many items"); + } + + PyObject[] range = new PyObject[n]; + for (int i = 0; i < n; i++) { + range[i] = ilow.__long__(); + ilow = ilow.__add__(istep); + } + return new PyList(range); + } + + /** + * Return number of items in range (lo, hi, step), when arguments are PyInteger or + * PyLong objects. step > 0 required. Return a value < 0 if & only if the true value + * is too large to fit in an int, or there is an error. + * + * @param lo PyInteger or PyLong value + * @param hi PyInteger or PyLong value + * @param step PyInteger or PyLong value (> 0) + * @return int length of range + */ + private static int getLenOfRangeLongs(PyObject lo, PyObject hi, PyObject step) { + // if (lo >= hi), return length of 0 + if (lo._cmp(hi) >= 0) { + return 0; + } + try { + // See PyXRange.getLenOfRange for the primitive version + PyObject diff = hi.__sub__(lo).__sub__(Py.One); + PyObject n = diff.__floordiv__(step).__add__(Py.One); + return n.asInt(); + } catch (PyException pye) { + return -1; + } + } + private static PyString readline(PyObject file) { if (file instanceof PyFile) { return ((PyFile) file).readline(); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-10-30 02:49:50
|
Revision: 5527 http://jython.svn.sourceforge.net/jython/?rev=5527&view=rev Author: pjenvey Date: 2008-10-30 02:49:44 +0000 (Thu, 30 Oct 2008) Log Message: ----------- small cleanup Modified Paths: -------------- trunk/jython/src/org/python/core/PyFile.java trunk/jython/src/org/python/modules/zipimport/zipimporter.java Modified: trunk/jython/src/org/python/core/PyFile.java =================================================================== --- trunk/jython/src/org/python/core/PyFile.java 2008-10-30 02:48:30 UTC (rev 5526) +++ trunk/jython/src/org/python/core/PyFile.java 2008-10-30 02:49:44 UTC (rev 5527) @@ -19,7 +19,6 @@ import org.python.core.io.TextIOBase; import org.python.core.io.TextIOWrapper; import org.python.core.io.UniversalIOWrapper; -import org.python.core.util.FileUtil; import org.python.expose.ExposedDelete; import org.python.expose.ExposedGet; import org.python.expose.ExposedMethod; @@ -529,7 +528,7 @@ throw Py.TypeError("can't delete numeric/char attribute"); } - public Object __tojava__(Class cls) { + public Object __tojava__(Class<?> cls) { Object o = file.__tojava__(cls); if (o == null) { o = super.__tojava__(cls); Modified: trunk/jython/src/org/python/modules/zipimport/zipimporter.java =================================================================== --- trunk/jython/src/org/python/modules/zipimport/zipimporter.java 2008-10-30 02:48:30 UTC (rev 5526) +++ trunk/jython/src/org/python/modules/zipimport/zipimporter.java 2008-10-30 02:49:44 UTC (rev 5527) @@ -498,8 +498,9 @@ } PyObject files = new PyDictionary(); - for (Enumeration zipEntries = zipFile.entries(); zipEntries.hasMoreElements();) { - ZipEntry zipEntry = (ZipEntry)zipEntries.nextElement(); + for (Enumeration<? extends ZipEntry> zipEntries = zipFile.entries(); + zipEntries.hasMoreElements();) { + ZipEntry zipEntry = zipEntries.nextElement(); String name = zipEntry.getName().replace('/', File.separatorChar); PyObject __file__ = new PyString(archive + File.separator + name); @@ -664,9 +665,9 @@ */ protected static class SearchOrderEntry { public String suffix; - public EnumSet type; + public EnumSet<EntryType> type; - public SearchOrderEntry(String suffix, EnumSet type) { + public SearchOrderEntry(String suffix, EnumSet<EntryType> type) { this.suffix = suffix; this.type = type; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-10-30 02:48:41
|
Revision: 5526 http://jython.svn.sourceforge.net/jython/?rev=5526&view=rev Author: pjenvey Date: 2008-10-30 02:48:30 +0000 (Thu, 30 Oct 2008) Log Message: ----------- forgot most of the Serializable bits Modified Paths: -------------- trunk/jython/src/org/python/core/util/ConcurrentHashSet.java Modified: trunk/jython/src/org/python/core/util/ConcurrentHashSet.java =================================================================== --- trunk/jython/src/org/python/core/util/ConcurrentHashSet.java 2008-10-29 02:38:55 UTC (rev 5525) +++ trunk/jython/src/org/python/core/util/ConcurrentHashSet.java 2008-10-30 02:48:30 UTC (rev 5526) @@ -1,6 +1,9 @@ /* Copyright (c) Jython Developers */ package org.python.core.util; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.Serializable; import java.util.AbstractSet; import java.util.Collection; import java.util.Iterator; @@ -10,10 +13,10 @@ /** * A Set backed by ConcurrentHashMap. */ -public class ConcurrentHashSet<E> extends AbstractSet<E> { +public class ConcurrentHashSet<E> extends AbstractSet<E> implements Serializable { /** The backing Map. */ - private ConcurrentHashMap<E, Object> map; + private final ConcurrentHashMap<E, Object> map; /** Backing's KeySet. */ private transient Set<E> keySet; @@ -87,4 +90,9 @@ public int hashCode() { return keySet.hashCode(); } + + private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + in.defaultReadObject(); + keySet = map.keySet(); + } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |