Java Code Examples for spoon.reflect.declaration.CtClass

The following examples show how to use spoon.reflect.declaration.CtClass. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: gumtree-spoon-ast-diff   Source File: AstComparatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testJDTBasedSpoonCompiler() {
	String content1 = "package spoon1.test; " //
			+ "class X {" //
			+ "public void foo0() {" //
			+ " int x = 0;" //
			+ "}" + "}";

	Factory factory = new Launcher().createFactory();

	SpoonModelBuilder compiler = new JDTSnippetCompiler(factory, content1);
	compiler.build();
	CtClass<?> clazz1 = (CtClass<?>) factory.Type().getAll().get(0);

	Assert.assertNotNull(clazz1);
}
 
Example 2
Source Project: astor   Source File: EvoSuiteFacade.java    License: GNU General Public License v2.0 6 votes vote down vote up
public List<CtType<?>> getClassesToProcess(ProgramVariant variant) {
	List<CtType<?>> typesToProcess = null;

	if (ConfigurationProperties.getPropertyBool("evo_buggy_class")) {

		//
		if (ConfigurationProperties.getPropertyBool("evo_affected_by_op")) {
			logger.info("Affected Buggy classes");
			typesToProcess = variant.computeAffectedClassesByOperators();
		} else {
			logger.info("All Buggy classes");
			typesToProcess = variant.getAffectedClasses();
		}

	} else

	{
		typesToProcess = new ArrayList<>();
		for (CtClass<?> classes : variant.getModifiedClasses()) {
			typesToProcess.add(classes);
		}
	}
	logger.info("Classes for generating test: "
			+ typesToProcess.stream().map(e -> e.getQualifiedName()).collect(Collectors.toList()));
	return typesToProcess;
}
 
Example 3
public Object createStatementResourceObjectTransformed() throws Exception{
   	Selector.reset();

       Launcher l = new Launcher();
       l.addInputResource("src/test/java/resources/StatementResource.java");
       l.addProcessor(new StatementDeletionMetaMutator());
       l.run();

       // now we get the code of StatementResource
       CtClass c = l.getFactory().Package().getRootPackage().getElements(new NamedElementFilter<>(CtClass.class, "StatementResource")).get(0);
       
       // printing the metaprogram
       System.out.println("// Metaprogram: ");
       System.out.println(c.toString());

       // we prepare an interpreter for the transformed code
       Interpreter bsh = new Interpreter();

       // creating a new instance of the class
       Object o = ((Class)bsh.eval(c.toString())).newInstance();
       
       return o;

}
 
Example 4
Source Project: spoon-examples   Source File: Spoonerism.java    License: GNU General Public License v2.0 6 votes vote down vote up
Spoonerism determineBaseTestingClassPackage(){
    // Find the package to place it - basically package covering all tests
    // Get one of the classes to start, first one will do
    CtClass<?> firstClass = testingClasses.iterator().next();
    String qualifiedName = firstClass.getPackage().getQualifiedName();
    List<String> commonComponents = Arrays.asList(
            qualifiedName.split("[.]"));
    // For all the testing classes find the common subsequence of package names
    for (CtClass<?> ctClass: testingClasses) {
        List<String> currentComponents = Arrays.asList(
                ctClass.getPackage().getQualifiedName().split("[.]"));
        int max = Math.min(currentComponents.size(), commonComponents.size());
        for (int i = 0; i < max; i++ ) {
            if (!currentComponents.get(i).equals(commonComponents.get(i))) {
                commonComponents = commonComponents.subList(0, i);
                break;
            }
        }
    }
    baseTestingClassPackage = String.join(".", commonComponents);
    return this;
}
 
Example 5
Source Project: coming   Source File: VariableAnalyzer.java    License: MIT License 6 votes vote down vote up
private void analyzeV14_VarInstanceOfClass (List<CtVariableAccess> varsAffected, Cntx<Object> context,
		CtClass parentClass) {
	
	try {
		for (CtVariableAccess varAffected : varsAffected) {
			
			boolean v14VarInstanceOfClass= false;
			
			if(varAffected.getType()!=null) {
			   if(varAffected.getType().toString().equals(parentClass.getQualifiedName()) ||
					varAffected.getType().toString().endsWith(parentClass.getQualifiedName()) ||
					parentClass.getQualifiedName().endsWith(varAffected.getType().toString()))
				v14VarInstanceOfClass=true;
			}
			
			writeGroupedInfo(context, adjustIdentifyInJson(varAffected), 
					CodeFeatures.V14_VAR_INSTANCE_OF_CLASS,
					(v14VarInstanceOfClass), "FEATURES_VARS");
		}
	} catch (Throwable e) {
		e.printStackTrace();
	}
}
 
Example 6
Source Project: astor   Source File: MutationSupporter.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Saves Java File and Compiles it The Program Variant as well as the rest of
 * the project is saved on disk. Not any more: Additionally, the compiled class
 * are saved it on disk. Finally, the current Thread has a reference to a class
 * loader with the ProgramVariant
 * 
 * @param instance
 * @throws Exception
 */
public void saveSourceCodeOnDiskProgramVariant(ProgramVariant instance, String srcOutput) throws Exception {
	// Set up the dir where we save the generated output
	this.output.updateOutput(srcOutput);
	Collection<CtClass> _classes = new ArrayList<>();
	// We save only the classes affected by operations.
	List<OperatorInstance> opin = instance.getAllOperations();
	for (OperatorInstance operatorInstance : opin) {
		CtClass _classopin = operatorInstance.getModificationPoint().getCtClass();
		if (_classopin != null && !_classes.contains(_classopin))
			_classes.add(_classopin);
	}
	if (_classes.isEmpty()) {
		_classes = instance.getBuiltClasses().values();
	}

	for (CtClass ctclass : instance.getBuiltClasses().values()) {
		this.generateSourceCodeFromCtClass(ctclass);
	}

}
 
Example 7
Source Project: coming   Source File: ConstructorAnalyzer.java    License: MIT License 6 votes vote down vote up
private void analyzeWhetherConstructorOftheclass (List<CtConstructorCall> constructorsaffected, Cntx<Object> context,
		CtClass parentclss) {
	
	 try {
		 for (CtConstructorCall conAffected : constructorsaffected) {
			
			boolean con5oftheclass = false;
			
			if (conAffected.getType()!=null && (conAffected.getType().getQualifiedName().endsWith(parentclss.getSimpleName()))) {
				con5oftheclass = true;
			}
			
			writeGroupedInfo(context, adjustIdentifyInJson(conAffected),
					CodeFeatures.CON5_Of_Class, 
					con5oftheclass, "FEATURES_CONSTRUCTOR");
		}
	} catch (Throwable e) {
		e.printStackTrace();
	}
}
 
Example 8
Source Project: coming   Source File: MethodAnalyzer.java    License: MIT License 6 votes vote down vote up
private void analyzeMethodFeature_Extend (CtElement originalElement, Cntx<Object> context,
		CtClass parentClass, List<CtInvocation> invocationsFromClass, List<CtInvocation> invocations) {
	
	List<CtConstructorCall> emptyconstructorcallfromclass = new ArrayList<CtConstructorCall>();
	List<CtConstructorCall> emptyconstructorcallunderstudy = new ArrayList<CtConstructorCall>();

	for(CtInvocation invocationAffected : invocations) {
           
           boolean[] methdofeature91012 = analyze_SamerMethodWithGuardOrTrywrap(originalElement, parentClass, invocationsFromClass,
           		Arrays.asList(invocationAffected), emptyconstructorcallfromclass, emptyconstructorcallunderstudy);

           if(methdofeature91012 != null) {
			
           	writeGroupedInfo(context, adjustIdentifyInJson(invocationAffected), CodeFeatures.M9_METHOD_CALL_WITH_NORMAL_GUARD, 
           			methdofeature91012[0], "FEATURES_METHODS");
			
           	writeGroupedInfo(context, adjustIdentifyInJson(invocationAffected), CodeFeatures.M10_METHOD_CALL_WITH_NULL_GUARD, 
           			methdofeature91012[1], "FEATURES_METHODS");
           	
           	writeGroupedInfo(context, adjustIdentifyInJson(invocationAffected), CodeFeatures.M12_METHOD_CALL_WITH_TRY_CATCH, 
           			methdofeature91012[2], "FEATURES_METHODS");
		}         
	}	
}
 
Example 9
@SuppressWarnings({ "rawtypes", "unchecked" })
private void fetchLibOverload(CtInvocation call) {
       
	List<String> origTypes = resolveTypes(call.getArguments());
	CtExpression exp = call.getTarget();
	String typename=exp.getType().getQualifiedName();
	if(typename==null||typename.isEmpty())
		return;
	
       CtClass classname = parser.getClassMap().get(typename); 

	if(classname!=null) {
		Set<CtMethod> overloadmethods=classname.getMethods();
           for(CtMethod methodoverloaded : overloadmethods) {
           	if(call.getExecutable().getSimpleName().equals(methodoverloaded.getSimpleName())) {
           	  List<CtParameter> paramlist=methodoverloaded.getParameters();
           	  List<String> target=resolveParams(paramlist);
           	  transformOneMethod(origTypes,target, call);
           	}
           }
	} else {
		List<Class[]> params = parser.fetchMethods(typename, call.getExecutable().getSimpleName());
		for (Class[] p : params)
			transformOneConstructor(origTypes, call, p);
	}
}
 
Example 10
Source Project: astor   Source File: ProgramVariantFactory.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * This method revolve a CtClass from one suspicious statement. If it was
 * resolved before, it get it from a "cache" of CtClasses stored in the Program
 * Instance.
 * 
 * @param suspiciousCode
 * @param progInstance
 * @return
 */
public CtClass resolveCtClass(String className, ProgramVariant progInstance) {

	// if the ctclass exists in the cache, return it.
	if (progInstance.getBuiltClasses().containsKey(className)) {
		return progInstance.getBuiltClasses().get(className);
	}

	CtClass ctclasspointed = getCtClassFromName(className);
	if (ctclasspointed == null)
		return null;
	// Save the CtClass in cache
	progInstance.getBuiltClasses().put(className, ctclasspointed);

	return ctclasspointed;
}
 
Example 11
Source Project: gumtree-spoon-ast-diff   Source File: AstComparatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void test_t_223056() throws Exception {
	AstComparator diff = new AstComparator();
	// meld src/test/resources/examples/t_223056/left_Server_1.646.java
	// src/test/resources/examples/t_223056/right_Server_1.647.java
	File fl = new File("src/test/resources/examples/t_223056/left_Server_1.646.java");
	File fr = new File("src/test/resources/examples/t_223056/right_Server_1.647.java");
	Diff result = diff.compare(fl, fr);

	CtElement ancestor = result.commonAncestor();
	assertTrue(ancestor instanceof CtClass);

	List<Operation> actions = result.getRootOperations();
	result.debugInformation();
	assertEquals(actions.size(), 2);
	assertTrue(result.containsOperation(OperationKind.Update, "Literal", "\" \""));
	assertTrue(result.containsOperation(OperationKind.Update, "Literal", "\"        \\n\""));
}
 
Example 12
Source Project: coming   Source File: EnhancedRepairGenerator.java    License: MIT License 6 votes vote down vote up
private Set<CtElement> fuzzyLocator(CtElement statement) {
    Set<CtElement> locations = new HashSet<>();
    if (statement instanceof CtMethod || statement instanceof CtClass || statement instanceof CtIf || statement instanceof CtStatementList) {
        locations.add(statement);
    } else {
        // "int a;" is not CtStatement?
        CtElement parent = statement.getParent();
        if (parent != null) {
            List<CtElement> statements = parent.getElements(new TypeFilter<>(CtElement.class));
            if (parent instanceof CtStatement) {
                statements = statements.subList(1, statements.size());
            }
            int idx = statements.indexOf(statement);
            if (idx >= 0) {
                if (idx > 0)
                    locations.add(statements.get(idx - 1));
                locations.add(statements.get(idx));
                if (idx < statements.size() - 1)
                    locations.add(statements.get(idx + 1));
            }
        }
    }
    return locations;
}
 
Example 13
Source Project: coming   Source File: OriginalRepairGenerator.java    License: MIT License 6 votes vote down vote up
private Set<CtElement> fuzzyLocator(CtElement statement) {
    Set<CtElement> locations = new HashSet<>();
    if (statement instanceof CtMethod || statement instanceof CtClass || statement instanceof CtIf || statement instanceof CtStatementList) {
        locations.add(statement);
    } else {
        // "int a;" is not CtStatement?
        CtElement parent = statement.getParent();
        if (parent != null) {
            List<CtElement> statements = parent.getElements(new TypeFilter<>(CtElement.class));
            if (parent instanceof CtStatement) {
                statements = statements.subList(1, statements.size());
            }
            int idx = statements.indexOf(statement);
            if (idx >= 0) {
                if (idx > 0)
                    locations.add(statements.get(idx - 1));
                locations.add(statements.get(idx));
                if (idx < statements.size() - 1)
                    locations.add(statements.get(idx + 1));
            }
        }
    }
    return locations;
}
 
Example 14
Source Project: coming   Source File: S4RORepairGenerator.java    License: MIT License 6 votes vote down vote up
private Set<CtElement> fuzzyLocator(CtElement statement) {
    Set<CtElement> locations = new HashSet<>();
    if (statement instanceof CtMethod || statement instanceof CtClass || statement instanceof CtIf || statement instanceof CtStatementList) {
        locations.add(statement);
    } else {
        // "int a;" is not CtStatement?
        CtElement parent = statement.getParent();
        if (parent != null) {
            List<CtElement> statements = parent.getElements(new TypeFilter<>(CtElement.class));
            if (parent instanceof CtStatement) {
                statements = statements.subList(1, statements.size());
            }
            int idx = statements.indexOf(statement);
            if (idx >= 0) {
                if (idx > 0)
                    locations.add(statements.get(idx - 1));
                locations.add(statements.get(idx));
                if (idx < statements.size() - 1)
                    locations.add(statements.get(idx + 1));
            }
        }
    }
    return locations;
}
 
Example 15
Source Project: coming   Source File: ExtendedRepairGenerator.java    License: MIT License 6 votes vote down vote up
private Set<CtElement> fuzzyLocator(CtElement statement) {
    Set<CtElement> locations = new HashSet<>();
    if (statement instanceof CtMethod || statement instanceof CtClass || statement instanceof CtIf || statement instanceof CtStatementList) {
        locations.add(statement);
    } else {
        // "int a;" is not CtStatement?
        CtElement parent = statement.getParent();
        if (parent != null) {
            List<CtElement> statements = parent.getElements(new TypeFilter<>(CtElement.class));
            if (parent instanceof CtStatement) {
                statements = statements.subList(1, statements.size());
            }
            int idx = statements.indexOf(statement);
            if (idx >= 0) {
                if (idx > 0)
                    locations.add(statements.get(idx - 1));
                locations.add(statements.get(idx));
                if (idx < statements.size() - 1)
                    locations.add(statements.get(idx + 1));
            }
        }
    }
    return locations;
}
 
Example 16
Source Project: gumtree-spoon-ast-diff   Source File: AstComparatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testExtendsGenerics2() throws Exception {
	CtClass c1a = Launcher.parseClass("class Main extends SuperClass { }");
	CtClass c2a = Launcher.parseClass("class Main extends SuperClass<One> { }");

	AstComparator diff = new AstComparator();
	Diff result = diff.compare(c1a, c2a);

	List<Operation> actions = result.getRootOperations();
	result.debugInformation();

	assertEquals(1, actions.size());
	assertTrue(result.containsOperation(OperationKind.Update, "SUPER_TYPE", "SuperClass"));
}
 
Example 17
@Override
public void process(CtStatement element) {
	if (!(element instanceof CtBlock || element instanceof CtClass || element instanceof CtMethod
			|| element instanceof CtTry || element instanceof CtCatch) && 
			(element.getParent() instanceof CtBlock) && 
			(!(element.toString().startsWith("super"))
					|| ConfigurationProperties.getPropertyBool("manipulatesuper"))) {
		add(element);
	}
}
 
Example 18
Source Project: astor   Source File: SpoonClassCompiler.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public CompilationResult compile(ProgramVariant instance, URL[] cp) {
	List<CtClass> ctClasses = new ArrayList<CtClass>(instance.getBuiltClasses().values());
	CompilationResult compilation2 = this.compile(ctClasses, cp);

	return compilation2;
}
 
Example 19
@Test
public void test() throws Exception {
	Launcher spoon = new Launcher();
	spoon.addInputResource("src/test/java");
	spoon.addProcessor(new UniqueTestGenerator());
	spoon.run();
	CtClass<Object> testClass = spoon.getFactory().Class().get("test.TestSuite");
	System.out.println(testClass);
	assertNotNull(testClass);
}
 
Example 20
Source Project: astor   Source File: TransformStrategy.java    License: GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "static-access" })
protected void addImportsForSketch() {
	 CtClass classA = this.modificationPoint.getCtClass();
	 CompilationUnit unitA = this.mutSupporter.getFactory().CompilationUnit().getMap().get(
			 classA.getPosition().getFile().getPath());
	 Collection<CtImport> imports = unitA.getImports();
	 CtImport sketchlib=this.mutSupporter.getFactory().Type().createImport(this.mutSupporter.getFactory().Type().createReference
			 ("fr.inria.astor.approaches.scaffold.scaffoldsynthesis.ScaffoldSynthesisEntry"));
	 imports.add(sketchlib);
//	 unitA.setImports(imports);
}
 
Example 21
Source Project: gumtree-spoon-ast-diff   Source File: AstComparatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testExtendsGenerics1() throws Exception {
	CtClass c1a = Launcher.parseClass("class Main extends SuperClass<One> { }");
	CtClass c2a = Launcher.parseClass("class Main extends SuperClass<Two> { }");

	AstComparator diff = new AstComparator();
	Diff result = diff.compare(c1a, c2a);

	List<Operation> actions = result.getRootOperations();
	result.debugInformation();

	assertEquals(1, actions.size());
	assertTrue(result.containsOperation(OperationKind.Update, "SUPER_TYPE", "SuperClass<One>"));
}
 
Example 22
Source Project: nopol   Source File: MethodFromLocation.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean isToBeProcessed(CtStatement candidate) {
    CtClass parent = candidate.getParent(CtClass.class);
    if (parent == null || !parent.getQualifiedName().equals(this.location.getContainingClassName())) {
        return false;
    }
    return parent.getPosition().getLine() == location.getLineNumber();
}
 
Example 23
Source Project: spoon-examples   Source File: Spoonerism.java    License: GNU General Public License v2.0 5 votes vote down vote up
Spoonerism extendTestingClasses() {
    // Now we need to extend the classes.
    // WARNING: There is a small problem with this, can you spot it?
    // Answer at bottom
    CtTypeReference<?> baseTestingClassRef =
            baseTestingClass.getReference();
    for (CtClass<?> ctClass: testingClasses) {
        if (ctClass.getSuperclass() == null) {
            ctClass.setSuperclass(baseTestingClassRef);
        }
    }
    return this;
}
 
Example 24
Source Project: spoon-examples   Source File: Collector.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void collect(Launcher launcher, CtMethod<?> testMethod, List<CtLocalVariable> localVariables) {
	CtClass testClass = testMethod.getParent(CtClass.class);
	testClass.removeMethod(testMethod);
	CtMethod<?> clone = testMethod.clone();
	instrument(clone, localVariables);
	testClass.addMethod(clone);
	System.out.println(clone);
	run(launcher, testClass, clone);
	testClass.removeMethod(clone);
	testClass.addMethod(testMethod);
}
 
Example 25
Source Project: spoon-examples   Source File: Collector.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void run(Launcher launcher, CtClass testClass, CtMethod<?> clone) {
	String fullQualifiedName = testClass.getQualifiedName();
	String testMethodName = clone.getSimpleName();
	try {
		final SpoonModelBuilder compiler = launcher.createCompiler();
		compiler.compile(SpoonModelBuilder.InputType.CTTYPES);
		TestRunner.runTest(fullQualifiedName, testMethodName, new String[]{"spooned-classes"});
	} catch (ClassNotFoundException | MalformedURLException e) {
		throw new RuntimeException(e);
	}
}
 
Example 26
@Test
public void test() {
	Launcher launcher = new Launcher();
	launcher.getEnvironment().setAutoImports(true);
	launcher.getEnvironment().setLevel(Level.ALL.toString());
	launcher.addInputResource("src/test/resources/project/src/main/java/");
	launcher.addInputResource("src/test/resources/project/src/test/java/");
	launcher.addInputResource("src/main/java/fr/inria/gforge/spoon/assertgenerator/Logger.java");
	launcher.getEnvironment().setSourceClasspath(getPathToJunit());
	launcher.buildModel();

	final Analyzer analyzer = new Analyzer();
	final Collector collector = new Collector(launcher.getFactory());
	final AssertionAdder assertionAdder = new AssertionAdder(launcher.getFactory());

	launcher.getFactory().Class().getAll().forEach(ctClass -> {
		// Analyze
		Map<CtMethod, List<CtLocalVariable>> localVariablesPerTestMethod = analyzer.analyze(ctClass);
		localVariablesPerTestMethod.keySet().stream().forEach(key -> System.out.println("{"+ key.getParent(CtClass.class).getSimpleName() + "#" + key.getSimpleName() + "=["+ localVariablesPerTestMethod.get(key) +"]"));
		if (!localVariablesPerTestMethod.isEmpty()) {
			// Collect
			localVariablesPerTestMethod.keySet().forEach(ctMethod -> collector.collect(launcher, ctMethod, localVariablesPerTestMethod.get(ctMethod)));
			// Generate
			localVariablesPerTestMethod.keySet().forEach(ctMethod -> assertionAdder.addAssertion(ctMethod, localVariablesPerTestMethod.get(ctMethod)));
		}
	});
}
 
Example 27
public void process(CtConstructorCall<?> newClass) {
	// skip factory creation
	if (newClass.getExecutable().getDeclaringType().isSubtypeOf(getFactoryType()))
		return;
	// skip creations in factories
	if (newClass.getParent(CtClass.class).isSubtypeOf(getFactoryType()))
		return;
	// only report for types created by the factory
	for (CtTypeReference<?> t : getCreatedTypes()) {
		if (newClass.getType().isSubtypeOf(t)) {
			this.listWrongUses.add(newClass);
		}
	}

}
 
Example 28
@Override
public void process(CtMethod method) {
    final Factory factory = method.getFactory();

    CtBlock methodBody = method.getBody();

    List<CtComment> bodyComments = new ArrayList<>();

    ArrayList<CtStatement> ctStatements = new ArrayList<>(methodBody.getStatements());
    for (CtStatement ctStatement : ctStatements) {
        String statement = ctStatement.toString();
        bodyComments.add(factory.createInlineComment(statement));
        methodBody.removeStatement(ctStatement);
    }

    CtClass<? extends Throwable> myExceptionClass = factory.Class().get(EXCEPTION_FQN);
    CtConstructorCall<? extends Throwable> myNewException = factory.createConstructorCall(myExceptionClass.getReference());

    CtThrow throwMyException = factory.createThrow();
    throwMyException.setThrownExpression(myNewException);
    methodBody.addStatement(throwMyException);

    bodyComments.add(factory.createInlineComment("FIXME: The private API type should never be return in a public API."));

    for (CtComment bodyComment : bodyComments) {
        throwMyException.addComment(bodyComment);
    }
}
 
Example 29
Source Project: spoon-examples   Source File: LogProcessor.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void process(CtExecutable element) {
	CtCodeSnippetStatement snippet = getFactory().Core().createCodeSnippetStatement();

	// Snippet which contains the log.
	final String value = String.format("System.out.println(\"Enter in the method %s from class %s\");",
			element.getSimpleName(),
			element.getParent(CtClass.class).getSimpleName());
	snippet.setValue(value);

	// Inserts the snippet at the beginning of the method body.
	if (element.getBody() != null) {
		element.getBody().insertBegin(snippet);
	}
}
 
Example 30
public void process(DBAccess dbAccess, CtClass<?> target) {
	Factory f = target.getFactory();
	DBType t = dbAccess.type();
	if (t != DBType.RELATIONAL)
		f.getEnvironment().report(
				this,
				Level.ERROR,
				target.getAnnotation(f.Type().createReference(
						DBAccess.class)), "unsupported DB system");

	DBCodeTemplate template = new DBCodeTemplate(f, dbAccess.database(),
			dbAccess.username(), dbAccess.password(), dbAccess.tableName());
	Substitution.insertField(target, template, f.Class().get(
			DBCodeTemplate.class).getField("connection"));
	for (CtConstructor<?> c : target.getConstructors()) {
		c.getBody().insertBegin((CtStatement)
				Substitution.substituteMethodBody(target, template,
						"initializerCode"));
	}
	for (CtMethod<?> m : target.getMethods()) {
		template._columnName_ = m.getSimpleName().substring(3)
				.toLowerCase();
		m.getBody().replace(
				Substitution.substituteMethodBody(target, template,
						"accessCode"));
	}
}