KickJava   Java API By Example, From Geeks To Geeks.

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


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 RandomDataGenerator extends Object JavaDoc {
38
39     // variables ................................................................
40

41     // extent in which random data are generated
42
private RefPackage target;
43     // maximal number of instances that should be generated per one class proxy
44
private int maxInstancesPerClass;
45     // used random generator
46
private Random random = new Random ();
47         
48     protected ElementsCache elementsCache;
49     
50     // stores the number of created instaces
51
private int instancesCounter = 0;
52     // stores all currently processed packages (see generateUniformly() method)
53
private HashMap trackedPackages = new HashMap ();
54     
55     // init .....................................................................
56

57     public RandomDataGenerator () {
58     }
59     
60     public RandomDataGenerator (RefPackage pkg) {
61         elementsCache = new ElementsCache (pkg);
62     }
63     
64     // methods ..................................................................
65

66     /**
67      * Generates random data in given extent.
68      *
69      * @param target extent
70      * @param randSeed value to initialize random generator with
71      * @param max maximal number of instances that should be generated per one class proxy
72      */

73     public void generate (RefPackage target, long randSeed, int max) {
74         random.setSeed (randSeed);
75         this.target = target;
76         this.maxInstancesPerClass = max;
77         elementsCache = new ElementsCache (target);
78         generateUniformly (target);
79     }
80     
81     public void generateUniformly (RefPackage target) {
82         if (trackedPackages.get (target) != null)
83             return;
84         trackedPackages.put (target, target);
85         System.out.println("package: " + target);
86         Iterator iter = target.refAllClasses ().iterator ();
87         while (iter.hasNext ()) {
88             RefClass proxy = (RefClass) iter.next ();
89             MofClass metaClass = (MofClass) proxy.refMetaObject ();
90             System.out.println ("class: " + metaClass.getName ());
91             if (!metaClass.isAbstract ()) {
92                 int count = 1 + random.nextInt (maxInstancesPerClass);
93                 for (int x = 0; x < count; x++)
94                     generateInstance (metaClass);
95             } // if
96
} // while
97
iter = target.refAllAssociations ().iterator ();
98         while (iter.hasNext ()) {
99             RefAssociation proxy = (RefAssociation) iter.next ();
100             int count = 1 + random.nextInt (2 * maxInstancesPerClass / 3);
101             generateAssociation (proxy, count);
102         } // while
103
iter = target.refAllPackages ().iterator ();
104         while (iter.hasNext ())
105             generateUniformly ((RefPackage) iter.next ());
106     }
107     
108     public RefStruct generateStructure (StructureType type) {
109         List fields = elementsCache.structureFields (type);
110         List values = new LinkedList ();
111         Iterator iter = fields.iterator ();
112         while (iter.hasNext ()) {
113             StructureField field = (StructureField) iter.next ();
114             Classifier fieldType = field.getType ();
115             values.add (generateValue (fieldType));
116         }
117         RefBaseObject proxy = elementsCache.findProxy (type);
118         if (proxy instanceof RefClass)
119             return ((RefClass) proxy).refCreateStruct (type, values);
120         else
121             return ((RefPackage) proxy).refCreateStruct (type, values);
122     }
123     
124     public Collection generateCollection (CollectionType colType) {
125         Classifier type = colType.getType ();
126         MultiplicityType mul = colType.getMultiplicity ();
127         int upper = mul.getUpper ();
128         int lower = mul.getLower ();
129         int num;
130         if (lower > 0)
131             num = lower + random.nextInt (5);
132         else
133             num = 3 + random.nextInt (5);
134         if ((upper > 0) && (num > upper))
135             num = upper;
136         List values = new LinkedList ();
137         for (int x = 0; x < num; x++)
138             values.add (generateValue (type));
139         return values;
140     }
141     
142     public RefEnum generateEnumeration (EnumerationType type) {
143         List labels = type.getLabels ();
144         int index = random.nextInt (labels.size ());
145         RefBaseObject proxy = elementsCache.findProxy (type);
146         if (proxy instanceof RefClass)
147             return ((RefClass) proxy).refGetEnum (type, (String JavaDoc) labels.get (index));
148         else
149             return ((RefPackage) proxy).refGetEnum (type, (String JavaDoc) labels.get (index));
150     }
151     
152     public Object JavaDoc generatePrimitive (PrimitiveType type) {
153         String JavaDoc typeName = type.getName ();
154         if (XmiConstants.BOOLEAN_TYPE.equals (typeName))
155             return random.nextBoolean () ? Boolean.TRUE : Boolean.FALSE;
156         if (XmiConstants.DOUBLE_TYPE.equals (typeName))
157             return new Double JavaDoc (random.nextDouble ());
158         if (XmiConstants.FLOAT_TYPE.equals (typeName))
159             return new Float JavaDoc (random.nextFloat ());
160         if (XmiConstants.INTEGER_TYPE.equals (typeName))
161             return new Integer JavaDoc (random.nextInt ());
162         if (XmiConstants.LONG_TYPE.equals (typeName))
163             return new Long JavaDoc (random.nextLong ());
164         if (XmiConstants.STRING_TYPE.equals (typeName))
165             return generateString ();
166         throw new DebugException ("Unknown type: " + typeName);
167     }
168     
169     public String JavaDoc generateString () {
170         int length = random.nextInt (20);
171         byte [] chars = new byte [length];
172         random.nextBytes (chars);
173         for (int x = 0; x < length; x++)
174             chars [x] = (byte) ('a' + Math.abs (chars [x] % 24)); // convert to alpha characters only
175
return new String JavaDoc (chars);
176     }
177     
178     public Object JavaDoc generateValue (Classifier type) {
179         while (type instanceof AliasType)
180             type = ((AliasType) type).getType ();
181         if (type instanceof MofClass)
182             return generateInstance ((MofClass) type);
183         if (type instanceof PrimitiveType)
184             return generatePrimitive ((PrimitiveType) type);
185         if (type instanceof StructureType)
186             return generateStructure ((StructureType) type);
187         if (type instanceof EnumerationType)
188             return generateEnumeration ((EnumerationType) type);
189         if (type instanceof CollectionType)
190             return generateCollection ((CollectionType) type);
191         throw new DebugException ("Unknown or unsupported type: " + type.getName ());
192     }
193     
194     public RefObject generateInstance (MofClass mofClass) {
195         RefPackage refPackage = (RefPackage) elementsCache.findProxy (mofClass);
196         RefClass proxy = refPackage.refClass (mofClass);
197         List args = new LinkedList ();
198         Iterator iter = elementsCache.instanceAttributes (mofClass).iterator ();
199         while (iter.hasNext ()) {
200             Attribute attr = (Attribute) iter.next ();
201             args.add (generateAttributeValue (attr));
202         } // while
203
instancesCounter++;
204         return proxy.refCreateInstance (args);
205     }
206     
207     public Object JavaDoc generateAttributeValue (Attribute attribute) {
208         MultiplicityType multType = attribute.getMultiplicity ();
209         Classifier type = attribute.getType ();
210         while (type instanceof AliasType)
211             type = ((AliasType) type).getType ();
212         // check, if type is not an abstract class, if so find a suitable descendant
213
if ((type instanceof MofClass) && ((MofClass) type).isAbstract ())
214             type = findSubtype ((MofClass) type);
215         int upper = multType.getUpper ();
216         int lower = multType.getLower ();
217         boolean isMultivalued = upper != 1;
218         
219         if ((lower == 0) && random.nextBoolean ()) {
220             // if the attribute is optional, generate no value with 50% probality
221
return isMultivalued ? new LinkedList () : null;
222         }
223         
224         if (!isMultivalued)
225             return generateValue (type); // [PENDING] it would be better to generate instances of
226
// various subtypes of a given type ...
227
if (upper == -1) upper = lower + 3;
228         int count = lower + random.nextInt (upper - lower + 2);
229         // we limit the nuber of generated values to be between 1 and 10
230
if (count == 0) count = 1;
231         if (count > 10) count = 10;
232         
233         if (multType.isUnique ())
234             count = 1;
235         
236         List values = new LinkedList ();
237         for (int x = 0; x < count; x++)
238             values.add (generateValue (type));
239         return values;
240     }
241
242     public void generateAssociation (RefAssociation proxy, int count) {
243         Association assoc = (Association) proxy.refMetaObject ();
244         if (assoc.isDerived ())
245             return;
246         
247         AssociationEnd endA = null, endB = null;
248         Iterator content = assoc.getContents ().iterator ();
249         while (content.hasNext ()) {
250             Object JavaDoc elem = content.next ();
251             if (elem instanceof AssociationEnd) {
252                 if (endA == null)
253                     endA = (AssociationEnd) elem;
254                 else {
255                     endB = (AssociationEnd) elem;
256                     break;
257                 } // if
258
} // if
259
} // while
260

261         MofClass typeA = findSubtype ((MofClass) endA.getType ());
262         MofClass typeB = findSubtype ((MofClass) endB.getType ());
263
264         if ((typeA == null) || (typeB == null))
265             return;
266
267         MultiplicityType multA = endA.getMultiplicity ();
268         MultiplicityType multB = endB.getMultiplicity ();
269         int lowerA = Math.max (1, multA.getLower ());
270         int lowerB = Math.max (1, multB.getLower ());
271         int upperA = lowerA + 4;
272         int upperB = lowerB + 4;
273         if (multA.getUpper () != -1)
274             upperA = Math.min (upperA, multA.getUpper ());
275         if (multB.getUpper () != -1)
276             upperB = Math.min (upperB, multB.getUpper ());
277
278         do {
279             int x, y;
280             int countA = lowerA + ((upperA - lowerA > 0) ? random.nextInt (upperA - lowerA) : 0);
281             int countB = lowerB + ((upperB - lowerB > 0) ? random.nextInt (upperB - lowerB) : 0);
282             RefObject [] objA = new RefObject [countA];
283             RefObject [] objB = new RefObject [countB];
284             for (x = 0; x < countA; x++) {
285                 objA [x] = generateInstance (typeA);
286             }
287             for (x = 0; x < countB; x++) {
288                 objB [x] = generateInstance (typeB);
289             }
290             for (x = 0; x < countA; x++)
291                 for (y = 0; y < countB; y++)
292                     proxy.refAddLink (objA[x], objB[y]);
293         } while (--count > 0);
294
295     }
296     
297     public MofClass findSubtype (MofClass mofClass) {
298         if (!mofClass.isAbstract())
299             return mofClass;
300         List list = elementsCache.nonAbstractSubtypes (mofClass);
301         if ((list == null) || (list.size () == 0))
302             return null;
303         int index = random.nextInt (list.size ());
304         return (MofClass) list.get (index);
305     }
306     
307 }
308
Popular Tags