summaryrefslogtreecommitdiffstats
path: root/src/VBox/ExtPacks/VBoxDTrace/onnv/cmd/dtrace/test/tst/common/java_api/src/TestBean.java
blob: dd4a969d435519dbe489596c94c9904e11d042ca (plain)
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
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 *
 * ident	"%Z%%M%	%I%	%E% SMI"
 */

import org.opensolaris.os.dtrace.*;
import java.util.*;
import java.io.*;
import java.beans.*;
import java.lang.reflect.*;

/**
 * Regression test for serialization and XML encoding/decoding.  Tests
 * every Serializable class in the Java DTrace API by creating a dummy
 * instance, writing it to a file, then reading it back in and comparing
 * the string values of the object before and after, as well as
 * verifying object equality before and after if the class overrides the
 * equals() method.
 */
public class TestBean {
    public static final String[] TESTS = new String[] {
	"ExitRecord",
	"AggregationRecord",
	"Aggregation",
	"Tuple",
	"ScalarRecord",
	"KernelStackRecord",
	"LogDistribution",
	"LinearDistribution",
	"Option",
	"ProcessState",
	"ProbeDescription",
	"PrintaRecord",
	"PrintfRecord",
	"ProbeData",
	"Aggregate",
	"UserStackRecord",
	"AvgValue",
	"CountValue",
	"SumValue",
	"MinValue",
	"MaxValue",
	"Error",
	"Drop",
	"InterfaceAttributes",
	"ProgramInfo",
	"ProbeInfo",
	"Probe",
	"Flow",
	"KernelSymbolRecord",
	"UserSymbolRecord",
	"UserSymbolRecord$Value",
	"Program",
	"Program$File",
	"StddevValue"
    };

    static File file;

    static void
    exit(int status)
    {
	System.out.flush();
	System.err.flush();
	System.exit(status);
    }

    public static XMLEncoder
    getXMLEncoder(File file)
    {
        XMLEncoder encoder = null;
        try {
            OutputStream out = new BufferedOutputStream
                    (new FileOutputStream(file));
            encoder = new XMLEncoder(out);
        } catch (Exception e) {
	    e.printStackTrace();
	    exit(1);
        }
        return encoder;
    }

    public static XMLDecoder
    getXMLDecoder(File file)
    {
        return getXMLDecoder(file, null);
    }

    public static XMLDecoder
    getXMLDecoder(File file, ExceptionListener exceptionListener)
    {
        XMLDecoder decoder = null;
        try {
            InputStream in = new BufferedInputStream
                    (new FileInputStream(file));
            decoder = new XMLDecoder(in, null, exceptionListener);
        } catch (Exception e) {
	    e.printStackTrace();
	    exit(1);
        }
        return decoder;
    }

    public static ExitRecord
    getExitRecord()
    {
	ExitRecord r = new ExitRecord(1);
	return r;
    }

    public static AggregationRecord
    getAggregationRecord()
    {
	Tuple tuple = getTuple();
	AggregationValue value = new CountValue(7);
	AggregationRecord r = new AggregationRecord(tuple, value);
	return r;
    }

    public static Aggregation
    getAggregation()
    {
	List < AggregationRecord > list =
	    new ArrayList < AggregationRecord > ();
	AggregationRecord r;
	r = getAggregationRecord();
	list.add(r);

	ValueRecord v1 = new ScalarRecord(new byte[] {(byte)1, (byte)2,
	    (byte)3}, 3);
	ValueRecord v2 = new ScalarRecord("shebang!", 256);
	Tuple tuple = new Tuple(v1, v2);
	AggregationValue value = getLinearDistribution();
	r = new AggregationRecord(tuple, value);
	list.add(r);

	Aggregation a = new Aggregation("counts", 2, list);
	return a;
    }

    public static Tuple
    getTuple()
    {
	ValueRecord r1 = new ScalarRecord("cat", 256);
	ValueRecord r2 = new ScalarRecord(new Integer(9), 2);
	ValueRecord r3 = new KernelStackRecord(
		new StackFrame[] {
		    new StackFrame("has"),
		    new StackFrame("nine"),
		    new StackFrame("lives")},
		new byte[] { (byte)0, (byte)1, (byte)2 });
	ValueRecord r4 = new ScalarRecord(new byte[] {(byte)1, (byte)2,
	    (byte)3}, 3);

	Tuple tuple = new Tuple(r1, r2, r3, r4);
	return tuple;
    }

    public static ScalarRecord
    getScalarRecord()
    {
	Object v = new byte[] {(byte)1, (byte)2, (byte)3};
	ScalarRecord r = new ScalarRecord(v, 3);
	return r;
    }

    public static KernelStackRecord
    getKernelStackRecord()
    {
	StackFrame[] stackFrames = new StackFrame[] {
	    new StackFrame("Frame 1"),
	    new StackFrame("Frame 2"),
	    new StackFrame("Frame 3")
	};
	KernelStackRecord r = new KernelStackRecord(stackFrames,
		new byte[] { (byte)0, (byte)1, (byte)2 });
	return r;
    }

    public static LogDistribution
    getLogDistribution()
    {
	List < Distribution.Bucket > buckets =
		new ArrayList < Distribution.Bucket > ();
	Distribution.Bucket bucket;
	int n = 0;
	long base = 0;
	long i;
	long sign;
	long nextSign;
	long power;
	long nextPower;
	long lowerBound;
	long upperBound;
	for (i = -62; i <= 62; ++i) {
	    if (i == 0) {
		bucket = new Distribution.Bucket(-1, -1, n++);
		buckets.add(bucket);
		bucket = new Distribution.Bucket(0, 0, n++);
		buckets.add(bucket);
		bucket = new Distribution.Bucket(1, 1, n++);
		buckets.add(bucket);
		continue;
	    }
	    sign = ((i < 0) ? -1L : 1L);
	    power = (sign * i);
	    nextSign = (((i + 1) < 0) ? -1L : 1L);
	    nextPower = (nextSign * (i + 1));
	    lowerBound = sign * ((long) Math.pow(2L, power));
	    upperBound = (nextPower == 0 ? -2L :
		    (nextSign * ((long) Math.pow(2L, nextPower))) - 1);
	    if ((upperBound > 0) && ((upperBound * 2L) < 0)) {
		upperBound = Long.MAX_VALUE;
	    }
	    bucket = new Distribution.Bucket(lowerBound, upperBound, n++);
	    buckets.add(bucket);
	}
	LogDistribution d = new LogDistribution(buckets);
	return d;
    }

    public static LinearDistribution
    getLinearDistribution()
    {
	List < Distribution.Bucket > buckets =
		new ArrayList < Distribution.Bucket > ();
	Distribution.Bucket bucket;
	int n = 10; // number of buckets
	int base = 1;
	int step = 10;
	bucket = new Distribution.Bucket(Long.MIN_VALUE, (base - 1), 0);
	buckets.add(bucket);
	for (int i = base; i < (n * step); i += step) {
	    bucket = new Distribution.Bucket(i, (i + (step - 1)),
		    ((i - 1) / step));
	    buckets.add(bucket);
	}
	bucket = new Distribution.Bucket((n * step) + 1, Long.MAX_VALUE, 0);
	buckets.add(bucket);
	LinearDistribution d = new LinearDistribution(base, step, buckets);
	return d;
    }

    public static Option
    getOption()
    {
	Option option = new Option("aggrate", "1s");
	return option;
    }

    public static ProcessState
    getProcessState()
    {
	ProcessState p = new ProcessState(123456, "UNDEAD",
		3, "SIGSTOP",
		-2, "Process stopped on dime");
	return p;
    }

    public static ProbeDescription
    getProbeDescription()
    {
	ProbeDescription d = new ProbeDescription(256, "syscall", null,
	    "malloc", "entry");
	return d;
    }

    public static PrintaRecord
    getPrintaRecord()
    {
	List < Aggregation > aggregations = new ArrayList < Aggregation > ();
	Aggregation a = getAggregation();
	aggregations.add(a);
	aggregations.add(a);
	Map < Tuple, String > formattedOutput =
		new HashMap < Tuple, String > ();
	for (Tuple t : a.asMap().keySet()) {
	    formattedOutput.put(t, "cat");
	}
	List < Tuple > tuples = new ArrayList < Tuple > ();
	for (Tuple t : a.asMap().keySet()) {
	    tuples.add(t);
	}
	Collections.sort(tuples);
	PrintaRecord r = new PrintaRecord(1234567890L,
	    aggregations, formattedOutput, tuples,
	    "Yes, this is the formatted printa() output");
	return r;
    }

    public static PrintfRecord
    getPrintfRecord()
    {
	List < ValueRecord > list = new ArrayList < ValueRecord > ();
	ValueRecord v1 = getScalarRecord();
	ValueRecord v2 = new ScalarRecord(new Integer(7), 4);
	list.add(v1);
	list.add(v2);
	PrintfRecord r = new PrintfRecord(list,
		"long formatted string");
	return r;
    }

    public static ProbeData
    getProbeData()
    {
	List < Record > list = new ArrayList < Record > ();
	list.add(getPrintaRecord());
	list.add(getPrintfRecord());
	list.add(getScalarRecord());
	list.add(getUserSymbolRecord());
	list.add(getUserStackRecord());
	list.add(getExitRecord());
	ProbeData d = new ProbeData(7, 1, getProbeDescription(),
	    getFlow(), list);
	return d;
    }

    public static Aggregate
    getAggregate()
    {
	List < Aggregation > list = new ArrayList < Aggregation > ();
	list.add(getAggregation());

	List < AggregationRecord > reclist =
	    new ArrayList < AggregationRecord > ();
	AggregationRecord r;
	ValueRecord v1 = new ScalarRecord("cat", 256);
	ValueRecord v2 = new ScalarRecord("dog", 256);
	ValueRecord v3 = new ScalarRecord("mouse", 256);
	ValueRecord v4 = new ScalarRecord("mouse", 256);
	ValueRecord v5 = new ScalarRecord(new Byte((byte) 'C'), 1);
	ValueRecord v6 = new ScalarRecord(new Short((short) 7), 2);
	Tuple tuple = new Tuple(v1, v2, v3, v4, v5, v6);
	AggregationValue value = getCountValue();
	r = new AggregationRecord(tuple, value);
	reclist.add(r);
	list.add(new Aggregation("times", 1, reclist));

        Aggregate a = new Aggregate(1234567890L, list);
	return a;
    }

    public static UserStackRecord
    getUserStackRecord()
    {
	StackFrame[] frames = new StackFrame[] {
	    new StackFrame("User Stack Frame 1"),
	    new StackFrame("User Stack Frame 2"),
	    new StackFrame("User Stack Frame 3")
	};
	UserStackRecord r = new UserStackRecord(123456, frames,
		new byte[] { (byte)0, (byte)1, (byte)2 });
	return r;
    }

    public static AvgValue
    getAvgValue()
    {
	AvgValue v = new AvgValue(5, 20, 4);
	return v;
    }

    public static CountValue
    getCountValue()
    {
	CountValue v = new CountValue(9);
	return v;
    }

    public static MinValue
    getMinValue()
    {
	MinValue v = new MinValue(101);
	return v;
    }

    public static MaxValue
    getMaxValue()
    {
	MaxValue v = new MaxValue(101);
	return v;
    }

    public static SumValue
    getSumValue()
    {
	SumValue v = new SumValue(25);
	return v;
    }

    public static org.opensolaris.os.dtrace.Error
    getError()
    {
	ProbeDescription probe = getProbeDescription();
	org.opensolaris.os.dtrace.Error e =
	    new org.opensolaris.os.dtrace.Error(probe, 8, 3,
	    1, 20, "DTRACEFLT_BADALIGN", -1, "error on enabled probe ID 8 " +
	    "(ID " + probe.getID() + ": " + probe + "): Bad alignment " +
	    "(0x33ef) in action #1 at DIF offset 20");
	return e;
    }

    public static Drop
    getDrop()
    {
	Drop drop = new Drop(2, "SPECBUSY", 72, 1041,
	    "Guess we dropped stuff all over the place.");
	return drop;
    }

    public static InterfaceAttributes
    getInterfaceAttributes()
    {
	InterfaceAttributes a = new InterfaceAttributes(
                InterfaceAttributes.Stability.UNSTABLE,
                InterfaceAttributes.Stability.EVOLVING,
                InterfaceAttributes.DependencyClass.ISA);
	return a;
    }

    public static ProgramInfo
    getProgramInfo()
    {
	ProgramInfo info = new ProgramInfo(getInterfaceAttributes(),
		getInterfaceAttributes(), 256);
	return info;
    }

    public static ProbeInfo
    getProbeInfo()
    {
	ProbeInfo info = new ProbeInfo(getInterfaceAttributes(),
		getInterfaceAttributes());
	return info;
    }

    public static Probe
    getProbe()
    {
	Probe p = new Probe(getProbeDescription(), getProbeInfo());
	return p;
    }

    public static Flow
    getFlow()
    {
	Flow f = new Flow(Flow.Kind.RETURN.name(), 3);
	return f;
    }

    public static KernelSymbolRecord
    getKernelSymbolRecord()
    {
	KernelSymbolRecord r = new KernelSymbolRecord("mod`func+0x4", -1L);
	return r;
    }

    public static UserSymbolRecord
    getUserSymbolRecord()
    {
	UserSymbolRecord r = new UserSymbolRecord(7, "mod`func+0x4", -1L);
	return r;
    }

    public static UserSymbolRecord.Value
    getUserSymbolRecord$Value()
    {
	UserSymbolRecord.Value v = new UserSymbolRecord.Value(7, -1L);
	return v;
    }

    public static Program
    getProgram()
    {
	final String PROGRAM = "syscall:::entry { @[execname] = count(); }";
	Consumer consumer = new LocalConsumer();
	Program p;
	try {
	    consumer.open();
	    p = consumer.compile(PROGRAM);
	    consumer.close();
	} catch (DTraceException e) {
	    e.printStackTrace();
	    p = null;
	}
	return p;
    }

    public static Program.File
    getProgram$File()
    {
	final String PROGRAM = "syscall:::entry { @[execname] = count(); }";
	Consumer consumer = new LocalConsumer();
	Program p;
	try {
            OutputStream out = new FileOutputStream(file);
	    out.write(PROGRAM.getBytes(), 0, PROGRAM.length());
	    out.flush();
	    out.close();
	    consumer.open();
	    p = consumer.compile(file);
	    consumer.close();
	} catch (Exception e) {
	    e.printStackTrace();
	    p = null;
	}
	return Program.File.class.cast(p);
    }

    public static StddevValue
    getStddevValue()
    {
	StddevValue v = new StddevValue(37, 114, 5, Integer.toString(9544));
	return v;
    }

    @SuppressWarnings("unchecked")
    static String
    getString(Object o)
    {
	String s;
	if (o instanceof ScalarRecord) {
	    o = ((ScalarRecord)o).getValue();
	}

	if (o instanceof byte[]) {
	    s = Arrays.toString((byte[])o);
	} else if (o instanceof Object[]) {
	    s = Arrays.toString((Object[])o);
	} else {
	    Class c = o.getClass();
	    try {
		Method m = c.getDeclaredMethod("toLogString");
		s = (String)m.invoke(o);
	    } catch (Exception e) {
		s = o.toString();
	    }
	}
	return s;
    }

    static void
    checkEquality(Object obj, Object newobj)
    {
	// If the class overrides equals(), make sure the re-created
	// object still equals the original object
	try {
	    Method eq = obj.getClass().getDeclaredMethod("equals",
		    Object.class);
	    Boolean ret = (Boolean) eq.invoke(obj, newobj);
	    if (ret != true) {
		System.err.println("serialization failed: " +
			obj.getClass().getName());
		exit(1);
	    }
	} catch (Exception e) {
	    // Does not override equals(), although a super-class might.
	    // A better test would check for any superclass other than
	    // Object.class.
	}
    }

    static void
    performSerializationTest(File file, String classname)
            throws IOException, ClassNotFoundException
    {
	String methodName = "get" + classname;
	Object obj = null;
	Object newobj = null;
	try {
	    Method method = TestBean.class.getDeclaredMethod(methodName);
	    obj = method.invoke(null);
	} catch (Exception e) {
	    e.printStackTrace();
	    exit(1);
	}

	System.out.println(classname + ":");
	String serialized = getString(obj);
	System.out.println("  serialized: " + serialized);
	FileOutputStream fos = new FileOutputStream(file);
	ObjectOutputStream out = new ObjectOutputStream(fos);
	out.writeObject(obj);
	out.close();
	FileInputStream fis = new FileInputStream(file);
	ObjectInputStream in = new ObjectInputStream(fis);
	newobj = in.readObject();
	in.close();
	String deserialized = getString(newobj);
	System.out.println("  deserialized: " + deserialized);

	if (!serialized.equals(deserialized)) {
	    System.err.println("serialization failed: " + classname);
	    exit(1);
	}
	checkEquality(obj, newobj);
    }

    static void
    performBeanTest(File file, String classname)
    {
	String methodName = "get" + classname;
	Object obj = null;
	Object newobj = null;
	try {
	    Method method = TestBean.class.getDeclaredMethod(methodName);
	    obj = method.invoke(null);
	} catch (Exception e) {
	    e.printStackTrace();
	    exit(1);
	}

	Class c = obj.getClass();
	if (c.getConstructors().length == 0) {
	    return;
	}

	System.out.println(classname + ":");
	XMLEncoder encoder = getXMLEncoder(file);
	String encoded = getString(obj);
	System.out.println("  encoded: " + encoded);
	encoder.writeObject(obj);
	encoder.close();
	XMLDecoder decoder = getXMLDecoder(file);
	newobj = decoder.readObject();
	String decoded = getString(newobj);
	System.out.println("  decoded: " + decoded);
	decoder.close();

	if (!encoded.equals(decoded)) {
	    System.err.println("bean persistence failed: " + classname);
	    exit(1);
	}
	checkEquality(obj, newobj);
    }

    public static void
    main(String[] args)
    {
	if ((args.length != 1) && (args.length != 2)) {
	    System.err.println("usage: java TestBean < filename > " +
		    "[ < classname > ]");
	    exit(1);
	}

	String filename = args[0];
	String classname = null;
	if (args.length >= 2) {
	    classname = args[1];
	}

	file = new File(filename);
	try {
	    if (!file.canRead()) {
		try {
		    file.createNewFile();
		} catch (Exception e) {
		    System.err.println("failed to create " + filename);
		    exit(1);
		}
	    }
	} catch (SecurityException e) {
	    System.err.println("failed to open " + filename);
	    exit(1);
	}

	String[] tests = (classname == null ? TESTS:
		new String[] { classname });
	try {
	    for (int i = 0; i < tests.length; ++i) {
		performSerializationTest(file, tests[i]);
		performBeanTest(file, tests[i]);
	    }
	} catch (IOException e) {
	    e.printStackTrace();
	    exit(1);
	} catch (ClassNotFoundException e) {
	    e.printStackTrace();
	    exit(1);
	}
    }
}