forked from fredlund/JavaErlang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJavaErlang.java
More file actions
1634 lines (1489 loc) · 62.3 KB
/
JavaErlang.java
File metadata and controls
1634 lines (1489 loc) · 62.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2011, Lars-Ake Fredlund
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// // Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// // Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// // Neither the name of the copyright holders nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS''
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// @author Lars-Ake Fredlund (lfredlund@fi.upm.es)
// @copyright 2011 Lars-Ake Fredlund
//
package javaErlang;
import java.io.File;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.net.URL;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import java.util.logging.Level;
import java.util.logging.ConsoleHandler;
import javassist.util.proxy.ProxyFactory;
import com.ericsson.otp.erlang.OtpErlangAtom;
import com.ericsson.otp.erlang.OtpErlangBoolean;
import com.ericsson.otp.erlang.OtpErlangByte;
import com.ericsson.otp.erlang.OtpErlangChar;
import com.ericsson.otp.erlang.OtpErlangDouble;
import com.ericsson.otp.erlang.OtpErlangFloat;
import com.ericsson.otp.erlang.OtpErlangInt;
import com.ericsson.otp.erlang.OtpErlangList;
import com.ericsson.otp.erlang.OtpErlangLong;
import com.ericsson.otp.erlang.OtpErlangObject;
import com.ericsson.otp.erlang.OtpErlangPid;
import com.ericsson.otp.erlang.OtpErlangShort;
import com.ericsson.otp.erlang.OtpErlangString;
import com.ericsson.otp.erlang.OtpErlangTuple;
import com.ericsson.otp.erlang.OtpMbox;
import com.ericsson.otp.erlang.OtpNode;
@SuppressWarnings("rawtypes")
public class JavaErlang {
volatile private Map<RefEqualsObject, JavaObjectEntry> toErlangMap;
volatile private Map<JavaObjectKey, JavaObjectEntry> fromErlangMap;
volatile private Map<Object, OtpErlangObject> accToErlangMap;
volatile private Map<OtpErlangObject, Object> accFromErlangMap;
volatile private Map<OtpErlangObject, ThreadMsgHandler> threadMap;
volatile private Map<Class,Integer> classMap;
volatile int objCounter = 0;
volatile int classCounter = 0;
volatile private int accCounter = 0;
volatile private int threadCounter = 0;
volatile OtpMbox msgs;
volatile OtpErlangObject nodeIdentifier = null;
static volatile Logger logger = Logger.getLogger("JavaErlangLogger");
boolean isConnected = false;
public static void main(final String args[]) {
Level logLevel = Level.WARNING;
int currentArg = 0;
final String name = args[currentArg++];
String cookie = null;
while (currentArg < args.length) {
final String arg = args[currentArg++];
if (arg.equals("-loglevel"))
if (currentArg < args.length)
logLevel = Level.parse(args[currentArg++]);
else {
System.err.println("Missing argument for -loglevel option");
System.exit(-1);
}
else if (arg.equals("-setcookie"))
if (currentArg < args.length)
cookie = args[currentArg++];
else {
System.err.println("Missing argument for -setcookie option");
System.exit(-1);
}
else {
System.err.println("\rCannot understand argument " + arg);
System.exit(-1);
}
}
logger.setLevel(logLevel);
ConsoleHandler consoleHandler = new ConsoleHandler();
consoleHandler.setLevel(logger.getLevel());
logger.addHandler(consoleHandler);
try {
new JavaErlang(name,cookie).do_receive();
} catch (final Exception e) {
logger.log
(Level.SEVERE,
"*** Unexpected exception failure in JavaErlang: "
+ e,e);
}
}
public JavaErlang(final String name, final String cookie) {
toErlangMap = new ConcurrentHashMap<RefEqualsObject, JavaObjectEntry>();
fromErlangMap = new ConcurrentHashMap<JavaObjectKey, JavaObjectEntry>();
accToErlangMap = new ConcurrentHashMap<Object, OtpErlangObject>();
accFromErlangMap = new ConcurrentHashMap<OtpErlangObject, Object>();
classMap = new ConcurrentHashMap<Class, Integer>();
threadMap = new ConcurrentHashMap<OtpErlangObject, ThreadMsgHandler>();
try {
final OtpNode node;
if (cookie == null) node = new OtpNode(name);
else node = new OtpNode(name,cookie);
node.registerStatusHandler(new OtpStatusHandler(nodeIdentifier));
if (logger.isLoggable(Level.INFO)) {
logger.log(Level.INFO,"\rRegistered host " + node.node());
}
msgs = node.createMbox("javaNode");
} catch (final Throwable e) {
if (logger.isLoggable(Level.SEVERE))
logger.log
(Level.SEVERE,
"*** Unexpected exception failure in JavaErlang: "
+ e,
e);
}
}
void do_receive() throws Exception {
do {
final OtpErlangObject msg = msgs.receive();
if (logger.isLoggable(Level.FINER)) {
logger.log(Level.FINER,"\rGot message " + msg);
}
if (msg instanceof OtpErlangTuple) {
final OtpErlangTuple t = (OtpErlangTuple) msg;
if (t.arity() == 3 && t.elementAt(0) instanceof OtpErlangLong
&& t.elementAt(2) instanceof OtpErlangPid) {
handle_nonthread_msg(t);
} else if (t.arity() == 4
&& t.elementAt(0) instanceof OtpErlangLong
&& t.elementAt(3) instanceof OtpErlangPid) {
handle_thread_msg(t);
} else if (t.arity() == 2
&& t.elementAt(0) instanceof OtpErlangLong) {
handle_noncall_msg(t);
} else {
if (logger.isLoggable(Level.FINER))
logger.log(Level.FINER,"\nMalformed message " + msg
+ " received");
}
} else {
if (logger.isLoggable(Level.FINER))
logger.log(Level.FINER,"\nMalformed message " + msg + " received");
}
} while (true);
}
public void reply(final Object reply, final OtpErlangPid replyPid)
throws Exception {
// logger.log(Level.FINER,"returning "+return_value(reply)+" to "+replyPid);
msgs.send(replyPid, return_value(reply));
}
void handle_nonthread_msg(final OtpErlangTuple t) throws Exception {
final short tag = ((OtpErlangLong) t.elementAt(0)).uShortValue();
final OtpErlangObject argument = t.elementAt(1);
final OtpErlangPid replyPid = (OtpErlangPid) t.elementAt(2);
if (!isConnected) {
if (tag == Tags.connectTag) {
final String nameOfRunningVM = ManagementFactory
.getRuntimeMXBean().getName();
final int p = nameOfRunningVM.indexOf('@');
final String pid = nameOfRunningVM.substring(0, p);
final Integer intPid = new Integer(pid);
if (nodeIdentifier == null) {
nodeIdentifier = argument;
}
reply(makeErlangTuple(new OtpErlangAtom("connected"),
msgs.self(), new OtpErlangLong(intPid)), replyPid);
isConnected = true;
} else {
if (logger.isLoggable(Level.FINER))
logger.log(Level.FINER,"\nFirst message should be connect " + t);
}
} else {
Object result;
try {
result = handleNonThreadMsg(tag, argument, replyPid);
} catch (final Throwable e) {
if (logger.isLoggable(Level.WARNING)) {
logger.log(Level.WARNING,"\r\n*** Exception " + e + " thrown\r");
e.printStackTrace();
}
result = e;
}
reply(result, replyPid);
}
}
void handle_noncall_msg(final OtpErlangTuple t) throws Exception {
final short tag = ((OtpErlangLong) t.elementAt(0)).uShortValue();
final OtpErlangObject argument = t.elementAt(1);
try {
handleNonCallMsg(tag, argument);
} catch (final Throwable e) {
if (logger.isLoggable(Level.WARNING)) {
logger.log(Level.WARNING,"\r\n*** Exception " + e + " thrown\r");
e.printStackTrace();
}
}
}
void handle_thread_msg(final OtpErlangTuple t) throws Exception {
final Object map_result = threadMap.get(t.elementAt(1));
if (map_result instanceof ThreadMsgHandler) {
final ThreadMsgHandler th = (ThreadMsgHandler) map_result;
th.queue.put(t);
} else {
if (logger.isLoggable(Level.FINER))
logger.log(Level.FINER,"Thread " + t.elementAt(1) + " not found");
}
}
OtpErlangObject handleNonThreadMsg(final short tag,
final OtpErlangObject argument, final OtpErlangPid replyPid)
throws Exception {
switch (tag) {
case Tags.resetTag:
objCounter = 0;
toErlangMap = new ConcurrentHashMap<RefEqualsObject, JavaObjectEntry>();
fromErlangMap = new ConcurrentHashMap<JavaObjectKey, JavaObjectEntry>();
for (final ThreadMsgHandler th : threadMap.values()) {
stop_thread(th);
}
threadMap = new ConcurrentHashMap<OtpErlangObject, ThreadMsgHandler>();
System.gc();
return new OtpErlangAtom("ok");
case Tags.terminateTag:
if (logger.isLoggable(Level.FINER)) {
logger.log(Level.FINER,"\r\nterminating java...");
}
reply(new OtpErlangAtom("ok"), replyPid);
System.exit(0);
return map_to_erlang_void();
case Tags.connectTag:
return new OtpErlangAtom("already_connected");
case Tags.lookupClassTag:
return lookupClass(argument);
case Tags.getConstructorsTag:
return getConstructors(argument);
case Tags.getMethodsTag:
return getMethods(argument);
case Tags.getClassesTag:
return getClasses(argument);
case Tags.getFieldsTag:
return getFields(argument);
case Tags.getConstructorTag:
return getConstructor(argument);
case Tags.getMethodTag:
return getMethod(argument);
case Tags.getFieldTag:
return getField(argument);
case Tags.objTypeCompatTag:
return objTypeCompat(argument);
case Tags.freeTag:
return free(argument);
case Tags.freeInstanceTag:
return freeInstance(argument);
case Tags.memoryUsageTag:
return memoryUsage(argument);
case Tags.identityTag:
return identity(argument);
case Tags.createThreadTag:
return create_thread();
case Tags.new_proxy_classTag:
return new_proxy_class(argument);
case Tags.new_proxy_objectTag:
return new_proxy_object(argument);
case Tags.proxy_replyTag:
return proxy_reply(argument);
default:
logger.log
(Level.SEVERE,
"*** Error: JavaErlang: \nTag " + tag
+ " not recognized");
throw new Exception();
}
}
OtpErlangObject handleNonCallMsg(final short tag,
final OtpErlangObject argument)
throws Exception {
switch (tag) {
case Tags.freeInstanceTag:
return freeInstance(argument);
case Tags.stopThreadTag:
final Object map_result = threadMap.get(argument);
if (map_result instanceof ThreadMsgHandler) {
final ThreadMsgHandler th = (ThreadMsgHandler) map_result;
threadMap.remove(argument);
stop_thread(th);
} else {
if (logger.isLoggable(Level.FINER))
logger.log
(Level.FINER,
"*** Warning: thread missing in stopThread");
//throw new Exception();
}
return map_to_erlang_void();
default:
logger.log
(Level.SEVERE,
"*** Error: JavaErlang: \nTag " + tag
+ " not recognized");
throw new Exception();
}
}
OtpErlangObject create_thread() {
final ThreadMsgHandler th = ThreadMsgHandler
.createThreadMsgHandler(this);
return map_new_thread_to_erlang(th);
}
static void stop_thread(final ThreadMsgHandler th) throws Exception {
th.queue.put(mkStopThreadMsg());
}
static OtpErlangObject mkStopThreadMsg() {
OtpErlangObject nullObj = map_to_erlang_null();
return makeErlangTuple(new OtpErlangLong(Tags.stopThreadTag),
nullObj, nullObj, nullObj);
}
public static OtpErlangTuple makeErlangTuple(
final OtpErlangObject... arguments) {
return new OtpErlangTuple(arguments);
}
public static OtpErlangObject makeErlangKey(final String tag,
final IntKey key, final OtpErlangObject nodeId) {
return makeErlangTuple(new OtpErlangAtom(tag),
new OtpErlangInt(key.key()), nodeId);
}
Object java_value_from_erlang(final OtpErlangObject value) throws Exception {
if (value instanceof OtpErlangAtom) {
final String stringValue = ((OtpErlangAtom) value).atomValue();
if (stringValue.equals("null")) {
return null;
}
if (stringValue.equals("true")) {
return new Boolean(true);
}
if (stringValue.equals("false")) {
return new Boolean(false);
}
if (logger.isLoggable(Level.WARNING))
logger.log(Level.WARNING,"java_value_from_erlang: " + value);
throw new Exception();
}
if (value instanceof OtpErlangTuple) {
OtpErlangTuple t = (OtpErlangTuple) value;
final int arity = t.arity();
if (arity == 2) {
final OtpErlangObject arg = t.elementAt(1);
if (t.elementAt(0) instanceof OtpErlangAtom) {
final String classSpecifier = ((OtpErlangAtom) t
.elementAt(0)).atomValue();
if (classSpecifier.equals("int")) {
return convert_to_integer(arg);
} else if (classSpecifier.equals("long")) {
return convert_to_long(arg);
} else if (classSpecifier.equals("short")) {
return convert_to_short(arg);
} else if (classSpecifier.equals("char")) {
return convert_to_character(arg);
} else if (classSpecifier.equals("byte")) {
return convert_to_byte(arg);
} else if (classSpecifier.equals("float")) {
return convert_to_float(arg);
} else if (classSpecifier.equals("double")) {
return convert_to_double(arg);
}
} else {
t = (OtpErlangTuple) t.elementAt(0);
final String classSpecifier = ((OtpErlangAtom) t
.elementAt(0)).atomValue();
if (classSpecifier.equals("array")) {
final Class comp = (Class) fromErlType(t.elementAt(1));
final int dimensions = ((OtpErlangLong) t.elementAt(2))
.intValue();
final int[] arr_dimensions =
checkDimensions(dimensions, arg);
final Object array = Array.newInstance(comp,
arr_dimensions);
initializeArray(array, arg, comp);
return array;
}
}
} else if (arity == 5) {
final String tag = ((OtpErlangAtom) t.elementAt(0)).atomValue();
if (tag.equals("object")) {
final JavaObjectKey key = objectKeyFromErlang(t);
final JavaObjectEntry entry = fromErlangMap.get(key);
final Object result = entry.object();
if (result == null) {
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE,"\rTranslating " + value);
}
throw new Exception();
}
return result;
} else if (tag.equals("executable")) {
final Object result = accFromErlangMap.get(t);
if (result == null) {
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE,"\rTranslating " + value);
}
throw new Exception();
}
return result;
}
}
}
if (logger.isLoggable(Level.WARNING))
logger.log(Level.WARNING,"java_value_from_erlang: " + value);
throw new Exception();
}
Object[] java_values_from_erlang(final OtpErlangObject[] values,
final Type[] types) throws Exception {
final Object[] objects = new Object[values.length];
for (int i = 0; i < values.length; i++) {
final Object value = java_value_from_erlang(values[i], types[i]);
objects[i] = value;
}
return objects;
}
Object java_value_from_erlang(Object value, final Type type)
throws Exception {
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE,"\rvalue_from_erlang " + value +
" type "+type);
}
if (value instanceof OtpErlangAtom) {
OtpErlangAtom a = (OtpErlangAtom) value;
return java_value_from_erlang(a);
}
if (value instanceof OtpErlangTuple) {
OtpErlangTuple t = (OtpErlangTuple) value;
value = java_value_from_erlang(t);
}
// We have to use type information to interpret the value
if (type == java.lang.Integer.TYPE || type == java.lang.Integer.class) {
return convert_to_integer(value);
} else if (type == java.lang.Long.TYPE || type == java.lang.Long.class) {
return convert_to_long(value);
} else if (type == java.lang.Short.TYPE
|| type == java.lang.Short.class) {
return convert_to_short(value);
} else if (type == java.lang.Character.TYPE
|| type == java.lang.Character.class) {
return convert_to_character(value);
} else if (type == java.lang.Byte.TYPE || type == java.lang.Byte.class) {
return convert_to_byte(value);
} else if (type == java.lang.Float.TYPE
|| type == java.lang.Float.class) {
return convert_to_float(value);
} else if (type == java.lang.Double.TYPE
|| type == java.lang.Double.class) {
return convert_to_double(value);
} else if (type == java.lang.Void.TYPE || type == java.lang.Void.class) {
return convert_to_void(value);
} else if (value instanceof OtpErlangLong) {
return convert_to_integer(value);
} else if (value instanceof OtpErlangDouble) {
return convert_to_double(value);
} else if ((value instanceof OtpErlangString) &&
(type == java.lang.String.class)) {
return ((OtpErlangString) value).stringValue();
} else if ((value instanceof OtpErlangString) &&
(type == java.lang.CharSequence.class)) {
return ((OtpErlangString) value).stringValue();
} else if ((value instanceof OtpErlangList) &&
(type == java.lang.String.class)) {
return ((OtpErlangList) value).stringValue();
} else {
if (type instanceof Class) {
final Class typeClass = (Class) type;
final int dimensions = dimensions(typeClass);
if (logger.isLoggable(Level.FINE)) {
logger.log
(Level.FINE,
"typeClass="+typeClass+
", dimensions="+dimensions+
", value="+value);
}
if (dimensions > 0) {
if (typeClass.isArray()) {
final Class arrElement =
getArrayElementClass(typeClass);
final int[] lengths =
checkDimensions(dimensions, value);
final Object arr =
Array.newInstance(arrElement, lengths);
initializeArray(arr, value, arrElement);
return arr;
} else {
if (logger.isLoggable(Level.FINE)) {
logger.log
(Level.FINE,
"Cannot convert " + value + " to type "
+ typeClass + " dimensions = "+dimensions);
}
throw new Exception();
}
}
return value;
}
if (logger.isLoggable(Level.FINE)) {
logger.log
(Level.FINE,"Cannot convert " + value + " to type "
+ type);
}
throw new Exception();
}
}
static Object convert_to_character(final Object value)
throws Exception {
if (value instanceof OtpErlangLong) {
return ((OtpErlangLong) value).charValue();
} else if (value instanceof Character) {
return value;
}
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE,"\rerror: convert_to_character " + value);
logger.log(Level.FINE,"\rtype is " + value.getClass());
}
throw new Exception();
}
static Object convert_to_byte(final Object value) throws Exception {
if (value instanceof OtpErlangLong) {
return ((OtpErlangLong) value).byteValue();
} else if (value instanceof Byte) {
return value;
}
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE,"\rerror: convert_to_byte " + value);
logger.log(Level.FINE,"\rtype is " + value.getClass());
}
throw new Exception();
}
static Object convert_to_float(final Object value)
throws Exception {
if (value instanceof OtpErlangDouble) {
return ((OtpErlangDouble) value).floatValue();
} else if (value instanceof OtpErlangLong) {
return ((OtpErlangLong) value).longValue();
} else if (value instanceof Float) {
return value;
} else if (value instanceof Long) {
return ((Long) value).floatValue();
} else if (value instanceof Integer) {
return ((Integer) value).floatValue();
} else if (value instanceof Byte) {
return ((Byte) value).floatValue();
} else if (value instanceof Short) {
return ((Short) value).floatValue();
} else if (value instanceof Character) {
return new Float(((Character) value).charValue());
}
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE,"\rerror: convert_to_float " + value);
logger.log(Level.FINE,"\rtype is " + value.getClass());
}
throw new Exception();
}
static Object convert_to_double(final Object value)
throws Exception {
if (value instanceof OtpErlangDouble) {
return ((OtpErlangDouble) value).doubleValue();
} else if (value instanceof OtpErlangLong) {
return ((OtpErlangLong) value).longValue();
} else if (value instanceof Float) {
return ((Float) value).doubleValue();
} else if (value instanceof Long) {
return ((Long) value).floatValue();
} else if (value instanceof Integer) {
return ((Integer) value).doubleValue();
} else if (value instanceof Byte) {
return ((Byte) value).doubleValue();
} else if (value instanceof Short) {
return ((Short) value).doubleValue();
} else if (value instanceof Character) {
return new Double(((Character) value).charValue());
}
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE,"\rerror: convert_to_double " + value);
logger.log(Level.FINE,"\rtype is " + value.getClass());
}
throw new Exception();
}
static Object convert_to_void(final Object value) throws Exception {
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE,"\rerror: convert_to_void " + value);
logger.log(Level.FINE,"\rtype is " + value.getClass());
}
throw new Exception();
}
static Object convert_to_short(final Object value)
throws Exception {
if (value instanceof OtpErlangLong) {
return ((OtpErlangLong) value).shortValue();
} else if (value instanceof Byte) {
return ((Byte) value).shortValue();
} else if (value instanceof Short) {
return value;
}
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE,"\rerror: convert_to_short " + value);
logger.log(Level.FINE,"\rtype is " + value.getClass());
}
throw new Exception();
}
static Object convert_to_integer(final Object value)
throws Exception {
if (value instanceof OtpErlangLong) {
return ((OtpErlangLong) value).intValue();
} else if (value instanceof Integer) {
return value;
} else if (value instanceof Byte) {
return ((Byte) value).intValue();
} else if (value instanceof Short) {
return ((Short) value).intValue();
} else if (value instanceof Character) {
return new Integer(((Character) value).charValue());
}
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE,"\rerror: convert_to_integer " + value);
logger.log(Level.FINE,"\rtype is " + value.getClass());
}
throw new Exception();
}
static Object convert_to_long(final Object value) throws Exception {
if (value instanceof OtpErlangLong) {
return ((OtpErlangLong) value).longValue();
} else if (value instanceof Long) {
return value;
} else if (value instanceof Integer) {
return ((Integer) value).longValue();
} else if (value instanceof Byte) {
return ((Byte) value).longValue();
} else if (value instanceof Short) {
return ((Short) value).longValue();
} else if (value instanceof Character) {
return new Long(((Character) value).charValue());
}
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE,"\rerror: convert_to_long " + value);
logger.log(Level.FINE,"\rtype is " + value.getClass());
}
throw new Exception();
}
static Object[] elements(final Object t) throws Exception {
if (t instanceof OtpErlangList) {
return ((OtpErlangList) t).elements();
} else if (t instanceof OtpErlangString) {
// Jinterface braindamage follows...
final String value = ((OtpErlangString) t).stringValue();
final byte[] bytes = value.getBytes();
final OtpErlangObject[] otpBytes =
new OtpErlangObject[bytes.length];
for (int i = 0; i < bytes.length; i++) {
otpBytes[i] = new OtpErlangLong(bytes[i]);
}
return otpBytes;
} else if (t.getClass().isArray()) {
Object arr[] = new Object[Array.getLength(t)];
for (int i=0; i<arr.length; i++)
arr[i] = Array.get(t,i);
return arr;
} else {
throw new Exception();
}
}
void initializeArray(final Object arr, final Object value, Class objClass)
throws Exception {
final int len = Array.getLength(arr);
final Object[] elements = elements(value);
for (int i = 0; i < len; i++) {
final Object element = elements[i];
final Object obj_at_i = Array.get(arr, i);
if (objClass.isArray()) {
initializeArray(obj_at_i, element, objClass);
} else {
final Class arrElement = getArrayElementClass(objClass);
final Object setValue = java_value_from_erlang(element,
arrElement);
Array.set(arr, i, setValue);
}
}
}
static Class getArrayElementClass(final Class arrClass) {
if (arrClass.isArray()) {
return getArrayElementClass(arrClass.getComponentType());
} else {
return arrClass;
}
}
static int[] checkDimensions(int dimensions, final Object value)
throws Exception
{
final ArrayList<Integer> result = new ArrayList<Integer>();
while (dimensions > 0) {
final Object[] elements = elements(value);
result.add(elements.length);
dimensions--;
}
final int[] return_value = new int[result.size()];
int i = 0;
for (final Integer ri : result) {
return_value[i++] = ri;
}
return return_value;
}
static int dimensions(final Class arrClass) {
if (arrClass.isArray()) {
return 1 + dimensions(arrClass.getComponentType());
} else {
return 0;
}
}
static Type[] fromErlTypes(final OtpErlangObject[] erlTypes)
throws Exception {
final int len = erlTypes.length;
// logger.log(Level.FINER,"\rfromErlTypes(len="+len+")");
final Type types[] = new Type[len];
for (int i = 0; i < len; i++) {
types[i] = fromErlType(erlTypes[i]);
}
return types;
}
static Type fromErlType(final OtpErlangObject erlType) throws Exception {
if (erlType instanceof OtpErlangAtom) {
final String name = ((OtpErlangAtom) erlType).atomValue();
if (name.equals("int")) {
return java.lang.Integer.TYPE;
} else if (name.equals("short")) {
return java.lang.Short.TYPE;
} else if (name.equals("long")) {
return java.lang.Long.TYPE;
} else if (name.equals("char")) {
return java.lang.Character.TYPE;
} else if (name.equals("boolean")) {
return java.lang.Boolean.TYPE;
} else if (name.equals("byte")) {
return java.lang.Byte.TYPE;
} else if (name.equals("float")) {
return java.lang.Float.TYPE;
} else if (name.equals("double")) {
return java.lang.Double.TYPE;
} else if (name.equals("void")) {
return java.lang.Void.TYPE;
} else {
return findClass(name);
}
} else if (erlType instanceof OtpErlangTuple) {
final OtpErlangTuple t = (OtpErlangTuple) erlType;
final OtpErlangAtom a = (OtpErlangAtom) t.elementAt(0);
if (a.atomValue().equals("array")) {
final Class comp = (Class) fromErlType(t.elementAt(1));
int ndimensions = 1;
if (t.arity() == 3) {
ndimensions = ((OtpErlangLong) t.elementAt(2)).intValue();
}
final int[] dimensions = new int[ndimensions];
for (int i = 0; i < ndimensions; i++) {
dimensions[i] = 0;
}
final Object array = Array.newInstance(comp, dimensions);
final Class arrayClass = array.getClass();
return arrayClass;
}
}
if (logger.isLoggable(Level.WARNING))
logger.log(Level.WARNING,"\rtype " + erlType + " is not understood?");
throw new Exception();
}
Class findClass(final OtpErlangObject classRef) throws Exception {
if (classRef instanceof OtpErlangAtom) {
final String className = ((OtpErlangAtom) classRef).atomValue();
return findClass(className);
} else {
Class cl = (Class) java_value_from_erlang(classRef);
return cl;
}
}
static Class findClass(final String className) throws Exception {
try {
final Class c = Class.forName(className);
return c;
} catch (final Exception e) { }
final StringBuilder str = new StringBuilder(className);
do {
final int lastIndex = str.lastIndexOf(".");
if (lastIndex == -1) {
if (logger.isLoggable(Level.WARNING))
logger.log
(Level.WARNING,
"findClass: cannot locate class " + str +
" using classpath\n"+System.getProperty("java.class.path")+
"\nworking directory is "+System.getProperty("user.dir"));
if (logger.isLoggable(Level.WARNING)) {
logger.log(Level.WARNING,"findClass: cannot locate class " + str);
}
throw new Exception();
}
str.replace(lastIndex, lastIndex + 1, "$");
try {
final Class c = Class.forName(str.toString());
return c;
} catch (final Exception exc) { }
} while (true);
}
public OtpErlangObject makeErlangObjectKey(final long key, final long counter, final long classNumber, final OtpErlangObject nodeId) {
return makeErlangTuple
(new OtpErlangAtom("object"),
new OtpErlangLong(key),
new OtpErlangLong(counter),
new OtpErlangLong(classNumber),
nodeId);
}
public synchronized OtpErlangObject map_to_erlang(final Object obj) {
if (obj == null) {
return map_to_erlang_null();
}
final RefEqualsObject obj_key =
new RefEqualsObject(obj);
final JavaObjectEntry oldValue =
toErlangMap.get(obj_key);
if (oldValue != null) {
long refCount = oldValue.alias();
if (logger.isLoggable(Level.INFO))
logger.log
(Level.INFO,
"increasing count for "+
System.identityHashCode(oldValue.object()));
return makeErlangObjectKey
(oldValue.key(),refCount,oldValue.classNumber(), oldValue.nodeId());
}
final int newCounter = objCounter++;
Class cl = obj.getClass();
Integer classNumber = classMap.get(cl);
if (classNumber == null) {
classNumber = classCounter;
classMap.put(cl,classCounter++);
}
final JavaObjectEntry entry =
new JavaObjectEntry(obj, newCounter, classNumber, nodeIdentifier);
if (logger.isLoggable(Level.INFO))
logger.log
(Level.INFO,
"returning new object "+
System.identityHashCode(entry.object()));
toErlangMap.put(obj_key, entry);
final JavaObjectKey key =
new JavaObjectKey(newCounter,nodeIdentifier);
fromErlangMap.put(key, entry);
long refCount = entry.alias();
return makeErlangObjectKey(key.key(), refCount, entry.classNumber(), key.nodeId());
}
public synchronized OtpErlangObject acc_map_to_erlang(final Object obj) {
final Object obj_key = obj;
final OtpErlangObject oldValue = accToErlangMap.get(obj_key);
if (oldValue != null) {
return oldValue;
}
final IntKey key = new IntKey(accCounter++);
final OtpErlangObject erlangKey = makeErlangKey("executable", key,
nodeIdentifier);
accToErlangMap.put(obj_key, erlangKey);
accFromErlangMap.put(erlangKey, obj);
return erlangKey;
}
synchronized OtpErlangObject map_new_thread_to_erlang(final ThreadMsgHandler th) {
final IntKey key = new IntKey(threadCounter++);
final OtpErlangObject erlangKey = makeErlangKey("thread", key,
nodeIdentifier);
threadMap.put(erlangKey, th);
return erlangKey;
}
public OtpErlangObject map_to_erlang(final Object obj, final Class classType)
throws Exception {
if (classType == java.lang.Integer.TYPE) {
return map_to_erlang_int(((Integer) obj).intValue());
} else if (classType == java.lang.Short.TYPE) {
return map_to_erlang_short(((Short) obj).shortValue());
} else if (classType == java.lang.Long.TYPE) {
return map_to_erlang_long(((Long) obj).longValue());
} else if (classType == java.lang.Byte.TYPE) {
return map_to_erlang_byte(((Byte) obj).byteValue());
} else if (classType == java.lang.Boolean.TYPE) {
return map_to_erlang_boolean(((Boolean) obj).booleanValue());
} else if (classType == java.lang.Character.TYPE) {
return map_to_erlang_character(((Character) obj).charValue());
} else if (classType == java.lang.Float.TYPE) {
return map_to_erlang_float(((Float) obj).floatValue());
} else if (classType == java.lang.Double.TYPE) {
return map_to_erlang_double(((Double) obj).doubleValue());
} else if (classType == java.lang.Void.TYPE) {
return map_to_erlang_void();
} else {