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: <am...@us...> - 2010-10-06 22:44:59
|
Revision: 7139 http://jython.svn.sourceforge.net/jython/?rev=7139&view=rev Author: amak Date: 2010-10-06 22:44:52 +0000 (Wed, 06 Oct 2010) Log Message: ----------- Correcting a small error; socket module has always supported ephemeral ports. Modified Paths: -------------- trunk/jython/NEWS Modified: trunk/jython/NEWS =================================================================== --- trunk/jython/NEWS 2010-10-06 22:08:18 UTC (rev 7138) +++ trunk/jython/NEWS 2010-10-06 22:44:52 UTC (rev 7139) @@ -7,7 +7,7 @@ - [ 1568 ] sys.stdout.encoding returns wrong value in Windows with Jython 2.5.1 (fixed on Java 6 only) - [ 1647 ] zxJDBC does not handle NVARCHAR - socket module now supports ephemeral server ports (by using port 0); see discussion for #1660 + SocketServer module now supports ephemeral server ports (by using port 0); see discussion for #1660 Jython 2.5.2b2 Bugs Fixed This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2010-10-06 22:08:25
|
Revision: 7138 http://jython.svn.sourceforge.net/jython/?rev=7138&view=rev Author: zyasoft Date: 2010-10-06 22:08:18 +0000 (Wed, 06 Oct 2010) Log Message: ----------- Updated NEWS Modified Paths: -------------- trunk/jython/NEWS Modified: trunk/jython/NEWS =================================================================== --- trunk/jython/NEWS 2010-10-06 22:00:23 UTC (rev 7137) +++ trunk/jython/NEWS 2010-10-06 22:08:18 UTC (rev 7138) @@ -2,10 +2,13 @@ Jython 2.5.2rc1 Bugs Fixed + - [ 1660 ] threading module memory leak - [ 1452 ] pydoc help() function fails because sys.executable is None in stand-alone Jython - [ 1568 ] sys.stdout.encoding returns wrong value in Windows with Jython 2.5.1 (fixed on Java 6 only) - [ 1647 ] zxJDBC does not handle NVARCHAR + socket module now supports ephemeral server ports (by using port 0); see discussion for #1660 + Jython 2.5.2b2 Bugs Fixed - [ 1327 ] Classloaders cannot GC, which exhausts permgen (partial bug fix) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2010-10-06 22:00:30
|
Revision: 7137 http://jython.svn.sourceforge.net/jython/?rev=7137&view=rev Author: zyasoft Date: 2010-10-06 22:00:23 +0000 (Wed, 06 Oct 2010) Log Message: ----------- Added socket server test (navie multithreaded server, thread pool using client) to verify that the memory leak for #1662 remains fixed. Modified Paths: -------------- trunk/jython/Lib/test/test_threading_jy.py Added Paths: ----------- trunk/jython/Lib/test/socketserver_test.py Added: trunk/jython/Lib/test/socketserver_test.py =================================================================== --- trunk/jython/Lib/test/socketserver_test.py (rev 0) +++ trunk/jython/Lib/test/socketserver_test.py 2010-10-06 22:00:23 UTC (rev 7137) @@ -0,0 +1,59 @@ +# Used by test_threading_jy.py to verify no memory leaks in using a +# relatively large number of threads. This is of course an absolutely +# silly way to write real code on the JVM :), use a thread pool. So +# just for testing. +# +# However, the client here does use a thread pool. +# +# TODO monitor heap consumption too from appropriate MBean. Then we +# could presumably be adaptive or something clever like that. +# +# Test for http://bugs.jython.org/issue1660 + +import socket +import threading +import SocketServer +import time +from java.lang import Runtime +from java.util.concurrent import Executors, ExecutorCompletionService + +class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler): + + def handle(self): + data = self.request.recv(1024) + cur_thread = threading.currentThread() + response = "%s: %s" % (cur_thread.getName(), data) + self.request.send(response) + +class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): + "mix together" + +def client(ip, port, message): + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.connect((ip, port)) + sock.send(message) + response = sock.recv(1024) + # print threading.currentThread().getName(), response + sock.close() + +if __name__ == "__main__": + # ephemeral ports should work on every Java system now + HOST, PORT = "localhost", 0 + + server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler) + ip, port = server.server_address + + # Start a daemon thread with the server -- that thread will then start one + # more thread for each request + server_thread = threading.Thread(target=server.serve_forever) + server_thread.setDaemon(True) + server_thread.start() + + # create a client pool to run all client requests + pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 1) + ecs = ExecutorCompletionService(pool) + for i in xrange(4000): # empirically, this will exhaust heap when run with 16m heap + ecs.submit(lambda: client(ip, port, "Hello World %i" % i)) + ecs.take() # wait until we have a thread available in the pool + pool.shutdown() + Modified: trunk/jython/Lib/test/test_threading_jy.py =================================================================== --- trunk/jython/Lib/test/test_threading_jy.py 2010-10-05 22:26:34 UTC (rev 7136) +++ trunk/jython/Lib/test/test_threading_jy.py 2010-10-06 22:00:23 UTC (rev 7137) @@ -4,11 +4,15 @@ """ from __future__ import with_statement +import random +import subprocess +import sys +import threading +import time import unittest + +from subprocess import PIPE, Popen from test import test_support -import threading -import time -import random from threading import Condition, Lock, Thread from java.lang import Thread as JThread, InterruptedException @@ -84,8 +88,24 @@ self.assertEqual(joined_threads, num_threads) +class MemoryLeakTestCase(unittest.TestCase): + def test_socket_server(self): + # run socketserver with a small amount of memory; verify it exits cleanly + + + rc = subprocess.call([sys.executable, + "-J-Xmx32m", + test_support.findfile("socketserver_test.py")]) + # stdout=PIPE) + self.assertEquals(rc, 0) + + def test_main(): - test_support.run_unittest(JavaIntegrationTestCase, ThreadingTestCase, TwistedTestCase) + test_support.run_unittest( + JavaIntegrationTestCase, + MemoryLeakTestCase, + ThreadingTestCase, + TwistedTestCase) if __name__ == "__main__": This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2010-10-05 22:26:40
|
Revision: 7136 http://jython.svn.sourceforge.net/jython/?rev=7136&view=rev Author: zyasoft Date: 2010-10-05 22:26:34 +0000 (Tue, 05 Oct 2010) Log Message: ----------- Upgraded Guava Google collections to 0.7. Modified Paths: -------------- trunk/jython/build.xml Added Paths: ----------- trunk/jython/extlibs/guava-r07.jar Removed Paths: ------------- trunk/jython/extlibs/guava-r05.jar Modified: trunk/jython/build.xml =================================================================== --- trunk/jython/build.xml 2010-10-05 20:19:43 UTC (rev 7135) +++ trunk/jython/build.xml 2010-10-05 22:26:34 UTC (rev 7136) @@ -189,7 +189,7 @@ <pathelement path="${extlibs.dir}/asm-3.1.jar" /> <pathelement path="${extlibs.dir}/asm-commons-3.1.jar" /> <pathelement path="${extlibs.dir}/constantine.jar" /> - <pathelement path="${extlibs.dir}/guava-r05.jar" /> + <pathelement path="${extlibs.dir}/guava-r07.jar" /> <pathelement path="${extlibs.dir}/jaffl.jar"/> <pathelement path="${extlibs.dir}/jffi-Darwin.jar"/> <pathelement path="${extlibs.dir}/jffi-i386-FreeBSD.jar"/> @@ -588,7 +588,7 @@ <zipfileset src="extlibs/asm-commons-3.1.jar"/> <zipfileset src="extlibs/asm-util-3.1.jar"/> <rule pattern="org.objectweb.asm.**" result="org.python.objectweb.asm.@1"/> - <zipfileset src="extlibs/guava-r05.jar"/> + <zipfileset src="extlibs/guava-r07.jar"/> <rule pattern="com.google.**" result="org.python.google.@1"/> <zipfileset src="extlibs/jaffl.jar"/> <zipfileset src="extlibs/jffi-Darwin.jar"/> Deleted: trunk/jython/extlibs/guava-r05.jar =================================================================== (Binary files differ) Added: trunk/jython/extlibs/guava-r07.jar =================================================================== (Binary files differ) Property changes on: trunk/jython/extlibs/guava-r07.jar ___________________________________________________________________ Added: svn:mime-type + application/octet-stream This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2010-10-05 20:19:49
|
Revision: 7135 http://jython.svn.sourceforge.net/jython/?rev=7135&view=rev Author: zyasoft Date: 2010-10-05 20:19:43 +0000 (Tue, 05 Oct 2010) Log Message: ----------- Canonical map _jthread_to_pythread needs to have both weak keys AND weak values to avoid memory leaks. Fixes #1660, threading module memory leak Modified Paths: -------------- trunk/jython/src/org/python/modules/_threading/_threading.java Modified: trunk/jython/src/org/python/modules/_threading/_threading.java =================================================================== --- trunk/jython/src/org/python/modules/_threading/_threading.java 2010-10-04 19:52:55 UTC (rev 7134) +++ trunk/jython/src/org/python/modules/_threading/_threading.java 2010-10-05 20:19:43 UTC (rev 7135) @@ -20,7 +20,7 @@ // internals to support threading.py, test_threading.py public static Map<Long, PyObject> _threads = new MapMaker().weakValues().makeMap(); - public static Map<Thread, PyObject> _jthread_to_pythread = new MapMaker().weakKeys().makeMap(); + public static Map<Thread, PyObject> _jthread_to_pythread = new MapMaker().weakKeys().weakValues().makeMap(); public static Map<Long, PyObject> _active = _threads; public static void _register_thread(Thread jthread, PyObject pythread) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <otm...@us...> - 2010-10-04 19:53:01
|
Revision: 7134 http://jython.svn.sourceforge.net/jython/?rev=7134&view=rev Author: otmarhumbel Date: 2010-10-04 19:52:55 +0000 (Mon, 04 Oct 2010) Log Message: ----------- enable help() in standalone mode fixes issue #1452 thanks to David Handy for the patch! Modified Paths: -------------- trunk/jython/Lib/pydoc.py trunk/jython/NEWS Modified: trunk/jython/Lib/pydoc.py =================================================================== --- trunk/jython/Lib/pydoc.py 2010-10-04 17:28:05 UTC (rev 7133) +++ trunk/jython/Lib/pydoc.py 2010-10-04 19:52:55 UTC (rev 7134) @@ -1623,7 +1623,11 @@ self.input = input self.output = output self.docdir = None - execdir = os.path.dirname(sys.executable) + if sys.executable is None: + execdir = os.getcwd() + else: + execdir = os.path.dirname(sys.executable) + homedir = os.environ.get('PYTHONHOME') for dir in [os.environ.get('PYTHONDOCS'), homedir and os.path.join(homedir, 'doc'), Modified: trunk/jython/NEWS =================================================================== --- trunk/jython/NEWS 2010-10-04 17:28:05 UTC (rev 7133) +++ trunk/jython/NEWS 2010-10-04 19:52:55 UTC (rev 7134) @@ -2,6 +2,7 @@ Jython 2.5.2rc1 Bugs Fixed + - [ 1452 ] pydoc help() function fails because sys.executable is None in stand-alone Jython - [ 1568 ] sys.stdout.encoding returns wrong value in Windows with Jython 2.5.1 (fixed on Java 6 only) - [ 1647 ] zxJDBC does not handle NVARCHAR This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2010-10-04 17:28:11
|
Revision: 7133 http://jython.svn.sourceforge.net/jython/?rev=7133&view=rev Author: zyasoft Date: 2010-10-04 17:28:05 +0000 (Mon, 04 Oct 2010) Log Message: ----------- Handle boundary case where the last literal character in the strptime format specifier did not get an end quote. Fixes #1662. Modified Paths: -------------- trunk/jython/src/org/python/modules/time/Time.java Modified: trunk/jython/src/org/python/modules/time/Time.java =================================================================== --- trunk/jython/src/org/python/modules/time/Time.java 2010-10-03 21:14:29 UTC (rev 7132) +++ trunk/jython/src/org/python/modules/time/Time.java 2010-10-04 17:28:05 UTC (rev 7133) @@ -790,6 +790,9 @@ builder.append(translated != null ? translated : charAt); directive = false; } + if (inQuote) { + builder.append("'"); + } return builder.toString(); } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <otm...@us...> - 2010-10-03 21:14:35
|
Revision: 7132 http://jython.svn.sourceforge.net/jython/?rev=7132&view=rev Author: otmarhumbel Date: 2010-10-03 21:14:29 +0000 (Sun, 03 Oct 2010) Log Message: ----------- handle the new JDBC 4.0 java.sql.Types as well (this hopefully really fixes issue 1647) Modified Paths: -------------- trunk/jython/src/com/ziclix/python/sql/DataHandler.java trunk/jython/tests/java/com/ziclix/python/sql/DataHandlerTest.java Modified: trunk/jython/src/com/ziclix/python/sql/DataHandler.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/DataHandler.java 2010-10-03 19:47:13 UTC (rev 7131) +++ trunk/jython/src/com/ziclix/python/sql/DataHandler.java 2010-10-03 21:14:29 UTC (rev 7132) @@ -236,11 +236,14 @@ case Types.CHAR: case Types.VARCHAR: + case Java6Types.NCHAR: + case Java6Types.NVARCHAR: String string = set.getString(col); obj = string == null ? Py.None : Py.newUnicode(string); break; case Types.LONGVARCHAR: + case Java6Types.LONGNVARCHAR: Reader reader = set.getCharacterStream(col); obj = reader == null ? Py.None : Py.newUnicode(read(reader)); break; @@ -310,6 +313,8 @@ break; case Types.CLOB: + case Java6Types.NCLOB: + case Java6Types.SQLXML: Clob clob = set.getClob(col); obj = clob == null ? Py.None : Py.java2py(read(clob.getCharacterStream())); break; @@ -323,6 +328,8 @@ throw createUnsupportedTypeSQLException("DISTINCT", col); case Types.REF: throw createUnsupportedTypeSQLException("REF", col); + case Java6Types.ROWID: + throw createUnsupportedTypeSQLException("STRUCT", col); case Types.STRUCT: throw createUnsupportedTypeSQLException("STRUCT", col); @@ -560,5 +567,60 @@ public String toString() { return getClass().getName(); } + + /** + * This interface can be removed as soon as we target java 6 + */ + private static interface Java6Types{ + /** + * The constant in the Java programming language, sometimes referred to + * as a type code, that identifies the generic SQL type <code>ROWID</code> + * + * @since 1.6 + * + */ + public final static int ROWID = -8; + + /** + * The constant in the Java programming language, sometimes referred to + * as a type code, that identifies the generic SQL type <code>NCHAR</code> + * + * @since 1.6 + */ + public static final int NCHAR = -15; + + /** + * The constant in the Java programming language, sometimes referred to + * as a type code, that identifies the generic SQL type <code>NVARCHAR</code>. + * + * @since 1.6 + */ + public static final int NVARCHAR = -9; + + /** + * The constant in the Java programming language, sometimes referred to + * as a type code, that identifies the generic SQL type <code>LONGNVARCHAR</code>. + * + * @since 1.6 + */ + public static final int LONGNVARCHAR = -16; + + /** + * The constant in the Java programming language, sometimes referred to + * as a type code, that identifies the generic SQL type <code>NCLOB</code>. + * + * @since 1.6 + */ + public static final int NCLOB = 2011; + + /** + * The constant in the Java programming language, sometimes referred to + * as a type code, that identifies the generic SQL type <code>XML</code>. + * + * @since 1.6 + */ + public static final int SQLXML = 2009; + } + } Modified: trunk/jython/tests/java/com/ziclix/python/sql/DataHandlerTest.java =================================================================== --- trunk/jython/tests/java/com/ziclix/python/sql/DataHandlerTest.java 2010-10-03 19:47:13 UTC (rev 7131) +++ trunk/jython/tests/java/com/ziclix/python/sql/DataHandlerTest.java 2010-10-03 21:14:29 UTC (rev 7132) @@ -39,6 +39,7 @@ "DATALINK", "DISTINCT", "REF", + "ROWID", // java 6 "STRUCT"); for (Field field : Types.class.getDeclaredFields()) { String typeName = field.getName(); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <am...@us...> - 2010-10-03 19:47:19
|
Revision: 7131 http://jython.svn.sourceforge.net/jython/?rev=7131&view=rev Author: amak Date: 2010-10-03 19:47:13 +0000 (Sun, 03 Oct 2010) Log Message: ----------- Fix and tests for a jython-specific bug relating to deferred creation of sockets. Modified Paths: -------------- trunk/jython/Lib/SocketServer.py Added Paths: ----------- trunk/jython/Lib/test/test_socketserver_jython.py Modified: trunk/jython/Lib/SocketServer.py =================================================================== --- trunk/jython/Lib/SocketServer.py 2010-10-03 17:54:49 UTC (rev 7130) +++ trunk/jython/Lib/SocketServer.py 2010-10-03 19:47:13 UTC (rev 7131) @@ -348,6 +348,9 @@ """ self.socket.listen(self.request_queue_size) + # Adding a second call to getsockname() because of this issue + # http://wiki.python.org/jython/NewSocketModule#Deferredsocketcreationonjython + self.server_address = self.socket.getsockname() def server_close(self): """Called to clean-up the server. @@ -517,12 +520,11 @@ self.request = request self.client_address = client_address self.server = server + self.setup() try: - self.setup() self.handle() + finally: self.finish() - finally: - sys.exc_traceback = None # Help garbage collection def setup(self): pass Added: trunk/jython/Lib/test/test_socketserver_jython.py =================================================================== --- trunk/jython/Lib/test/test_socketserver_jython.py (rev 0) +++ trunk/jython/Lib/test/test_socketserver_jython.py 2010-10-03 19:47:13 UTC (rev 7131) @@ -0,0 +1,17 @@ +# -*- coding: windows-1252 -*- + +import unittest + +import SocketServer + +class TestSocketServer(unittest.TestCase): + + def testEphemeralPort(self): + """ Test that an ephemeral port is set correctly """ + host, port = "localhost", 0 # If we specify 0, system should pick an emphemeral port + server = SocketServer.TCPServer( (host, port), None) # Request handler never instantiated + server_host, server_port = server.server_address + self.failIfEqual(server_port, 0, "System assigned ephemeral port should not be zero") + +if __name__ == "__main__": + unittest.main() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <am...@us...> - 2010-10-03 17:54:56
|
Revision: 7130 http://jython.svn.sourceforge.net/jython/?rev=7130&view=rev Author: amak Date: 2010-10-03 17:54:49 +0000 (Sun, 03 Oct 2010) Log Message: ----------- Copying over SocketServer and test_socketserver.py from CPythonLib in order to make some jython-specific bug fixes. Added Paths: ----------- trunk/jython/Lib/SocketServer.py trunk/jython/Lib/test/test_socketserver.py Added: trunk/jython/Lib/SocketServer.py =================================================================== --- trunk/jython/Lib/SocketServer.py (rev 0) +++ trunk/jython/Lib/SocketServer.py 2010-10-03 17:54:49 UTC (rev 7130) @@ -0,0 +1,588 @@ +"""Generic socket server classes. + +This module tries to capture the various aspects of defining a server: + +For socket-based servers: + +- address family: + - AF_INET{,6}: IP (Internet Protocol) sockets (default) + - AF_UNIX: Unix domain sockets + - others, e.g. AF_DECNET are conceivable (see <socket.h> +- socket type: + - SOCK_STREAM (reliable stream, e.g. TCP) + - SOCK_DGRAM (datagrams, e.g. UDP) + +For request-based servers (including socket-based): + +- client address verification before further looking at the request + (This is actually a hook for any processing that needs to look + at the request before anything else, e.g. logging) +- how to handle multiple requests: + - synchronous (one request is handled at a time) + - forking (each request is handled by a new process) + - threading (each request is handled by a new thread) + +The classes in this module favor the server type that is simplest to +write: a synchronous TCP/IP server. This is bad class design, but +save some typing. (There's also the issue that a deep class hierarchy +slows down method lookups.) + +There are five classes in an inheritance diagram, four of which represent +synchronous servers of four types: + + +------------+ + | BaseServer | + +------------+ + | + v + +-----------+ +------------------+ + | TCPServer |------->| UnixStreamServer | + +-----------+ +------------------+ + | + v + +-----------+ +--------------------+ + | UDPServer |------->| UnixDatagramServer | + +-----------+ +--------------------+ + +Note that UnixDatagramServer derives from UDPServer, not from +UnixStreamServer -- the only difference between an IP and a Unix +stream server is the address family, which is simply repeated in both +unix server classes. + +Forking and threading versions of each type of server can be created +using the ForkingMixIn and ThreadingMixIn mix-in classes. For +instance, a threading UDP server class is created as follows: + + class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass + +The Mix-in class must come first, since it overrides a method defined +in UDPServer! Setting the various member variables also changes +the behavior of the underlying server mechanism. + +To implement a service, you must derive a class from +BaseRequestHandler and redefine its handle() method. You can then run +various versions of the service by combining one of the server classes +with your request handler class. + +The request handler class must be different for datagram or stream +services. This can be hidden by using the request handler +subclasses StreamRequestHandler or DatagramRequestHandler. + +Of course, you still have to use your head! + +For instance, it makes no sense to use a forking server if the service +contains state in memory that can be modified by requests (since the +modifications in the child process would never reach the initial state +kept in the parent process and passed to each child). In this case, +you can use a threading server, but you will probably have to use +locks to avoid two requests that come in nearly simultaneous to apply +conflicting changes to the server state. + +On the other hand, if you are building e.g. an HTTP server, where all +data is stored externally (e.g. in the file system), a synchronous +class will essentially render the service "deaf" while one request is +being handled -- which may be for a very long time if a client is slow +to reqd all the data it has requested. Here a threading or forking +server is appropriate. + +In some cases, it may be appropriate to process part of a request +synchronously, but to finish processing in a forked child depending on +the request data. This can be implemented by using a synchronous +server and doing an explicit fork in the request handler class +handle() method. + +Another approach to handling multiple simultaneous requests in an +environment that supports neither threads nor fork (or where these are +too expensive or inappropriate for the service) is to maintain an +explicit table of partially finished requests and to use select() to +decide which request to work on next (or whether to handle a new +incoming request). This is particularly important for stream services +where each client can potentially be connected for a long time (if +threads or subprocesses cannot be used). + +Future work: +- Standard classes for Sun RPC (which uses either UDP or TCP) +- Standard mix-in classes to implement various authentication + and encryption schemes +- Standard framework for select-based multiplexing + +XXX Open problems: +- What to do with out-of-band data? + +BaseServer: +- split generic "request" functionality out into BaseServer class. + Copyright (C) 2000 Luke Kenneth Casson Leighton <lk...@sa...> + + example: read entries from a SQL database (requires overriding + get_request() to return a table entry from the database). + entry is processed by a RequestHandlerClass. + +""" + +# Author of the BaseServer patch: Luke Kenneth Casson Leighton + +# XXX Warning! +# There is a test suite for this module, but it cannot be run by the +# standard regression test. +# To run it manually, run Lib/test/test_socketserver.py. + +__version__ = "0.4" + + +import socket +import sys +import os + +__all__ = ["TCPServer","UDPServer","ForkingUDPServer","ForkingTCPServer", + "ThreadingUDPServer","ThreadingTCPServer","BaseRequestHandler", + "StreamRequestHandler","DatagramRequestHandler", + "ThreadingMixIn", "ForkingMixIn"] +if hasattr(socket, "AF_UNIX"): + __all__.extend(["UnixStreamServer","UnixDatagramServer", + "ThreadingUnixStreamServer", + "ThreadingUnixDatagramServer"]) + +class BaseServer: + + """Base class for server classes. + + Methods for the caller: + + - __init__(server_address, RequestHandlerClass) + - serve_forever() + - handle_request() # if you do not use serve_forever() + - fileno() -> int # for select() + + Methods that may be overridden: + + - server_bind() + - server_activate() + - get_request() -> request, client_address + - verify_request(request, client_address) + - server_close() + - process_request(request, client_address) + - close_request(request) + - handle_error() + + Methods for derived classes: + + - finish_request(request, client_address) + + Class variables that may be overridden by derived classes or + instances: + + - address_family + - socket_type + - allow_reuse_address + + Instance variables: + + - RequestHandlerClass + - socket + + """ + + def __init__(self, server_address, RequestHandlerClass): + """Constructor. May be extended, do not override.""" + self.server_address = server_address + self.RequestHandlerClass = RequestHandlerClass + + def server_activate(self): + """Called by constructor to activate the server. + + May be overridden. + + """ + pass + + def serve_forever(self): + """Handle one request at a time until doomsday.""" + while 1: + self.handle_request() + + # The distinction between handling, getting, processing and + # finishing a request is fairly arbitrary. Remember: + # + # - handle_request() is the top-level call. It calls + # get_request(), verify_request() and process_request() + # - get_request() is different for stream or datagram sockets + # - process_request() is the place that may fork a new process + # or create a new thread to finish the request + # - finish_request() instantiates the request handler class; + # this constructor will handle the request all by itself + + def handle_request(self): + """Handle one request, possibly blocking.""" + try: + request, client_address = self.get_request() + except socket.error: + return + if self.verify_request(request, client_address): + try: + self.process_request(request, client_address) + except: + self.handle_error(request, client_address) + self.close_request(request) + + def verify_request(self, request, client_address): + """Verify the request. May be overridden. + + Return True if we should proceed with this request. + + """ + return True + + def process_request(self, request, client_address): + """Call finish_request. + + Overridden by ForkingMixIn and ThreadingMixIn. + + """ + self.finish_request(request, client_address) + self.close_request(request) + + def server_close(self): + """Called to clean-up the server. + + May be overridden. + + """ + pass + + def finish_request(self, request, client_address): + """Finish one request by instantiating RequestHandlerClass.""" + self.RequestHandlerClass(request, client_address, self) + + def close_request(self, request): + """Called to clean up an individual request.""" + pass + + def handle_error(self, request, client_address): + """Handle an error gracefully. May be overridden. + + The default is to print a traceback and continue. + + """ + print '-'*40 + print 'Exception happened during processing of request from', + print client_address + import traceback + traceback.print_exc() # XXX But this goes to stderr! + print '-'*40 + + +class TCPServer(BaseServer): + + """Base class for various socket-based server classes. + + Defaults to synchronous IP stream (i.e., TCP). + + Methods for the caller: + + - __init__(server_address, RequestHandlerClass) + - serve_forever() + - handle_request() # if you don't use serve_forever() + - fileno() -> int # for select() + + Methods that may be overridden: + + - server_bind() + - server_activate() + - get_request() -> request, client_address + - verify_request(request, client_address) + - process_request(request, client_address) + - close_request(request) + - handle_error() + + Methods for derived classes: + + - finish_request(request, client_address) + + Class variables that may be overridden by derived classes or + instances: + + - address_family + - socket_type + - request_queue_size (only for stream sockets) + - allow_reuse_address + + Instance variables: + + - server_address + - RequestHandlerClass + - socket + + """ + + address_family = socket.AF_INET + + socket_type = socket.SOCK_STREAM + + request_queue_size = 5 + + allow_reuse_address = False + + def __init__(self, server_address, RequestHandlerClass): + """Constructor. May be extended, do not override.""" + BaseServer.__init__(self, server_address, RequestHandlerClass) + self.socket = socket.socket(self.address_family, + self.socket_type) + self.server_bind() + self.server_activate() + + def server_bind(self): + """Called by constructor to bind the socket. + + May be overridden. + + """ + if self.allow_reuse_address: + self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + self.socket.bind(self.server_address) + self.server_address = self.socket.getsockname() + + def server_activate(self): + """Called by constructor to activate the server. + + May be overridden. + + """ + self.socket.listen(self.request_queue_size) + + def server_close(self): + """Called to clean-up the server. + + May be overridden. + + """ + self.socket.close() + + def fileno(self): + """Return socket file number. + + Interface required by select(). + + """ + return self.socket.fileno() + + def get_request(self): + """Get the request and client address from the socket. + + May be overridden. + + """ + return self.socket.accept() + + def close_request(self, request): + """Called to clean up an individual request.""" + request.close() + + +class UDPServer(TCPServer): + + """UDP server class.""" + + allow_reuse_address = False + + socket_type = socket.SOCK_DGRAM + + max_packet_size = 8192 + + def get_request(self): + data, client_addr = self.socket.recvfrom(self.max_packet_size) + return (data, self.socket), client_addr + + def server_activate(self): + # No need to call listen() for UDP. + pass + + def close_request(self, request): + # No need to close anything. + pass + +class ForkingMixIn: + + """Mix-in class to handle each request in a new process.""" + + active_children = None + max_children = 40 + + def collect_children(self): + """Internal routine to wait for died children.""" + while self.active_children: + if len(self.active_children) < self.max_children: + options = os.WNOHANG + else: + # If the maximum number of children are already + # running, block while waiting for a child to exit + options = 0 + try: + pid, status = os.waitpid(0, options) + except os.error: + pid = None + if not pid: break + self.active_children.remove(pid) + + def process_request(self, request, client_address): + """Fork a new subprocess to process the request.""" + self.collect_children() + pid = os.fork() + if pid: + # Parent process + if self.active_children is None: + self.active_children = [] + self.active_children.append(pid) + self.close_request(request) + return + else: + # Child process. + # This must never return, hence os._exit()! + try: + self.finish_request(request, client_address) + os._exit(0) + except: + try: + self.handle_error(request, client_address) + finally: + os._exit(1) + + +class ThreadingMixIn: + """Mix-in class to handle each request in a new thread.""" + + # Decides how threads will act upon termination of the + # main process + daemon_threads = False + + def process_request_thread(self, request, client_address): + """Same as in BaseServer but as a thread. + + In addition, exception handling is done here. + + """ + try: + self.finish_request(request, client_address) + self.close_request(request) + except: + self.handle_error(request, client_address) + self.close_request(request) + + def process_request(self, request, client_address): + """Start a new thread to process the request.""" + import threading + t = threading.Thread(target = self.process_request_thread, + args = (request, client_address)) + if self.daemon_threads: + t.setDaemon (1) + t.start() + + +class ForkingUDPServer(ForkingMixIn, UDPServer): pass +class ForkingTCPServer(ForkingMixIn, TCPServer): pass + +class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass +class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass + +if hasattr(socket, 'AF_UNIX'): + + class UnixStreamServer(TCPServer): + address_family = socket.AF_UNIX + + class UnixDatagramServer(UDPServer): + address_family = socket.AF_UNIX + + class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): pass + + class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): pass + +class BaseRequestHandler: + + """Base class for request handler classes. + + This class is instantiated for each request to be handled. The + constructor sets the instance variables request, client_address + and server, and then calls the handle() method. To implement a + specific service, all you need to do is to derive a class which + defines a handle() method. + + The handle() method can find the request as self.request, the + client address as self.client_address, and the server (in case it + needs access to per-server information) as self.server. Since a + separate instance is created for each request, the handle() method + can define arbitrary other instance variariables. + + """ + + def __init__(self, request, client_address, server): + self.request = request + self.client_address = client_address + self.server = server + try: + self.setup() + self.handle() + self.finish() + finally: + sys.exc_traceback = None # Help garbage collection + + def setup(self): + pass + + def handle(self): + pass + + def finish(self): + pass + + +# The following two classes make it possible to use the same service +# class for stream or datagram servers. +# Each class sets up these instance variables: +# - rfile: a file object from which receives the request is read +# - wfile: a file object to which the reply is written +# When the handle() method returns, wfile is flushed properly + + +class StreamRequestHandler(BaseRequestHandler): + + """Define self.rfile and self.wfile for stream sockets.""" + + # Default buffer sizes for rfile, wfile. + # We default rfile to buffered because otherwise it could be + # really slow for large data (a getc() call per byte); we make + # wfile unbuffered because (a) often after a write() we want to + # read and we need to flush the line; (b) big writes to unbuffered + # files are typically optimized by stdio even when big reads + # aren't. + rbufsize = -1 + wbufsize = 0 + + def setup(self): + self.connection = self.request + self.rfile = self.connection.makefile('rb', self.rbufsize) + self.wfile = self.connection.makefile('wb', self.wbufsize) + + def finish(self): + if not self.wfile.closed: + self.wfile.flush() + self.wfile.close() + self.rfile.close() + + +class DatagramRequestHandler(BaseRequestHandler): + + # XXX Regrettably, I cannot get this working on Linux; + # s.recvfrom() doesn't return a meaningful client address. + + """Define self.rfile and self.wfile for datagram sockets.""" + + def setup(self): + try: + from cStringIO import StringIO + except ImportError: + from StringIO import StringIO + self.packet, self.socket = self.request + self.rfile = StringIO(self.packet) + self.wfile = StringIO() + + def finish(self): + self.socket.sendto(self.wfile.getvalue(), self.client_address) Added: trunk/jython/Lib/test/test_socketserver.py =================================================================== --- trunk/jython/Lib/test/test_socketserver.py (rev 0) +++ trunk/jython/Lib/test/test_socketserver.py 2010-10-03 17:54:49 UTC (rev 7130) @@ -0,0 +1,218 @@ +# Test suite for SocketServer.py + +from test import test_support +from test.test_support import (verbose, verify, TESTFN, TestSkipped, + reap_children) +test_support.requires('network') + +from SocketServer import * +import socket +import errno +import select +import time +import threading +import os + +NREQ = 3 +DELAY = 0.5 + +class MyMixinHandler: + def handle(self): + time.sleep(DELAY) + line = self.rfile.readline() + time.sleep(DELAY) + self.wfile.write(line) + +class MyStreamHandler(MyMixinHandler, StreamRequestHandler): + pass + +class MyDatagramHandler(MyMixinHandler, DatagramRequestHandler): + pass + +class MyMixinServer: + def serve_a_few(self): + for i in range(NREQ): + self.handle_request() + def handle_error(self, request, client_address): + self.close_request(request) + self.server_close() + raise + +teststring = "hello world\n" + +def receive(sock, n, timeout=20): + r, w, x = select.select([sock], [], [], timeout) + if sock in r: + return sock.recv(n) + else: + raise RuntimeError, "timed out on %r" % (sock,) + +def testdgram(proto, addr): + s = socket.socket(proto, socket.SOCK_DGRAM) + s.sendto(teststring, addr) + buf = data = receive(s, 100) + while data and '\n' not in buf: + data = receive(s, 100) + buf += data + verify(buf == teststring) + s.close() + +def teststream(proto, addr): + s = socket.socket(proto, socket.SOCK_STREAM) + s.connect(addr) + s.sendall(teststring) + buf = data = receive(s, 100) + while data and '\n' not in buf: + data = receive(s, 100) + buf += data + verify(buf == teststring) + s.close() + +class ServerThread(threading.Thread): + def __init__(self, addr, svrcls, hdlrcls): + threading.Thread.__init__(self) + self.__addr = addr + self.__svrcls = svrcls + self.__hdlrcls = hdlrcls + def run(self): + class svrcls(MyMixinServer, self.__svrcls): + pass + if verbose: print "thread: creating server" + svr = svrcls(self.__addr, self.__hdlrcls) + # pull the address out of the server in case it changed + # this can happen if another process is using the port + addr = svr.server_address + if addr: + self.__addr = addr + if self.__addr != svr.socket.getsockname(): + raise RuntimeError('server_address was %s, expected %s' % + (self.__addr, svr.socket.getsockname())) + if verbose: print "thread: serving three times" + svr.serve_a_few() + if verbose: print "thread: done" + +seed = 0 +def pickport(): + global seed + seed += 1 + return 10000 + (os.getpid() % 1000)*10 + seed + +host = "localhost" +testfiles = [] +def pickaddr(proto): + if proto == socket.AF_INET: + return (host, pickport()) + else: + fn = TESTFN + str(pickport()) + if os.name == 'os2': + # AF_UNIX socket names on OS/2 require a specific prefix + # which can't include a drive letter and must also use + # backslashes as directory separators + if fn[1] == ':': + fn = fn[2:] + if fn[0] in (os.sep, os.altsep): + fn = fn[1:] + fn = os.path.join('\socket', fn) + if os.sep == '/': + fn = fn.replace(os.sep, os.altsep) + else: + fn = fn.replace(os.altsep, os.sep) + testfiles.append(fn) + return fn + +def cleanup(): + for fn in testfiles: + try: + os.remove(fn) + except os.error: + pass + testfiles[:] = [] + +def testloop(proto, servers, hdlrcls, testfunc): + for svrcls in servers: + addr = pickaddr(proto) + if verbose: + print "ADDR =", addr + print "CLASS =", svrcls + t = ServerThread(addr, svrcls, hdlrcls) + if verbose: print "server created" + t.start() + if verbose: print "server running" + for i in range(NREQ): + time.sleep(DELAY) + if verbose: print "test client", i + testfunc(proto, addr) + if verbose: print "waiting for server" + t.join() + if verbose: print "done" + +class ForgivingTCPServer(TCPServer): + # prevent errors if another process is using the port we want + def server_bind(self): + host, default_port = self.server_address + # this code shamelessly stolen from test.test_support + # the ports were changed to protect the innocent + import sys + for port in [default_port, 3434, 8798, 23833]: + try: + self.server_address = host, port + TCPServer.server_bind(self) + break + except socket.error, (err, msg): + if err != errno.EADDRINUSE: + raise + print >>sys.__stderr__, \ + ' WARNING: failed to listen on port %d, trying another' % port + +tcpservers = [ForgivingTCPServer, ThreadingTCPServer] +if hasattr(os, 'fork') and os.name not in ('os2',): + tcpservers.append(ForkingTCPServer) +udpservers = [UDPServer, ThreadingUDPServer] +if hasattr(os, 'fork') and os.name not in ('os2',): + udpservers.append(ForkingUDPServer) + +if not hasattr(socket, 'AF_UNIX'): + streamservers = [] + dgramservers = [] +else: + class ForkingUnixStreamServer(ForkingMixIn, UnixStreamServer): pass + streamservers = [UnixStreamServer, ThreadingUnixStreamServer] + if hasattr(os, 'fork') and os.name not in ('os2',): + streamservers.append(ForkingUnixStreamServer) + class ForkingUnixDatagramServer(ForkingMixIn, UnixDatagramServer): pass + dgramservers = [UnixDatagramServer, ThreadingUnixDatagramServer] + if hasattr(os, 'fork') and os.name not in ('os2',): + dgramservers.append(ForkingUnixDatagramServer) + +def sloppy_cleanup(): + # See http://python.org/sf/1540386 + # We need to reap children here otherwise a child from one server + # can be left running for the next server and cause a test failure. + time.sleep(DELAY) + reap_children() + +def testall(): + testloop(socket.AF_INET, tcpservers, MyStreamHandler, teststream) + sloppy_cleanup() + testloop(socket.AF_INET, udpservers, MyDatagramHandler, testdgram) + if hasattr(socket, 'AF_UNIX'): + sloppy_cleanup() + testloop(socket.AF_UNIX, streamservers, MyStreamHandler, teststream) + # Alas, on Linux (at least) recvfrom() doesn't return a meaningful + # client address so this cannot work: + ##testloop(socket.AF_UNIX, dgramservers, MyDatagramHandler, testdgram) + +def test_main(): + import imp + if imp.lock_held(): + # If the import lock is held, the threads will hang. + raise TestSkipped("can't run when import lock is held") + + try: + testall() + finally: + cleanup() + reap_children() + +if __name__ == "__main__": + test_main() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2010-10-01 02:13:49
|
Revision: 7129 http://jython.svn.sourceforge.net/jython/?rev=7129&view=rev Author: zyasoft Date: 2010-10-01 02:13:43 +0000 (Fri, 01 Oct 2010) Log Message: ----------- Attempting to remove a shutdown hook when the JVM is already shutting down should be quietly ignored. Modified Paths: -------------- trunk/jython/src/org/python/core/PySystemState.java Modified: trunk/jython/src/org/python/core/PySystemState.java =================================================================== --- trunk/jython/src/org/python/core/PySystemState.java 2010-09-29 06:29:59 UTC (rev 7128) +++ trunk/jython/src/org/python/core/PySystemState.java 2010-10-01 02:13:43 UTC (rev 7129) @@ -1343,7 +1343,11 @@ // close this thread so we can unload any associated classloaders in cycle with this instance if (shutdownHook != null) { - Runtime.getRuntime().removeShutdownHook(shutdownHook); + try { + Runtime.getRuntime().removeShutdownHook(shutdownHook); + } catch (IllegalStateException e) { + // JVM is already shutting down, so we cannot remove this shutdown hook anyway + } } for (Callable callable : resourceClosers) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <otm...@us...> - 2010-09-29 06:30:05
|
Revision: 7128 http://jython.svn.sourceforge.net/jython/?rev=7128&view=rev Author: otmarhumbel Date: 2010-09-29 06:29:59 +0000 (Wed, 29 Sep 2010) Log Message: ----------- try to get the console encoding from java.io.Console using reflection fixes issue #1568 (given that Jython runs on Java 6) thanks to Regis Desgroppes for the hints Modified Paths: -------------- trunk/jython/NEWS trunk/jython/src/org/python/core/PySystemState.java Modified: trunk/jython/NEWS =================================================================== --- trunk/jython/NEWS 2010-09-28 05:35:21 UTC (rev 7127) +++ trunk/jython/NEWS 2010-09-29 06:29:59 UTC (rev 7128) @@ -2,6 +2,7 @@ Jython 2.5.2rc1 Bugs Fixed + - [ 1568 ] sys.stdout.encoding returns wrong value in Windows with Jython 2.5.1 (fixed on Java 6 only) - [ 1647 ] zxJDBC does not handle NVARCHAR Jython 2.5.2b2 Modified: trunk/jython/src/org/python/core/PySystemState.java =================================================================== --- trunk/jython/src/org/python/core/PySystemState.java 2010-09-28 05:35:21 UTC (rev 7127) +++ trunk/jython/src/org/python/core/PySystemState.java 2010-09-29 06:29:59 UTC (rev 7128) @@ -10,6 +10,7 @@ import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; +import java.lang.reflect.Method; import java.net.URL; import java.net.URLDecoder; import java.nio.charset.Charset; @@ -652,12 +653,7 @@ } } if (!registry.containsKey(PYTHON_CONSOLE_ENCODING)) { - String encoding; - try { - encoding = System.getProperty("file.encoding"); - } catch (SecurityException se) { - encoding = null; - } + String encoding = getPlatformEncoding(); if (encoding != null) { registry.put(PYTHON_CONSOLE_ENCODING, encoding); } @@ -665,7 +661,40 @@ // Set up options from registry Options.setFromRegistry(); } + + /** + * @return the encoding of the underlying platform; can be <code>null</code> + */ + private static String getPlatformEncoding() { + // first try to grab the Console encoding + String encoding = getConsoleEncoding(); + if (encoding == null) { + try { + encoding = System.getProperty("file.encoding"); + } catch (SecurityException se) { + // ignore, can't do anything about it + } + } + return encoding; + } + /** + * @return the console encoding; can be <code>null</code> + */ + private static String getConsoleEncoding() { + String encoding = null; + try { + // the Console class is only present in java 6 - have to use reflection + Class<?> consoleClass = Class.forName("java.io.Console"); + Method encodingMethod = consoleClass.getDeclaredMethod("encoding"); + encodingMethod.setAccessible(true); // private static method + encoding = (String)encodingMethod.invoke(consoleClass); + } catch (Exception e) { + // ignore any exception + } + return encoding; + } + private static void addRegistryFile(File file) { if (file.exists()) { if (!file.isDirectory()) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <otm...@us...> - 2010-09-28 05:35:28
|
Revision: 7127 http://jython.svn.sourceforge.net/jython/?rev=7127&view=rev Author: otmarhumbel Date: 2010-09-28 05:35:21 +0000 (Tue, 28 Sep 2010) Log Message: ----------- handle more SQL types in zxJDBC DataHandler (fixes issue #1647) thanks to Stephen Layland for the first patch thanks to Patrick Reinhart for discovering the missing types Modified Paths: -------------- trunk/jython/NEWS trunk/jython/src/com/ziclix/python/sql/DataHandler.java trunk/jython/src/com/ziclix/python/sql/Jython22DataHandler.java trunk/jython/src/com/ziclix/python/sql/handler/OracleDataHandler.java trunk/jython/src/com/ziclix/python/sql/handler/PostgresqlDataHandler.java trunk/jython/src/com/ziclix/python/sql/resource/zxJDBCMessages.properties Added Paths: ----------- trunk/jython/tests/java/com/ trunk/jython/tests/java/com/ziclix/ trunk/jython/tests/java/com/ziclix/python/ trunk/jython/tests/java/com/ziclix/python/sql/ trunk/jython/tests/java/com/ziclix/python/sql/DataHandlerTest.java Modified: trunk/jython/NEWS =================================================================== --- trunk/jython/NEWS 2010-09-27 13:14:22 UTC (rev 7126) +++ trunk/jython/NEWS 2010-09-28 05:35:21 UTC (rev 7127) @@ -1,5 +1,9 @@ Jython NEWS +Jython 2.5.2rc1 + Bugs Fixed + - [ 1647 ] zxJDBC does not handle NVARCHAR + Jython 2.5.2b2 Bugs Fixed - [ 1327 ] Classloaders cannot GC, which exhausts permgen (partial bug fix) Modified: trunk/jython/src/com/ziclix/python/sql/DataHandler.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/DataHandler.java 2010-09-27 13:14:22 UTC (rev 7126) +++ trunk/jython/src/com/ziclix/python/sql/DataHandler.java 2010-09-28 05:35:21 UTC (rev 7127) @@ -8,11 +8,6 @@ */ package com.ziclix.python.sql; -import org.python.core.Py; -import org.python.core.PyFile; -import org.python.core.PyObject; -import org.python.core.PyList; - import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -20,9 +15,11 @@ import java.io.Reader; import java.io.StringReader; import java.lang.reflect.Constructor; +import java.math.BigDecimal; import java.math.BigInteger; -import java.math.BigDecimal; +import java.sql.Blob; import java.sql.CallableStatement; +import java.sql.Clob; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -32,6 +29,11 @@ import java.sql.Timestamp; import java.sql.Types; +import org.python.core.Py; +import org.python.core.PyFile; +import org.python.core.PyList; +import org.python.core.PyObject; + /** * The DataHandler is responsible mapping the JDBC data type to * a Jython object. Depending on the version of the JDBC @@ -250,6 +252,7 @@ break; case Types.BIT: + case Types.BOOLEAN: obj = set.getBoolean(col) ? Py.True : Py.False; break; @@ -291,6 +294,7 @@ break; case Types.OTHER: + case Types.JAVA_OBJECT: obj = Py.java2py(set.getObject(col)); break; @@ -300,16 +304,41 @@ obj = Py.java2py(set.getBytes(col)); break; + case Types.BLOB: + Blob blob = set.getBlob(col); + obj = blob == null ? Py.None : Py.java2py(read(blob.getBinaryStream())); + break; + + case Types.CLOB: + Clob clob = set.getClob(col); + obj = clob == null ? Py.None : Py.java2py(read(clob.getCharacterStream())); + break; + + // TODO can we support these? + case Types.ARRAY: + throw createUnsupportedTypeSQLException("ARRAY", col); + case Types.DATALINK: + throw createUnsupportedTypeSQLException("DATALINK", col); + case Types.DISTINCT: + throw createUnsupportedTypeSQLException("DISTINCT", col); + case Types.REF: + throw createUnsupportedTypeSQLException("REF", col); + case Types.STRUCT: + throw createUnsupportedTypeSQLException("STRUCT", col); + default : - Integer[] vals = {new Integer(col), new Integer(type)}; - String msg = zxJDBC.getString("errorGettingIndex", vals); - - throw new SQLException(msg); + throw createUnsupportedTypeSQLException(new Integer(type), col); } return set.wasNull() || obj == null ? Py.None : obj; } + protected final SQLException createUnsupportedTypeSQLException(Object type, int col) { + Object[] vals = {type, new Integer(col)}; + String msg = zxJDBC.getString("unsupportedTypeForColumn", vals); + return new SQLException(msg); + } + /** * Given a CallableStatement, column and type, return the appropriate * Jython object. @@ -387,10 +416,7 @@ break; default : - Integer[] vals = {new Integer(col), new Integer(type)}; - String msg = zxJDBC.getString("errorGettingIndex", vals); - - throw new SQLException(msg); + createUnsupportedTypeSQLException(type, col); } return stmt.wasNull() || obj == null ? Py.None : obj; Modified: trunk/jython/src/com/ziclix/python/sql/Jython22DataHandler.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/Jython22DataHandler.java 2010-09-27 13:14:22 UTC (rev 7126) +++ trunk/jython/src/com/ziclix/python/sql/Jython22DataHandler.java 2010-09-28 05:35:21 UTC (rev 7127) @@ -51,6 +51,7 @@ * most notably Oracle. This callback allows a DataHandler to affect the * name. */ + @Override public String getMetaDataName(PyObject name) { return ((name == Py.None) ? null : name.__str__().toString()); } @@ -63,6 +64,7 @@ * @return an instance of a Procedure * @throws SQLException */ + @Override public Procedure getProcedure(PyCursor cursor, PyObject name) throws SQLException { return new Procedure(cursor, name); } @@ -75,6 +77,7 @@ * @throws SQLException thrown if an exception occurs * */ + @Override public PyObject getRowId(Statement stmt) throws SQLException { return Py.None; } @@ -83,6 +86,7 @@ * A callback prior to each execution of the statement. If the statement is * a PreparedStatement, all the parameters will have been set. */ + @Override public void preExecute(Statement stmt) throws SQLException { return; } @@ -90,6 +94,7 @@ /** * A callback after successfully executing the statement. */ + @Override public void postExecute(Statement stmt) throws SQLException { return; } @@ -103,6 +108,7 @@ * @param object the PyObject in question * @throws SQLException */ + @Override public void setJDBCObject(PreparedStatement stmt, int index, PyObject object) throws SQLException { try { @@ -133,6 +139,7 @@ * @param type the <i>java.sql.Types</i> for which this PyObject should be bound * @throws SQLException */ + @Override public void setJDBCObject(PreparedStatement stmt, int index, PyObject object, int type) throws SQLException { try { @@ -209,6 +216,7 @@ * @param type the column type * @throws SQLException if the type is unmappable */ + @Override @SuppressWarnings("deprecation") public PyObject getPyObject(ResultSet set, int col, int type) throws SQLException { @@ -308,10 +316,7 @@ break; default : - Integer[] vals = {new Integer(col), new Integer(type)}; - String msg = zxJDBC.getString("errorGettingIndex", vals); - - throw new SQLException(msg); + throw createUnsupportedTypeSQLException(new Integer(type), col); } return (set.wasNull() || (obj == null)) ? Py.None : obj; @@ -326,6 +331,7 @@ * @param type the column type * @throws SQLException if the type is unmappable */ + @Override @SuppressWarnings("deprecation") public PyObject getPyObject(CallableStatement stmt, int col, int type) throws SQLException { @@ -398,10 +404,7 @@ break; default : - Integer[] vals = {new Integer(col), new Integer(type)}; - String msg = zxJDBC.getString("errorGettingIndex", vals); - - throw new SQLException(msg); + throw createUnsupportedTypeSQLException(new Integer(type), col); } return (stmt.wasNull() || (obj == null)) ? Py.None : obj; @@ -420,6 +423,7 @@ * @throws SQLException * */ + @Override public void registerOut(CallableStatement statement, int index, int colType, int dataType, String dataTypeName) throws SQLException { try { @@ -445,6 +449,7 @@ * * @return a list of datahandlers */ + @Override public PyObject __chain__() { return new PyList(Py.javas2pys(this)); } Modified: trunk/jython/src/com/ziclix/python/sql/handler/OracleDataHandler.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/handler/OracleDataHandler.java 2010-09-27 13:14:22 UTC (rev 7126) +++ trunk/jython/src/com/ziclix/python/sql/handler/OracleDataHandler.java 2010-09-28 05:35:21 UTC (rev 7127) @@ -8,26 +8,25 @@ */ package com.ziclix.python.sql.handler; -import com.ziclix.python.sql.DataHandler; -import com.ziclix.python.sql.FilterDataHandler; -import com.ziclix.python.sql.zxJDBC; +import java.sql.CallableStatement; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.sql.Types; + import oracle.jdbc.OracleResultSet; import oracle.jdbc.OracleTypes; import oracle.sql.BLOB; import oracle.sql.ROWID; + import org.python.core.Py; import org.python.core.PyInteger; import org.python.core.PyObject; -import java.io.BufferedInputStream; -import java.io.InputStream; -import java.sql.CallableStatement; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.sql.Types; +import com.ziclix.python.sql.DataHandler; +import com.ziclix.python.sql.FilterDataHandler; /** * Oracle specific data handling. @@ -96,13 +95,6 @@ super.setJDBCObject(stmt, index, object, Types.DOUBLE); break; - case Types.BLOB: - case Types.CLOB: - Integer[] vals = {new Integer(index), new Integer(type)}; - String msg = zxJDBC.getString("errorSettingIndex", vals); - - throw new SQLException(msg); - case OracleTypes.ROWID: stmt.setString(index, (String) object.__tojava__(String.class)); break; Modified: trunk/jython/src/com/ziclix/python/sql/handler/PostgresqlDataHandler.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/handler/PostgresqlDataHandler.java 2010-09-27 13:14:22 UTC (rev 7126) +++ trunk/jython/src/com/ziclix/python/sql/handler/PostgresqlDataHandler.java 2010-09-28 05:35:21 UTC (rev 7127) @@ -38,6 +38,7 @@ super(datahandler); } + @Override protected String getRowIdMethodName() { return "getLastOID"; } @@ -51,6 +52,7 @@ * @return the mapped Python object * @throws SQLException thrown for a sql exception */ + @Override public PyObject getPyObject(ResultSet set, int col, int type) throws SQLException { PyObject obj = Py.None; @@ -90,6 +92,7 @@ * @param type * @throws SQLException */ + @Override public void setJDBCObject(PreparedStatement stmt, int index, PyObject object, int type) throws SQLException { if (DataHandler.checkNull(stmt, index, object, type)) { @@ -115,6 +118,8 @@ super.setJDBCObject(stmt, index, object, type); } } + + @Override public void setJDBCObject(PreparedStatement stmt, int index, PyObject object) throws SQLException { // PostgreSQL doesn't support BigIntegers without explicitely setting the // type. Modified: trunk/jython/src/com/ziclix/python/sql/resource/zxJDBCMessages.properties =================================================================== --- trunk/jython/src/com/ziclix/python/sql/resource/zxJDBCMessages.properties 2010-09-27 13:14:22 UTC (rev 7126) +++ trunk/jython/src/com/ziclix/python/sql/resource/zxJDBCMessages.properties 2010-09-28 05:35:21 UTC (rev 7127) @@ -94,8 +94,7 @@ noColInfo=unable to obtain column info excludedAllCols=excluded all columns invalidTableName=invalid table name [None] -errorSettingIndex=error setting index [{0}], type [{1}] -errorGettingIndex=error getting index [{0}], type [{1}] +unsupportedTypeForColumn=type [{0}] is not supported for column index: {1} maybeCallproc=use .callproc() for stored procedures nodynamiccursors=this version of jdbc does not support dynamic cursors nocallprocsupport=dynamic cursor does not support .callproc; use static cursors instead Added: trunk/jython/tests/java/com/ziclix/python/sql/DataHandlerTest.java =================================================================== --- trunk/jython/tests/java/com/ziclix/python/sql/DataHandlerTest.java (rev 0) +++ trunk/jython/tests/java/com/ziclix/python/sql/DataHandlerTest.java 2010-09-28 05:35:21 UTC (rev 7127) @@ -0,0 +1,95 @@ +package com.ziclix.python.sql; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; +import java.util.Arrays; +import java.util.List; + +import org.python.core.PySystemState; + +import junit.framework.TestCase; + +public class DataHandlerTest extends TestCase { + + private DataHandler _handler; + + @Override + protected void setUp() throws Exception { + PySystemState.initialize(); + _handler = new DataHandler(); + } + + /** + * make sure we handle every {@link java.sql.Types} somehow + * + * @throws Exception + */ + public void testGetPyObjectResultSetIntInt() throws Exception { + ResultSet rs = (ResultSet)Proxy.newProxyInstance(getClass().getClassLoader(), + new Class<?>[] {ResultSet.class}, + new DefaultReturnHandler()); + List<String> unsupportedTypes = Arrays.asList("ARRAY", + "DATALINK", + "DISTINCT", + "REF", + "STRUCT"); + for (Field field : Types.class.getDeclaredFields()) { + String typeName = field.getName(); + int type = field.getInt(null); + if (unsupportedTypes.contains(typeName)) { + try { + _handler.getPyObject(rs, 1, type); + fail("SQLException expected"); + } catch (SQLException sqle) { + // expected + } + } else { + assertNotNull(typeName + " should return None", _handler.getPyObject(rs, 1, type)); + } + } + } + + /** + * This is a poor man's mock - i cannot introduce a mock framework at this point in time + */ + static class DefaultReturnHandler implements InvocationHandler { + + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + Class<?> returnType = method.getReturnType(); + if (returnType.equals(Boolean.class) || returnType.equals(Boolean.TYPE)) { + return Boolean.FALSE; + } else if (Character.TYPE.equals(returnType)) { + return Character.valueOf('0'); + } else if (Byte.TYPE.equals(returnType)) { + return Byte.valueOf((byte)0); + } else if (Short.TYPE.equals(returnType)) { + return Short.valueOf((short)0); + } else if (Integer.TYPE.equals(returnType)) { + return Integer.valueOf(0); + } else if (Long.TYPE.equals(returnType)) { + return Long.valueOf(0L); + } else if (Float.TYPE.equals(returnType)) { + return Float.valueOf(0); + } else if (Double.TYPE.equals(returnType)) { + return Double.valueOf(0); + } else if (returnType.isPrimitive()) { + throw new RuntimeException("unhandled primitve type " + returnType); + } else if (returnType.isAssignableFrom(BigInteger.class)) { + return BigInteger.ZERO; + } else if (returnType.isAssignableFrom(BigDecimal.class)) { + return BigDecimal.ZERO; + } else if (returnType.isAssignableFrom(Number.class)) { + return 0; + } else { + return null; + } + } + } +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <otm...@us...> - 2010-09-13 21:46:54
|
Revision: 7124 http://jython.svn.sourceforge.net/jython/?rev=7124&view=rev Author: otmarhumbel Date: 2010-09-13 21:46:48 +0000 (Mon, 13 Sep 2010) Log Message: ----------- copy tag Release_2_5_2beta2 Added Paths: ----------- tags/Release_2_5_2beta2/ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2010-09-13 18:00:02
|
Revision: 7123 http://jython.svn.sourceforge.net/jython/?rev=7123&view=rev Author: zyasoft Date: 2010-09-13 17:59:56 +0000 (Mon, 13 Sep 2010) Log Message: ----------- Fixed typos in README.txt Modified Paths: -------------- trunk/jython/README.txt Modified: trunk/jython/README.txt =================================================================== --- trunk/jython/README.txt 2010-09-13 17:53:05 UTC (rev 7122) +++ trunk/jython/README.txt 2010-09-13 17:59:56 UTC (rev 7123) @@ -3,7 +3,7 @@ This is the second beta release of the 2.5.2 version of Jython. Our current plans is that this will be the last beta of 2.5.2, but this -will depend on bug report. +will depend on bug reports. This release fixes bugs related to resource leaks, Java integration, and a number of other issues. See the NEWS file for more details. In @@ -16,7 +16,7 @@ app containers, because the ThreadState often may not cleaned up by the app server's thread pool. -Fixing this problem without a breakwards breaking API change appears +Fixing this problem without a backwards breaking API change appears to be difficult. Therefore we recommend exploring workarounds, such as the one published in this blog post, http://weblogs.java.net/blog/jjviana/archive/2010/06/09/dealing-glassfish-301-memory-leak-or-threadlocal-thread-pool-bad-ide This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2010-09-13 17:53:12
|
Revision: 7122 http://jython.svn.sourceforge.net/jython/?rev=7122&view=rev Author: zyasoft Date: 2010-09-13 17:53:05 +0000 (Mon, 13 Sep 2010) Log Message: ----------- Updated NEWS and README.txt in prep of 2.5.2b2 Modified Paths: -------------- trunk/jython/NEWS trunk/jython/README.txt Modified: trunk/jython/NEWS =================================================================== --- trunk/jython/NEWS 2010-09-13 13:44:33 UTC (rev 7121) +++ trunk/jython/NEWS 2010-09-13 17:53:05 UTC (rev 7122) @@ -2,6 +2,7 @@ Jython 2.5.2b2 Bugs Fixed + - [ 1327 ] Classloaders cannot GC, which exhausts permgen (partial bug fix) - [ 1604 ] PyBuiltinCallable.Info should be serializable - [ 1397 ] Bugs in PyList and PyJavaType.ListIndexDelegate slice setting - [ 1503 ] Java constructors should take keyword arguments Modified: trunk/jython/README.txt =================================================================== --- trunk/jython/README.txt 2010-09-13 13:44:33 UTC (rev 7121) +++ trunk/jython/README.txt 2010-09-13 17:53:05 UTC (rev 7122) @@ -1,13 +1,43 @@ Welcome to Jython 2.5.2 Beta2 ============================= -This is the second beta release of the 2.5.2 version of Jython. This release -fixes a number of bugs and addresses memory and threading issues. See the NEWS file for -more details. +This is the second beta release of the 2.5.2 version of Jython. Our +current plans is that this will be the last beta of 2.5.2, but this +will depend on bug report. -The release was compiled on Mac OS X with JDK 5 and requires JDK 5 to run. +This release fixes bugs related to resource leaks, Java integration, +and a number of other issues. See the NEWS file for more details. In +particular, we did not completely fix #1327, "Classloaders cannot GC, +which exhausts permgen." Jython uses instances of ThreadLocal-managed +class, ThreadState, to manage its execution state, including frames, +exceptions, and the global namespace. The ThreadState also indirectly +refers to the ClassLoaders used by Jython. Such usage can cause +resource leaks when a Jython application is restarted under certain +app containers, because the ThreadState often may not cleaned up by +the app server's thread pool. -Please try it out and report any bugs at http://bugs.jython.org. +Fixing this problem without a breakwards breaking API change appears +to be difficult. Therefore we recommend exploring workarounds, such as +the one published in this blog post, +http://weblogs.java.net/blog/jjviana/archive/2010/06/09/dealing-glassfish-301-memory-leak-or-threadlocal-thread-pool-bad-ide -And - last but not least - please help spread the word: -If companies still are using Jython 2.2.1, they really should start testing against 2.5.2 now. +Jython 2.6 will introduce limited backwards breaking API changes, so +it will be possible to fully resolve this bug, and related issues, in +that version instead. + +And -- last but not least -- please help spread the word: + +Organizations using Jython 2.2.1, or earlier, should test their code +against 2.5.2 beta 2 now so that bug fixes and/or workarounds may be +identified. In particular, please note the following: + + * No additional work is anticipated on Jython 2.2. + + * Jython 2.5.2 is the last release in Jython 2.5.x series that will + address non-severe issues, including Java integration issues. + + * Jython 2.6 development will begin immediately following the 2.5.2 + release. Jython 2.6 will require the use of JDK 6. + +The release was compiled on Mac OS X with JDK 5 and requires JDK 5 to +run. Please try it out and report any bugs at http://bugs.jython.org. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <otm...@us...> - 2010-09-13 13:44:39
|
Revision: 7121 http://jython.svn.sourceforge.net/jython/?rev=7121&view=rev Author: otmarhumbel Date: 2010-09-13 13:44:33 +0000 (Mon, 13 Sep 2010) Log Message: ----------- prepare for 2.5.2b2 Modified Paths: -------------- trunk/jython/README.txt trunk/jython/build.xml Modified: trunk/jython/README.txt =================================================================== --- trunk/jython/README.txt 2010-09-12 23:08:19 UTC (rev 7120) +++ trunk/jython/README.txt 2010-09-13 13:44:33 UTC (rev 7121) @@ -1,11 +1,13 @@ -Welcome to Jython 2.5.2 Beta1 +Welcome to Jython 2.5.2 Beta2 ============================= -This is the first beta release of the 2.5.2 version of Jython. This release -fixes a number of bugs, including some Java integration problems, several modjy -bugs, a number of Python compatibility bugs, and more. See the NEWS file for +This is the second beta release of the 2.5.2 version of Jython. This release +fixes a number of bugs and addresses memory and threading issues. See the NEWS file for more details. The release was compiled on Mac OS X with JDK 5 and requires JDK 5 to run. -Please try this out and report any bugs at http://bugs.jython.org. +Please try it out and report any bugs at http://bugs.jython.org. + +And - last but not least - please help spread the word: +If companies still are using Jython 2.2.1, they really should start testing against 2.5.2 now. Modified: trunk/jython/build.xml =================================================================== --- trunk/jython/build.xml 2010-09-12 23:08:19 UTC (rev 7120) +++ trunk/jython/build.xml 2010-09-13 13:44:33 UTC (rev 7121) @@ -123,13 +123,13 @@ <property name="PY_RELEASE_LEVEL_SNAPSHOT" value="170"/> <!-- 0xAA --> <!-- The current version info --> - <property name="jython.version" value="2.5.2b1"/> - <property name="jython.version.noplus" value="2.5.2b1"/> + <property name="jython.version" value="2.5.2b2"/> + <property name="jython.version.noplus" value="2.5.2b2"/> <property name="jython.major_version" value="2"/> <property name="jython.minor_version" value="5"/> <property name="jython.micro_version" value="2"/> <property name="jython.release_level" value="${PY_RELEASE_LEVEL_BETA}"/> - <property name="jython.release_serial" value="1"/> + <property name="jython.release_serial" value="2"/> <condition property="do.snapshot.build"> <isset property="snapshot.revision" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2010-09-12 23:08:25
|
Revision: 7120 http://jython.svn.sourceforge.net/jython/?rev=7120&view=rev Author: zyasoft Date: 2010-09-12 23:08:19 +0000 (Sun, 12 Sep 2010) Log Message: ----------- Backed out support for nulling out ThreadState support. We need a better solution that doesn't introduce synchronization issues and a backwards breaking API change. See the discussion in #1327. Modified Paths: -------------- trunk/jython/src/org/python/core/PySystemState.java trunk/jython/src/org/python/core/ThreadStateMapping.java trunk/jython/tests/java/org/python/core/WrappedBooleanTest.java trunk/jython/tests/java/org/python/core/WrappedFloatTest.java trunk/jython/tests/java/org/python/core/WrappedIntegerTest.java trunk/jython/tests/java/org/python/core/WrappedLongTest.java trunk/jython/tests/java/org/python/tests/ExceptionTest.java trunk/jython/tests/java/org/python/tests/SerializationTest.java trunk/jython/tests/java/org/python/tests/props/BeanPropertyTest.java Modified: trunk/jython/src/org/python/core/PySystemState.java =================================================================== --- trunk/jython/src/org/python/core/PySystemState.java 2010-09-12 23:04:58 UTC (rev 7119) +++ trunk/jython/src/org/python/core/PySystemState.java 2010-09-12 23:08:19 UTC (rev 7120) @@ -1244,10 +1244,6 @@ return f; } - public void registerThreadState(ThreadState[] threadLocal, ThreadState ts) { - closer.registerThreadState(threadLocal, ts); - } - public void registerCloser(Callable resourceCloser) { closer.registerCloser(resourceCloser); } @@ -1281,7 +1277,6 @@ private static class PySystemStateCloser { - private final ArrayList<WeakReference<ThreadState[]>> threadStateList = new ArrayList<WeakReference<ThreadState[]>>(); private final Set<Callable> resourceClosers = new LinkedHashSet<Callable>(); private volatile boolean isCleanup = false; private final Thread shutdownHook; @@ -1301,13 +1296,6 @@ } } - private synchronized void registerThreadState(ThreadState[] threadLocal, ThreadState ts) { - if (!isCleanup) { - threadLocal[0] = ts; - threadStateList.add(new WeakReference<ThreadState[]>(threadLocal)); - } - } - private synchronized void registerCloser(Callable closer) { if (!isCleanup) { resourceClosers.add(closer); @@ -1329,15 +1317,6 @@ Runtime.getRuntime().removeShutdownHook(shutdownHook); } - // clear out existing ThreadStates so that they can be GCed - this resolves ClassLoader issues - for (WeakReference<ThreadState[]> ref : threadStateList) { - ThreadState[] o = ref.get(); - if (o != null) { - o[0] = null; - } - } - threadStateList.clear(); - for (Callable callable : resourceClosers) { try { callable.call(); Modified: trunk/jython/src/org/python/core/ThreadStateMapping.java =================================================================== --- trunk/jython/src/org/python/core/ThreadStateMapping.java 2010-09-12 23:04:58 UTC (rev 7119) +++ trunk/jython/src/org/python/core/ThreadStateMapping.java 2010-09-12 23:08:19 UTC (rev 7120) @@ -1,19 +1,15 @@ package org.python.core; class ThreadStateMapping { - private static final ThreadLocal<ThreadState[]> cachedThreadState = - new ThreadLocal<ThreadState[]>() { - @Override - protected ThreadState[] initialValue() { - return new ThreadState[1]; - } - }; + private static final ThreadLocal<ThreadState> cachedThreadState = new ThreadLocal<ThreadState>(); - public synchronized ThreadState getThreadState(PySystemState newSystemState) { - ThreadState[] threadLocal = cachedThreadState.get(); - if (threadLocal[0] != null) - return threadLocal[0]; + public ThreadState getThreadState(PySystemState newSystemState) { + ThreadState ts = cachedThreadState.get(); + if (ts != null) { + return ts; + } + Thread t = Thread.currentThread(); if (newSystemState == null) { Py.writeDebug("threadstate", "no current system state"); @@ -23,8 +19,8 @@ newSystemState = Py.defaultSystemState; } - ThreadState ts = new ThreadState(t, newSystemState); - newSystemState.registerThreadState(threadLocal, ts); + ts = new ThreadState(t, newSystemState); + cachedThreadState.set(ts); return ts; } } Modified: trunk/jython/tests/java/org/python/core/WrappedBooleanTest.java =================================================================== --- trunk/jython/tests/java/org/python/core/WrappedBooleanTest.java 2010-09-12 23:04:58 UTC (rev 7119) +++ trunk/jython/tests/java/org/python/core/WrappedBooleanTest.java 2010-09-12 23:08:19 UTC (rev 7120) @@ -32,7 +32,6 @@ @Override protected void setUp() throws Exception { - PythonInterpreter.initialize(null, null, null); interp = new PythonInterpreter(new PyStringMap(), new PySystemState()); a = new WrappedBoolean(); b = new WrappedBoolean(); Modified: trunk/jython/tests/java/org/python/core/WrappedFloatTest.java =================================================================== --- trunk/jython/tests/java/org/python/core/WrappedFloatTest.java 2010-09-12 23:04:58 UTC (rev 7119) +++ trunk/jython/tests/java/org/python/core/WrappedFloatTest.java 2010-09-12 23:08:19 UTC (rev 7120) @@ -32,7 +32,6 @@ @Override protected void setUp() throws Exception { - PythonInterpreter.initialize(null, null, null); interp = new PythonInterpreter(new PyStringMap(), new PySystemState()); a = new WrappedFloat(); b = new WrappedFloat(); Modified: trunk/jython/tests/java/org/python/core/WrappedIntegerTest.java =================================================================== --- trunk/jython/tests/java/org/python/core/WrappedIntegerTest.java 2010-09-12 23:04:58 UTC (rev 7119) +++ trunk/jython/tests/java/org/python/core/WrappedIntegerTest.java 2010-09-12 23:08:19 UTC (rev 7120) @@ -32,7 +32,6 @@ @Override protected void setUp() throws Exception { - PythonInterpreter.initialize(null, null, null); interp = new PythonInterpreter(new PyStringMap(), new PySystemState()); a = new WrappedInteger(); b = new WrappedInteger(); Modified: trunk/jython/tests/java/org/python/core/WrappedLongTest.java =================================================================== --- trunk/jython/tests/java/org/python/core/WrappedLongTest.java 2010-09-12 23:04:58 UTC (rev 7119) +++ trunk/jython/tests/java/org/python/core/WrappedLongTest.java 2010-09-12 23:08:19 UTC (rev 7120) @@ -34,7 +34,6 @@ @Override protected void setUp() throws Exception { - PythonInterpreter.initialize(null, null, null); interp = new PythonInterpreter(new PyStringMap(), new PySystemState()); a = new WrappedLong(); b = new WrappedLong(); Modified: trunk/jython/tests/java/org/python/tests/ExceptionTest.java =================================================================== --- trunk/jython/tests/java/org/python/tests/ExceptionTest.java 2010-09-12 23:04:58 UTC (rev 7119) +++ trunk/jython/tests/java/org/python/tests/ExceptionTest.java 2010-09-12 23:08:19 UTC (rev 7120) @@ -28,7 +28,6 @@ " else:\n" + " raise Throwable()\n" + "r = Raiser()"; - PythonInterpreter.initialize(null, null, null); PythonInterpreter interp = new PythonInterpreter(); interp.exec(raiser); t = Py.tojava(interp.get("r"), Thrower.class); Modified: trunk/jython/tests/java/org/python/tests/SerializationTest.java =================================================================== --- trunk/jython/tests/java/org/python/tests/SerializationTest.java 2010-09-12 23:04:58 UTC (rev 7119) +++ trunk/jython/tests/java/org/python/tests/SerializationTest.java 2010-09-12 23:08:19 UTC (rev 7120) @@ -18,7 +18,6 @@ @Override protected void setUp() throws Exception { - PythonInterpreter.initialize(null, null, null); interp = new PythonInterpreter(new PyStringMap(), new PySystemState()); interp.exec("from java.io import Serializable"); interp.exec("class Test(Serializable): pass"); Modified: trunk/jython/tests/java/org/python/tests/props/BeanPropertyTest.java =================================================================== --- trunk/jython/tests/java/org/python/tests/props/BeanPropertyTest.java 2010-09-12 23:04:58 UTC (rev 7119) +++ trunk/jython/tests/java/org/python/tests/props/BeanPropertyTest.java 2010-09-12 23:08:19 UTC (rev 7120) @@ -12,7 +12,6 @@ @Override protected void setUp() throws Exception { - PythonInterpreter.initialize(null, null, null); interp = new PythonInterpreter(new PyStringMap(), new PySystemState()); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2010-09-12 23:05:04
|
Revision: 7119 http://jython.svn.sourceforge.net/jython/?rev=7119&view=rev Author: zyasoft Date: 2010-09-12 23:04:58 +0000 (Sun, 12 Sep 2010) Log Message: ----------- Files that were not included in r7115 Added Paths: ----------- trunk/jython/tests/java/org/python/tests/constructor_kwargs/ trunk/jython/tests/java/org/python/tests/constructor_kwargs/ConstructorKWArgsTest.java trunk/jython/tests/java/org/python/tests/constructor_kwargs/KWArgsObject.java trunk/jython/tests/python/constructorkwargs_test.py Added: trunk/jython/tests/java/org/python/tests/constructor_kwargs/ConstructorKWArgsTest.java =================================================================== --- trunk/jython/tests/java/org/python/tests/constructor_kwargs/ConstructorKWArgsTest.java (rev 0) +++ trunk/jython/tests/java/org/python/tests/constructor_kwargs/ConstructorKWArgsTest.java 2010-09-12 23:04:58 UTC (rev 7119) @@ -0,0 +1,23 @@ +package org.python.tests.constructor_kwargs; + +import junit.framework.TestCase; + +import org.python.core.PyString; +import org.python.core.PyStringMap; +import org.python.core.PySystemState; +import org.python.util.PythonInterpreter; + +public class ConstructorKWArgsTest extends TestCase { + + private PythonInterpreter interp; + + @Override + protected void setUp() throws Exception { + PySystemState sys = new PySystemState(); + interp = new PythonInterpreter(new PyStringMap(), sys); + } + + public void testConstructorKWArgs() { + interp.execfile("tests/python/constructorkwargs_test.py"); + } +} Added: trunk/jython/tests/java/org/python/tests/constructor_kwargs/KWArgsObject.java =================================================================== --- trunk/jython/tests/java/org/python/tests/constructor_kwargs/KWArgsObject.java (rev 0) +++ trunk/jython/tests/java/org/python/tests/constructor_kwargs/KWArgsObject.java 2010-09-12 23:04:58 UTC (rev 7119) @@ -0,0 +1,21 @@ +package org.python.tests.constructor_kwargs; + +import java.util.HashMap; +import java.util.Arrays; + +import org.python.core.PyObject; + +public class KWArgsObject { + private HashMap<String, PyObject> data = new HashMap<String, PyObject>(); + + public KWArgsObject(PyObject[] values, String[] names) { + int offset = values.length-names.length; + for (int i = 0; i<names.length; i++) { + data.put(names[i], values[offset+i]); + } + } + + public PyObject getValue(String key) { + return data.get(key); + } +} Added: trunk/jython/tests/python/constructorkwargs_test.py =================================================================== --- trunk/jython/tests/python/constructorkwargs_test.py (rev 0) +++ trunk/jython/tests/python/constructorkwargs_test.py 2010-09-12 23:04:58 UTC (rev 7119) @@ -0,0 +1,8 @@ +from org.python.tests.constructor_kwargs import KWArgsObject + +x = KWArgsObject(a=1, b=2, c=3) + +assert x.getValue('a') == 1 +assert x.getValue('b') == 2 +assert x.getValue('c') == 3 + This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <otm...@us...> - 2010-09-10 11:45:02
|
Revision: 7118 http://jython.svn.sourceforge.net/jython/?rev=7118&view=rev Author: otmarhumbel Date: 2010-09-10 11:44:56 +0000 (Fri, 10 Sep 2010) Log Message: ----------- default svn.revision to HEAD this allows rebuilding releases without remembering the exact revision number Modified Paths: -------------- trunk/jython/build.xml Modified: trunk/jython/build.xml =================================================================== --- trunk/jython/build.xml 2010-09-09 16:28:05 UTC (rev 7117) +++ trunk/jython/build.xml 2010-09-10 11:44:56 UTC (rev 7118) @@ -70,9 +70,10 @@ #svn.main.dir=trunk # - the revision; only needed for a snapshot full-build -# To create a snapshot build: uncomment and indicate the correct revision (it has to be a number) +# To create a snapshot build: uncomment the two revision lines, and indicate the correct revision (it has to be a number) # For 'normal' builds, this defaults to the latest revision on svn.main.dir (HEAD) -#snapshot.revision=3444 +#svn.revision=7114 +#snapshot.revision=${svn.revision} # - the directory containing libsvnjavahl-1.dll (on windows) and svnjavahl.jar; only needed for full-build # how to get these (for windows): @@ -241,6 +242,8 @@ <property name="svn.main.dir" value="trunk" /> <property name="svn.code.dir" value="jython" /> <property name="svn.installer.dir" value="installer" /> + <!-- predefined revision for checkout (this works for both trunk and release branches --> + <property name="svn.revision" value="HEAD" /> <!-- properties work.dir and jython.base.dir are also definied in init, so full-preinit must run first to work --> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2010-09-09 16:28:12
|
Revision: 7117 http://jython.svn.sourceforge.net/jython/?rev=7117&view=rev Author: zyasoft Date: 2010-09-09 16:28:05 +0000 (Thu, 09 Sep 2010) Log Message: ----------- More work on #1327. ThreadStateMapping has a bad implementation of double-checked locking. The aspect of how it interacts with thread locals makes it subtle, so I'm going to make the whole lookup synchronized. Going forward, we should reconsider the use of ThreadLocal to manage the ThreadState mapping. Synchronizing this loses any performance from using ThreadLocal, but we have to deal with the other issues seen here. Also, I think we should expose the registration process more, in the case of usage with thread pools. Modified Paths: -------------- trunk/jython/src/org/python/core/ThreadStateMapping.java Modified: trunk/jython/src/org/python/core/ThreadStateMapping.java =================================================================== --- trunk/jython/src/org/python/core/ThreadStateMapping.java 2010-09-08 20:48:17 UTC (rev 7116) +++ trunk/jython/src/org/python/core/ThreadStateMapping.java 2010-09-09 16:28:05 UTC (rev 7117) @@ -9,33 +9,22 @@ } }; - public ThreadState getThreadState(PySystemState newSystemState) { + public synchronized ThreadState getThreadState(PySystemState newSystemState) { + ThreadState[] threadLocal = cachedThreadState.get(); + if (threadLocal[0] != null) + return threadLocal[0]; - // usual double checked locking pattern - ThreadState ts = cachedThreadState.get()[0]; - - if (ts != null) { - return ts; - } - - synchronized(this) { - ThreadState[] threadLocal = cachedThreadState.get(); - if(threadLocal[0] != null) - return threadLocal[0]; - - Thread t = Thread.currentThread(); - if (newSystemState == null) { - Py.writeDebug("threadstate", "no current system state"); - if (Py.defaultSystemState == null) { - PySystemState.initialize(); - } - newSystemState = Py.defaultSystemState; + Thread t = Thread.currentThread(); + if (newSystemState == null) { + Py.writeDebug("threadstate", "no current system state"); + if (Py.defaultSystemState == null) { + PySystemState.initialize(); } - - ts = new ThreadState(t, newSystemState); - - newSystemState.registerThreadState(threadLocal, ts); - return ts; + newSystemState = Py.defaultSystemState; } + + ThreadState ts = new ThreadState(t, newSystemState); + newSystemState.registerThreadState(threadLocal, ts); + return ts; } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2010-09-08 20:48:23
|
Revision: 7116 http://jython.svn.sourceforge.net/jython/?rev=7116&view=rev Author: zyasoft Date: 2010-09-08 20:48:17 +0000 (Wed, 08 Sep 2010) Log Message: ----------- Updated NEWS on bugs that were in fact fixed Modified Paths: -------------- trunk/jython/NEWS Modified: trunk/jython/NEWS =================================================================== --- trunk/jython/NEWS 2010-09-08 20:36:15 UTC (rev 7115) +++ trunk/jython/NEWS 2010-09-08 20:48:17 UTC (rev 7116) @@ -2,9 +2,10 @@ Jython 2.5.2b2 Bugs Fixed + - [ 1604 ] PyBuiltinCallable.Info should be serializable - [ 1397 ] Bugs in PyList and PyJavaType.ListIndexDelegate slice setting - [ 1503 ] Java constructors should take keyword arguments - - [ 1648 ] Incomplete implementation of pep328 for relative imports + - [ 1648,1495,1516 ] Incomplete implementation of pep328 for relative imports - [ 1611 ] Jython bytecode violated JLS, causing NPE on Sun's JVM when using -Xcomp option - [ 1643 ] Tools subdirectory still exists in trunk - [ 1455 ] Classes loaded dynamically from sys.path do not have their package defined This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2010-09-08 20:36:22
|
Revision: 7115 http://jython.svn.sourceforge.net/jython/?rev=7115&view=rev Author: zyasoft Date: 2010-09-08 20:36:15 +0000 (Wed, 08 Sep 2010) Log Message: ----------- Fixed PyJavaType#setSlice so it properly works with Python objects that are subclasses of Java classes implementing List. Resolves #1397. Thanks Geoffrey French for the patch! Modified Paths: -------------- trunk/jython/Lib/test/test_java_list_delegate.py trunk/jython/NEWS trunk/jython/src/org/python/core/PyJavaType.java trunk/jython/src/org/python/core/PyList.java Modified: trunk/jython/Lib/test/test_java_list_delegate.py =================================================================== --- trunk/jython/Lib/test/test_java_list_delegate.py 2010-09-08 11:37:00 UTC (rev 7114) +++ trunk/jython/Lib/test/test_java_list_delegate.py 2010-09-08 20:36:15 UTC (rev 7115) @@ -21,17 +21,25 @@ except Exception, e: return type(e) - def check_list(self, control, results, initial): - for result in results: + def _arraylist_of(self, xs): + """ + Converts a python list to a java.util.ArrayList + """ + a = ArrayList() + a.addAll( xs ) + return a + + def check_list(self, control, results, list_type_names, initial, test_name): + for result, type_name in zip(results, list_type_names): try: len(result) except: print result - self.assertEquals(len(control), len(result), "%s is wrong for %s" % (type(result), initial)) - for pvalue, jvalue in zip(control, result): - self.assertEquals(pvalue, jvalue) + self.assertEquals(len(control), len(result), "%s: length for %s does not match that of list" % (test_name, type_name)) + for control_value, result_value in zip(control, result): + self.assertEquals(control_value, result_value, "%s: values from %s do not match those from list" % (test_name, type_name)) - def _list_op_test(self, initial_value, op_func, check_value): + def _list_op_test(self, initial_value, op_func, test_name): """ Tests a list operation @@ -39,24 +47,33 @@ - a python list - a java.util.List instance - givens the same result in both cases + gives the same result in both cases """ lists = [list(initial_value), ArrayList(initial_value), Vector(initial_value)] + list_type_names = ['list', 'ArrayList', 'Vector'] results = [self._perform_op(l, op_func) for l in lists] - self.check_list(lists[0], lists[1:], initial_value) - if check_value or not isinstance(results[0], list): - for r in results[1:]: - self.assertEquals(results[0], r) + self.check_list(lists[0], lists[1:], list_type_names[1:], initial_value, test_name) + if not isinstance(results[0], list): + for r,n in zip(results[1:], list_type_names[1:]): + self.assertEquals(results[0], r, '%s: result for list does not match result for java type %s' % (test_name,n) ) else: - self.check_list(results[0], results[1:], initial_value) + self.check_list(results[0], results[1:], list_type_names[1:], initial_value, test_name) def test_get_integer(self): initial_value = range(0, 5) for i in xrange(-7, 7): - self._list_op_test(initial_value, lambda xs: xs[i], True) + self._list_op_test(initial_value, lambda xs: xs[i], 'get_integer [%d]' % (i,)) + def test_get_slice(self): + initial_value = range(0, 5) + + for i in [None] + range(-7, 7): + for j in [None] + range(-7, 7): + for k in [None] + range(-7, 7): + self._list_op_test(initial_value, lambda xs: xs[i:j:k], 'get_slice [%s:%s:%s]' % (i,j,k)) + def test_set_integer(self): initial_value = range(0, 5) @@ -66,24 +83,27 @@ return _f for i in xrange(-7, 7): - self._list_op_test(initial_value, make_op_func(i), True) + self._list_op_test(initial_value, make_op_func(i), 'set_integer [%d]' % (i,)) def test_set_slice(self): - initial_value = range(0, 10) + initial_value = range(0, 5) def make_op_func(i, j, k, v): def _f(xs): xs[i:j:k] = v return _f + + for i in [None] + range(-7, 7): + for j in [None] + range(-7, 7): + for k in [None] + range(-7, 7): + self._list_op_test(initial_value, make_op_func(i, j, k, []), 'set_slice [%s:%s:%s]=[]' % (i,j,k)) + self._list_op_test(initial_value, make_op_func(i, j, k, range(0,2)), 'set_slice [%s:%s:%s]=range(0,2)' % (i,j,k)) + self._list_op_test(initial_value, make_op_func(i, j, k, range(0,4)), 'set_slice [%s:%s:%s]=range(0,4)' % (i,j,k)) + self._list_op_test(initial_value, make_op_func(i, j, k, xrange(0,2)), 'set_slice [%s:%s:%s]=xrange(0,2)' % (i,j,k)) + self._list_op_test(initial_value, make_op_func(i, j, k, self._arraylist_of(range(0,2))), 'set_slice [%s:%s:%s]=ArrayList(range(0,2))' % (i,j,k)) + + self._list_op_test([1,2,3,4,5], make_op_func(1, None, None, [1,2,3,4,5]), 'set_slice [1:]=[1,2,3,4,5]') - for i in xrange(-12, 12): - for j in xrange(-12, 12): - for k in xrange(-12, 12): - self._list_op_test(initial_value, make_op_func(i, j, k, []), True) - self._list_op_test(initial_value, make_op_func(i, j, k, range(0,2)), True) - self._list_op_test(initial_value, make_op_func(i, j, k, range(0,4)), True) - self._list_op_test(initial_value, make_op_func(i, j, k, xrange(0,2)), True) - def test_del_integer(self): initial_value = range(0,5) @@ -93,20 +113,20 @@ return _f for i in xrange(-7, 7): - self._list_op_test(initial_value, make_op_func(i), True) + self._list_op_test(initial_value, make_op_func(i), 'del_integer [%d]' % (i,)) def test_del_slice(self): - initial_value = range(0,10) + initial_value = range(0,5) def make_op_func(i, j, k): def _f(xs): del xs[i:j:k] return _f - for i in xrange(-12, 12): - for j in xrange(-12, 12): - for k in xrange(-12, 12): - self._list_op_test(initial_value, make_op_func(i, j, k), True) + for i in [None] + range(-7, 7): + for j in [None] + range(-7, 7): + for k in [None] + range(-7, 7): + self._list_op_test(initial_value, make_op_func(i, j, k), 'del_slice [%s:%s:%s]' % (i,j,k)) def test_len(self): jlist = ArrayList() @@ -174,6 +194,43 @@ self.assert_(m.size() == 11) self.assert_(m.get(10) == 84) + + + def test_set_slice_from_input_types(self): + """ + Tests the slice setting functionality of Python lists + Ensures that the results are all the same, whether the source list is a Python list, a java.util.List or an iterator + """ + initial_value = range(0, 5) + + def make_op_func(i, j, k, v): + def _f(xs): + xs[i:j:k] = v + return _f + + for i in [None] + range(-7, 7): + for j in [None] + range(-7, 7): + for k in [None] + range(-7, 7): + destPy = copy(initial_value) + destJUL = copy(initial_value) + destIter = copy(initial_value) + + sourcePy = range(0, 2) + sourceJUL = self._arraylist_of(range(0, 2)) + sourceIter = xrange(0, 2) + + resultPy = self._perform_op(destPy, make_op_func(i, j, k, sourcePy)) + resultJUL = self._perform_op(destJUL, make_op_func(i, j, k, sourceJUL)) + resultIter = self._perform_op(destIter, make_op_func(i, j, k, sourceIter)) + + self.assertEquals(resultPy, resultJUL) + self.assertEquals(resultPy, resultIter) + + self.assertEquals(destPy, destJUL) + self.assertEquals(destPy, destIter) + + + def test_main(): test.test_support.run_unittest(CollectionProxyTest) Modified: trunk/jython/NEWS =================================================================== --- trunk/jython/NEWS 2010-09-08 11:37:00 UTC (rev 7114) +++ trunk/jython/NEWS 2010-09-08 20:36:15 UTC (rev 7115) @@ -2,6 +2,7 @@ Jython 2.5.2b2 Bugs Fixed + - [ 1397 ] Bugs in PyList and PyJavaType.ListIndexDelegate slice setting - [ 1503 ] Java constructors should take keyword arguments - [ 1648 ] Incomplete implementation of pep328 for relative imports - [ 1611 ] Jython bytecode violated JLS, causing NPE on Sun's JVM when using -Xcomp option Modified: trunk/jython/src/org/python/core/PyJavaType.java =================================================================== --- trunk/jython/src/org/python/core/PyJavaType.java 2010-09-08 11:37:00 UTC (rev 7114) +++ trunk/jython/src/org/python/core/PyJavaType.java 2010-09-08 20:36:15 UTC (rev 7115) @@ -1079,26 +1079,94 @@ public void setItem(int idx, PyObject value) { list.set(idx, value.__tojava__(Object.class)); } - + @Override public void setSlice(int start, int stop, int step, PyObject value) { - if (step == 0) { - return; + if (stop < start) { + stop = start; } - if (value.javaProxy == this) { - List newseq = new ArrayList(len()); - for (Object object : ((List)value.javaProxy)) { - newseq.add(object); + if (value.javaProxy == this.list) { + List<Object> xs = Generic.list(); + xs.addAll(this.list); + setsliceList(start, stop, step, xs); + } else if (value instanceof PyList) { + setslicePyList(start, stop, step, (PyList)value); + } else { + Object valueList = value.__tojava__(List.class); + if (valueList != null && valueList != Py.NoConversion) { + setsliceList(start, stop, step, (List)valueList); + } else { + setsliceIterator(start, stop, step, value.asIterable().iterator()); } - value = Py.java2py(newseq); } - int j = start; - for (PyObject obj : value.asIterable()) { - setItem(j, obj); - j += step; + } + + + + final private void setsliceList(int start, int stop, int step, List<Object> value) { + if (step == 1) { + list.subList(start, stop).clear(); + list.addAll(start, value); + } else { + int size = list.size(); + Iterator<Object> iter = value.listIterator(); + for (int j = start; iter.hasNext(); j += step) { + Object item =iter.next(); + if (j >= size) { + list.add(item); + } else { + list.set(j, item); + } + } } } + final private void setsliceIterator(int start, int stop, int step, Iterator<PyObject> iter) { + if (step == 1) { + List<Object> insertion = new ArrayList<Object>(); + if (iter != null) { + while (iter.hasNext()) { + insertion.add(iter.next().__tojava__(Object.class)); + } + } + list.subList(start, stop).clear(); + list.addAll(start, insertion); + } else { + int size = list.size(); + for (int j = start; iter.hasNext(); j += step) { + Object item = iter.next().__tojava__(Object.class); + if (j >= size) { + list.add(item); + } else { + list.set(j, item); + } + } + } + } + + final private void setslicePyList(int start, int stop, int step, PyList value) { + if (step == 1) { + list.subList(start, stop).clear(); + int n = value.getList().size(); + for (int i=0, j=start; i<n; i++, j++) { + Object item = value.getList().get(i).__tojava__(Object.class); + list.add(j, item); + } + } else { + int size = list.size(); + Iterator<PyObject> iter = value.getList().listIterator(); + for (int j = start; iter.hasNext(); j += step) { + Object item = iter.next().__tojava__(Object.class); + if (j >= size) { + list.add(item); + } else { + list.set(j, item); + } + } + } + } + + @Override public void delItems(int start, int stop) { int n = stop - start; Modified: trunk/jython/src/org/python/core/PyList.java =================================================================== --- trunk/jython/src/org/python/core/PyList.java 2010-09-08 11:37:00 UTC (rev 7114) +++ trunk/jython/src/org/python/core/PyList.java 2010-09-08 20:36:15 UTC (rev 7115) @@ -147,26 +147,38 @@ setslicePyList(start, stop, step, (PyList) value); } else if (value instanceof PySequence) { setsliceIterator(start, stop, step, value.asIterable().iterator()); - } else if (value != null && !(value instanceof List)) { - value = new PyList(value); - setsliceIterator(start, stop, step, value.asIterable().iterator()); + } else if (value instanceof List) { + setsliceList(start, stop, step, (List)value); } else { - List valueList = (List) value.__tojava__(List.class); + Object valueList = value.__tojava__(List.class); if (valueList != null && valueList != Py.NoConversion) { - setsliceList(start, stop, step, valueList); + setsliceList(start, stop, step, (List)valueList); + } else { + value = new PyList(value); + setsliceIterator(start, stop, step, value.asIterable().iterator()); } } } final private void setsliceList(int start, int stop, int step, List value) { - int n = sliceLength(start, stop, step); - if (list instanceof ArrayList) { - ((ArrayList) list).ensureCapacity(start + n); + if (step == 1) { + list.subList(start, stop).clear(); + int n = value.size(); + for (int i=0, j=start; i<n; i++, j++) { + list.add(j, Py.java2py(value.get(i))); + } + } else { + int size = list.size(); + Iterator<Object> iter = value.listIterator(); + for (int j = start; iter.hasNext(); j += step) { + PyObject item = Py.java2py(iter.next()); + if (j >= size) { + list.add(item); + } else { + list.set(j, item); + } + } } - ListIterator src = value.listIterator(); - for (int j = start; src.hasNext(); j += step) { - set(j, src.next()); - } } final private void setsliceIterator(int start, int stop, int step, Iterator<PyObject> iter) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <otm...@us...> - 2010-09-08 11:37:10
|
Revision: 7114 http://jython.svn.sourceforge.net/jython/?rev=7114&view=rev Author: otmarhumbel Date: 2010-09-08 11:37:00 +0000 (Wed, 08 Sep 2010) Log Message: ----------- remove redundant cast Modified Paths: -------------- trunk/jython/src/org/python/core/ThreadStateMapping.java Modified: trunk/jython/src/org/python/core/ThreadStateMapping.java =================================================================== --- trunk/jython/src/org/python/core/ThreadStateMapping.java 2010-09-08 07:18:48 UTC (rev 7113) +++ trunk/jython/src/org/python/core/ThreadStateMapping.java 2010-09-08 11:37:00 UTC (rev 7114) @@ -21,7 +21,7 @@ synchronized(this) { ThreadState[] threadLocal = cachedThreadState.get(); if(threadLocal[0] != null) - return (ThreadState)threadLocal[0]; + return threadLocal[0]; Thread t = Thread.currentThread(); if (newSystemState == null) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2010-09-08 07:18:55
|
Revision: 7113 http://jython.svn.sourceforge.net/jython/?rev=7113&view=rev Author: zyasoft Date: 2010-09-08 07:18:48 +0000 (Wed, 08 Sep 2010) Log Message: ----------- Fixed #1503, Java constructors should take keyword arguments. Thanks Geoffrey French! Modified Paths: -------------- trunk/jython/NEWS trunk/jython/src/org/python/core/PyReflectedConstructor.java Modified: trunk/jython/NEWS =================================================================== --- trunk/jython/NEWS 2010-09-08 06:27:14 UTC (rev 7112) +++ trunk/jython/NEWS 2010-09-08 07:18:48 UTC (rev 7113) @@ -2,6 +2,7 @@ Jython 2.5.2b2 Bugs Fixed + - [ 1503 ] Java constructors should take keyword arguments - [ 1648 ] Incomplete implementation of pep328 for relative imports - [ 1611 ] Jython bytecode violated JLS, causing NPE on Sun's JVM when using -Xcomp option - [ 1643 ] Tools subdirectory still exists in trunk Modified: trunk/jython/src/org/python/core/PyReflectedConstructor.java =================================================================== --- trunk/jython/src/org/python/core/PyReflectedConstructor.java 2010-09-08 06:27:14 UTC (rev 7112) +++ trunk/jython/src/org/python/core/PyReflectedConstructor.java 2010-09-08 07:18:48 UTC (rev 7113) @@ -115,32 +115,77 @@ } ReflectedCallData callData = new ReflectedCallData(); Object method = null; - // Remove keyword args + + // If we have keyword args, there are two ways this can be handled; + // a) we find a constructor that takes keyword args, and use it. + // b) we don't, in which case we strip the keyword args, and pass the + // non-keyword args, and then use the keyword args to set bean properties + // If we don't have keyword args; just look for a constructor that + // takes the right number of args. int nkeywords = keywords.length; + ReflectedArgs rargs = null; PyObject[] allArgs = args; + boolean usingKeywordArgsCtor = false; if (nkeywords > 0) { - args = new PyObject[allArgs.length - nkeywords]; - System.arraycopy(allArgs, 0, args, 0, args.length); - } - // Check for a matching constructor to call - int n = nargs; - for (int i = 0; i < n; i++) { - ReflectedArgs rargs = argslist[i]; - if (rargs.matches(null, args, Py.NoKeywords, callData)) { - method = rargs.data; - break; + // We have keyword args. + + // Look for a constructor; the ReflectedArgs#matches() method exits early in the case + // where keyword args are used + int n = nargs; + for (int i = 0; i < n; i++) { + rargs = argslist[i]; + if (rargs.matches(null, args, keywords, callData)) { + method = rargs.data; + break; + } } - } + + if (method != null) { + // Constructor found that will accept the keyword args + usingKeywordArgsCtor = true; + } else { + // No constructor found that will take keyword args + + // Remove the keyword args + args = new PyObject[allArgs.length - nkeywords]; + System.arraycopy(allArgs, 0, args, 0, args.length); + + // Look for a constructor with no keyword args + for (int i = 0; i < n; i++) { + rargs = argslist[i]; + if (rargs.matches(null, args, Py.NoKeywords, callData)) { + method = rargs.data; + break; + } + } + } + } else { + // Just look for a constructor with no keyword args + int n = nargs; + for (int i = 0; i < n; i++) { + rargs = argslist[i]; + if (rargs.matches(null, args, Py.NoKeywords, callData)) { + method = rargs.data; + break; + } + } + } + // Throw an error if no valid set of arguments if (method == null) { throwError(callData.errArg, args.length, false, false); } // Do the actual constructor call constructProxy(self, (Constructor<?>)method, callData.getArgsArray(), javaClass); - // Do setattr's for keyword args - int offset = args.length; - for (int i = 0; i < nkeywords; i++) { - self.__setattr__(keywords[i], allArgs[i + offset]); + // Do setattr's for keyword args. This convenience allows Java bean properties to be set in + // by a Python constructor call. + // However, this is not done if the Java constructor accepts (PyObject[], String[]) as its arguments, + // in which case the intention is that the Java constructor will handle the keyword arguments itself. + if (!usingKeywordArgsCtor) { + int offset = args.length; + for (int i = 0; i < nkeywords; i++) { + self.__setattr__(keywords[i], allArgs[i + offset]); + } } return Py.None; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |