data generate
来源:互联网 发布:古墓丽影for mac 编辑:程序博客网 时间:2024/06/06 03:03
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoGen {
String value() default "";
}
--------------------------
public class RandomBoolean extends RandomObject<Boolean> {
List<Boolean> bs = new ArrayList<Boolean>();
@Override
public void validate(String expression){
// TODO Auto-generated method stub
}
@Override
public List<Boolean> gen(int n) {
bs.clear();
for(int i = 0; i < n; i++){
bs.add(random.nextBoolean());
}
return bs;
}
}
--------------
public class RandomByte extends RandomObject<Byte> {
List<Byte> bs = new ArrayList<Byte>();
@Override
public void validate(String expression) {
// TODO Auto-generated method stub
}
@Override
public List<Byte> gen(int n) {
bs.clear();
for(int i = 0; i < n; i++){
bs.add((byte) (random.nextInt(256) - 128));
}
return bs;
}
}
-----
public class RandomDate extends RandomObject<Date> {
List<Date> dates = new ArrayList<Date>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date beginDate, endDate;
@Override
public void validate(String expression) throws ValidateException {
try {
expression = expression.substring(1, expression.length() - 1);
String[] beginEndDataArr = expression.split(",");
if(beginEndDataArr.length == 1){
beginDate = sdf.parse(beginEndDataArr[0]);
endDate = beginDate;
} else if(beginEndDataArr.length == 2){
beginDate = sdf.parse(beginEndDataArr[0].trim());
endDate = sdf.parse(beginEndDataArr[1].trim());
} else {
throw new ValidateException("Invalid Expression: " + Arrays.toString(beginEndDataArr));
}
} catch (Exception e) {
throw new ValidateException("Invalid Expression: " + e.getMessage());
}
}
@Override
public List<Date> gen(int n) {
validate(expression);
dates.clear();
Long beginDateLong = beginDate.getTime();
Long endDateLong = endDate.getTime();
for(int i = 0; i < n; i++){
long dateLong = (long) Math.floor(Math.random() * (endDateLong - beginDateLong) + beginDateLong);
dates.add(new Date(dateLong));
}
return dates;
}
}
------
public class RandomDouble extends RandomNumber<Double> {
List<Double> ds = new ArrayList<Double>();
@Override
public void validate(String expression) throws ValidateException {
super.validate(this.expression);
}
@Override
public List<Double> gen(int n) {
try {
ds.clear();
validate(expression);
switch (n) {
case 1:
ds.add(gen());
break;
case 2:
ds.add(gen());
boolean addStart = random.nextBoolean();
// Make the result always include bound values when the bound are exist in expression.
if(addStart){
if(minIncluded){
ds.add(startVal.doubleValue());
}
} else {
if(maxIncluded){
ds.add(endVal.doubleValue());
}
}
break;
default:
for (int i = 0; i < n - 2; i++) {
ds.add(gen());
}
// Make the result always include bound values
ds.add(startVal.doubleValue());
ds.add(endVal.doubleValue());
}
} catch (Exception e) {
e.printStackTrace();
}
return ds;
}
private Double gen() {
Double spread = endVal.doubleValue() - startVal.doubleValue();
return random.nextDouble() * spread + startVal.doubleValue();
}
}
------------
public class RandomFloat extends RandomNumber<Float> {
List<Float> ds = new ArrayList<Float>();
@Override
public void validate(String expression) {
// TODO Auto-generated method stub
}
@Override
public List<Float> gen(int n) {
ds.clear();
for(int i = 0; i < n; i++){
ds.add(0f);
}
return ds;
}
}
---
public class RandomInt extends RandomNumber<Integer> {
List<Integer> ds = new ArrayList<Integer>();
@Override
public void validate(String expression) {
// TODO Auto-generated method stub
}
@Override
public List<Integer> gen(int n) {
// TODO Auto-generated method stub
ds.clear();
for(int i = 0; i < n; i++){
ds.add(random.nextInt());
}
return ds;
}
}
----
public class RandomLong extends RandomNumber<Long> {
List<Long> ds = new ArrayList<Long>();
@Override
public void validate(String expression) {
// TODO Auto-generated method stub
}
@Override
public List<Long> gen(int n) {
ds.clear();
for(int i = 0; i < n; i++){
ds.add(0l);
}
return ds;
}
}
---
public class RandomNumber<N> extends RandomObject<N> {
protected Number startVal = null;
protected Number endVal = null;
protected boolean minIncluded;
protected boolean minNotIncluded;
protected boolean maxIncluded;
protected boolean maxNotIncluded;
@Override
public void validate(String expression) throws ValidateException {
boolean isDefaultValue = expression.equals("");
minIncluded = expression.startsWith("[");
minNotIncluded = expression.startsWith("(");
maxIncluded = expression.endsWith("]");
maxNotIncluded = expression.endsWith(")");
if (isDefaultValue)
return;
if ((minIncluded || minNotIncluded) && (maxIncluded || maxNotIncluded)) {
String innerExpression = expression.substring(1, expression.length() - 1);
String[] parts = innerExpression.split(",");
try {
switch (parts.length) {
case 1:
startVal = Double.parseDouble(parts[0]);
break;
case 2:
startVal = Double.parseDouble(parts[0]);
endVal = Double.parseDouble(parts[1]);
break;
default:
throw new ValidateException("irregular expression: " + expression + ", mutiple ',' are found in the expression.");
}
} catch (RuntimeException e) {
throw new ValidateException("irregular expression: " + e.getMessage());
}
} else {
if (!(minIncluded || minNotIncluded)) {
throw new ValidateException("irregular expression: " + expression + ", the expression should be started with '[' or '('");
} else if (!(maxIncluded || maxNotIncluded)) {
throw new ValidateException("irregular expression: " + expression + ", the expression should be ended with ']' or ')'");
} else {
throw new ValidateException("irregular expression: " + expression);
}
}
}
@Override
public List<N> gen(int n) {
return null;
}
}
---
public class RandomObject<O> implements IGenerator<O>, IValidator {
protected Random random = new Random();
protected String expression;
public String getExpression() {
return expression;
}
public RandomObject<O> setExpression(String expression) {
this.expression = expression;
return this;
}
@Override
public void validate(String expression) throws ValidateException {
}
@Override
public List<O> gen(int n) throws Exception {
return null;
}
}
---
public class RandomShort extends RandomNumber<Short> {
List<Short> ds = new ArrayList<Short>();
@Override
public void validate(String expression) {
// TODO Auto-generated method stub
}
@Override
public List<Short> gen(int n) {
ds.clear();
for(int i = 0; i < n; i++){
ds.add((short)0);
}
return ds;
}
}
--
public class RandomString extends RandomObject<String> {
public List<String> gen(int n) throws Exception {
return RegularParser.parse(this.expression, n);
}
@Override
public void validate(String expression) {
//TODO
}
}
---
class ASCII {
static final Character Numerics[] = new Character[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
static final Character NewLines[] = new Character[] { '\n' };
static final Character Carriages[] = new Character[] { '\r' };
static final Character HTabs[] = new Character[] { '\t' };
static final Character VTabs[] = new Character[] { '\u000B' };
static final Character symbols[] = new Character[]{'!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~'};
static final Character Uppers[] = new Character[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
static final Character Lowers[] = new Character[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
static final Character Blanks[] = new Character[] { '\n', '\r', '\t', '\u000B', '\f' };
static final Character Alphas[] = concatArray(Uppers, Lowers);
static final Character ANs[] = concatArray(Numerics, Alphas);
static final Character NonBlanks[] = concatArray(Numerics, Alphas);
static final Character NonNums[] = concatArray(Blanks, Uppers, Lowers);
static final Character NonANs[] = concatArray(Blanks);
static final Character AllCodes[] = concatArray(Numerics, Uppers, Lowers, Blanks, symbols);
static Character[] concatArray(Character[]... arrays) {
int length = 0;
for (Character[] array : arrays)
length = length + array.length;
Character[] returnArr = new Character[length];
int progress = 0;
for (Character[] array : arrays) {
System.arraycopy(array, 0, returnArr, progress, array.length);
progress = progress + array.length;
}
return returnArr;
}
}
---
public class RegularParser {
public static List<String> parse(String inputStr, int num) throws Exception {
Pattern.compile(inputStr);
List<String> tmpList = new ArrayList<String>();
List<String> returnList = new ArrayList<String>();
List<Param> params = replaceSpecialChar(inputStr);
for (int i = 0; i < num; i++) {
String tmp = inputStr;
tmp = updateByParam(tmp, params);
tmp = replaceBracketedContent(tmp);
tmp = replaceParenContent(tmp);
tmpList.add(tmp);
}
for (String tmp : tmpList) {
tmp = replaceMetaChar(tmp);
returnList.add(tmp);
}
return returnList;
}
public static List<Param> replaceSpecialChar(String inputStr) throws Exception {
List<Param> returnList = new ArrayList<Param>();
boolean furtherReplace = true;
while (furtherReplace) {
furtherReplace = false;
for (SpecialChar sc : SpecialChar.values()) {
int index = inputStr.indexOf(sc.pattern);
int floorCapArr[] = new int[2];
String target = "";
Param param = new Param();
if (index >= 0) {
int nextCharIndex = index + sc.pattern.length();
char nextChar = (nextCharIndex <= inputStr.length() - 1) ? inputStr.charAt(nextCharIndex) : '\u0000';
switch (nextChar) {
case '?':
case '*':
case '+':
case '{':
String repeatExp = fetchRepeatExpressionAtGivenIndex(inputStr, nextCharIndex);
floorCapArr = parseRepeatTimes(repeatExp);
target = sc.pattern + repeatExp;
break;
default:
target = sc.pattern;
floorCapArr[0] = 1;
floorCapArr[1] = 1;
param.setTarget(target);
param.setFloorCapArr(floorCapArr);
param.setSc(sc);
returnList.add(param);
continue;
}
param.setTarget(target);
param.setFloorCapArr(floorCapArr);
param.setSc(sc);
// Add the target with special repeat time to the beginning. so it won't be replaced by the one with no repeat time by mistake.
returnList.add(0, param);
inputStr = inputStr.substring(0, index) + inputStr.substring(index + target.length());
furtherReplace = true;
}
}
}
return returnList;
}
public static String replaceMetaChar(String inputStr) throws Exception {
List<Character> newStr = new ArrayList<Character>();
// To avoid out of bound exception.
inputStr = " " + inputStr + " ";
for (int i = 2; i < inputStr.length() - 1; i++) {
char currChar = inputStr.charAt(i);
char nextChar = inputStr.charAt(i + 1);
int nextCharIndex = i + 1;
String repeatExpression;
switch (currChar) {
case '\\':
if(isEscMark(nextChar)){
repeatExpression = fetchRepeatExpressionAtGivenIndex(inputStr, nextCharIndex + 1);
addChar(newStr, repeat(parseRepeatTimes(repeatExpression), currChar));
i = i + repeatExpression.length() + 1;
} else if(MetaChar.isMetaChar(nextChar)){
repeatExpression = fetchRepeatExpressionAtGivenIndex(inputStr, nextCharIndex + 1);
addChar(newStr, repeat(parseRepeatTimes(repeatExpression), nextChar));
i = i + repeatExpression.length() + 1;
} else {
i++;
}
continue;
case '.':
repeatExpression = fetchRepeatExpressionAtGivenIndex(inputStr, nextCharIndex);
if(isEscChar(inputStr, i)){
addChar(newStr, repeat(parseRepeatTimes(repeatExpression), currChar));
} else {
List<Character> chs = new ArrayList<Character>();
Collections.addAll(chs, ASCII.AllCodes);
addChar(newStr, repeat(parseRepeatTimes(repeatExpression), chs));
}
i = i + repeatExpression.length();
continue;
case '-':
case '^':
case '$':
case '|':
case '{':
case '}':
case '(':
case ')':
case '[':
case ']':
case '?':
case '*':
case '+':
if(isEscChar(inputStr, i)) {
repeatExpression = fetchRepeatExpressionAtGivenIndex(inputStr, nextCharIndex);
String a = repeat(parseRepeatTimes(repeatExpression), currChar);
addChar(newStr, a);
i = i + repeatExpression.length();
}else {
continue;
}
break;
default:
newStr.add(currChar);
}
}
return convertCharListToString(newStr);
}
public static String replaceParenContent(String inputStr) throws Exception{
List<String> contents = getInnerContent(inputStr, MetaChar.OpenParen.symbol, MetaChar.CloseParen.symbol);
List<String> groups = new ArrayList<String>();
for(String content : contents){
boolean furtherReplace = true;
String contentInner = content.substring(1, content.length() - 1);
groups = new ArrayList<String>();
while(furtherReplace){
furtherReplace = false;
int indexOfPipe = contentInner.indexOf(MetaChar.Pipe.symbol);
if(indexOfPipe > 0){
if(!isEscChar(inputStr, indexOfPipe)){
groups.add(contentInner.substring(0, indexOfPipe));
contentInner = contentInner.substring(indexOfPipe + 1);
}
furtherReplace = true;
} else {
groups.add(contentInner);
}
}
String repeatExp = fetchRepeatExpressionAtGivenIndex(inputStr, inputStr.indexOf(content) + content.length());
int floorCapArr[] = parseRepeatTimes(repeatExp);
int num = random.nextInt(floorCapArr[1] - floorCapArr[0] + 1) + floorCapArr[0];
List<String> replacementParts = getRandomValuesFromList(groups, num);
stb.delete(0, stb.length());
for(String part: replacementParts){
stb.append(part);
}
inputStr = replaceFirstTargetAndRepeatexpression(inputStr, content+repeatExp, "", stb.toString());
}
return inputStr;
}
/**
* Generate data according to the content in bracket,
* and use the generated string to replace the original content.
* @param inputStr
* @return
* @throws Exception
*/
public static String replaceBracketedContent(String inputStr) throws Exception{
List<String> contents = getInnerContent(inputStr, MetaChar.OpenBracket.symbol, MetaChar.CloseBracket.symbol);
List<Character> charsOfReplacement = new ArrayList<Character>();
for(String content: contents) {
int contentIndex = inputStr.indexOf(content);
List<String> atomExps = splitContentToAtomExpression(content);
charsOfReplacement = new ArrayList<Character>();
for(String atomExp : atomExps) {
if(isAvailaleAtomExpression(atomExp)){
List<Character> tmpChars = generateCharByExpression(atomExp);
charsOfReplacement.addAll(tmpChars);
}
}
String repeatExp = fetchRepeatExpressionAtGivenIndex(inputStr, contentIndex + content.length());
String replacement = repeat(parseRepeatTimes(repeatExp), charsOfReplacement);
inputStr = replaceFirstTargetAndRepeatexpression(inputStr, content, repeatExp, replacement);
}
return inputStr;
}
public static List<String> getInnerContent(String inputStr, char startTag, char endTag) throws Exception{
List<String> contents = new ArrayList<String>();
List<Integer> leftBrackets = new ArrayList<Integer>();
List<Integer> rightBrackets = new ArrayList<Integer>();
for(int i = 0; i < inputStr.length(); i++){
char currChar = inputStr.charAt(i);
if(!isEscChar(inputStr, i)){
if(currChar == startTag) {
leftBrackets.add(i);
} else if(currChar == endTag){
rightBrackets.add(i);
}
}
}
if(leftBrackets.size() != rightBrackets.size()){
throw new Exception("Azygous brackets: " + startTag + "," + endTag);
}
for(int i = 0; i < leftBrackets.size(); i++){
if(leftBrackets.get(i) >= rightBrackets.get(i)){
throw new Exception("Incorrect order of the brackets.");
}
contents.add(inputStr.substring(leftBrackets.get(i), rightBrackets.get(i) + 1));
}
return contents;
}
/**
* Split the content into atoms. an atom can be a char or an expression,
* such as : 'a' or 'a-z' or '\+'
* @param content
* @return
* @throws Exception
*/
public static List<String> splitContentToAtomExpression(String content){
//Remove "[" and "]"
content = content.substring(0, content.length() - 1);
List<String> atomExpression = new ArrayList<String>();
for(int i = 0; i < content.length(); i++){
char currChar = content.charAt(i);
char nextChar = (i < content.length() - 1) ? content.charAt(i + 1) : '\u0000';
if(currChar == '\\'){
char next2Char = (i < content.length() - 2) ? content.charAt(i + 2) : '\u0000';
if(next2Char == '-'){
atomExpression.add((content.substring(i, i + 5)).intern());
i = i + 4;
} else {
atomExpression.add("\\" + nextChar);
i = i + 1;
}
} else {
if(nextChar == '-'){
if(i + 2 < content.length()){
atomExpression.add(currChar + "-" + content.charAt(i + 2));
i = i + 2;
} else {
atomExpression.add(currChar + "-");
i = i + 1;
}
} else {
atomExpression.add(currChar + "");
}
}
}
List<String> returnList = new ArrayList<String>();
for(int i = 0; i < atomExpression.size(); i++){
if(atomExpression.get(i).equals("^") && i < atomExpression.size() - 1){
returnList.add(atomExpression.get(i) + atomExpression.get(i + 1));
i++;
} else {
returnList.add(atomExpression.get(i));
}
}
return returnList;
}
static int ATOM_EXPRESSION_MAX_LENGTH = 5;
public static boolean isAvailaleAtomExpression(String atomExpression) throws Exception{
int indexOfHyphen = atomExpression.indexOf("-");
if(indexOfHyphen > -1){
if(atomExpression.length() > ATOM_EXPRESSION_MAX_LENGTH){
return false;
}
String floorCapExpression[] = atomExpression.split("-");
String floorExpression, capExpression;
if(floorCapExpression.length == 2){
if(atomExpression.startsWith("^")){
floorCapExpression[0] = floorCapExpression[0].substring(1);
}
// If there is a '-' at the end of the expression, it'll be removed. So we should get it back here.
if(atomExpression.endsWith("-")){
floorCapExpression[1] = floorCapExpression[1] + "-";
}
floorExpression = floorCapExpression[0];
capExpression = floorCapExpression[1];
if(isAvailableFloorCapChar(floorExpression) && isAvailableFloorCapChar(capExpression)){
if(floorExpression.charAt(floorExpression.length() - 1) < capExpression.charAt(capExpression.length() - 1)){
return true;
} else {
return false;
}
}
} else if(floorCapExpression.length >= 2){
int segmentIndex = -1;
for(int i = 0; i < atomExpression.length(); i++){
char c = atomExpression.charAt(i);
if(c == '-'){
if(!isEscChar(atomExpression, i)){
segmentIndex = i;
}
}
}
if(segmentIndex >= 0){
floorExpression = atomExpression.substring(0, segmentIndex);
capExpression = atomExpression.substring(segmentIndex + 1);
if(isAvailableFloorCapChar(floorExpression) && isAvailableFloorCapChar(capExpression)){
if(floorExpression.charAt(floorExpression.length() - 1) < capExpression.charAt(capExpression.length() - 1)){
return true;
} else {
return false;
}
}
} else {
return false;
}
} else {
return false;
}
} else {
if(atomExpression.length() == 1){
for(char availaleChar : ASCII.ANs){
if(availaleChar == atomExpression.charAt(0)){
return true;
}
}
return false;
} else if(atomExpression.length() == 2){
char fristChar = atomExpression.charAt(0);
char lastChar = atomExpression.charAt(1);
if(fristChar == '^'){
return true;
} else if (fristChar == '\\') {
return isCanEscChar(lastChar);
}
} else if(atomExpression.length() == 3){
char fristChar = atomExpression.charAt(0);
char secondChar = atomExpression.charAt(1);
char lastChar = atomExpression.charAt(2);
if(fristChar == '^'){
if(secondChar == '\\') {
return isCanEscChar(lastChar);
} else {
return false;
}
} else {
return false;
}
}
}
return false;
}
public static boolean isAvailableFloorCapChar(String inputStr){
switch (inputStr.length()) {
case 1:
char c = inputStr.charAt(0);
for(char tmp : ASCII.AllCodes) {
if(tmp == c){
return true;
}
}
return false;
case 2:
if(MetaChar.isMetaCharPattern(inputStr)){
return true;
}
return false;
}
return false;
}
public static List<Character> generateCharByExpression(String expression) throws Exception{
List<Character> returnList = new ArrayList<Character>();
if(expression.startsWith("^")){
List<Character> allChars = new ArrayList<Character>();
Collections.addAll(allChars, ASCII.AllCodes);
List<Character> excludedChars = new ArrayList<Character>();
if(expression.startsWith("^\\")){
char metaChar = expression.charAt(2);
if(MetaChar.isMetaChar(metaChar)){
excludedChars.add(metaChar);
}
switch (metaChar){
case 'n':
excludedChars.add('\n');
break;
case 'r':
excludedChars.add('r');
break;
case 't':
excludedChars.add('\t');
break;
case 'f':
excludedChars.add('\f');
break;
case 'd':
Collections.addAll(excludedChars, ASCII.Numerics);
break;
case 'D':
Collections.addAll(returnList, ASCII.Numerics);
return returnList;
case 's':
Collections.addAll(excludedChars, ASCII.Blanks);
break;
case 'S':
Collections.addAll(returnList, ASCII.Blanks);
return returnList;
case 'w':
Collections.addAll(excludedChars, ASCII.Alphas);
break;
case 'W':
Collections.addAll(returnList, ASCII.Alphas);
return returnList;
}
} else {
if(expression.length() == 2){
excludedChars.add(expression.charAt(1));
} else if(expression.length() > 3){
if(expression.charAt(2) == '-'){
String[] floorCapExpression = expression.split("-");
char floor = floorCapExpression[0].charAt(floorCapExpression[0].length() - 1);
char cap = floorCapExpression[1].charAt(floorCapExpression[1].length() - 1);
excludedChars.addAll(getIntervalChars(floor, cap));
}
} else {
throw new Exception("Unavailable expression: " + expression);
}
}
allChars.removeAll(excludedChars);
returnList.addAll(allChars);
} else if(expression.startsWith(escMark.toString())){
char metaChar = expression.charAt(1);
if(MetaChar.isMetaChar(metaChar)){
returnList.add(metaChar);
} else {
SpecialChar sc = SpecialChar.getSpecialChar(metaChar);
if(sc != null) Collections.addAll(returnList, sc.indexes);
}
} else {
if(expression.length() == 1){
returnList.add(expression.charAt(0));
} else {
String[] floorCapExpression = expression.split("-");
if(floorCapExpression.length == 2){
char floor = floorCapExpression[0].charAt(floorCapExpression[0].length() - 1);
char cap = floorCapExpression[1].charAt(floorCapExpression[1].length() - 1);
returnList.addAll(getIntervalChars(floor, cap));
} else {
throw new Exception("Unavailable expression: " + expression);
}
}
}
return returnList;
}
public static char generateCharByGivenChars(List<Character> chars){
Random random = new Random();
return chars.get(random.nextInt(chars.size() + 1));
}
/**
* Check the char in the special index if an escaped char.
* @param inputStr
* @param index
* @return
* @throws Exception
*/
public static boolean isEscChar(String inputStr, int index) throws Exception{
if(index < 0)
throw new Exception("Out of bound: " + index);
if(index == 0)
return false;
if(index > 1 && isEscMark(inputStr.charAt(index - 1)) && !isEscMark(inputStr.charAt(index - 2)))
return true;
return false;
}
public static boolean isCanEscChar(char inputChar){
switch (inputChar){
case '\\':
case '+':
case '*':
case '?':
case '|':
case '^':
case 'd':
case 'D':
case 's':
case 'S':
case 'w':
case 'W':
case 'n':
case 'r':
case 't':
case 'f':
return true;
default:
return false;
}
}
public static void main(String[] args) throws Exception {
StringBuilder stb = new StringBuilder("ab");
stb.insert(1, getSpaces(6));
}
static String getSpaces(int num){
for(int i = 0; i < num; i++){
stb.append(" ");
}
return stb.toString();
}
public HashMap<Integer, String> replaceAllEsc(String inputStr) {
List<Integer> escIndiecs = new ArrayList<Integer>();
for (int i = 0; i < inputStr.length(); i++) {
if (isEscMark(inputStr.charAt(i))) {
escIndiecs.add(i);
}
}
return null;
}
public static List<Character> getIntervalChars(Character c1, Character c2){
List<Character> returnList = new ArrayList<Character>();
if(c1 > c2){
return returnList;
} else {
for(int i = c1; i <= c2; i++){
returnList.add((char)i);
}
}
return returnList;
}
public static String convertCharListToString(List<Character> chs){
char[] chars = new char[chs.size()];
for(int i = 0; i < chs.size(); i++){
chars[i] = chs.get(i);
}
return new String(chars);
}
private static Random random = new Random();
public static String repeat(int[] floorCapArr, List<Character> chs){
int time = random.nextInt(floorCapArr[1] - floorCapArr[0] + 1) + floorCapArr[0];
char[] chsOfStr = new char[time];
for(int i = 0; i < time; i++){
chsOfStr[i] = chs.get(random.nextInt(chs.size()));
}
return new String(chsOfStr);
}
public static String repeat(int[] floorCapArr, char... chs){
int time = random.nextInt(floorCapArr[1] - floorCapArr[0] + 1) + floorCapArr[0];
char[] chsOfStr = new char[time];
for(int i = 0; i < time; i++){
chsOfStr[i] = chs[random.nextInt(chs.length)];
}
return new String(chsOfStr);
}
public static int[] parseRepeatTimes(String expression) throws Exception{
int floorCapArr[] = new int[2];
if(expression.length() > 0) {
if(expression.length() == 1){
char c = expression.charAt(0);
switch (c) {
case '+':
floorCapArr[0] = 1;
floorCapArr[1] = 100;
break;
case '*':
floorCapArr[0] = 0;
floorCapArr[1] = 100;
break;
case '?':
floorCapArr[0] = 0;
floorCapArr[1] = 1;
break;
default:
throw new Exception("Cannot parse this meta character: " + expression);
}
} else {
if(expression.startsWith("{") && expression.endsWith("}")){
String floorCapStrs[] = expression.substring(1, expression.length() - 1).split(",");
if(floorCapStrs.length == 1){
floorCapArr[0] = Integer.parseInt(floorCapStrs[0]);
floorCapArr[1] = floorCapArr[0];
} else if(floorCapStrs.length == 2){
floorCapArr[0] = Integer.parseInt(floorCapStrs[0]);
floorCapArr[1] = Integer.parseInt(floorCapStrs[1]);
} else {
throw new Exception("Cannot parse this expression: " + expression);
}
if(floorCapArr[1] < floorCapArr[0]){
throw new Exception("Cannot parse this expression: " + expression);
}
} else {
throw new Exception("Cannot parse this expression: " + expression);
}
}
} else {
floorCapArr[0] = 1;
floorCapArr[1] = 1;
}
return floorCapArr;
}
public static String fetchRepeatExpressionAtGivenIndex(String inputStr, int index){
if(index >= inputStr.length())
return "";
char c = inputStr.charAt(index);
switch (c) {
case '?':
case '*':
case '+':
return String.valueOf(c);
case '{':
String tmp = inputStr.substring(index);
return tmp.substring(0, tmp.indexOf('}') + 1);
default:
return "";
}
}
public static boolean isRepeatExpression(String inputStr, int index){
if(index >= inputStr.length())
return false;
char c = inputStr.charAt(index);
switch (c) {
case '?':
case '*':
case '+':
return true;
case '{':
String tmp = inputStr.substring(index);
return tmp.indexOf('}') > 0;
default:
return false;
}
}
public static boolean isSpecialOrMetaExpression(String expression) {
return SpecialChar.isSpecialCharPattern(expression) || MetaChar.isMetaCharPattern(expression);
}
public static void addChar(List<Character> c, String src){
for(int i =0; i < src.length(); i++){
c.add(src.charAt(i));
}
}
private static Character escMark = '\\';
public static boolean isEscMark(char c){
return c == escMark;
}
public static <T> List<T> getRandomValuesFromList(List<T> srcList, int volume){
List<T> ts = new ArrayList<T>();
for(int i = 0; i < volume; i++){
ts.add(srcList.get(random.nextInt(srcList.size())));
}
return ts;
}
private static StringBuilder stb = new StringBuilder();
public static String replaceFirstTargetAndRepeatexpression(String src, String target, String repeatExpression, String replacement){
stb.delete(0, stb.length());
int index = src.indexOf(target);
return stb.append(src.substring(0, index)).append(replacement).append(src.substring(index + target.length() + repeatExpression.length())).toString();
}
public static String updateByParam(String src, List<Param> params){
for(Param param: params){
SpecialChar sc = param.getSc();
sc.setFloorCapArr(param.getFloorCapArr());
String a = sc.getRandomString();
src = src.replace(param.getTarget(), a);
}
return src;
}
enum MetaChar {
wildcard('.', "\\."),
QuestionMark('?', "\\?"),
Asterisk('*', "\\*"),
Hypten('-', "\\-"),
Plus('+', "\\+"),
Caret('^', "\\^"),
Backslash('\\', "\\\\"),
Dollar('$', "\\$"),
Pipe('|', "\\|"),
OpenBrace('{', "\\{"),
CloseBrace('}', "\\}"),
OpenParen('(', "\\("),
CloseParen(')', "\\)"),
OpenBracket('[', "\\["),
CloseBracket(']', "\\]"),
;
protected String pattern;
protected Character symbol;
MetaChar(Character symbol, String pattern){
this.symbol = symbol;
this.pattern = pattern;
}
public static boolean isMetaCharPattern(String value){
for(MetaChar metaChar : MetaChar.values()){
if(metaChar.pattern.equals(value)){
return true;
}
}
return false;
}
public static boolean isMetaChar(Character c){
for(MetaChar metaChar : MetaChar.values()){
if(metaChar.symbol == c) {
return true;
}
}
return false;
}
}
enum SpecialChar {
Numeric('d', "\\d", ASCII.Numerics),
Newline('n', "\\n", ASCII.NewLines),
Carriage('r', "\\r", ASCII.Carriages),
Blank('s', "\\s", ASCII.Blanks),
Horizontal_Tab('t', "\\t", ASCII.HTabs),
Vertical_Tab('v', "\\v", ASCII.VTabs),
Alphanumeric('w', "\\w", ASCII.ANs),
Non_Blank('S', "\\S", ASCII.NonBlanks),
Non_Numeric('D', "\\D", ASCII.NonNums),
Non_Alphanumeric('W', "\\W", ASCII.NonANs);
SpecialChar(Character originalChar, String pattern, Character[] indexes) {
this.originalChar = originalChar;
this.pattern = pattern;
this.indexes = indexes;
}
protected String pattern;
protected Character[] indexes;
protected Character originalChar;
protected int[] floorCapArr;
public void setFloorCapArr(int[] value) {
this.floorCapArr = value;
}
public String getPattern() {
return this.pattern;
}
public String getRandomString() {
int length = random.nextInt(floorCapArr[1] - floorCapArr[0] + 1) + floorCapArr[0];
char[] chars = new char[length];
for (int i = 0; i < length; i++) {
chars[i] = getRandomChar();
}
return new String(chars);
}
protected char getRandomChar() {
return (char) indexes[random.nextInt(indexes.length)];
}
public static SpecialChar getSpecialChar(Character c){
for(SpecialChar sc: SpecialChar.values()){
if(sc.originalChar == c) {
return sc;
}
}
return null;
}
public static boolean isSpecialCharPattern(String expression){
for(SpecialChar sc: SpecialChar.values()){
if(sc.getPattern().equals(expression)){
return true;
}
}
return false;
}
}
}
class Param {
private String target;
private int[] floorCapArr;
private SpecialChar sc;
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
public void setSc(SpecialChar sc) {
this.sc = sc;
}
public void setFloorCapArr(int[] floorCapArr) {
this.floorCapArr = floorCapArr;
}
public int[] getFloorCapArr() {
return floorCapArr;
}
public SpecialChar getSc() {
return sc;
}
@Override
public String toString() {
return "target: " + target + ", floorCapArr: " + Arrays.toString(floorCapArr) + ", esc: " + sc.name();
}
}
----
public interface IValidator {
void validate(String expression) throws ValidateException;
}
----
public enum Type {
String(
new String[]{"java.lang.String"},
new RandomString(),
"\\w{1,50}"
),
Date(
new String[]{"java.util.Date"},
new RandomDate(),
"[1900-01-01,2900-01-01]"
),
Int(
new String[]{"int", "java.lang.Integer"},
new RandomInt(),
"[" + java.lang.Integer.MIN_VALUE + "," + java.lang.Integer.MAX_VALUE + "]"
),
Double(
new String[]{"double", "java.lang.Double"},
new RandomDouble(),
"[" + java.lang.Double.MIN_VALUE + "," + java.lang.Double.MAX_VALUE + "]"
),
Byte(
new String[]{"byte", "java.lang.Byte"},
new RandomByte(),
"[" + java.lang.Byte.MIN_VALUE + "," + java.lang.Byte.MAX_VALUE + "]"
),
Short(
new String[]{"short", "java.lang.Short"},
new RandomShort(),
"[" + java.lang.Short.MIN_VALUE + "," + java.lang.Short.MAX_VALUE + "]"
),
Float(
new String[]{"float", "java.lang.Float"},
new RandomFloat(),
"[" + java.lang.Float.MIN_VALUE + "," + java.lang.Float.MAX_VALUE + "]"
),
Long(
new String[]{"long", "java.lang.Long"},
new RandomLong(),
"[" + java.lang.Long.MIN_VALUE + "," + java.lang.Long.MAX_VALUE + "]"
),
Boolean(
new String[]{"boolean", "java.lang.Boolean"},
new RandomBoolean(),
"false"
);
protected String[] patterns;
protected RandomObject<?> randomObject;
protected String expression;
public String getExpression() {
return expression;
}
public Type setExpression(String expression) {
this.expression = expression;
return this;
}
Type(String[] initPatterns, RandomObject<?> initRandomObject, String defaultExpression){
patterns = initPatterns;
randomObject = initRandomObject;
expression = defaultExpression;
}
public RandomObject<?> getRandomObject(){
return randomObject;
}
public static Type getType(String inputParams) throws ValidateException {
for (Type type : Type.values()) {
if (type.match(inputParams)) {
return type;
}
}
return null;
}
protected boolean match(String inputParams){
for(String pattern : patterns)
if(inputParams.equals(pattern)) return true;
return false;
}
}
---
public class DataGenException extends Exception {
private static final long serialVersionUID = 1L;
public DataGenException() {
super();
}
/**
* Constructs an instance of <code>DataGenException</code> with the
* specified detail message.
*
* @param msg
* the detail message.
*/
public DataGenException(String msg) {
super(msg);
}
/**
* Constructs a new DataGenException with the specified detail message and
* cause.
* <p>
* Note that the detail message associated with <code>cause</code> is
* <i>not</i> automatically incorporated in this exception's detail message.
*
* @param message
* the detail message (which is saved for later retrieval by the
* {@link #getMessage()} method).
* @param cause
* the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A <tt>null</tt> value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
*/
public DataGenException(String message, Throwable cause) {
super(message, cause);
}
/**
* Constructs an instance of <code>DataGenException</code> with the
* specified detail message.
*
* @param cause
* the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A <tt>null</tt> value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
*/
public DataGenException(Throwable cause) {
super(cause);
}
}
---
public class ValidateException extends DataGenException{
private static final long serialVersionUID = 1L;
public ValidateException() {
super();
}
/**
* Constructs an instance of <code>ValidateException</code> with the
* specified detail message.
*
* @param msg
* the detail message.
*/
public ValidateException(String msg) {
super(msg);
}
/**
* Constructs a new ValidateException with the specified detail message and
* cause.
* <p>
* Note that the detail message associated with <code>cause</code> is
* <i>not</i> automatically incorporated in this exception's detail message.
*
* @param message
* the detail message (which is saved for later retrieval by the
* {@link #getMessage()} method).
* @param cause
* the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A <tt>null</tt> value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
*/
public ValidateException(String message, Throwable cause) {
super(message, cause);
}
/**
* Constructs an instance of <code>ValidateException</code> with the
* specified detail message.
*
* @param cause
* the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A <tt>null</tt> value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
*/
public ValidateException(Throwable cause) {
super(cause);
}
}
--
public interface IGenerator<T> {
List<T> gen(int n) throws Exception;
}
--
public class Generator<T> {
private Map<Method, Type> map1 = new HashMap<Method, Type>();
private Map<Method, String> map2 = new HashMap<Method, String>();
private void parseClass(Class<T> clz) throws ValidateException{
List<Method> setters = Utils.getPublicSetter(clz);
for(Method setter : setters) {
AutoGen autoGen = setter.getAnnotation(AutoGen.class);
if(autoGen != null){
Class<?>[] paramters = setter.getParameterTypes();
if(paramters.length == 1){
map1.put(setter, Type.getType(paramters[0].getName()));
map2.put(setter, autoGen.value());
}
}
}
}
public List<T> gen(Class<T> clz, int num) throws Exception{
List<T> returnList;
parseClass(clz);
returnList = genObjects(clz, num);
return returnList;
}
@SuppressWarnings("unchecked")
private List<T> genObjects(Class<T> clz, int num) throws Exception {
List<T> returnList = new ArrayList<T>();
for (int i = 0; i < num; i++) {
returnList.add(clz.newInstance());
}
for (Entry<Method, Type> entry : map1.entrySet()) {
Method setter = entry.getKey();
String expression = map2.get(setter) != null ? map2.get(setter) : entry.getValue().getExpression();
RandomObject<T> randomer = (RandomObject<T>) entry.getValue().getRandomObject();
List<T> generatedValues = randomer.setExpression(expression).gen(num);
if (generatedValues == null){
continue;
}
int j = 0;
for (T t : returnList) {
setter.invoke(t, generatedValues.get(j));
j++;
}
}
return returnList;
}
}
---
public class Utils {
@SuppressWarnings("unused")
private static final String getDateRegular(Date beginDate, Date endDate, String format){
String returnStr = format;
String yearExp = null, monthExp = null, dayExp = null;
int beginYear, endYear, beginMonth, endMonth, beginDay, endDay;
Calendar c = Calendar.getInstance();
c.setTime(beginDate);
beginYear = c.get(Calendar.YEAR);
beginMonth = c.get(Calendar.MONTH);;
beginDay = c.get(Calendar.DAY_OF_MONTH);
c.clear();
c.setTime(endDate);
endYear = c.get(Calendar.YEAR);
endMonth = c.get(Calendar.MONTH);;
endDay = c.get(Calendar.DAY_OF_MONTH);
getIntervalYear(beginYear, endYear);
returnStr.replaceAll("yyyy", yearExp);
returnStr.replaceAll("MMM", yearExp);
returnStr.replaceAll("MM", monthExp);
returnStr.replaceAll("dd", dayExp);
returnStr.replaceAll("yy", yearExp);
return returnStr;
}
private static int[] getIntervalYear(int begin, int end){
int[] intervalYears = new int[end - begin];
for(int i = 0; i < end - begin; i++){
intervalYears[i] = i + begin;
}
return intervalYears;
}
// private static int[] getIntervalMonthAndDay(int begin, int end){
//
// }
//
// private static int[] getIntervalDay(int begin, int end){
//
// }
public static void main(String[] args) throws ParseException {
}
}
- Generate Data
- data generate
- Java - Generate Random Data
- Data Center Outages Generate Big Losses
- 转载:Generate test data using DBGen
- Generate Data Dictionary from SQL Server
- generate
- Redmine: ArgumentError (A secret is required to generate an integrity hash for cookie session data)
- Data migration to generate the maximum value of the sequence between beta scheme and appbeta scheme
- No way to generate HTML markup with data-link and helper functions in JsViews like in JsRender
- How to generate the complex data regularly to Ministry of Transport of P.R.C by DB Query Analyzer
- 89.Which two kinds of failures make the Data Recovery Advisor (DRA) generate a manual checklist? (Ch
- generate report
- Generate winpe
- prime generate
- generate详解
- Generate Parentheses
- Generate Parentheses
- hdu 1829 A Bug's Life
- extjs/基本标签收集
- 今天我要开始书写我的丰功伟绩
- linux会话浅析
- 字符设备之open()与release()函数
- data generate
- 基于adt-bundle-windows-x86的android开发环境搭建
- 分布式服务框架 Zookeeper -- 管理分布式环境中的数据
- ie6/7兼容问题
- 模拟键盘鼠标按键
- wikioi 1002 搭桥
- 小流涓涓成江海,拙技点点构平台——OpenGL里画个带方向箭头的线段
- C++第14周项目1——数组折腾一下就明白了
- surfaceview