1 19 20 package org.netbeans.lib.lexer.test; 21 22 import java.util.Random ; 23 24 public class RandomTextProvider { 25 26 private static final RandomCharDescriptor[] EMPTY_DESCRIPTORS = {}; 27 28 private static final FixedTextDescriptor[] EMPTY_FIXED_TEXTS = {}; 29 30 private RandomCharDescriptor[] randomCharDescriptors; 31 32 private FixedTextDescriptor[] fixedTexts; 33 34 private double ratioSum; 35 36 private double fixedTextsRatioSum; 37 38 public RandomTextProvider(RandomCharDescriptor[] randomCharDescriptors) { 39 this(randomCharDescriptors, null); 40 } 41 42 public RandomTextProvider(RandomCharDescriptor[] randomCharDescriptors, 43 FixedTextDescriptor[] fixedTexts) { 44 if (randomCharDescriptors == null) { 45 randomCharDescriptors = EMPTY_DESCRIPTORS; 46 } 47 if (fixedTexts == null) { 48 fixedTexts = EMPTY_FIXED_TEXTS; 49 } 50 this.randomCharDescriptors = randomCharDescriptors; 51 this.fixedTexts = fixedTexts; 52 53 for (int i = 0; i < randomCharDescriptors.length; i++) { 55 ratioSum += randomCharDescriptors[i].ratio(); 56 } 57 for (int i = 0; i < fixedTexts.length; i++) { 58 fixedTextsRatioSum += fixedTexts[i].ratio(); 59 } 60 } 61 62 public char randomChar(Random random) { 63 double r = random.nextDouble() * ratioSum; 64 for (int i = 0; i < randomCharDescriptors.length; i++) { 65 RandomCharDescriptor descriptor = randomCharDescriptors[i]; 66 if ((r -= descriptor.ratio()) < 0) { 67 return descriptor.randomChar(random); 68 } 69 } 70 throw new IllegalStateException ("No random char descriptions available"); 72 } 73 74 public boolean randomCharAvailable() { 75 return (randomCharDescriptors.length > 0); 76 } 77 78 82 public String randomText(Random random, int maxTextLength) { 83 if (randomCharAvailable()) { 84 int len = random.nextInt(maxTextLength); 85 StringBuilder sb = new StringBuilder (); 86 while (--len >= 0) { 87 sb.append(randomChar(random)); 88 } 89 return sb.toString(); 90 } else { 91 return ""; 92 } 93 } 94 95 public String randomFixedText(Random random) { 96 double r = random.nextDouble() * fixedTextsRatioSum; 97 for (int i = 0; i < fixedTexts.length; i++) { 98 FixedTextDescriptor fixedText = fixedTexts[i]; 99 if ((r -= fixedText.ratio()) < 0) { 100 return fixedText.text(); 101 } 102 } 103 return ""; } 105 106 } | Popular Tags |