spoon.reflect.declaration.CtPackage Java Examples

The following examples show how to use spoon.reflect.declaration.CtPackage. 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: VariableResolver.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 
 * @param var
 * @param rootElement
 * @return
 */
private static boolean checkParent(CtVariable var, CtElement rootElement) {

	if (rootElement == null)
		logger.error("Error! root element null");
	CtElement parent = var;
	while (parent != null
			&& !(parent instanceof CtPackage)/*
												 * && !CtPackage. TOP_LEVEL_PACKAGE_NAME. equals(parent.toString())
												 */) {
		if (parent.equals(rootElement))
			return true;
		parent = parent.getParent();
	}

	return false;
}
 
Example #2
Source File: GramProcessor.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Deprecated
public Map<String, NGrams> calculateByPackage(List<CtType<?>> all) throws JSAPException {

	Map<String, NGrams> result = new HashedMap();
	CodeParserLauncher ingp = new CodeParserLauncher<>(ingredientProcessor);
	int allElements = 0;

	for (CtType<?> ctType : all) {
		NGrams ns = new NGrams();
		CtPackage parent = (CtPackage) ctType.getParent(CtPackage.class);
		if (!result.containsKey(parent.getQualifiedName())) {
			allElements += getNGramsFromCodeElements(parent, ns, ingp);
			result.put(parent.getQualifiedName(), ns);
		}
	}
	logger.debug("allElements " + allElements);
	return result;
}
 
Example #3
Source File: QueryExampleTest.java    From spoon-examples with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("all")
@Test
public void main() {
    MavenLauncher launcher = new MavenLauncher(
            "./src/test/resources/project/",
            MavenLauncher.SOURCE_TYPE.APP_SOURCE);

    CtModel model = launcher.buildModel();
    List<CtMethod> methodList = model.
            filterChildren(new NamedElementFilter<CtPackage>(CtPackage.class, "ow2con")).
            filterChildren(new NamedElementFilter<CtPackage>(CtPackage.class, "publicapi")).
            filterChildren(new TypeFilter<CtMethod>(CtMethod.class)).
            filterChildren(new Filter<CtMethod>() {
                @Override
                public boolean matches(CtMethod element) {
                    boolean isPublic = element.isPublic();
                    CtTypeReference returnType = element.getType();
                    String privateApiPackage = "ow2con.privateapi";
                    boolean isTypeFromPrivateApi = returnType.getQualifiedName().contains(privateApiPackage);
                    return isPublic && isTypeFromPrivateApi;
                }
            }).list();
}
 
Example #4
Source File: ReferenceProcessor.java    From spoon-examples with GNU General Public License v2.0 6 votes vote down vote up
public void process(CtPackage element) {
	CtPackageReference pack = element.getReference();
	Set<CtPackageReference> refs = new HashSet<>();
	for (CtType t : element.getTypes()) {
		List<CtTypeReference<?>> listReferences = Query.getReferences(t, new ReferenceTypeFilter<>(CtTypeReference.class));

		for (CtTypeReference<?> tref : listReferences) {
			if (tref.getPackage() != null && !tref.getPackage().equals(pack)) {
				if (ignoredTypes.contains(tref))
					continue;
				refs.add(tref.getPackage());
			}
		}
	}
	if (!refs.isEmpty()) {
		packRefs.put(pack, refs);
	}
}
 
Example #5
Source File: PackageBasicFixSpace.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void defineSpace(ProgramVariant variant) {
	List<CtType<?>> affected = variant.getAffectedClasses();

	List<CtPackage> packageAnalyzed = new ArrayList<>();
	for (CtType<?> ing : affected) {

		CtPackage p = ing.getParent(CtPackage.class);
		if (!packageAnalyzed.contains(p)) {
			packageAnalyzed.add(p);
			for (CtType<?> t : p.getTypes()) {
				this.createFixSpaceFromAClass(t);
			}

		}

	}

}
 
Example #6
Source File: ASTInfoResolver.java    From coming with MIT License 6 votes vote down vote up
public static List<CtElement> getPathToRootNode(CtElement element) {
	CtElement par = null;
	try {
		par = element.getParent();
		if (par == null || par instanceof CtPackage || element == par) {
			List<CtElement> res = new ArrayList<>();
			res.add(element);
			return res;
		}
		List<CtElement> pathToParent = getPathToRootNode(par);
		pathToParent.add(element);
		return pathToParent;
	} catch (ParentNotInitializedException e) {
		return new ArrayList<>();
	}
}
 
Example #7
Source File: VariableResolver.java    From coming with MIT License 6 votes vote down vote up
/**
 * 
 * @param var
 * @param rootElement
 * @return
 */
private static boolean checkParent(CtVariable var, CtElement rootElement) {

	if (rootElement == null)
		logger.error("Error! root element null");
	CtElement parent = var;
	while (parent != null
			&& !(parent instanceof CtPackage)/*
												 * && !CtPackage. TOP_LEVEL_PACKAGE_NAME. equals(parent.toString())
												 */) {
		if (parent.equals(rootElement))
			return true;
		parent = parent.getParent();
	}

	return false;
}
 
Example #8
Source File: LiteralsSpace.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
protected List<CtType<?>> obtainClassesFromScope(ProgramVariant variant) {

		if (IngredientPoolScope.PACKAGE.equals(scope)) {
			List<CtType<?>> affected = variant.getAffectedClasses();
			List<CtType<?>> types = new ArrayList<>();
			List<CtPackage> packageAnalyzed = new ArrayList<>();
			for (CtType<?> ing : affected) {

				CtPackage p = ing.getParent(CtPackage.class);
				if (!packageAnalyzed.contains(p)) {
					packageAnalyzed.add(p);
					for (CtType<?> type : p.getTypes()) {
						types.add(type);
					}
				}
			}
			return types;
		}
		if (IngredientPoolScope.LOCAL.equals(scope)) {
			return variant.getAffectedClasses();
		}
		if (IngredientPoolScope.GLOBAL.equals(scope)) {
			return MutationSupporter.getFactory().Type().getAll();
		}
		return null;
	}
 
Example #9
Source File: TOSIngredientPool.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
protected List<CtType<?>> obtainClassesFromScope(ProgramVariant variant) {

		if (IngredientPoolScope.PACKAGE.equals(scope)) {
			List<CtType<?>> affected = variant.getAffectedClasses();
			List<CtType<?>> types = new ArrayList<>();
			List<CtPackage> packageAnalyzed = new ArrayList<>();
			for (CtType<?> ing : affected) {

				CtPackage p = ing.getParent(CtPackage.class);
				if (!packageAnalyzed.contains(p)) {
					packageAnalyzed.add(p);
					for (CtType<?> type : p.getTypes()) {
						types.add(type);
					}
				}
			}
			return types;
		}
		if (IngredientPoolScope.LOCAL.equals(scope)) {
			return variant.getAffectedClasses();
		}
		if (IngredientPoolScope.GLOBAL.equals(scope)) {
			return MutationSupporter.getFactory().Type().getAll();
		}
		return null;
	}
 
Example #10
Source File: SpoonedFile.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
public Collection<String> packageNames(Collection<CtPackage> packages) {
    Collection<String> names = MetaList.newArrayList();
    for (CtPackage aPackage : packages) {
        names.add(aPackage.getQualifiedName());
    }
    return names;
}
 
Example #11
Source File: ExpressionTypeIngredientSpace.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String calculateLocation(CtElement elementToModify) {

	if (IngredientPoolScope.PACKAGE.equals(scope)) {
		return elementToModify.getParent(CtPackage.class).getQualifiedName();
	} else if (IngredientPoolScope.LOCAL.equals(scope)) {
		return elementToModify.getParent(CtType.class).getQualifiedName();
	} else if (IngredientPoolScope.GLOBAL.equals(scope))
		return "Global";

	return null;

}
 
Example #12
Source File: TOSIngredientPool.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String calculateLocation(CtElement elementToModify) {

	if (IngredientPoolScope.PACKAGE.equals(scope)) {
		return elementToModify.getParent(CtPackage.class).getQualifiedName();
	} else if (IngredientPoolScope.LOCAL.equals(scope)) {
		return elementToModify.getParent(CtType.class).getQualifiedName();
	} else if (IngredientPoolScope.GLOBAL.equals(scope))
		return "Global";

	return null;

}
 
Example #13
Source File: LiteralsSpace.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String calculateLocation(CtElement elementToModify) {

	if (IngredientPoolScope.PACKAGE.equals(scope)) {
		return elementToModify.getParent(CtPackage.class).getQualifiedName();
	} else if (IngredientPoolScope.LOCAL.equals(scope)) {
		return elementToModify.getParent(CtType.class).getQualifiedName();
	} else if (IngredientPoolScope.GLOBAL.equals(scope))
		return "Global";

	return null;

}
 
Example #14
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 #15
Source File: PackageBasicFixSpace.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
@Override
public String calculateLocation(CtElement original) {

	return original.getParent(CtPackage.class).getQualifiedName();
}
 
Example #16
Source File: BigTransfoScenarioTest.java    From spoon-examples with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings("all")
@Test
public void main() {
    MavenLauncher launcher = new MavenLauncher(
            "./src/test/resources/project/",
            MavenLauncher.SOURCE_TYPE.APP_SOURCE);

    CtModel model = launcher.buildModel();
    List<CtMethod> methodList = model.
            filterChildren(new NamedElementFilter<CtPackage>(CtPackage.class, "ow2con")).
            filterChildren(new NamedElementFilter<CtPackage>(CtPackage.class, "publicapi")).
            filterChildren(new TypeFilter<CtMethod>(CtMethod.class)).
            filterChildren(new Filter<CtMethod>() {
                @Override
                public boolean matches(CtMethod element) {
                    boolean isPublic = element.isPublic();
                    CtTypeReference returnType = element.getType();
                    String privateApiPackage = "ow2con.privateapi";
                    boolean isTypeFromPrivateApi = returnType.getQualifiedName().contains(privateApiPackage);
                    return isPublic && isTypeFromPrivateApi;
                }
            }).list();

    Factory factory = launcher.getFactory();
    CtClass<? extends Throwable> exceptionClass = factory.createClass("ow2con.PrivateAPIException");
    CtConstructorCall<? extends Throwable> exceptionInstance = factory.createConstructorCall(exceptionClass.getReference());

    for (CtMethod method : methodList) {
        CtBlock methodBody = method.getBody();
        List<CtComment> bodyComments = new ArrayList<>();

        ArrayList<CtStatement> ctStatements = new ArrayList<>(methodBody.getStatements());

        for (CtStatement ctStatement : ctStatements) {
            String statement = ctStatement.toString();
            CtComment statementAsComment = factory.createInlineComment(statement);
            bodyComments.add(statementAsComment);
            methodBody.removeStatement(ctStatement);
        }

        CtThrow throwMyException = factory.createThrow();
        CtConstructorCall<? extends Throwable> constructorCall = exceptionInstance.clone();
        throwMyException.setThrownExpression(constructorCall);
        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);
        }
    }

    Environment environment = launcher.getEnvironment();
    environment.setCommentEnabled(true);
    environment.setAutoImports(true);
    // the transformation must produce compilable code
    environment.setShouldCompile(true);
    launcher.prettyprint();

    // look in folder spooned/ow2con/publicapi/ the transformed code
}
 
Example #17
Source File: CtPackageIngredientScope.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Class getCtElementForSplitSpace() {
	return CtPackage.class;
}
 
Example #18
Source File: CtGlobalIngredientScope.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Class getCtElementForSplitSpace() {
	return CtPackage.class;
}
 
Example #19
Source File: SpoonedFile.java    From nopol with GNU General Public License v2.0 4 votes vote down vote up
public Collection<CtPackage> allPackages() {
    return spoonFactory().Package().getAll();
}
 
Example #20
Source File: IngredientPoolTest.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void testMath85ScopePackageSpace() throws Exception {

	AstorMain main1 = new AstorMain();
	String dep = new File("./examples/libs/junit-4.4.jar").getAbsolutePath();
	String[] args = new String[] { "-dependencies", dep, "-mode", "jgenprog", "-failing",
			"org.apache.commons.math.distribution.NormalDistributionTest", "-location",
			new File("./examples/math_85").getAbsolutePath(), "-package", "org.apache.commons", "-srcjavafolder",
			"/src/java/", "-srctestfolder", "/src/test/", "-binjavafolder", "/target/classes", "-bintestfolder",
			"/target/test-classes", "-javacompliancelevel", "7", "-flthreshold", "0.5", "-stopfirst", "false",
			// We put 0 as max generation, so we force to not evolve the
			// population
			"-maxgen", "0", "-scope", "package", "-seed", "10", "-ingredientstrategy",
			ShortestIngredientSearchStrategy.class.getName() };

	main1.execute(args);
	JGenProg astor = (JGenProg) main1.getEngine();
	IngredientSearchStrategy ingStrategy = astor.getIngredientSearchStrategy();

	//
	AstorOperator operator = new ReplaceOp();
	// Let's take a modification point from the first variant. I take the
	// element at 12, it's an assignement.
	ModificationPoint mpoint = astor.getVariants().get(0).getModificationPoints().get(12);
	Ingredient ingLast = ingStrategy.getFixIngredient(mpoint, operator);
	Assert.assertNotNull(ingLast);

	List<String> packages = ingStrategy.getIngredientSpace().getLocations();
	Assert.assertTrue(packages.size() > 0);
	Assert.assertTrue(packages.contains(
			mpoint.getProgramVariant().getAffectedClasses().get(0).getParent(CtPackage.class).getQualifiedName()));

	List<Ingredient> ingredients = ingStrategy.getIngredientSpace().getIngredients(mpoint.getCodeElement());
	Assert.assertTrue(ingredients.size() > 0);
	Assert.assertTrue(hasIngredient(ingredients, ingLast));

	boolean ingrePackageCorrect = false;
	// Now, we check if all ingredients retrieved belongs affected classes
	for (Ingredient ctCodeElement : ingredients) {
		for (CtType aff : mpoint.getProgramVariant().getAffectedClasses()) {
			if (aff.getPackage().equals(ctCodeElement.getCode().getParent(CtPackage.class)))
				ingrePackageCorrect = true;
		}
		;

	}
	assertTrue(ingrePackageCorrect);

}