*/
private void insertDeclaration(ICompilationUnit target,
TypeDeclaration typeDeclaration) throws JavaModelException,
MalformedTreeException, BadLocationException {
try {
ICompilationUnit icu = target.getWorkingCopy(null);
// creation of DOM/AST from an ICompilationUnit
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setSource(icu);
CompilationUnit astRoot = (CompilationUnit) parser.createAST(null);
StringBuffer signature = new StringBuffer();
signature.append(typeDeclaration.getName().getFullyQualifiedName());
typeDeclaration.setProperty("Signature", signature.toString());
TypeDeclaration dropTypeDec = (TypeDeclaration) ASTNode
.copySubtree(astRoot.getAST(), typeDeclaration);
// creation of ASTRewrite
AST ast = astRoot.getAST();
ASTRewrite rewrite = ASTRewrite.create(ast);
// description of the change
for (Object typeObj : astRoot.types()) {
if (typeObj instanceof TypeDeclaration) {
TypeDeclaration typeDec = (TypeDeclaration) typeObj;
if (typeDec.getName().toString()
.equals(dropTypeDec.getName().toString())) {
logger.debug("Replace existing type declaration");
if (Activator
.getDefault()
.getPreferenceStore()
.getString(
PreferenceConstants.P_OVERWRITE_ON_INSERT)
.equals("true")) {
rewrite.remove(typeDec, null);
}
}
}
}
ASTNode a = ASTNode.copySubtree(ast, dropTypeDec);
@SuppressWarnings("unchecked")
List<TypeDeclaration> types = astRoot.types();
ArrayList<TypeDeclaration> newTypes = new ArrayList<TypeDeclaration>();
newTypes.add((TypeDeclaration) a);
if (types.addAll(newTypes)) {
if (!target.getElementName().equals(
dropTypeDec.getName().toString() + ".java")) {
List<?> modifiers = dropTypeDec.modifiers();
for (Object mod : modifiers) {
if (mod instanceof Modifier) {
Modifier modifier = (Modifier) mod;
if (modifier.getKeyword().toString()
.equals("public")) {
dropTypeDec.modifiers().remove(modifier);
break;
}
}
}
}
String preambule = createPreambule(typeDeclaration) + "\r\n";
icu.createType(preambule + dropTypeDec.toString(), null, true,
null);
logger.debug("New type added successfully");
}
String source = icu.getSource();
Document document = new Document(source);
// computation of the text edits
TextEdit edits = rewrite.rewriteAST(document, icu.getJavaProject()
.getOptions(true));
// computation of the new source code
if (edits != null) {
edits.apply(document);
}
String newSource = document.get();
// update of the compilation unit
icu.getBuffer().setContents(newSource);
icu.reconcile(ICompilationUnit.NO_AST, false, null, null);
icu.commitWorkingCopy(false, null);
icu.discardWorkingCopy();
} catch (Exception e) {
CrashReporter.reportException(e);
logger.debug("Could not insert result: " + e.toString());
}
}