source: trunk/abcl/contrib/jss/invoke.lisp @ 14929

Last change on this file since 14929 was 14929, checked in by Mark Evenson, 5 years ago

jss: remove duplicate declaration of *MUFFLE-WARNINGS* special

File size: 30.1 KB
Line 
1;; Copyright (C) 2005 Alan Ruttenberg
2;; Copyright (C) 2011-2 Mark Evenson
3;;
4;; Since JSS 1.0 was largely derivative of the Jscheme System, the
5;; current system is licensed under the same terms, namely:
6
7;; This software is provided 'as-is', without any express or
8;; implied warranty.
9
10;; In no event will the author be held liable for any damages
11;; arising from the use of this software.
12
13;; Permission is granted to anyone to use this software for any
14;; purpose, including commercial applications, and to alter it
15;; and redistribute it freely, subject to the following
16;; restrictions:
17
18;; 1. The origin of this software must not be misrepresented; you
19;;    must not claim that you wrote the original software. If you
20;;    use this software in a product, an acknowledgment in the
21;;    product documentation would be appreciated but is not
22;;    required.
23
24;; 2. Altered source versions must be plainly marked as such, and
25;;    must not be misrepresented as being the original software.
26
27;; 3. This notice may not be removed or altered from any source
28;;    distribution.
29
30
31;; The dynamic dispatch of the java.lang.reflect package is used to
32;; make it real easy, if perhaps less efficient, to write Java code
33;; since you don't need to be bothered with imports, or with figuring
34;; out which method to call.  The only time that you need to know a
35;; class name is when you want to call a static method, or a
36;; constructor, and in those cases, you only need to know enough of
37;; the class name that is unique wrt to the classes on your classpath.
38;;
39;; Java methods look like this: #"toString". Java classes are
40;; represented as symbols, which are resolved to the appropriate java
41;; class name. When ambiguous, you need to be more specific. A simple example:
42
43;; (let ((sw (new 'StringWriter)))
44;;   (#"write" sw "Hello ")
45;;   (#"write" sw "World")
46;;   (print (#"toString" sw)))
47
48;; What's happened here? First, all the classes in all the jars in the
49;; classpath have been collected.  For each class a.b.C.d, we have
50;; recorded that b.c.d, b.C.d, C.d, c.d, and d potentially refer to
51;; this class. In your call to new, as long as the symbol can refer to
52;; only one class, we use that class. In this case, it is
53;; java.io.StringWriter. You could also have written (new
54;; 'io.stringwriter), (new '|io.StringWriter|), (new
55;; 'java.io.StringWriter)...
56
57;; the call (#"write" sw "Hello "), uses the code in invoke.java to
58;; call the method named "write" with the arguments sw and "Hello ".
59;; JSS figures out the right java method to call, and calls it.
60
61;; If you want to do a raw java call, use #0"toString". Raw calls
62;; return their results as Java objects, avoiding doing the usual Java
63;; object to Lisp object conversions that ABCL does.
64
65;; (with-constant-signature ((name jname raw?)*) &body body)
66;; binds a macro which expands to a jcall, promising that the same method
67;; will be called every time. Use this if you are making a lot of calls and
68;; want to avoid the overhead of a the dynamic dispatch.
69;; e.g. (with-constant-signature ((tostring "toString"))
70;;        (time (dotimes (i 10000) (tostring "foo"))))
71;; runs about 3x faster than (time (dotimes (i 10000) (#"toString" "foo")))
72;;
73;; (with-constant-signature ((tostring "toString" t)) ...) will cause the
74;; toString to be a raw java call. see get-all-jar-classnames below for an example.
75;;
76;; Implementation is that the first time the function is called, the
77;; method is looked up based on the arguments passed, and thereafter
78;; that method is called directly.  Doesn't work for static methods at
79;; the moment (lazy)
80;;
81;; (japropos string) finds all class names matching string
82;; (jcmn class-name) lists the names of all methods for the class
83;;
84;; TODO
85;;   - Make with-constant-signature work for static methods too.
86;;   - #2"toString" to work like function scoped (with-constant-signature ((tostring "toString")) ...)
87;;   - #3"toString" to work like runtime scoped (with-constant-signature ((tostring "toString")) ...)
88;;      (both probably need compiler support to work)
89;;   - Maybe get rid of second " in reader macro. #"toString looks nicer, but might
90;;     confuse lisp mode.
91;;   - write jmap, analogous to map, but can take java collections, java arrays etc.
92;;   - write loop clauses for java collections.
93;;   - Register classes in .class files below classpath directories (when :wild-inferiors works)
94;;   - Make documentation like Edi Weitz
95;;
96;; Thanks: Peter Graves, Jscheme developers, Mike Travers for skij, 
97;; Andras Simon for jfli-abcl which bootstrapped me and taught me how to do
98;; get-all-jar-classnames
99;;
100
101;; changelog
102
103;; Sat January 28, 2006, alanr:
104
105;; Change imports strategy. Only index by last part of class name,
106;; case insensitive. Make the lookup-class-name logic be a bit more
107;; complicated. This substantially reduces the time it takes to do the
108;; auto imports and since class name lookup is relatively infrequent,
109;; and in any case cached, this doesn't effect run time speed.  (did
110;; try caching, but didn't pay - more time was spent reading and
111;; populating large hash table)
112;;
113;; Split class path by ";" in addition to ":" for windows.
114;;
115;; Tested on windows, linux.
116
117;; 2011-05-21 Mark Evenson
118;;   "ported" to native ABCL without needing the jscheme.jar or bsh-2.0b4.jar
119
120(in-package :jss)
121
122(eval-when (:compile-toplevel :load-toplevel :execute)
123  (defvar *do-auto-imports* t 
124    "Whether to automatically introspect all Java classes on the classpath when JSS is loaded."))
125
126(defvar *muffle-warnings* t)
127
128(defvar *imports-resolved-classes* (make-hash-table :test 'equalp))
129
130(defun find-java-class (name)
131  "Returns the java.lang.Class representation of NAME.
132
133NAME can either string or a symbol according to the usual JSS conventions."
134  (jclass (maybe-resolve-class-against-imports name)))
135
136(defmacro invoke-add-imports (&rest imports)
137  "Push these imports onto the search path. If multiple, earlier in list take precedence"
138  `(eval-when (:compile-toplevel :load-toplevel :execute)
139     (clrhash *imports-resolved-classes*)
140     (dolist (i (reverse ',imports))
141       (setq *imports-resolved-classes* (delete i *imports-resolved-classes* :test 'equal))
142       )))
143
144(defun clear-invoke-imports ()
145  (clrhash *imports-resolved-classes*))
146
147(defun maybe-resolve-class-against-imports (classname)
148  (or (gethash (string classname) *imports-resolved-classes*)
149      (let ((found (lookup-class-name classname)))
150        (if found
151            (progn 
152              (setf (gethash classname *imports-resolved-classes*) found)
153              found)
154            (string classname)))))
155
156(defvar *class-name-to-full-case-insensitive* (make-hash-table :test 'equalp))
157
158;; This is the function that calls invoke to call your java
159;; method. The first argument is the method name or 'new. The second
160;; is the object you are calling it on, followed by the rest of the
161;; arguments. If the "object" is a symbol, then that symbol is assumed
162;; to be a java class, and a static method on the class is called,
163;; otherwise a regular method is called.
164
165(defun invoke (method object &rest args)
166  (invoke-restargs method object args))
167
168(defun invoke-restargs (method object args &optional (raw? nil))
169  (let* ((object-as-class-name 
170          (if (symbolp object) (maybe-resolve-class-against-imports object)))
171         (object-as-class 
172          (if object-as-class-name (find-java-class object-as-class-name))))
173    (if (eq method 'new)
174        (apply #'jnew (or object-as-class-name object) args)
175        (if raw?
176            (if (symbolp object)
177                (apply #'jstatic-raw method object-as-class  args)
178                (apply #'jcall-raw method object  args))
179            (if (symbolp object)
180                (apply #'jstatic method object-as-class args)
181                (apply #'jcall method object args))))))
182
183(defconstant +set-accessible+ 
184  (jmethod "java.lang.reflect.AccessibleObject" "setAccessible" "boolean"))
185
186(defun invoke-find-method (method object args)
187  (let ((result 
188         (if (symbolp object)
189                ;;; static method
190             (apply #'jmethod (lookup-class-name object) 
191                    method (mapcar #'jobject-class args))
192                  ;;; instance method
193             (apply #'jresolve-method 
194                    method object args))))
195    (jcall +set-accessible+ result +true+)
196    result))
197
198;; This is the reader macro for java methods. it translates the method
199;; into a lambda form that calls invoke. Which is nice because you
200;; can, e.g. do this: (mapcar #"toString" list-of-java-objects). The reader
201;; macro takes one arg. If 0, then jstatic-raw is called, so that abcl doesn't
202;; automagically convert the returned java object into a lisp object. So
203;; #0"toString" returns a java.lang.String object, where as #"toString" returns
204;; a regular Lisp string as ABCL converts the Java string to a Lisp string.
205
206(eval-when (:compile-toplevel :load-toplevel :execute)
207  (defun read-invoke (stream char arg) 
208    (unread-char char stream)
209    (let ((name (read stream)))
210      (let ((object-var (gensym))
211            (args-var (gensym)))
212        `(lambda (,object-var &rest ,args-var) 
213           (invoke-restargs ,name  ,object-var ,args-var ,(eql arg 0))))))
214  (set-dispatch-macro-character #\# #\" 'read-invoke))
215
216(defmacro with-constant-signature (fname-jname-pairs &body body)
217  "Expand all references to FNAME-JNAME-PAIRS in BODY into static function calls promising that the same function bound in the FNAME-JNAME-PAIRS will be invoked with the same argument signature.
218
219FNAME-JNAME-PAIRS is a list of (symbol function &optional raw)
220elements where symbol will be the symbol bound to the method named by
221the string function.  If the optional parameter raw is non-nil, the
222result will be the raw JVM object, uncoerced by the usual conventions.
223
224Use this macro if you are making a lot of calls and
225want to avoid the overhead of the dynamic dispatch."
226
227  (if (null fname-jname-pairs)
228      `(progn ,@body)
229      (destructuring-bind ((fname jname &optional raw) &rest ignore) fname-jname-pairs
230        (declare (ignore ignore))
231        (let ((varname (gensym)))
232          `(let ((,varname nil))
233             (macrolet ((,fname (&rest args)
234                          `(if ,',varname
235                               (if ,',raw
236                                   (jcall-raw ,',varname ,@args)
237                                   (jcall ,',varname ,@args))
238                               (progn
239                                 (setq ,',varname (invoke-find-method ,',jname ,(car args) (list ,@(rest args))))
240                                 (if ,',raw
241                                     (jcall-raw ,',varname ,@args)
242                                     (jcall ,',varname ,@args))))))
243               (with-constant-signature ,(cdr fname-jname-pairs)
244                 ,@body)))))))
245
246(defun lookup-class-name (name &key (muffle *muffle-warnings*))
247  (setq name (string name))
248  (let* (;; cant (last-name-pattern (#"compile" '|java.util.regex.Pattern| ".*?([^.]*)$"))
249         ;; reason: bootstrap - the class name would have to be looked up...
250         (last-name-pattern (load-time-value (jstatic (jmethod "java.util.regex.Pattern" "compile"
251                                                               (jclass "java.lang.String"))
252                                                      (jclass "java.util.regex.Pattern") 
253                                                      ".*?([^.]*)$")))
254         (last-name 
255          (let ((matcher (#0"matcher" last-name-pattern name)))
256            (#"matches" matcher)
257            (#"group" matcher 1))))
258    (let* ((bucket (gethash last-name *class-name-to-full-case-insensitive*))
259           (bucket-length (length bucket)))
260      (or (find name bucket :test 'equalp)
261          (flet ((matches-end (end full test)
262                   (= (+ (or (search end full :from-end t :test test) -10)
263                         (length end))
264                      (length full)))
265                 (ambiguous (choices)
266                   (error "Ambiguous class name: ~a can be ~{~a~^, ~}" name choices)))
267            (if (zerop bucket-length)
268    (progn (unless muffle (warn "can't find class named ~a" name)) nil)
269                (let ((matches (loop for el in bucket when (matches-end name el 'char=) collect el)))
270                  (if (= (length matches) 1)
271                      (car matches)
272                      (if (= (length matches) 0)
273                          (let ((matches (loop for el in bucket when (matches-end name el 'char-equal) collect el)))
274                            (if (= (length matches) 1)
275                                (car matches)
276                                (if (= (length matches) 0)
277            (progn (unless muffle (warn "can't find class named ~a" name)) nil)
278                                    (ambiguous matches))))
279                          (ambiguous matches))))))))))
280
281(defun get-all-jar-classnames (jar-file-name)
282  (let* ((jar (jnew (jconstructor "java.util.jar.JarFile" (jclass "java.lang.String")) (namestring (truename jar-file-name))))
283         (entries (#"entries" jar)))
284    (with-constant-signature ((matcher "matcher" t) (substring "substring")
285                              (jreplace "replace" t) (jlength "length")
286                              (matches "matches") (getname "getName" t)
287                              (next "nextElement" t) (hasmore "hasMoreElements")
288                              (group "group"))
289      (loop while (hasmore entries)
290         for name =  (getname (next entries))
291         with class-pattern = (jstatic "compile" "java.util.regex.Pattern" ".*\\.class$")
292         with name-pattern = (jstatic "compile" "java.util.regex.Pattern" ".*?([^.]*)$")
293         when (matches (matcher class-pattern name))
294         collect
295           (let* ((fullname (substring (jreplace name #\/ #\.) 0 (- (jlength name) 6)))
296                  (matcher (matcher name-pattern fullname))
297                  (name (progn (matches matcher) (group matcher 1))))
298             (cons name fullname))
299           ))))
300
301(defun jar-import (file)
302  "Import all the Java classes contained in the pathname FILE into the JSS dynamic lookup cache."
303  (when (probe-file file)
304    (loop for (name . full-class-name) in (get-all-jar-classnames file)
305       do 
306         (pushnew full-class-name (gethash name *class-name-to-full-case-insensitive*) 
307                  :test 'equal))))
308
309(defun new (class-name &rest args)
310  "Invoke the Java constructor for CLASS-NAME with ARGS.
311
312CLASS-NAME may either be a symbol or a string according to the usual JSS conventions."
313  (invoke-restargs 'new class-name args))
314
315(defvar *running-in-osgi* (ignore-errors (jclass "org.osgi.framework.BundleActivator")))
316
317(define-condition no-such-java-field (error)
318  ((field-name
319    :initarg :field-name
320    :reader field-name
321    )
322   (object
323    :initarg :object
324    :reader object
325    ))
326  (:report (lambda (c stream)
327             (format stream "Unable to find a FIELD named ~a for ~a"
328                     (field-name c) (object c))))
329  )
330
331(defun get-java-field (object field &optional (try-harder *running-in-osgi*))
332  "Get the value of the FIELD contained in OBJECT.
333If OBJECT is a symbol it names a dot qualified static FIELD."
334  (if try-harder
335      (let* ((class (if (symbolp object)
336                        (setq object (find-java-class object))
337                        (if (equal "java.lang.Class" (jclass-name (jobject-class object)))
338                            object
339                            (jobject-class object))))
340             (jfield (if (java-object-p field)
341                         field
342                         (or (find-declared-field field class)
343                             (error 'no-such-java-field :field-name field :object object)))))
344        (#"setAccessible" jfield +true+)
345        (values (#"get" jfield object) jfield))
346      (if (symbolp object)
347          (let ((class (find-java-class object)))
348            (jfield class field))
349          (jfield field object))))
350
351(defun find-declared-field (field class)
352  "Return a FIELD object corresponding to the definition of FIELD
353\(a string\) visible at CLASS. *Not* restricted to public classes, and checks
354all superclasses of CLASS.
355   Returns NIL if no field object is found."
356  (loop while class
357     for field-obj = (get-declared-field class field)
358     if field-obj
359     do (return-from find-declared-field field-obj)
360     else
361     do (setf class (jclass-superclass class)))
362  nil)
363
364(defun get-declared-field (class fieldname)
365  (find fieldname (#"getDeclaredFields" class)
366        :key 'jfield-name :test 'equal))
367
368;; TODO use #"getSuperclass" and #"getInterfaces" to see whether there
369;; are fields in superclasses that we might set
370(defun set-java-field (object field value &optional (try-harder *running-in-osgi*))
371  "Set the FIELD of OBJECT to VALUE.
372If OBJECT is a symbol, it names a dot qualified Java class to look for
373a static FIELD.  If OBJECT is an instance of java:java-object, the
374associated is used to look up the static FIELD."
375  (if try-harder
376      (let* ((class (if (symbolp object)
377                        (setq object (find-java-class object))
378                        (if (equal "java.lang.Class" (jclass-name (jobject-class object)) )
379                            object
380                            (jobject-class object))))
381             (jfield (if (java-object-p field)
382                         field
383                         (or (find-declared-field field class)
384                             (error 'no-such-java-field :field-name field :object object)))))
385        (#"setAccessible" jfield +true+)
386        (values (#"set" jfield object value) jfield))
387      (if (symbolp object)
388          (let ((class (find-java-class object)))
389            (setf (jfield (#"getName" class) field) value))
390          (if (typep object 'java-object)
391              (setf (jfield (jclass-of object) field) value)
392              (setf (jfield object field) value)))))
393
394(defun (setf get-java-field) (value object field &optional (try-harder *running-in-osgi*))
395  (set-java-field object field value try-harder))
396
397
398(defconstant +for-name+ 
399  (jmethod "java.lang.Class" "forName" "java.lang.String" "boolean" "java.lang.ClassLoader"))
400
401(defun find-java-class (name)
402  (or (jstatic +for-name+ "java.lang.Class" 
403               (maybe-resolve-class-against-imports name) +true+ java::*classloader*)
404      (ignore-errors (jclass (maybe-resolve-class-against-imports name)))))
405
406(defmethod print-object ((obj (jclass "java.lang.Class")) stream) 
407  (print-unreadable-object (obj stream :identity nil)
408    (format stream "java class ~a" (jclass-name obj))))
409
410(defmethod print-object ((obj (jclass "java.lang.reflect.Method")) stream) 
411  (print-unreadable-object (obj stream :identity nil)
412    (format stream "method ~a" (#"toString" obj))))
413
414(defun do-auto-imports ()
415  (labels ((expand-paths (cp)
416             (loop :for s :in cp
417                :appending (loop :for entry 
418                              :in (let ((p (pathname s)))
419                                    (if (wild-pathname-p p)
420                                        (directory p)
421                                        (list p)))
422                              :collecting entry)))
423           (import-classpath (cp)
424             (mapcar 
425              (lambda (p) 
426                (when *load-verbose*
427                  (format t ";; Importing ~A~%" p))
428                (cond 
429                  ((file-directory-p p) )
430                  ((equal (pathname-type p) "jar")
431                   (jar-import (merge-pathnames p
432                                                (format nil "~a/" (jstatic "getProperty" "java.lang.System" "user.dir")))))))
433              cp))
434           (split-classpath (cp)
435             (coerce 
436              (jcall "split" cp 
437                     (string (jfield (jclass "java.io.File") "pathSeparatorChar")))
438              'cons))
439           (do-imports (cp)
440             (import-classpath (expand-paths (split-classpath cp)))))
441    (do-imports (jcall "getClassPath" (jstatic "getRuntimeMXBean" '|java.lang.management.ManagementFactory|)))
442    (do-imports (jcall "getBootClassPath" (jstatic "getRuntimeMXBean" '|java.lang.management.ManagementFactory|)))))
443
444(eval-when (:load-toplevel :execute)
445  (when *do-auto-imports* 
446    (do-auto-imports)))
447
448(defun japropos (string)
449  "Output the names of all Java class names loaded in the current process which match STRING.."
450  (setq string (string string))
451  (let ((matches nil))
452    (maphash (lambda(key value) 
453               (declare (ignore key))
454               (loop for class in value
455                  when (search string class :test 'string-equal)
456                  do (pushnew (list class "Java Class") matches :test 'equal)))
457             *class-name-to-full-case-insensitive*)
458    (loop for (match type) in (sort matches 'string-lessp :key 'car)
459       do (format t "~a: ~a~%" match type))
460    ))
461
462(defun jclass-method-names (class &optional full)
463  (if (java-object-p class)
464      (if (equal (jclass-name (jobject-class class)) "java.lang.Class")
465          (setq class (jclass-name class))
466          (setq class (jclass-name (jobject-class class)))))
467  (union
468   (remove-duplicates (map 'list (if full #"toString" 'jmethod-name) (#"getMethods" (find-java-class class))) :test 'equal)
469   (ignore-errors (remove-duplicates (map 'list (if full #"toString" 'jmethod-name) (#"getConstructors" (find-java-class class))) :test 'equal))))
470
471(defun java-class-method-names (class &optional stream)
472  "Return a list of the public methods encapsulated by the JVM CLASS.
473
474If STREAM non-nil, output a verbose description to the named output stream.
475
476CLASS may either be a string naming a fully qualified JVM class in dot
477notation, or a symbol resolved against all class entries in the
478current classpath."
479  (if stream
480      (dolist (method (jclass-method-names class t))
481        (format stream "~a~%" method))
482      (jclass-method-names class)))
483
484(setf (symbol-function 'jcmn) 'java-class-method-names)
485
486(defun path-to-class (classname)
487  (let ((full (lookup-class-name classname)))
488    (#"toString" 
489     (#"getResource" 
490      (find-java-class full)
491      (concatenate 'string "/" (substitute #\/ #\. full) ".class")))))
492
493;; http://www.javaworld.com/javaworld/javaqa/2003-07/02-qa-0725-classsrc2.html
494
495(defun all-loaded-classes ()
496  (let ((classes-field 
497         (find "classes" (#"getDeclaredFields" (jclass "java.lang.ClassLoader"))
498               :key #"getName" :test 'equal)))
499    (#"setAccessible" classes-field +true+)
500    (loop for classloader in (mapcar #'first (dump-classpath))
501       append
502         (loop with classesv = (#"get" classes-field classloader)
503            for i below (#"size" classesv)
504            collect (#"getName" (#"elementAt" classesv i)))
505       append
506         (loop with classesv = (#"get" classes-field (#"getParent" classloader))
507            for i below (#"size" classesv)
508            collect (#"getName" (#"elementAt" classesv i))))))
509
510(defun get-dynamic-class-path ()
511  (rest 
512   (find-if (lambda (loader) 
513              (string= "org.armedbear.lisp.JavaClassLoader"
514                       (jclass-name (jobject-class loader))))
515            (dump-classpath)
516            :key #'car)))
517
518(defun java-gc ()
519  (#"gc" (#"getRuntime" 'java.lang.runtime))
520  (#"runFinalization" (#"getRuntime" 'java.lang.runtime))
521  (#"gc" (#"getRuntime" 'java.lang.runtime))
522  (java-room))
523
524(defun java-room ()
525  (let ((rt (#"getRuntime" 'java.lang.runtime)))
526    (values (- (#"totalMemory" rt) (#"freeMemory" rt))
527            (#"totalMemory" rt)
528            (#"freeMemory" rt)
529            (list :used :total :free))))
530
531(defun verbose-gc (&optional (new-value nil new-value-supplied))
532  (if new-value-supplied
533      (progn (#"setVerbose" (#"getMemoryMXBean"  'java.lang.management.ManagementFactory) new-value) new-value)
534      (#"isVerbose" (#"getMemoryMXBean"  'java.lang.management.ManagementFactory))))
535
536(defun all-jars-below (directory) 
537  (loop with q = (system:list-directory directory) 
538     while q for top = (pop q)
539     if (null (pathname-name top)) do (setq q (append q (all-jars-below top))) 
540     if (equal (pathname-type top) "jar") collect top))
541
542(defun all-classfiles-below (directory) 
543  (loop with q = (system:list-directory directory) 
544     while q for top = (pop q)
545     if (null (pathname-name top)) do (setq q (append q (all-classfiles-below top ))) 
546     if (equal (pathname-type top) "class")
547     collect top
548       ))
549
550(defun all-classes-below-directory (directory)
551  (loop for file in (all-classfiles-below directory) collect
552       (format nil "~{~a.~}~a"
553               (subseq (pathname-directory file) (length (pathname-directory directory)))
554               (pathname-name file))
555       ))
556
557(defun classfiles-import (directory)
558  "Load all Java classes recursively contained under DIRECTORY in the current process."
559  (setq directory (truename directory))
560  (loop for full-class-name in (all-classes-below-directory directory)
561     for name = (#"replaceAll" full-class-name "^.*\\." "")
562     do
563       (pushnew full-class-name (gethash name *class-name-to-full-case-insensitive*) 
564                :test 'equal)))
565
566(defun set-to-list (set)
567  (declare (optimize (speed 3) (safety 0)))
568  (with-constant-signature ((iterator "iterator" t) (hasnext "hasNext") (next "next"))
569    (loop with iterator = (iterator set)
570       while (hasNext iterator)
571       for item = (next iterator)
572       collect item)))
573
574(defun jlist-to-list (list)
575  "Convert a LIST implementing java.util.List to a Lisp list."
576  (declare (optimize (speed 3) (safety 0)))
577  (loop :for i :from 0 :below (jcall "size" list)
578     :collecting (jcall "get" list i)))
579
580(defun jarray-to-list (jarray)
581  "Convert the Java array named by JARRARY into a Lisp list."
582  (declare (optimize (speed 3) (safety 0)))
583  (loop :for i :from 0 :below (jarray-length jarray)
584     :collecting (jarray-ref jarray i)))
585
586;;; Deprecated
587;;;
588;;; XXX unclear what sort of list this would actually work on, as it
589;;; certainly doesn't seem to be any of the Java collection types
590;;; (what implements getNext())?
591(defun list-to-list (list)
592  (declare (optimize (speed 3) (safety 0)))
593  (with-constant-signature ((isEmpty "isEmpty") (getfirst "getFirst")
594                            (getNext "getNext"))
595    (loop until (isEmpty list)
596       collect (getFirst list)
597       do (setq list (getNext list)))))
598
599;; Contribution of Luke Hope. (Thanks!)
600
601(defun iterable-to-list (iterable)
602  "Return the items contained the java.lang.Iterable ITERABLE as a list."
603  (declare (optimize (speed 3) (safety 0)))
604  (let ((it (#"iterator" iterable)))
605    (with-constant-signature ((has-next "hasNext")
606                              (next "next"))
607      (loop :while (has-next it)
608         :collect (next it)))))
609
610(defun vector-to-list (vector)
611  "Return the elements of java.lang.Vector VECTOR as a list."
612  (declare (optimize (speed 3) (safety 0)))
613  (with-constant-signature ((has-more "hasMoreElements")
614                            (next "nextElement"))
615    (let ((elements (#"elements" vector)))
616      (loop :while (has-more elements)
617         :collect (next elements)))))
618
619(defun hashmap-to-hashtable (hashmap &rest rest &key (keyfun #'identity) (valfun #'identity) (invert? nil)
620                                                  table 
621                             &allow-other-keys )
622  "Converts the a HASHMAP reference to a java.util.HashMap object to a Lisp hashtable.
623
624The REST paramter specifies arguments to the underlying MAKE-HASH-TABLE call.
625
626KEYFUN and VALFUN specifies functions to be run on the keys and values
627of the HASHMAP right before they are placed in the hashtable.
628
629If INVERT? is non-nil than reverse the keys and values in the resulting hashtable."
630  (let ((keyset (#"keySet" hashmap))
631        (table (or table (apply 'make-hash-table
632                                (loop for (key value) on rest by #'cddr
633                                   unless (member key '(:invert? :valfun :keyfun :table)) 
634                                   collect key and collect value)))))
635    (with-constant-signature ((iterator "iterator" t) (hasnext "hasNext") (next "next"))
636      (loop with iterator = (iterator keyset)
637         while (hasNext iterator)
638         for item = (next iterator)
639         do (if invert?
640                (setf (gethash (funcall valfun (#"get" hashmap item)) table) (funcall keyfun item))
641                (setf (gethash (funcall keyfun item) table) (funcall valfun (#"get" hashmap item)))))
642      table)))
643
644(defun jclass-all-interfaces (class)
645  "Return a list of interfaces the class implements"
646  (unless (java-object-p class)
647    (setq class (find-java-class class)))
648  (loop for aclass = class then (#"getSuperclass" aclass)
649     while aclass
650     append (coerce (#"getInterfaces" aclass) 'list)))
651
652(defun safely (f name)
653  (let ((fname (gensym)))
654    (compile fname
655             `(lambda(&rest args)
656                (with-simple-restart (top-level
657                                      "Return from lisp method implementation for ~a." ,name)
658                  (apply ,f args))))
659    (symbol-function fname)))
660
661(defun jdelegating-interface-implementation (interface dispatch-to &rest method-names-and-defs)
662  "Creates and returns an implementation of a Java interface with
663   methods calling Lisp closures as given in METHOD-NAMES-AND-DEFS.
664
665   INTERFACE is an interface
666
667   DISPATCH-TO is an existing Java object
668
669   METHOD-NAMES-AND-DEFS is an alternating list of method names
670   (strings) and method definitions (closures).
671
672   For missing methods, a dummy implementation is provided that
673   calls the method on DISPATCH-TO."
674  (let ((implemented-methods
675         (loop for m in method-names-and-defs
676            for i from 0
677            if (evenp i) 
678            do (assert (stringp m) (m) "Method names must be strings: ~s" m) and collect m
679            else
680            do (assert (or (symbolp m) (functionp m)) (m) "Methods must be function designators: ~s" m))))
681    (let ((safe-method-names-and-defs 
682           (loop for (name function) on method-names-and-defs by #'cddr
683              collect name collect (safely function name))))
684      (loop for method across
685           (jclass-methods interface :declared nil :public t)
686         for method-name = (jmethod-name method)
687         when (not (member method-name implemented-methods :test #'string=))
688         do
689           (let* ((def  `(lambda
690                             (&rest args)
691                           (invoke-restargs ,(jmethod-name method) ,dispatch-to args t)
692                           )))
693             (push (coerce def 'function) safe-method-names-and-defs)
694             (push method-name safe-method-names-and-defs)))
695      (apply #'java::%jnew-proxy  interface safe-method-names-and-defs))))
696
697
Note: See TracBrowser for help on using the repository browser.