@Test public void testBasicAPIUsage() throws Exception { // this test shows a basic usage of the Launcher API without command line // and asserts there is no exception SpoonAPI spoon = new Launcher(); spoon.addInputResource("src/test/resources/spoon/test/api"); spoon.setSourceOutputDirectory("target/spooned"); spoon.run(); Factory factory = spoon.getFactory(); for (CtPackage p : factory.Package().getAll()) { spoon.getEnvironment().debugMessage("package: " + p.getQualifiedName()); } for (CtType<?> s : factory.Class().getAll()) { spoon.getEnvironment().debugMessage("class: " + s.getQualifiedName()); } }
protected void generateProcessedSourceFilesUsingCUs() { 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<File>(); for (spoon.reflect.cu.CompilationUnit cu : factory.CompilationUnit().getMap().values()) { factory .getEnvironment() .debugMessage("Generating source for compilation unit: " + cu.getFile()); CtType<?> element = cu.getMainType(); CtPackage pack = element.getPackage(); // create package directory File packageDir; if (pack.getQualifiedName().equals(CtPackage.TOP_LEVEL_PACKAGE_NAME)) { 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 InputStream is = getCompilationUnitInputStream(cu.getFile().getPath()); IOUtils.copy(is, new FileOutputStream(file)); if (!printedFiles.contains(file)) { printedFiles.add(file); } } catch (Exception e) { Launcher.LOGGER.error(e.getMessage(), e); } } }
/** Creates a reference to an existing package. */ public CtPackageReference createReference(CtPackage pack) { if (pack == null) { throw new IllegalArgumentException(); } return createReference(pack.getQualifiedName()); }