Search in sources :

Example 1 with CtPackage

use of spoon.reflect.declaration.CtPackage in project spoon by INRIA.

the class PackageFactory method getOrCreate.

/**
 * Gets or creates a package.
 *
 * @param qualifiedName
 * 		the full name of the package
 */
public CtPackage getOrCreate(String qualifiedName) {
    if (qualifiedName.isEmpty()) {
        return factory.getModel().getRootPackage();
    }
    StringTokenizer token = new StringTokenizer(qualifiedName, CtPackage.PACKAGE_SEPARATOR);
    CtPackage last = factory.getModel().getRootPackage();
    while (token.hasMoreElements()) {
        String name = token.nextToken();
        CtPackage next = last.getPackage(name);
        if (next == null) {
            next = factory.Core().createPackage();
            next.setSimpleName(name);
            last.addPackage(next);
        }
        last = next;
    }
    return last;
}
Also used : StringTokenizer(java.util.StringTokenizer) CtPackage(spoon.reflect.declaration.CtPackage)

Example 2 with CtPackage

use of spoon.reflect.declaration.CtPackage in project spoon by INRIA.

the class PackageFactory method getSubPackageList.

private List<CtPackage> getSubPackageList(CtPackage pack) {
    List<CtPackage> packs = new ArrayList<>();
    packs.add(pack);
    for (CtPackage p : pack.getPackages()) {
        packs.addAll(getSubPackageList(p));
    }
    return packs;
}
Also used : ArrayList(java.util.ArrayList) CtPackage(spoon.reflect.declaration.CtPackage)

Example 3 with CtPackage

use of spoon.reflect.declaration.CtPackage in project spoon by INRIA.

the class JDTBasedSpoonCompiler method generateProcessedSourceFilesUsingCUs.

protected void generateProcessedSourceFilesUsingCUs() {
    File outputDirectory = getSourceOutputDirectory();
    factory.getEnvironment().debugMessage("Generating source using compilation units...");
    // Check output directory
    if (outputDirectory == null) {
        throw new RuntimeException("You should set output directory before generating source files");
    }
    // Create spooned directory
    if (outputDirectory.isFile()) {
        throw new RuntimeException("Output must be a directory");
    }
    if (!outputDirectory.exists()) {
        if (!outputDirectory.mkdirs()) {
            throw new RuntimeException("Error creating output directory");
        }
    }
    try {
        outputDirectory = outputDirectory.getCanonicalFile();
    } catch (IOException e1) {
        throw new SpoonException(e1);
    }
    factory.getEnvironment().debugMessage("Generating source files to: " + outputDirectory);
    List<File> printedFiles = new ArrayList<>();
    for (spoon.reflect.cu.CompilationUnit cu : factory.CompilationUnit().getMap().values()) {
        if (cu.getDeclaredTypes().size() == 0) {
            // case of package-info
            continue;
        }
        CtType<?> element = cu.getMainType();
        CtPackage pack = element.getPackage();
        // create package directory
        File packageDir;
        if (pack.isUnnamedPackage()) {
            packageDir = new File(outputDirectory.getAbsolutePath());
        } else {
            // Create current package directory
            packageDir = new File(outputDirectory.getAbsolutePath() + File.separatorChar + pack.getQualifiedName().replace('.', File.separatorChar));
        }
        if (!packageDir.exists()) {
            if (!packageDir.mkdirs()) {
                throw new RuntimeException("Error creating output directory");
            }
        }
        // print type
        try {
            File file = new File(packageDir.getAbsolutePath() + File.separatorChar + element.getSimpleName() + DefaultJavaPrettyPrinter.JAVA_FILE_EXTENSION);
            file.createNewFile();
            // the path must be given relatively to to the working directory
            try (InputStream is = getCompilationUnitInputStream(cu.getFile().getPath());
                FileOutputStream outFile = new FileOutputStream(file)) {
                IOUtils.copy(is, outFile);
            }
            if (!printedFiles.contains(file)) {
                printedFiles.add(file);
            }
        } catch (Exception e) {
            Launcher.LOGGER.error(e.getMessage(), e);
        }
    }
}
Also used : SpoonException(spoon.SpoonException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) IOException(java.io.IOException) ModelBuildingException(spoon.compiler.ModelBuildingException) SpoonException(spoon.SpoonException) IOException(java.io.IOException) FileOutputStream(java.io.FileOutputStream) CtPackage(spoon.reflect.declaration.CtPackage) File(java.io.File) SpoonFile(spoon.compiler.SpoonFile)

Example 4 with CtPackage

use of spoon.reflect.declaration.CtPackage in project spoon by INRIA.

the class JDTImportBuilder method build.

// package visible method in a package visible class, not in the public API
void build() {
    if (declarationUnit.imports == null || declarationUnit.imports.length == 0) {
        return;
    }
    for (ImportReference importRef : declarationUnit.imports) {
        String importName = importRef.toString();
        if (!importRef.isStatic()) {
            if (importName.endsWith("*")) {
                int lastDot = importName.lastIndexOf(".");
                String packageName = importName.substring(0, lastDot);
                // only get package from the model by traversing from rootPackage the model
                // it does not use reflection to achieve that
                CtPackage ctPackage = this.factory.Package().get(packageName);
                if (ctPackage != null) {
                    this.imports.add(factory.Type().createImport(ctPackage.getReference()));
                }
            } else {
                CtType klass = this.getOrLoadClass(importName);
                if (klass != null) {
                    this.imports.add(factory.Type().createImport(klass.getReference()));
                }
            }
        } else {
            int lastDot = importName.lastIndexOf(".");
            String className = importName.substring(0, lastDot);
            String methodOrFieldName = importName.substring(lastDot + 1);
            CtType klass = this.getOrLoadClass(className);
            if (klass != null) {
                if (methodOrFieldName.equals("*")) {
                    this.imports.add(factory.Type().createImport(factory.Type().createWildcardStaticTypeMemberReference(klass.getReference())));
                } else {
                    List<CtNamedElement> methodOrFields = klass.getElements(new NamedElementFilter<>(CtNamedElement.class, methodOrFieldName));
                    if (methodOrFields.size() > 0) {
                        CtNamedElement methodOrField = methodOrFields.get(0);
                        this.imports.add(factory.Type().createImport(methodOrField.getReference()));
                    }
                }
            }
        }
    }
    spoonUnit.setImports(this.imports);
}
Also used : ImportReference(org.eclipse.jdt.internal.compiler.ast.ImportReference) CtType(spoon.reflect.declaration.CtType) CtPackage(spoon.reflect.declaration.CtPackage) CtNamedElement(spoon.reflect.declaration.CtNamedElement)

Example 5 with CtPackage

use of spoon.reflect.declaration.CtPackage in project spoon by INRIA.

the class JDTTreeBuilder method visit.

@Override
public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) {
    if (new String(typeDeclaration.name).equals("package-info")) {
        context.enter(factory.Package().getOrCreate(new String(typeDeclaration.binding.fPackage.readableName())), typeDeclaration);
        return true;
    } else {
        CtPackage pack;
        if (typeDeclaration.binding.fPackage.shortReadableName() != null && typeDeclaration.binding.fPackage.shortReadableName().length > 0) {
            pack = factory.Package().getOrCreate(new String(typeDeclaration.binding.fPackage.shortReadableName()));
        } else {
            pack = factory.Package().getRootPackage();
        }
        context.enter(pack, typeDeclaration);
        pack.addType(helper.createType(typeDeclaration));
        return true;
    }
}
Also used : CtPackage(spoon.reflect.declaration.CtPackage)

Aggregations

CtPackage (spoon.reflect.declaration.CtPackage)53 Test (org.junit.Test)29 Launcher (spoon.Launcher)21 Factory (spoon.reflect.factory.Factory)13 CtType (spoon.reflect.declaration.CtType)12 File (java.io.File)8 CtClass (spoon.reflect.declaration.CtClass)6 CtElement (spoon.reflect.declaration.CtElement)6 CtTypeReference (spoon.reflect.reference.CtTypeReference)6 ArrayList (java.util.ArrayList)4 CtAnnotation (spoon.reflect.declaration.CtAnnotation)4 CtMethod (spoon.reflect.declaration.CtMethod)4 CtModule (spoon.reflect.declaration.CtModule)4 HashSet (java.util.HashSet)3 StringTokenizer (java.util.StringTokenizer)3 SpoonAPI (spoon.SpoonAPI)3 CtStatement (spoon.reflect.code.CtStatement)3 CtField (spoon.reflect.declaration.CtField)3 ModelUtils.createFactory (spoon.testing.utils.ModelUtils.createFactory)3 Annotation (java.lang.annotation.Annotation)2