spoon.reflect.declaration.CtClass Java Examples

The following examples show how to use spoon.reflect.declaration.CtClass. 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 File: MutationSupporter.java    From astor with 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 #2
Source File: OverloadMethodTransform.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@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 #3
Source File: ProgramVariantFactory.java    From astor with 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 #4
Source File: AstComparatorTest.java    From gumtree-spoon-ast-diff with 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 #5
Source File: StatementDeletionMetaMutatorTest.java    From metamutator with GNU General Public License v3.0 6 votes vote down vote up
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 #6
Source File: EvoSuiteFacade.java    From astor with 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 #7
Source File: EnhancedRepairGenerator.java    From coming with 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 #8
Source File: OriginalRepairGenerator.java    From coming with 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 #9
Source File: Spoonerism.java    From spoon-examples with 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 #10
Source File: VariableAnalyzer.java    From coming with 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 #11
Source File: S4RORepairGenerator.java    From coming with 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 #12
Source File: ExtendedRepairGenerator.java    From coming with 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 File: MethodAnalyzer.java    From coming with 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 #14
Source File: AstComparatorTest.java    From gumtree-spoon-ast-diff with 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 #15
Source File: ConstructorAnalyzer.java    From coming with 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 #16
Source File: WholeStatementAnalyzer.java    From coming with MIT License 5 votes vote down vote up
private void analyzeS15_HasObjectiveInvocations(CtElement element, Cntx<Object> context, CtClass parentClass,
		List<CtInvocation> invocationstostudy) {

	try {
		boolean S15anyReturnObjective = false;

		for (CtInvocation invocation : invocationstostudy) {

			CtStatement parent = invocation.getParent(new LineFilter());

			if (isNormalGuard(invocation, (parent)) || isNullCheckGuard(invocation, (parent)))
				continue;

			if ((invocation.getType() != null && !invocation.getType().isPrimitive())
					|| whetherhasobjective(inferPotentionalTypes(invocation, parentClass))) {
				S15anyReturnObjective = true;
			}

			if (S15anyReturnObjective)
				break;
		}

		context.put(CodeFeatures.S15_HAS_OBJECTIVE_METHOD_CALL, S15anyReturnObjective);
	} catch (Throwable e) {
		e.printStackTrace();
	}
}
 
Example #17
Source File: AstComparatorTest.java    From gumtree-spoon-ast-diff with Apache License 2.0 5 votes vote down vote up
@Test
public void testExtends() throws Exception {
	CtClass c1a = Launcher.parseClass("class Main extends SuperClass1 { }");
	CtClass c2a = Launcher.parseClass("class Main extends SuperClass2 { }");

	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", "SuperClass1"));
}
 
Example #18
Source File: RemoveOp.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean canBeAppliedToPoint(ModificationPoint point) {
	if (!(point.getCodeElement() instanceof CtStatement))
		return false;
	// Do not remove local declaration
	if (point.getCodeElement() instanceof CtLocalVariable) {
		CtLocalVariable lv = (CtLocalVariable) point.getCodeElement();
		boolean shadow = false;
		CtClass parentC = point.getCodeElement().getParent(CtClass.class);
		List<CtField> ff = parentC.getFields();
		for (CtField<?> f : ff) {
			if (f.getSimpleName().equals(lv.getSimpleName()))
				shadow = true;
		}
		if (!shadow)
			return false;
	}
	// do not remove the last statement
	CtMethod parentMethd = point.getCodeElement().getParent(CtMethod.class);
	if (point.getCodeElement() instanceof CtReturn
			&& parentMethd.getBody().getLastStatement().equals(point.getCodeElement())) {
		return false;
	}

	// Otherwise, accept the element
	return true;
}
 
Example #19
Source File: EvalTOSClusterApproach.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public List<ClusterExpressions> getEvaluatedExpression(ModificationPoint iModifPoint) {
	DynamothSynthesisContext contextCollected = null;
	try {
		contextCollected = this.collectorFacade.collectValues(getProjectFacade(), iModifPoint);
	} catch (Exception e) {
		log.error("Error calling Dynamoth value recolection MP id: " + iModifPoint.identified);
		log.error("Failing collecting values from class: "
				+ iModifPoint.getCodeElement().getParent(CtClass.class).getQualifiedName());
		log.error(e);
		currentStat.increment(GeneralStatEnum.NR_ERRONEOUS_VARIANCES);
		return null;
	}
	// Collecting values:
	// values are collected from all test.

	// Creating combinations (do not depend on the Holes because
	// they are combination of variables in context of a
	// modification point)
	DynamothSynthesizerWOracle synthesizer = new DynamothSynthesizerWOracle(contextCollected);

	Candidates evaluatedExpressions = synthesizer.combineValues();

	if (evaluatedExpressions.isEmpty()) {
		log.error("Error: not collected values for MP " + iModifPoint);
	}
	// This is only for logging info...
	MapCounter<String> typesOfCandidatesCombined = getTypesOfExpressions(evaluatedExpressions);

	log.info("types Of Candidates: " + typesOfCandidatesCombined.sorted());

	log.info("Start clustering");
	// Key: test name, value list of clusters, each cluster is a list of
	// evaluated expressions
	List<ClusterExpressions> cluster = clusterCandidatesByValue(evaluatedExpressions);
	return cluster;
}
 
Example #20
Source File: ProgramVariantFactory.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public CtClass getCtClassFromCtElement(CtElement element) {

		if (element == null)
			return null;
		if (element instanceof CtClass)
			return (CtClass) element;

		return getCtClassFromCtElement(element.getParent());
	}
 
Example #21
Source File: S4RORepairAnalyzer.java    From coming with MIT License 5 votes vote down vote up
public Set<CtElement> getGlobalCandidateExprs(CtElement element) {
    Set<CtElement> ret = new HashSet<>();
    CtClass ownedClass = element.getParent(new TypeFilter<>(CtClass.class));
    if (ownedClass != null) {
        ret.addAll(ownedClass.getElements(new TypeFilter<>(CtExpression.class)));
    }
    return ret;
}
 
Example #22
Source File: SupportOperators.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public static List getAllMethodsFromClass(CtClass parentClass) {
	List allMethods = new ArrayList(parentClass.getAllMethods());

	if (parentClass != null && parentClass.getParent() instanceof CtClass) {
		CtClass parentParentClass = (CtClass) parentClass.getParent();
		allMethods.addAll(parentParentClass.getAllMethods());

	}
	return allMethods;
}
 
Example #23
Source File: MutationSupporter.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Save on disk Source code file Should be configured before:
 * .getSpoonClassCompiler().updateOutput(srcOutput);
 * 
 * @param type
 * @return
 */
public void generateSourceCodeFromCtClass(CtType<?> type) {
	// WorkArround, for cloned
	SourcePosition sp = type.getPosition();
	type.setPosition(null);

	if (output == null || output.getJavaPrinter() == null) {
		throw new IllegalArgumentException("Spoon compiler must be initialized");
	}
	output.saveSourceCode((CtClass) type);
	// --
	// End Workarround
	type.setPosition(sp);

}
 
Example #24
Source File: AstComparatorTest.java    From gumtree-spoon-ast-diff with Apache License 2.0 5 votes vote down vote up
@Test
public void testModifEmpty() throws Exception {

	CtClass c1a = Launcher.parseClass(" class BehaviorCall implements Call{\n"
			+ "final AtomicReference failureRef = new AtomicReference<>();\n"
			+ "final CountDownLatch latch = new CountDownLatch(1);\n" + "\n" + " enqueue(new Callback<T>() {\n"
			+ "  @Override public void onResponse(Response<T> response) {\n" + "     responseRef.set(response);\n"
			+ "     latch.countDown();\n" + "   }\n" + "}\n" + ")\n" + "\n" + "}");

	CtClass c2a = Launcher.parseClass("class BehaviorCall implements Call {\n"
			+ "final AtomicReference failureRef = new AtomicReference<>();\n"
			+ "final CountDownLatch latch = new CountDownLatch(1);\n" + "enqueue(new Callback() {\n"
			// Here the difference
			+ "@override public void onResponse(Call call, Response response) {\n" + "responseRef.set(response);\n"
			+ "latch.countDown();\n" + "}\n" + "}\n" + ")\n" + "}");

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

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

	assertEquals(1, actions.size());

	assertTrue(resulta.containsOperation(OperationKind.Insert, "Parameter", "call"));
	// assertTrue(resulta.containsOperation(OperationKind.Update, "SUPER_TYPE",
	// "Callback<T>"));

	DiffImpl idiff = (DiffImpl) resulta;

	for (Mapping map : idiff.getMappingsComp()) {
		if ((map.getFirst().toPrettyString(idiff.getContext()).startsWith(NodeCreator.MODIFIERS))) {
			assertFalse(map.getFirst().getChildren().isEmpty());
			assertFalse(map.getSecond().getChildren().isEmpty());
		}
	}

}
 
Example #25
Source File: TypeaccessAnalyzer.java    From coming with MIT License 5 votes vote down vote up
private void analyzeC3C4_SimilarTypeAccessActualVar(CtElement element, Cntx<Object> context, 
		List<CtTypeAccess> typeaccessaaffected, CtClass parentClass) {
	
	try {
		List<CtTypeAccess> typeaccesss = new ArrayList();
		if(parentClass!=null)
		    typeaccesss = parentClass.getElements(new TypeFilter<>(CtTypeAccess.class));

		for (CtTypeAccess virtualtypeaccess : typeaccessaaffected) {
			
			boolean c3CurrentOtherTypeAccessActualVar = false;
			boolean c4CurrentOtherSimilarTypeAccessActualVar = false;
			
			if(isTypeAccessActualVar(virtualtypeaccess)) {
				c3CurrentOtherTypeAccessActualVar=true;
				
				for(CtTypeAccess certaintypeaccess: typeaccesss) {
					if(isTypeAccessActualVar(certaintypeaccess)) {
						if(whetherSimilarTypeAccessActualVar(virtualtypeaccess, certaintypeaccess)) {
							c4CurrentOtherSimilarTypeAccessActualVar=true;
							break;
						}
					}
				}
			}
			
			writeGroupedInfo(context, adjustIdentifyInJson(virtualtypeaccess), CodeFeatures.C3_TYPEACCESS_ACTUAL_VAR,
					c3CurrentOtherTypeAccessActualVar, "FEATURES_TYPEACCESS");
			
			writeGroupedInfo(context, adjustIdentifyInJson(virtualtypeaccess), CodeFeatures.C4_SIMILAR_TYPEACCESS_ACTUAL_VAR,
					c4CurrentOtherSimilarTypeAccessActualVar, "FEATURES_TYPEACCESS");
		}

	} catch (Throwable e) {
		e.printStackTrace();
	}	
}
 
Example #26
Source File: ProgramVariantFactory.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public static ModificationPoint clonePoint(ModificationPoint existingGen, CtElement modified) {
	CtClass ctClass = existingGen.getCtClass();
	List<CtVariable> context = existingGen.getContextOfModificationPoint();
	ModificationPoint newGen = new ModificationPoint(modified, ctClass, context);
	return newGen;

}
 
Example #27
Source File: ProgramVariantFactory.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public static SuspiciousModificationPoint clonePoint(SuspiciousModificationPoint existingGen, CtElement modified) {
	SuspiciousCode suspicious = existingGen.getSuspicious();
	CtClass ctClass = existingGen.getCtClass();
	List<CtVariable> context = existingGen.getContextOfModificationPoint();
	SuspiciousModificationPoint newGen = new SuspiciousModificationPoint(suspicious, modified, ctClass, context);
	return newGen;

}
 
Example #28
Source File: MutationTester.java    From spoon-examples with GNU General Public License v2.0 5 votes vote down vote up
/** compiles the mutants on the fly */
public List<Class<?>> compileMutants(List<CtClass> mutants) throws Exception {
	List<Class<?>> compiledMutants = new ArrayList<>();
	for (CtClass mutantClass : mutants) {
		Class<?> klass = InMemoryJavaCompiler.newInstance().compile(
				mutantClass.getQualifiedName(), "package "
						+ mutantClass.getPackage().getQualifiedName() + ";"
						+ mutantClass);
		compiledMutants.add(klass);
	}
	return compiledMutants;
}
 
Example #29
Source File: DBAccessProcessor.java    From spoon-examples with GNU General Public License v2.0 5 votes vote down vote up
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"));
	}
}
 
Example #30
Source File: LogProcessor.java    From spoon-examples with 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);
	}
}