spoon.reflect.factory.Factory Java Examples

The following examples show how to use spoon.reflect.factory.Factory. 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: 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 #2
Source File: ExpressionGenerator.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
private static CtExpression fetchExpressionOnType(Factory factory, List<CtVariable> visiablevars, String type, String query, Boolean whetherEnum) {
	if (type == null || type.equals(""))
		return null;
	CtCodeSnippetExpression typeexper = factory.Code().createCodeSnippetExpression(type+".class");
	ArrayList<CtExpression> param = getParameter(factory, visiablevars, type, whetherEnum);
	
	param.add(1, factory.Code().createCodeSnippetExpression(Integer.toString(0)));

	param.add(3, typeexper);
	
	CtExpression[] arr = param.toArray(new CtExpression[param.size()]);
	
	CtExecutableReference<Object> ref = factory.Core().createExecutableReference();
	ref.setSimpleName(query);
	
	CtInvocation methodcall=factory.Code().createInvocation(factory.Code().createCodeSnippetExpression("fr.inria.astor.approaches.scaffold.scaffoldsynthesis.ScaffoldSynthesisEntry"),
			ref, 
			arr);
			
	String castType = primToObj.containsKey(type) ? primToObj.get(type) : type;  
	CtCodeSnippetExpression castedexp = factory.Code().createCodeSnippetExpression("(" + castType+ ")"+"("+methodcall.toString()+
			".invoke()".toString()+")");
	return castedexp;
}
 
Example #3
Source File: CatchProcessorTest.java    From spoon-examples with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testCatchProcessor() throws Exception {
	final String[] args = {
			"-i", "src/test/resources/src/",
			"-o", "target/spooned/"
	};

	final Launcher launcher = new Launcher();
	launcher.setArgs(args);
	launcher.run();

	final Factory factory = launcher.getFactory();
	final ProcessingManager processingManager = new QueueProcessingManager(factory);
	final CatchProcessor processor = new CatchProcessor();
	processingManager.addProcessor(processor);
	processingManager.process(factory.Class().getAll());

	assertEquals(2, processor.emptyCatchs.size());
}
 
Example #4
Source File: ReferenceProcessorTest.java    From spoon-examples with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testReferenceProcessor() throws Exception {
	final String[] args = {
			"-i", "src/test/resources/src/",
			"-o", "target/spooned/",
	};

	final Launcher launcher = new Launcher();
	launcher.setArgs(args);
	launcher.run();

	final Factory factory = launcher.getFactory();
	final ProcessingManager processingManager = new QueueProcessingManager(factory);
	final ReferenceProcessor processor = new ReferenceProcessor();
	processingManager.addProcessor(processor);
	processingManager.process(factory.Package().getRootPackage());

	// implicit constructor is also counted
	assertThat(processor.circularPathes.size(), is(2));
}
 
Example #5
Source File: EmptyMethodBodyProcessorTest.java    From spoon-examples with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testEmptyMethodProcessor() throws Exception {
	final String[] args = {
			"-i", "src/test/resources/src/DocTest.java",
			"-o", "target/spooned/"
	};

	final Launcher launcher = new Launcher();
	launcher.setArgs(args);
	launcher.run();

	final Factory factory = launcher.getFactory();
	final ProcessingManager processingManager = new QueueProcessingManager(factory);
	final EmptyMethodBodyProcessor processor = new EmptyMethodBodyProcessor();
	processingManager.addProcessor(processor);
	processingManager.process(factory.Class().getAll());

	assertThat(processor.emptyMethods.size(), is(4));
}
 
Example #6
Source File: FactoryProcessorTest.java    From spoon-examples with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testReferenceProcessor() throws Exception {
	final String[] args = {
			"-i", "src/test/resources/factory/",
			"-o", "target/spooned/"
	};

	final Launcher launcher = new Launcher();
	launcher.setArgs(args);
	launcher.run();

	final Factory factory = launcher.getFactory();
	final ProcessingManager processingManager = new QueueProcessingManager(factory);
	List<CtInterface> listFactoryItf = factory.getModel().getElements(new NamedElementFilter<>(CtInterface.class, "Factory"));
	assertThat(listFactoryItf.size(), is(1));

	final FactoryProcessor processor = new FactoryProcessor(listFactoryItf.get(0).getReference());
	processingManager.addProcessor(processor);

	List<CtConstructorCall> ctNewClasses = factory.getModel().getElements(new TypeFilter<>(CtConstructorCall.class));
	processingManager.process(ctNewClasses);

	// implicit constructor is also counted
	assertThat(processor.listWrongUses.size(), is(2));
}
 
Example #7
Source File: CodeFeatureDetectorTest.java    From coming with MIT License 6 votes vote down vote up
protected CtType getCtType(SpoonResource resource) {
	Factory factory = createFactory();
	factory.getModel().setBuildModelIsFinished(false);
	SpoonModelBuilder compiler = new JDTBasedSpoonCompiler(factory);
	compiler.getFactory().getEnvironment().setLevel("OFF");
	compiler.addInputSource(resource);
	compiler.build();

	if (factory.Type().getAll().size() == 0) {
		return null;
	}

	// let's first take the first type.
	CtType type = factory.Type().getAll().get(0);
	// Now, let's ask to the factory the type (which it will set up the
	// corresponding
	// package)
	return factory.Type().get(type.getQualifiedName());
}
 
Example #8
Source File: AstComparatorTest.java    From gumtree-spoon-ast-diff with Apache License 2.0 5 votes vote down vote up
@Test
public void testgetCtType() throws Exception {
	final Factory factory = new Launcher().getFactory();
	String c1 = "package spoon1.test; " //
			+ "class X {" //
			+ "public void foo0() {" //
			+ " int x = 0;" //
			+ "}" //
			+ "}";
	assertTrue(getCtType(factory, c1) != null);
}
 
Example #9
Source File: ArithmeticBinaryOperatorMutator.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public ArithmeticBinaryOperatorMutator(Factory factory) {
	super(factory);
	operators = Arrays.asList(BinaryOperatorKind.PLUS, BinaryOperatorKind.MINUS, BinaryOperatorKind.MUL,
			BinaryOperatorKind.DIV, BinaryOperatorKind.MOD

	);

}
 
Example #10
Source File: AstorCoreEngine.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void initModel() throws Exception {

		if (!MutationSupporter.getFactory().Type().getAll().isEmpty()) {
			if (ConfigurationProperties.getPropertyBool("resetmodel")) {
				Factory fcurrent = MutationSupporter.getFactory();
				log.debug("The Spoon Model was already built.");
				Factory fnew = MutationSupporter.cleanFactory();
				log.debug("New factory created? " + !fnew.equals(fcurrent));
			} else {
				log.debug("we keep previous factory");
				// we do not generate a new model
				return;
			}
		}

		this.mutatorSupporter.buildSpoonModel(this.projectFacade);

		log.info("Number of CtTypes created: " + mutatorSupporter.getFactory().Type().getAll().size());

		///// ONCE ASTOR HAS BUILT THE MODEL,
		///// We apply different processes and manipulation over it.

		// We process the model to add blocks as parent of statement which are
		// not contained in a block
		BlockReificationScanner visitor = new BlockReificationScanner();
		for (CtType c : mutatorSupporter.getFactory().Type().getAll()) {
			c.accept(visitor);
		}

	}
 
Example #11
Source File: SpoonModelLibrary.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
public static Factory modelFor(Factory factory, File[] sourceFiles, URL[] classpath) {
    factory.getEnvironment().setLevel("OFF");
    factory.getEnvironment().setCommentEnabled(false);
    SpoonModelBuilder compiler = launcher().createCompiler(factory);
    if (classpath != null) {
        compiler.setSourceClasspath(JavaLibrary.asFilePath(classpath));
    }
    for (int i = 0; i < sourceFiles.length; i++) {
        File sourceFile = sourceFiles[i];
        compiler.addInputSource(sourceFile);
    }
    compiler.build();
    return factory;
}
 
Example #12
Source File: SpoonModelLibrary.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
public static CtTry newTryCatch(Factory factory, CtStatement tryBlock, List<CtCatch> catchers, CtElement parent) {
    CtTry tryCatch = factory.Core().createTry();
    tryCatch.setBody(asBlock(tryBlock, tryCatch));
    tryCatch.setCatchers(catchers);
    setParent(tryCatch, catchers);
    setParent(parent, tryCatch);
    return tryCatch;
}
 
Example #13
Source File: LoopInstrumenter.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
public static void instrument(LoopMonitor monitor, RuntimeValues<?> runtimeValues) {
    While loop = monitor.loop();
    CtWhile astLoop = loop.astLoop();
    Factory factory = astLoop.getFactory();
    CollectableValueFinder finder = CollectableValueFinder.valueFinderFromWhile(astLoop);
    CtStatement catchCallback = appendMonitorCallbacks(factory, monitor, loop, astLoop);
    CtIf newIf = loopBodyWrapper(factory, monitor, loop, astLoop, catchCallback);
    declareOriginalConditionEvaluation(factory, monitor, loop, newIf);
    declareConditionEvaluation(factory, monitor, loop, newIf);
    declareEntrancesCounter(factory, monitor, astLoop);
    traceReachableValues(monitor, loop, newIf, finder, runtimeValues);
}
 
Example #14
Source File: LoopInstrumenter.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
private static void appendMonitoredReturnExit(Factory factory, LoopMonitor monitor, Collection<CtReturn<?>> returns) {
    String counterName = counterName(monitor);
    for (CtReturn<?> returnStatement : returns) {
        CtStatement invocationOnLoopReturn = newStatementFromSnippet(factory, monitor.invocationOnLoopReturn(counterName));
        insertBeforeUnderSameParent(invocationOnLoopReturn, returnStatement);
    }
}
 
Example #15
Source File: LoopInstrumenter.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
private static void appendMonitoredBreakExit(Factory factory, LoopMonitor monitor, Collection<CtBreak> breaks) {
    String counterName = counterName(monitor);
    for (CtBreak breakStatement : breaks) {
        CtStatement invocationOnLoopBreak = newStatementFromSnippet(factory, monitor.invocationOnLoopBreak(counterName));
        insertBeforeUnderSameParent(invocationOnLoopBreak, breakStatement);
    }
}
 
Example #16
Source File: LoopInstrumenter.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
private static CtIf loopBodyWrapper(Factory factory, LoopMonitor monitor, While loop, CtWhile astLoop, CtStatement catchCallback) {
    CtIf newIf = originalLoopReplacement(factory, monitor, loop);
    CtBlock<?> catchBlock = newBlock(factory, catchCallback, newThrow(factory, Throwable.class, catchName(monitor)));
    CtTry tryCatch = newTryCatch(factory, newIf, Throwable.class, catchName(monitor), catchBlock, astLoop);
    setLoopBody(astLoop, tryCatch);
    setLoopingCondition(astLoop, newLiteral(factory, true));
    return newIf;
}
 
Example #17
Source File: LoopInstrumenter.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
private static CtIf originalLoopReplacement(Factory factory, LoopMonitor monitor, While loop) {
    CtExpression<Boolean> monitoredCondition = newExpressionFromSnippet(factory, conditionName(monitor), Boolean.class);
    CtIf newIf = newIf(factory, monitoredCondition, loop.loopBody(), newBreak(factory));
    CtStatement increment = newStatementFromSnippet(factory, format("%s += 1", counterName(monitor)));
    insertBeforeUnderSameParent(increment, newIf.getThenStatement());
    if (loop.isUnbreakable()) {
        newIf.setElseStatement(null);
    }
    return newIf;
}
 
Example #18
Source File: TestExecutorProcessor.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
public static void createMainTestClass(SpoonedFile spooner,
                                       String className) {
    Factory factory = spooner.spoonFactory();
    CtClass<Object> executeTestClass = factory.Class().create(className);

    CtTypeReference<String[]> typedReference = factory.Class()
            .createReference(String[].class);
    CtTypeReference<Object> returnTypedReference = factory.Class()
            .createReference("void");

    Set<ModifierKind> modifiers = new LinkedHashSet<>(2);
    modifiers.add(ModifierKind.PUBLIC);
    modifiers.add(ModifierKind.STATIC);

    HashSet<CtTypeReference<? extends Throwable>> exceptions = new HashSet<>();
    exceptions.add(factory.Class().createReference(Exception.class));

    CtBlock<?> body = spooner.spoonFactory().Core().createBlock();

    body.addStatement(factory
            .Code()
            .createCodeSnippetStatement(
                    "for (String method : methods) {\n\t\t"
                            + "String[] split = method.split(\"\\\\.\");\n\t\t"
                            + "Class.forName(method.replace(\".\" + split[split.length - 1], \"\")).getMethod(\"runJPFTest\", String[].class).invoke(null, new Object[] { new String[] { split[split.length - 1] }});}"));

    CtMethod<?> method = spooner
            .spoonFactory()
            .Method()
            .create(executeTestClass, modifiers, returnTypedReference,
                    "main", new ArrayList<CtParameter<?>>(), exceptions,
                    body);
    spooner.spoonFactory().Method()
            .createParameter(method, typedReference, "methods");
}
 
Example #19
Source File: ValuesCollectorTest.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
private CtElement elementFromSnippet(File sourceFile, String codeSnippet) {
	Factory model = SpoonModelLibrary.modelFor(new File[]{sourceFile});
	Filter filter = new CodeSnippetFilter(sourceFile, codeSnippet);
	// used to debug when the pretty-printed format of Spoon changes
	// for (CtType t : model.getModel().getAllTypes()) {
	//	System.out.println(t);
	//}
	List<CtElement> elements = SpoonElementLibrary.filteredElements(model, filter);
	assertEquals(1, elements.size());
	return elements.get(0);
}
 
Example #20
Source File: PatchGeneratorTest.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void simpleConditionChangeTest() {
	NopolContext nopolContext = new NopolContext(projectSourcePath, null, null);

	Launcher spoon = new Launcher();
	spoon.addInputResource(projectSourcePath);
	spoon.buildModel();

	Factory factory = spoon.getFactory();
	SourceLocation pathLocation = new SourceLocation("fr.inria.lille.diff.testclasses.Bar", 6);
	pathLocation.setSourceStart(83);
	pathLocation.setSourceEnd(98);

	ExpressionPatch patch = new ExpressionPatch(
			new LiteralImpl(ValueFactory.create(false), nopolContext),
			pathLocation,
			RepairType.CONDITIONAL);
	PatchGenerator test = new PatchGenerator(
			patch,
			factory, nopolContext);

	Assert.assertEquals("--- a/"+projectSourcePath+"/Bar.java\n"
			+ "+++ b/"+projectSourcePath+"/Bar.java\n"
			+ "@@ -5,4 +5,4 @@\n"
			+ " \tpublic void m() {\n"
			+ "-\t\tif (true) {\n"
			+ "-\n"
			+ "+\t\tif (false) {\n"
			+ "+\t\t\t\n"
			+ " \t\t}\n", test.getPatch());
}
 
Example #21
Source File: PatchGeneratorTest.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void simpleConditionChangeTestWithProjectRootPath() {
	NopolContext nopolContext = new NopolContext(projectSourcePath, null, null);
	Path projectRootPath = new File("src/test/java").toPath();
	nopolContext.setRootProject(projectRootPath);

	Launcher spoon = new Launcher();
	spoon.addInputResource(projectSourcePath);
	spoon.buildModel();

	Factory factory = spoon.getFactory();
	SourceLocation pathLocation = new SourceLocation("fr.inria.lille.diff.testclasses.Bar", 6);
	pathLocation.setSourceStart(83);
	pathLocation.setSourceEnd(98);

	ExpressionPatch patch = new ExpressionPatch(
			new LiteralImpl(ValueFactory.create(false), nopolContext),
			pathLocation,
			RepairType.CONDITIONAL);
	PatchGenerator test = new PatchGenerator(
			patch,
			factory, nopolContext);

	Assert.assertEquals("--- a/fr/inria/lille/diff/testclasses/Bar.java\n"
			+ "+++ b/fr/inria/lille/diff/testclasses/Bar.java\n"
			+ "@@ -5,4 +5,4 @@\n"
			+ " \tpublic void m() {\n"
			+ "-\t\tif (true) {\n"
			+ "-\n"
			+ "+\t\tif (false) {\n"
			+ "+\t\t\t\n"
			+ " \t\t}\n", test.getPatch());
}
 
Example #22
Source File: PatchGeneratorTest.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void conditionChangeElseIfTest() {
	NopolContext nopolContext = new NopolContext(projectSourcePath, null, null);

	Launcher spoon = new Launcher();
	spoon.addInputResource(projectSourcePath);
	spoon.buildModel();

	Factory factory = spoon.getFactory();
	SourceLocation pathLocation = new SourceLocation("fr.inria.lille.diff.testclasses.Bar", 12);
	pathLocation.setSourceStart(125);
	pathLocation.setSourceEnd(140);

	ExpressionPatch patch = new ExpressionPatch(
			new LiteralImpl(ValueFactory.create(false), nopolContext),
			pathLocation,
			RepairType.CONDITIONAL);
	PatchGenerator test = new PatchGenerator(
			patch,
			factory, nopolContext);

	Assert.assertEquals("--- a/"+projectSourcePath+"/Bar.java\n"
			+ "+++ b/"+projectSourcePath+"/Bar.java\n"
			+ "@@ -11,4 +11,4 @@\n"
			+ " \n"
			+ "-\t\t} else if (true) {\n"
			+ "-\n"
			+ "+\t\t} else if (false) {\n"
			+ "+\t\t\t\n"
			+ " \t\t}\n", test.getPatch());
}
 
Example #23
Source File: PatchGeneratorTest.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void preconditionElseIfTest() {
	NopolContext nopolContext = new NopolContext(projectSourcePath, null, null);

	Launcher spoon = new Launcher();
	spoon.addInputResource(projectSourcePath);
	spoon.buildModel();

	Factory factory = spoon.getFactory();
	SourceLocation pathLocation = new SourceLocation("fr.inria.lille.diff.testclasses.Bar", 12);
	pathLocation.setSourceStart(125);
	pathLocation.setSourceEnd(140);

	ExpressionPatch patch = new ExpressionPatch(
			new LiteralImpl(ValueFactory.create(false), nopolContext),
			pathLocation,
			RepairType.PRECONDITION);
	PatchGenerator test = new PatchGenerator(
			patch,
			factory, nopolContext);

	Assert.assertEquals("--- a/"+projectSourcePath+"/Bar.java\n"
			+ "+++ b/"+projectSourcePath+"/Bar.java\n"
			+ "@@ -11,4 +11,8 @@\n"
			+ " \n"
			+ "-\t\t} else if (true) {\n"
			+ "-\n"
			+ "+\t\t} else {\n"
			+ "+\t\t\tif (false) {\n"
			+ "+\t\t\t\tif (true) {\n"
			+ "+\t\t\t\t\t\n"
			+ "+\t\t\t\t}\n"
			+ "+\t\t\t}\n"
			+ " \t\t}\n", test.getPatch());
}
 
Example #24
Source File: PatchGeneratorTest.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void preconditionInvocationTest() {
	NopolContext nopolContext = new NopolContext(projectSourcePath, null, null);

	Launcher spoon = new Launcher();
	spoon.addInputResource(projectSourcePath);
	spoon.buildModel();

	Factory factory = spoon.getFactory();
	SourceLocation pathLocation = new SourceLocation("fr.inria.lille.diff.testclasses.Bar", 12);
	pathLocation.setSourceStart(145);
	pathLocation.setSourceEnd(171);

	ExpressionPatch patch = new ExpressionPatch(
			new LiteralImpl(ValueFactory.create(false), nopolContext),
			pathLocation,
			RepairType.PRECONDITION);
	PatchGenerator test = new PatchGenerator(
			patch,
			factory, nopolContext);

	Assert.assertEquals("--- a/"+projectSourcePath+"/Bar.java\n"
			+ "+++ b/"+projectSourcePath+"/Bar.java\n"
			+ "@@ -15,3 +15,5 @@\n"
			+ " \n"
			+ "-\t\tSystem.out.println(\"test\");\n"
			+ "+\t\tif (false) {\n"
			+ "+\t\t\tSystem.out.println(\"test\");\n"
			+ "+\t\t}\n"
			+ " \n", test.getPatch());
}
 
Example #25
Source File: PatchGeneratorTest.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void preconditionMultiLineStatementTest() {
	NopolContext nopolContext = new NopolContext(projectSourcePath, null, null);

	Launcher spoon = new Launcher();
	spoon.addInputResource(projectSourcePath);
	spoon.buildModel();

	Factory factory = spoon.getFactory();
	SourceLocation pathLocation = new SourceLocation("fr.inria.lille.diff.testclasses.Bar", 13);
	pathLocation.setSourceStart(176);
	pathLocation.setSourceEnd(250);

	ExpressionPatch patch = new ExpressionPatch(
			new LiteralImpl(ValueFactory.create(false), nopolContext),
			pathLocation,
			RepairType.PRECONDITION);
	PatchGenerator test = new PatchGenerator(
			patch,
			factory, nopolContext);

	Assert.assertEquals("--- a/"+projectSourcePath+"/Bar.java\n"
			+ "+++ b/"+projectSourcePath+"/Bar.java\n"
			+ "@@ -17,5 +17,7 @@\n"
			+ " \n"
			+ "-\t\tthrow new RuntimeException(\"FirstLine\" +\n"
			+ "-\t\t\"Second Line\" +\n"
			+ "-\t\t\"Third Line\");\n"
			+ "+\t\tif (false) {\n"
			+ "+\t\t\tthrow new RuntimeException(\"FirstLine\" +\n"
			+ "+\t\t\t\"Second Line\" +\n"
			+ "+\t\t\t\"Third Line\");\n"
			+ "+\t\t}\n"
			+ " \t}\n", test.getPatch());
}
 
Example #26
Source File: PatchGeneratorTest.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void preconditionInvocationInElseTest() {
	NopolContext nopolContext = new NopolContext(projectSourcePath, null, null);

	Launcher spoon = new Launcher();
	spoon.addInputResource(projectSourcePath);
	spoon.buildModel();

	Factory factory = spoon.getFactory();
	SourceLocation pathLocation = new SourceLocation("fr.inria.lille.diff.testclasses.Bar", 34);
	pathLocation.setSourceStart(408);
	pathLocation.setSourceEnd(435);

	ExpressionPatch patch = new ExpressionPatch(
			new LiteralImpl(ValueFactory.create(false), nopolContext),
			pathLocation,
			RepairType.PRECONDITION);
	PatchGenerator test = new PatchGenerator(
			patch,
			factory, nopolContext);

	Assert.assertEquals("--- a/"+projectSourcePath+"/Bar.java\n"
			+ "+++ b/"+projectSourcePath+"/Bar.java\n"
			+ "@@ -33,3 +33,5 @@\n"
			+ " \t\t\tSystem.out.println(\"test1\");\n"
			+ "-\t\t\tSystem.out.println(\"test2\");\n"
			+ "+\t\t\tif (false) {\n"
			+ "+\t\t\t\tSystem.out.println(\"test2\");\n"
			+ "+\t\t\t}\n"
			+ " \t\t}\n", test.getPatch());
}
 
Example #27
Source File: InfinitelTest.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
private Map<String, CtWhile> loopsByMethodIn(File[] sourceFiles, int numberOfLoops) {
	Factory model = SpoonModelLibrary.modelFor(sourceFiles);
	CtPackage root = model.Package().getRootPackage();
	Collection<CtWhile> elements = SpoonElementLibrary.allChildrenOf(root, CtWhile.class);
	assertEquals(numberOfLoops, elements.size());
	Map<String, CtWhile> byMethod = MetaMap.newHashMap();
	for (CtWhile loop : elements) {
		String methodName = loop.getParent(CtMethod.class).getSimpleName();
		byMethod.put(methodName, loop);
	}
	return byMethod;
}
 
Example #28
Source File: AssertionAdder.java    From spoon-examples with GNU General Public License v2.0 5 votes vote down vote up
public static CtInvocation createAssert(String name, CtExpression... parameters) {
	final Factory factory = parameters[0].getFactory();
	CtTypeAccess accessToAssert =
			factory.createTypeAccess(factory.createCtTypeReference(Assert.class));
	CtExecutableReference assertEquals = factory.Type().get(Assert.class)
			.getMethodsByName(name).get(0).getReference();
	return factory.createInvocation(
			accessToAssert,
			assertEquals,
			parameters[0],
			parameters[1]
	);
}
 
Example #29
Source File: APICheckingProcessor.java    From spoon-examples with GNU General Public License v2.0 5 votes vote down vote up
@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 #30
Source File: DBCodeTemplate.java    From spoon-examples with GNU General Public License v2.0 5 votes vote down vote up
public DBCodeTemplate(Factory f, String database, String username,
        String password, String tableName) {
    this._database_ = database;
    this._username_ = username;
    this._password_ = password;
    this._tableName_ = tableName;
}