Search in sources :

Example 6 with SpoonException

use of spoon.SpoonException 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 7 with SpoonException

use of spoon.SpoonException in project spoon by INRIA.

the class JDTCommentBuilder method cleanComment.

private static String cleanComment(Reader comment) {
    StringBuilder ret = new StringBuilder();
    try (BufferedReader br = new BufferedReader(comment)) {
        String line = br.readLine();
        if (line.length() < 2 || line.charAt(0) != '/') {
            throw new SpoonException("Unexpected beginning of comment");
        }
        boolean isLastLine = false;
        if (line.charAt(1) == '/') {
            // it is single line comment, which starts with "//"
            isLastLine = true;
            line = line.substring(2);
        } else {
            // check end first
            if (line.endsWith("*/")) {
                // it is last line
                line = endCommentRE.matcher(line).replaceFirst("");
                isLastLine = true;
            }
            // skip beginning
            line = startCommentRE.matcher(line).replaceFirst("");
        }
        // append first line
        ret.append(line);
        while ((line = br.readLine()) != null) {
            if (isLastLine) {
                throw new SpoonException("Unexpected next line after last line");
            }
            if (line.endsWith("*/")) {
                // it is last line
                line = endCommentRE.matcher(line).replaceFirst("");
                isLastLine = true;
            }
            // always clean middle comment, but after end comment is detected
            line = middleCommentRE.matcher(line).replaceFirst("");
            // write next line - Note that Spoon model comment's lines are always separated by "\n"
            ret.append(CtComment.LINE_SEPARATOR);
            ret.append(line);
        }
        return ret.toString().trim();
    } catch (IOException e) {
        throw new SpoonException(e);
    }
}
Also used : SpoonException(spoon.SpoonException) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException)

Example 8 with SpoonException

use of spoon.SpoonException in project spoon by INRIA.

the class ImportTest method testCanAccess.

@Test
public void testCanAccess() throws Exception {
    class Checker {

        final Launcher launcher;

        final CtTypeReference<?> aClientClass;

        final CtTypeReference<?> anotherClass;

        Checker() {
            launcher = new Launcher();
            launcher.setArgs(new String[] { "-i", "./src/test/java/spoon/test/imports/testclasses", "--with-imports" });
            launcher.buildModel();
            aClientClass = launcher.getFactory().Class().get(ClientClass.class).getReference();
            anotherClass = launcher.getFactory().Class().get(Tacos.class).getReference();
        }

        void checkCanAccess(String aClassName, boolean isInterface, boolean canAccessClientClass, boolean canAccessAnotherClass, String clientAccessType, String anotherAccessType) {
            CtTypeReference<?> target;
            if (isInterface) {
                target = launcher.getFactory().Interface().create(aClassName).getReference();
            } else {
                target = launcher.getFactory().Class().get(aClassName).getReference();
            }
            boolean isNested = target.getDeclaringType() != null;
            CtTypeReference<?> accessType;
            target.setParent(aClientClass.getTypeDeclaration());
            if (canAccessClientClass) {
                assertTrue("ClientClass should have access to " + aClassName + " but it has not", aClientClass.canAccess(target));
            } else {
                assertFalse("ClientClass should have NO access to " + aClassName + " but it has", aClientClass.canAccess(target));
            }
            if (isNested) {
                accessType = target.getAccessType();
                if (clientAccessType != null) {
                    assertEquals(clientAccessType, accessType.getQualifiedName());
                } else if (accessType != null) {
                    fail("ClientClass should have NO accessType to " + aClassName + " but it has " + accessType.getQualifiedName());
                }
            }
            target.setParent(anotherClass.getTypeDeclaration());
            if (canAccessAnotherClass) {
                assertTrue("Tacos class should have access to " + aClassName + " but it has not", anotherClass.canAccess(target));
            } else {
                assertFalse("Tacos class should have NO access to " + aClassName + " but it has", anotherClass.canAccess(target));
            }
            if (isNested) {
                if (anotherAccessType != null) {
                    accessType = target.getAccessType();
                    assertEquals(anotherAccessType, accessType.getQualifiedName());
                } else {
                    try {
                        accessType = target.getAccessType();
                    } catch (SpoonException e) {
                        if (e.getMessage().indexOf("Cannot compute access path to type: ") == -1) {
                            throw e;
                        }
                        // else OK, it should throw exception
                        accessType = null;
                    }
                    if (accessType != null) {
                        fail("Tacos class should have NO accessType to " + aClassName + " but it has " + accessType.getQualifiedName());
                    }
                }
            }
        }
    }
    Checker c = new Checker();
    c.checkCanAccess("spoon.test.imports.testclasses.ClientClass", false, true, true, null, null);
    c.checkCanAccess("spoon.test.imports.testclasses.ClientClass$InnerClass", false, true, false, "spoon.test.imports.testclasses.ClientClass", "spoon.test.imports.testclasses.ClientClass");
    c.checkCanAccess("spoon.test.imports.testclasses.internal.ChildClass", false, true, true, null, null);
    c.checkCanAccess("spoon.test.imports.testclasses.internal.PublicInterface2", true, true, true, null, null);
    c.checkCanAccess("spoon.test.imports.testclasses.internal.PublicInterface2$NestedInterface", true, true, true, "spoon.test.imports.testclasses.internal.PublicInterface2", "spoon.test.imports.testclasses.internal.PublicInterface2");
    c.checkCanAccess("spoon.test.imports.testclasses.internal.PublicInterface2$NestedClass", true, true, true, "spoon.test.imports.testclasses.internal.PublicInterface2", "spoon.test.imports.testclasses.internal.PublicInterface2");
    c.checkCanAccess("spoon.test.imports.testclasses.internal.SuperClass$PublicInterface", true, true, true, "spoon.test.imports.testclasses.internal.ChildClass", null);
    c.checkCanAccess("spoon.test.imports.testclasses.internal.SuperClass$PackageProtectedInterface", true, false, false, "spoon.test.imports.testclasses.internal.ChildClass", null);
    c.checkCanAccess("spoon.test.imports.testclasses.internal.SuperClass$ProtectedInterface", true, true, false, "spoon.test.imports.testclasses.internal.ChildClass", null);
    c.checkCanAccess("spoon.test.imports.testclasses.internal.SuperClass$ProtectedInterface$NestedOfProtectedInterface", true, true, true, /*canAccess, but has no access to accessType*/
    "spoon.test.imports.testclasses.internal.SuperClass$ProtectedInterface", null);
    c.checkCanAccess("spoon.test.imports.testclasses.internal.SuperClass$ProtectedInterface$NestedPublicInterface", true, true, true, /*canAccess, but has no access to accessType*/
    "spoon.test.imports.testclasses.internal.SuperClass$ProtectedInterface", null);
    c.checkCanAccess("spoon.test.imports.testclasses.internal.SuperClass$PublicInterface", true, true, true, /*canAccess, but has no access to accessType*/
    "spoon.test.imports.testclasses.internal.ChildClass", null);
    c.checkCanAccess("spoon.test.imports.testclasses.internal.SuperClass$PublicInterface$NestedOfPublicInterface", true, true, true, /*canAccess, has access to first accessType, but not to full accesspath*/
    "spoon.test.imports.testclasses.internal.SuperClass$PublicInterface", "spoon.test.imports.testclasses.internal.SuperClass$PublicInterface");
    c.checkCanAccess("spoon.test.imports.testclasses.internal.SuperClass$PublicInterface$NestedPublicInterface", true, true, true, /*canAccess, has access to first accessType, but not to full accesspath*/
    "spoon.test.imports.testclasses.internal.SuperClass$PublicInterface", "spoon.test.imports.testclasses.internal.SuperClass$PublicInterface");
}
Also used : SpoonException(spoon.SpoonException) CtTypeReference(spoon.reflect.reference.CtTypeReference) Launcher(spoon.Launcher) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) Test(org.junit.Test)

Example 9 with SpoonException

use of spoon.SpoonException in project spoon by INRIA.

the class TemplateTest method testTemplateWithWrongUsedStringParam.

@Test
public void testTemplateWithWrongUsedStringParam() throws Exception {
    Launcher spoon = new Launcher();
    Factory factory = spoon.createFactory();
    spoon.createCompiler(factory, SpoonResourceHelper.resources("./src/test/java/spoon/test/template/testclasses/constructors/C1.java"), SpoonResourceHelper.resources("./src/test/java/spoon/test/template/testclasses/constructors/TemplateWithFieldsAndMethods_Wrong.java")).build();
    CtClass<?> c1 = factory.Class().get(C1.class);
    new TemplateWithFieldsAndMethods_Wrong("testparam").apply(c1);
    CtMethod<?> m = c1.getMethod("methodToBeInserted");
    assertNotNull(m);
    // contract: printing of code which contains invalid field reference, fails with nice exception
    try {
        m.getBody().getStatement(0).toString();
    } catch (SpoonException e) {
        assertTrue("The error description doesn't contain name of invalid field. There is:\n" + e.getMessage(), e.getMessage().indexOf("testparam") >= 0);
    }
}
Also used : SpoonException(spoon.SpoonException) TemplateWithFieldsAndMethods_Wrong(spoon.test.template.testclasses.constructors.TemplateWithFieldsAndMethods_Wrong) Launcher(spoon.Launcher) Factory(spoon.reflect.factory.Factory) Test(org.junit.Test)

Example 10 with SpoonException

use of spoon.SpoonException in project spoon by INRIA.

the class DefaultJavaPrettyPrinter method scan.

/**
 * The generic scan method for an element.
 */
public DefaultJavaPrettyPrinter scan(CtElement e) {
    if (e != null) {
        enter(e);
        context.elementStack.push(e);
        if (env.isPreserveLineNumbers()) {
            if (!(e instanceof CtNamedElement)) {
                getPrinterHelper().adjustStartPosition(e);
            }
        }
        try {
            e.accept(this);
        } catch (SpoonException ex) {
            throw ex;
        } catch (Exception ex) {
            String elementInfo = e.getClass().getName();
            elementInfo += " on path " + getPath(e) + "\n";
            if (e.getPosition() != null) {
                elementInfo += "at position " + e.getPosition().toString() + " ";
            }
            throw new SpoonException("Printing of " + elementInfo + "failed", ex);
        }
        context.elementStack.pop();
        exit(e);
    }
    return this;
}
Also used : SpoonException(spoon.SpoonException) CtNamedElement(spoon.reflect.declaration.CtNamedElement) SpoonException(spoon.SpoonException) ParentNotInitializedException(spoon.reflect.declaration.ParentNotInitializedException)

Aggregations

SpoonException (spoon.SpoonException)57 Test (org.junit.Test)15 Launcher (spoon.Launcher)12 CtMethod (spoon.reflect.declaration.CtMethod)9 CtType (spoon.reflect.declaration.CtType)9 CtElement (spoon.reflect.declaration.CtElement)8 Factory (spoon.reflect.factory.Factory)8 File (java.io.File)7 IOException (java.io.IOException)7 ArrayList (java.util.ArrayList)7 CtField (spoon.reflect.declaration.CtField)6 URL (java.net.URL)4 CtTypeReference (spoon.reflect.reference.CtTypeReference)4 Collection (java.util.Collection)3 CompilationUnit (spoon.reflect.cu.CompilationUnit)3 CtExecutable (spoon.reflect.declaration.CtExecutable)3 CtParameter (spoon.reflect.declaration.CtParameter)3 CtScanner (spoon.reflect.visitor.CtScanner)3 Filter (spoon.reflect.visitor.Filter)3 FileNotFoundException (java.io.FileNotFoundException)2