基于语法树生成代码

package com.xxx.xx.xxx.ast;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.AnnotationTypeDeclaration;
import org.eclipse.jdt.core.dom.ArrayInitializer;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.FieldDeclaration;
import org.eclipse.jdt.core.dom.ImportDeclaration;
import org.eclipse.jdt.core.dom.MemberValuePair;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.dom.Name;
import org.eclipse.jdt.core.dom.NormalAnnotation;
import org.eclipse.jdt.core.dom.PackageDeclaration;
import org.eclipse.jdt.core.dom.SimpleType;
import org.eclipse.jdt.core.dom.Type;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.core.dom.TypeLiteral;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
import org.eclipse.jdt.core.dom.rewrite.ListRewrite;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.text.edits.MalformedTreeException;
import org.eclipse.text.edits.TextEdit;

import com.xxx.uxxxat.testcode.analyze.object.ClassInfo;

public  class ASTWriter {
	protected static AST ast = null;
	protected static CompilationUnit compilUnit = null;
	protected static TypeDeclaration classType = null;
	protected static List types = null;
	protected static ClassInfo classInfo = null;
	protected static String testedClassName = "";
	protected static String className = "";
	protected static String instanceName = "";
	protected static ASTRewrite rewriter = null;
	protected static String packageName = "";
	protected static String testFile = "";
	protected static char[] contents = {};
	protected static List importDeclarationNames = new LinkedList();
	
	
	public static String springFilePath = "";
	public static String excelFilePath = "";
	
	
 
        public ASTWriter(char[] content, ClassInfo classInfo) {
		
		if (content.length == 0 || content == null) {
			contents = "class Tmp{\n}".toCharArray();
		}
		else {
			contents = content;
		}
		
		ASTParser parsert = ASTParser.newParser(AST.JLS3);
		parsert.setSource(contents); 
               
                compilUnit = (CompilationUnit) parsert.createAST(null);
		types = compilUnit.types();
		ast = compilUnit.getAST();
		classType = (TypeDeclaration) types.get(0);
		rewriter = ASTRewrite.create(ast);
		
		ASTWriter.classInfo = classInfo;
		ASTWriter.testedClassName = classInfo.getClassName();
	}

	public ASTWriter() {
	}


	// This method only be used by create new test file ;
	@SuppressWarnings("unchecked")
	protected void addClassInfo(String className, String supperName) {
		Type type = ast.newSimpleType(ast.newSimpleName(supperName));		
		classType.setInterface(false);
		classType.setSuperclassType(type);
		classType.setName(ast.newSimpleName(className));
		classType.modifiers().add(ast.newModifiers(Modifier.PUBLIC).get(0));		
		
		compilUnit.types();//.add(classType);
	}

        //添加package 语句 ,例如package com.test.package
	protected void addPackageInfo(String PackageName) {
		PackageDeclaration pkgDecl = ast.newPackageDeclaration();
		pkgDecl.setName(ast.newName(PackageName));
		compilUnit.setPackage(pkgDecl);
	}

        //添加import 语句, 例如import java.io.*;
	@SuppressWarnings("unchecked")
	protected void addImportDeclaration(List importNames) {
		for(String importstr:importNames){
			ImportDeclaration importDeclaration = ast.newImportDeclaration();  
			if(importstr.endsWith("*")){
				String simpleName = "";
				simpleName = importstr.substring(0, importstr.indexOf("*")-1);
				importDeclaration.setName(ast.newName(simpleName));
				importDeclaration.setOnDemand(true);  
			}
			else if(importstr.startsWith("static")){				
				String simpeName = importstr.substring(importstr.indexOf("static")+7).trim();
				importDeclaration.setName(ast.newName(simpeName));
				importDeclaration.setOnDemand(false);  
				importDeclaration.setStatic(true);
			}
			else{
				String simpeName = importstr.trim();
				importDeclaration.setName(ast.newName(simpeName));
				importDeclaration.setOnDemand(false);  
			}			
			compilUnit.imports().add(importDeclaration);  
		}
	}

        //添加方法定义语句 例如 public void test1(){}
	@SuppressWarnings("unchecked")
	protected void addDeclareMethod(MethodDeclaration methodDeclaration) {
		classType.bodyDeclarations().add(methodDeclaration);
	}

        //批量添加方法定义语句
	protected void addBatchMDeclareMethod(Collection methods) {
		for (Iterator iter = methods.iterator(); iter.hasNext();) {
			this.addDeclareMethod(iter.next());
		}
	}

        //添加注解语句
	@SuppressWarnings("unchecked")
	protected void addAnnOnClass(String annName,Set initlist){
		NormalAnnotation normalAnnotation = ast.newNormalAnnotation();
		Name name = ast.newName(annName);
		normalAnnotation.setTypeName(name);
		ArrayInitializer arrayInit = ast.newArrayInitializer();;
		MemberValuePair memberValuePair = ast.newMemberValuePair();
		memberValuePair.setName(ast.newSimpleName("value"));
		
		System.out.println(classType.modifiers().get(0).toString());
		if(classType.modifiers().get(0).toString().contains(annName)){
			NormalAnnotation normalAnnotationtmp = (NormalAnnotation)classType.modifiers().get(0);
			MemberValuePair mp = (MemberValuePair) normalAnnotationtmp.values().get(0);
			for(Object obj : ((ArrayInitializer) mp.getValue()).expressions()){
				TypeLiteral tl = (TypeLiteral)obj;
				SimpleType st = (SimpleType) tl.getType();
				String valueName = st.getName().toString();
				initlist.add(valueName);						
			}
			for (String value : initlist) {
				if (!arrayInit.toString().contains(value)) {
					TypeLiteral tL = ast.newTypeLiteral();
					tL.setType(ast.newSimpleType(ast.newName(value)));
					arrayInit.expressions().add(tL);
				}
			}
			memberValuePair.setValue(arrayInit);
			normalAnnotation.values().add(memberValuePair);		
			classType.modifiers().set(0, normalAnnotation);
		}
		else{
			for(String value : initlist){
				  TypeLiteral tL = ast.newTypeLiteral();
				  tL.setType(ast.newSimpleType(ast.newName(value)));
				  arrayInit.expressions().add(tL);
			}	
			memberValuePair.setValue(arrayInit);
			normalAnnotation.values().add(memberValuePair);		
			classType.modifiers().set(0, normalAnnotation);
		}
	}

        //添加变量定义语句	
	@SuppressWarnings("unchecked")
	protected void addFieldDeclaration(String className, String instanceName) {
		// className instanceName ;
		VariableDeclarationFragment fragment = ast.newVariableDeclarationFragment();
		Expression express = ast.newNullLiteral();
		fragment.setInitializer(express);
		fragment.setName(ast.newSimpleName(instanceName));

		FieldDeclaration classVariDeclaration = ast.newFieldDeclaration(fragment);
		Type type = ast.newSimpleType(ast.newSimpleName(className));
		classVariDeclaration.setType(type);

		classType.bodyDeclarations().add(classVariDeclaration);

		// Object retObjc = null
		VariableDeclarationFragment fragment1 = ast.newVariableDeclarationFragment();
		fragment1.setName(ast.newSimpleName("retObj"));

		FieldDeclaration classVariDeclaration1 = ast.newFieldDeclaration(fragment1);
		Type type1 = ast.newSimpleType(ast.newSimpleName("Object"));
		classVariDeclaration1.setType(type1);
		classType.bodyDeclarations().add(classVariDeclaration1);
		
		// public static DBManage  dbManage = new DBManage();
		VariableDeclarationFragment fragment2 = ast.newVariableDeclarationFragment();
		Expression express2 = ast.newNullLiteral();
		fragment2.setInitializer(express2);
		fragment2.setName(ast.newSimpleName("dbManage"));

		FieldDeclaration classVariDeclaration2 = ast.newFieldDeclaration(fragment2);
		Type type2 = ast.newSimpleType(ast.newSimpleName("DBManage"));
		classVariDeclaration2.setType(type2);
		
		classType.bodyDeclarations().add(classVariDeclaration2);
	}

        //修改方法定义语句
	@SuppressWarnings("unchecked")
	protected void modifyDeclareMethod(MethodDeclaration oldmethod,MethodDeclaration newMethod) {
		int index = classType.bodyDeclarations().indexOf(oldmethod);
		classType.bodyDeclarations().add(index + 1, newMethod);
		classType.bodyDeclarations().remove(index);
	}

	public static String getInstanceName() {
		return instanceName;
	}

	public static void setInstanceName(String instanceName) {
		ASTWriter.instanceName = instanceName;
	}

	protected void setTestedClassName(String testedclassName) {
		ASTWriter.testedClassName = testedclassName;
	}

	protected String getTestedClassName() {
		return ASTWriter.testedClassName;
	}

	protected void setClassName(String className) {
		classType.setName(ast.newSimpleName(className));
		ASTWriter.className = className;
	}

	protected String getClassName() {
		return ASTWriter.className;
	}

	protected String getPackageName() {
		return compilUnit.getPackage().getName().toString();
	}

	protected int getClassModifiers() {
		return classType.getModifiers();
	}

	protected MethodDeclaration[] getDeclaredMethod() {
		return classType.getMethods();
	}

	public CompilationUnit getCompilationUnit() {
		return ASTWriter.compilUnit;
	}

	public static void setSpringFilepath(String springFilePath) {
		ASTWriter.springFilePath = springFilePath;
	}
	
	/**
	 * @return the spring_File_path
	 */
	public static final String getSpringFilepath() {
		return springFilePath;
	}


	

	/*
	 * NormalAnnotation normalAnnotation = ast.newNormalAnnotation(); Name name
	 * = ast.newName(annotationName); normalAnnotation.setTypeName(name);
	 * ArrayInitializer arrayInit = ast.newArrayInitializer(); for(String value
	 * : values){ TypeLiteral tL = ast.newTypeLiteral();
	 * tL.setType(ast.newSimpleType(ast.newName(value)));
	 * arrayInit.expressions().add(tL); }
	 * 
	 * MemberValuePair memberValuePair = ast.newMemberValuePair();
	 * memberValuePair.setName(ast.newSimpleName("value"));
	 * memberValuePair.setValue(arrayInit);
	 * 
	 * normalAnnotation.values().add(memberValuePair);
	 */

}

你可能感兴趣的:(单元测试,java技术)