1 16 17 package org.apache.taglibs.random; 18 19 import java.security.NoSuchAlgorithmException ; 20 import java.security.NoSuchProviderException ; 21 import java.security.SecureRandom ; 22 import java.util.Random ; 23 24 import javax.servlet.jsp.JspException ; 25 26 34 35 public class RandomNum { 36 37 40 private Long randomnum = null; 41 44 private Float randomfloat = null; 45 48 private boolean floatvalue = false; 49 52 private long upper = 100; 53 56 private long lower = 0; 57 60 private String algorithm = null; 61 64 private String provider = null; 65 69 private boolean secure = false; 70 73 private Random random = null; 74 77 private SecureRandom secrandom = null; 78 79 84 private final float getFloat() { 85 if (random == null) 86 return secrandom.nextFloat(); 87 else 88 return random.nextFloat(); 89 } 90 91 96 public final void generateRandomObject() throws JspException { 97 98 if (secure) { 100 try { 101 if (provider != null) 103 secrandom = SecureRandom.getInstance(algorithm, provider); 105 else 106 secrandom = SecureRandom.getInstance(algorithm); 107 } catch (NoSuchAlgorithmException ne) { 108 throw new JspException (ne.getMessage()); 109 } catch (NoSuchProviderException pe) { 110 throw new JspException (pe.getMessage()); 111 } 112 } else 113 random = new Random (); 114 } 115 116 120 private final void generaterandom() { 121 122 int tmprandom = 0; Integer rand; 124 125 if (floatvalue) 127 randomfloat = new Float (getFloat()); 128 else 129 randomnum = new Long (lower + (long) ((getFloat() * (upper - lower)))); 130 } 131 132 141 public final Number getRandom() { 142 143 generaterandom(); 145 if (floatvalue) 146 return randomfloat; 147 else 148 return randomnum; 149 } 150 151 158 public final void setRange(long low, long up) { 159 160 lower = low; 162 upper = up; 163 164 if ((lower == 0) && (upper == 1)) 166 floatvalue = true; 167 } 168 169 175 public final void setAlgorithm(String value) { 176 algorithm = value; 177 secure = true; } 179 180 186 public final void setProvider(String value) { 187 provider = value; 188 } 189 } 190 | Popular Tags |