KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > mdr > test > RandomDataSupport


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.mdr.test;
21
22 import java.io.*;
23 import java.util.*;
24
25 import org.netbeans.api.mdr.*;
26 import org.openide.util.Lookup;
27 import org.netbeans.lib.jmi.xmi.*;
28 import org.netbeans.lib.jmi.util.*;
29
30 import javax.jmi.reflect.*;
31 import javax.jmi.model.*;
32
33 /**
34  * Generates random data (instances, attribute values, links) in a given package.
35  */

36
37 public class RandomDataSupport extends Object JavaDoc {
38
39     // variables ................................................................
40

41     // used random generator
42
private Random random = new Random ();
43
44     // extent in which random data are generated
45
private RefPackage target;
46     private HashSet trackedPackages = new HashSet();
47
48     // maximal number of instances that should be generated per one class proxy
49
private int maxInstancesPerClass;
50     
51     private RefClass[] allClasses;
52     private RefAssociation[] allAssociations;
53     private ArrayList toDelete;
54
55     // stores the number of created instaces
56
private int instancesCounter = 0;
57     // stores the number of created links
58
private int linksCounter = 0;
59     private int othersCounter = 0;
60
61     private ElementsCache elementsCache;
62
63     private boolean warmUp;
64     private boolean testRun;
65
66     // init .....................................................................
67

68     public RandomDataSupport(RefPackage pkg) {
69         target = pkg;
70         elementsCache = new ElementsCache (target);
71         prepareAllClasses();
72         prepareAllAssociations();
73     }
74     
75     // methods ..................................................................
76

77     /**
78      * Generates random objects in given extent.
79      *
80      * @param target extent
81      * @param randSeed value to initialize random generator with
82      * @param max maximal number of instances that should be generated per one class proxy
83      */

84     public void generateObjects (long randSeed, int max, boolean warmUp, boolean testRun) {
85         random.setSeed (randSeed);
86         instancesCounter = 0;
87         this.maxInstancesPerClass = max;
88         this.warmUp = warmUp;
89         this.testRun = testRun;
90         for (int i = 0; i < allClasses.length; i++) {
91             RefClass proxy = allClasses[i];
92             MofClass metaClass = (MofClass) proxy.refMetaObject ();
93             if (!metaClass.isAbstract ()) {
94                 int count = (warmUp ? 1 : 1 + random.nextInt (maxInstancesPerClass));
95                 for (int x = 0; x < count; x++)
96                     generateInstance (metaClass);
97             }
98         }
99     }
100
101     public void modifyObjects (long randSeed, int max, boolean warmUp, boolean testRun) {
102         random.setSeed (randSeed);
103         instancesCounter = 0;
104         this.maxInstancesPerClass = max;
105         this.warmUp = warmUp;
106         this.testRun = testRun;
107         for (int i = 0; i < allClasses.length; i++) {
108             RefClass proxy = allClasses[i];
109             MofClass metaClass = (MofClass) proxy.refMetaObject ();
110             if (!metaClass.isAbstract ()) {
111                 int count = (warmUp ? 1 : 1 + random.nextInt (maxInstancesPerClass));
112                 for (int x = 0; x < count; x++)
113                     modifyInstance (metaClass);
114             }
115         }
116     }
117     
118     public void prepareAssociationEnds() {
119         for (int i = 0; i < allAssociations.length; i++)
120             elementsCache.associationEndInstances ((Association)allAssociations[i].refMetaObject());
121     }
122
123     
124     /**
125      * Generates random assiciations in given extent.
126      *
127      * @param target extent
128      * @param randSeed value to initialize random generator with
129      * @param max maximal number of instances that should be generated per one class proxy
130      */

131     public void generateAssociations (long randSeed, int max, boolean warmUp, boolean testRun) {
132         random.setSeed (randSeed);
133         instancesCounter = 0;
134         linksCounter = 0;
135         this.maxInstancesPerClass = max;
136         this.warmUp = warmUp;
137         this.testRun = testRun;
138         for (int i = 0; i < allAssociations.length; i++) {
139             RefAssociation assoc = allAssociations[i];
140             Association metaAssoc = (Association) assoc.refMetaObject ();
141             if (!metaAssoc.isAbstract () && !metaAssoc.isDerived ()) {
142                 int count = (warmUp ? 1 : 1 + random.nextInt (maxInstancesPerClass));
143                 for (int x = 0; x < count; x++)
144                     generateAssociation (metaAssoc);
145             }
146         }
147     }
148
149     public void findAllOfClass(int idx) {
150         allClasses[idx].refAllOfClass();
151     }
152     
153     public int iterateAllOfClass(int idx) {
154         int i = 0;
155         for (Iterator it = allClasses[idx].refAllOfClass().iterator(); it.hasNext(); it.next())
156             i++;
157         return i;
158     }
159     
160     public int queryAssociations(long randSeed, int max) {
161         random.setSeed(randSeed);
162         othersCounter = 0;
163         int totalNumOfIter = 0;
164         for (int i = 0; i < allAssociations.length; i++) {
165             RefAssociation assoc = allAssociations[i];
166             if (((Association)assoc.refMetaObject()).isDerived())
167                 continue;
168             int numOfIter = random.nextInt(max);
169             for (int j = 0; j < numOfIter; j++) {
170                 int end = random.nextInt(2);
171                 RefObject[] inst = (RefObject[])elementsCache.associationEndInstances((Association)assoc.refMetaObject()).get(end);
172                 if (inst.length == 0)
173                     continue;
174                 AssociationEnd aEnd = (AssociationEnd)elementsCache.associationEnds((Association)assoc.refMetaObject()).get(end);
175                 if (!aEnd.otherEnd().isNavigable())
176                     continue;
177                 Collection others = assoc.refQuery(aEnd, inst[random.nextInt(inst.length)]);
178                 totalNumOfIter++;
179                 for (Iterator it = others.iterator(); it.hasNext(); it.next())
180                     othersCounter++;
181             }
182         }
183         return totalNumOfIter;
184     }
185     
186     public int prepareObjectsToDelete(long randSeed, int max) {
187         random.setSeed(randSeed);
188         toDelete = new ArrayList();
189         HashSet composites = new HashSet();
190         for (int i = 0; i < allClasses.length; i++) {
191             Collection col = allClasses[i].refAllOfClass();
192             for (Iterator it = col.iterator(); it.hasNext();) {
193                 RefObject next = (RefObject)it.next();
194                 RefFeatured composite = next.refOutermostComposite();
195                 if ((random.nextInt(col.size()) < max) && (!composites.contains(composite))) {
196                     toDelete.add(next);
197                     composites.add(composite);
198                 }
199             }
200         }
201         return toDelete.size();
202     }
203     
204     public void deleteObjects() {
205         for (int i = 0; i < toDelete.size(); i++) {
206             RefObject obj = (RefObject)toDelete.get(i);
207             obj.refDelete();
208         }
209     }
210
211     public int getInstancesCounter() {
212         return instancesCounter;
213     }
214     
215     public int getLinksCounter() {
216         return linksCounter;
217     }
218
219     public int getOthersCounter() {
220         return othersCounter;
221     }
222     
223     public int getNumberOfClasses() {
224         return allClasses.length;
225     }
226     
227     // private methods .........................................................
228

229     private RefStruct generateStructure (StructureType type) {
230         List fields = elementsCache.structureFields (type);
231         List values = new LinkedList ();
232         Iterator iter = fields.iterator ();
233         while (iter.hasNext ()) {
234             StructureField field = (StructureField) iter.next ();
235             Classifier fieldType = field.getType ();
236             values.add (generateValue (fieldType));
237         }
238         RefBaseObject proxy = elementsCache.findProxy (type);
239         if (testRun)
240             return null;
241         if (proxy instanceof RefClass)
242             return ((RefClass) proxy).refCreateStruct (type, values);
243         else
244             return ((RefPackage) proxy).refCreateStruct (type, values);
245     }
246     
247     private RefEnum generateEnumeration (EnumerationType type) {
248         List labels = type.getLabels ();
249         int index = random.nextInt (labels.size ());
250         RefBaseObject proxy = elementsCache.findProxy (type);
251         if (testRun)
252             return null;
253         if (proxy instanceof RefClass)
254             return ((RefClass) proxy).refGetEnum (type, (String JavaDoc) labels.get (index));
255         else
256             return ((RefPackage) proxy).refGetEnum (type, (String JavaDoc) labels.get (index));
257     }
258     
259     private Object JavaDoc generatePrimitive (PrimitiveType type) {
260         String JavaDoc typeName = type.getName ();
261         if (XmiConstants.BOOLEAN_TYPE.equals (typeName))
262             return random.nextBoolean () ? Boolean.TRUE : Boolean.FALSE;
263         if (XmiConstants.DOUBLE_TYPE.equals (typeName))
264             return new Double JavaDoc (random.nextDouble ());
265         if (XmiConstants.FLOAT_TYPE.equals (typeName))
266             return new Float JavaDoc (random.nextFloat ());
267         if (XmiConstants.INTEGER_TYPE.equals (typeName))
268             return new Integer JavaDoc (random.nextInt ());
269         if (XmiConstants.LONG_TYPE.equals (typeName))
270             return new Long JavaDoc (random.nextLong ());
271         if (XmiConstants.STRING_TYPE.equals (typeName))
272             return generateString ();
273         throw new DebugException ("Unknown type: " + typeName);
274     }
275     
276     private String JavaDoc generateString () {
277         int length = random.nextInt (20);
278         byte [] chars = new byte [length];
279         random.nextBytes (chars);
280         for (int x = 0; x < length; x++)
281             chars [x] = (byte) ('a' + Math.abs (chars [x] % 24)); // convert to alpha characters only
282
return new String JavaDoc (chars);
283     }
284     
285     private Object JavaDoc generateValue (Classifier type) {
286         while (type instanceof AliasType)
287             type = ((AliasType) type).getType ();
288         if (type instanceof MofClass)
289             return generateInstance ((MofClass) type);
290         if (type instanceof PrimitiveType)
291             return generatePrimitive ((PrimitiveType) type);
292         if (type instanceof StructureType)
293             return generateStructure ((StructureType) type);
294         if (type instanceof EnumerationType)
295             return generateEnumeration ((EnumerationType) type);
296         throw new DebugException ("Unknown or unsupported type: " + type.getName ());
297     }
298     
299     private RefObject generateInstance (MofClass mofClass) {
300         RefPackage refPackage = (RefPackage) elementsCache.findProxy (mofClass);
301         RefClass proxy = refPackage.refClass (mofClass);
302         List args = new LinkedList ();
303         Iterator iter = elementsCache.instanceAttributes (mofClass).iterator ();
304         while (iter.hasNext ()) {
305             Attribute attr = (Attribute) iter.next ();
306             args.add (generateAttributeValue (attr));
307         } // while
308
instancesCounter++;
309         if (testRun)
310             return null;
311         return proxy.refCreateInstance (args);
312     }
313     
314     private RefObject modifyInstance(MofClass mofClass) {
315         RefObject inst = findInstance(elementsCache.classInstances(mofClass));
316         List list = elementsCache.instanceAttributes (mofClass);
317         if (list.size() > 0) {
318             int idx = random.nextInt(list.size());
319             Attribute attr = (Attribute) list.get (idx);
320             if (attr.isChangeable()) {
321                 Object JavaDoc value = generateAttributeValue (attr);
322                 if (!testRun)
323                     inst.refSetValue(attr, value);
324                 instancesCounter++;
325             }
326         }
327         return inst;
328     }
329
330     private RefObject findInstance (RefObject[] objs) {
331         if (objs == null || objs.length == 0)
332             return null;
333         return objs[random.nextInt(objs.length)];
334     }
335     
336     private Object JavaDoc generateAttributeValue (Attribute attribute) {
337         MultiplicityType multType = attribute.getMultiplicity ();
338         Classifier type = attribute.getType ();
339         while (type instanceof AliasType)
340             type = ((AliasType) type).getType ();
341         // check, if type is not an abstract class, if so find a suitable descendant
342
if ((type instanceof MofClass) && ((MofClass) type).isAbstract ())
343             type = findSubtype ((MofClass) type);
344         int upper = multType.getUpper ();
345         int lower = multType.getLower ();
346         boolean isMultivalued = upper != 1;
347         
348         if ((lower == 0) && random.nextBoolean ()) {
349             // if the attribute is optional, generate no value with 50% probality
350
return isMultivalued ? new LinkedList () : null;
351         }
352         
353         if (!isMultivalued)
354             return generateValue (type); // [PENDING] it would be better to generate instances of
355
// various subtypes of a given type ...
356
if (upper == -1) upper = lower + 3;
357         int count = lower + random.nextInt (upper - lower + 2);
358         // we limit the nuber of generated values to be between 1 and 10
359
if (count == 0) count = 1;
360         if (count > 10) count = 10;
361         List values = new LinkedList ();
362         for (int x = 0; x < count; x++)
363             values.add (generateValue (type));
364         return values;
365     }
366     
367     private MofClass findSubtype (MofClass mofClass) {
368         List list = elementsCache.nonAbstractSubtypes (mofClass);
369         if ((list == null) || (list.size () == 0))
370             throw new DebugException ("Cannot find a non-abstract subtype: " + mofClass.getName ());
371         int index = random.nextInt (list.size ());
372         return (MofClass) list.get (index);
373     }
374     
375     private void generateAssociation (Association mofAssoc) {
376         RefPackage refPackage = (RefPackage) elementsCache.findProxy (mofAssoc);
377         RefAssociation proxy = refPackage.refAssociation (mofAssoc);
378         List ends = elementsCache.associationEnds (mofAssoc);
379         List endInstances = elementsCache.associationEndInstances (mofAssoc);
380         AssociationEnd aEnd = (AssociationEnd) ends.get (0);
381         RefObject obj1 = null;
382         if (aEnd.otherEnd().getAggregation() == AggregationKindEnum.COMPOSITE) {
383             Classifier type = aEnd.getType ();
384             while (type instanceof AliasType)
385                 type = ((AliasType) type).getType ();
386             // check, if type is not an abstract class, if so find a suitable descendant
387
if ((type instanceof MofClass) && ((MofClass) type).isAbstract ())
388                 type = findSubtype ((MofClass) type);
389             obj1 = generateInstance((MofClass)type);
390         }
391         else {
392             obj1 = findInstance((RefObject[])endInstances.get(0));
393             if (obj1 == null)
394                 return;
395             int bound = aEnd.getMultiplicity().getUpper();
396             if (bound != -1 && proxy.refQuery(aEnd, obj1).size() >= bound)
397                 return;
398         }
399         aEnd = (AssociationEnd) ends.get (1);
400         RefObject obj2 = null;
401         if (aEnd.otherEnd().getAggregation() == AggregationKindEnum.COMPOSITE) {
402             Classifier type = aEnd.getType ();
403             while (type instanceof AliasType)
404                 type = ((AliasType) type).getType ();
405             // check, if type is not an abstract class, if so find a suitable descendant
406
if ((type instanceof MofClass) && ((MofClass) type).isAbstract ())
407                 type = findSubtype ((MofClass) type);
408             obj2 = generateInstance((MofClass)type);
409         }
410         else {
411             obj2 = findInstance((RefObject[])endInstances.get(1));
412             if (obj2 == null)
413                 return;
414             int bound = aEnd.getMultiplicity().getUpper();
415             if (bound != -1 && proxy.refQuery(aEnd, obj2).size() >= bound)
416                 return;
417         }
418         if (testRun)
419             return;
420         proxy.refAddLink (obj1, obj2);
421         linksCounter++;
422     }
423
424     private void prepareAllClasses () {
425         trackedPackages.clear();
426         Collection col = findAllClasses (target);
427         allClasses = (RefClass[]) col.toArray(new RefClass[col.size()]);
428     }
429     
430     private Collection findAllClasses (RefPackage target) {
431         if (trackedPackages.contains (target))
432             return null;
433         trackedPackages.add (target);
434         Collection clss = target.refAllClasses ();
435         Iterator iter = target.refAllPackages ().iterator ();
436         while (iter.hasNext ())
437             clss.addAll(findAllClasses ((RefPackage) iter.next ()));
438         return clss;
439     }
440
441     private void prepareAllAssociations () {
442         trackedPackages.clear();
443         Collection col = findAllAssociations (target);
444         allAssociations = (RefAssociation[]) col.toArray(new RefAssociation[col.size()]);
445     }
446     
447     private Collection findAllAssociations (RefPackage target) {
448         if (trackedPackages.contains (target))
449             return null;
450         trackedPackages.add (target);
451         Collection assocs = target.refAllAssociations ();
452         Iterator iter = target.refAllPackages ().iterator ();
453         while (iter.hasNext ())
454             assocs.addAll(findAllAssociations ((RefPackage) iter.next ()));
455         return assocs;
456     }
457
458 }
459
Popular Tags