@Override public String updateAndGetCompilationUnitContents( final String fileIdentifier, final ClassOrInterfaceTypeDetails cid) { // Validate parameters Validate.notBlank(fileIdentifier, "Oringinal unit path required"); Validate.notNull(cid, "Type details required"); // Load original compilation unit from file final File file = new File(fileIdentifier); String fileContents = ""; try { fileContents = FileUtils.readFileToString(file); } catch (final IOException ignored) { } if (StringUtils.isBlank(fileContents)) { return getCompilationUnitContents(cid); } CompilationUnit compilationUnit; try { compilationUnit = JavaParser.parse(new ByteArrayInputStream(fileContents.getBytes())); } catch (final IOException e) { throw new IllegalStateException(e); } catch (final ParseException e) { throw new IllegalStateException(e); } // Load new compilation unit from cid information final String cidContents = getCompilationUnitContents(cid); CompilationUnit cidCompilationUnit; try { cidCompilationUnit = JavaParser.parse(new ByteArrayInputStream(cidContents.getBytes())); } catch (final IOException e) { throw new IllegalStateException(e); } catch (final ParseException e) { throw new IllegalStateException(e); } // Update package if (!compilationUnit .getPackage() .getName() .getName() .equals(cidCompilationUnit.getPackage().getName().getName())) { compilationUnit.setPackage(cidCompilationUnit.getPackage()); } // Update imports UpdateCompilationUnitUtils.updateCompilationUnitImports(compilationUnit, cidCompilationUnit); // Update types UpdateCompilationUnitUtils.updateCompilationUnitTypes(compilationUnit, cidCompilationUnit); // Return new contents return compilationUnit.toString(); }
@Override public final String getCompilationUnitContents(final ClassOrInterfaceTypeDetails cid) { Validate.notNull(cid, "Class or interface type details are required"); // Create a compilation unit to store the type to be created final CompilationUnit compilationUnit = new CompilationUnit(); // NB: this import list is replaced at the end of this method by a // sorted version compilationUnit.setImports(new ArrayList<ImportDeclaration>()); if (!cid.getName().isDefaultPackage()) { compilationUnit.setPackage( new PackageDeclaration( ASTHelper.createNameExpr(cid.getName().getPackage().getFullyQualifiedPackageName()))); } // Add the class of interface declaration to the compilation unit final List<TypeDeclaration> types = new ArrayList<TypeDeclaration>(); compilationUnit.setTypes(types); updateOutput(compilationUnit, null, cid, null); return compilationUnit.toString(); }