Example usage for org.eclipse.jdt.core.dom AST newSingleMemberAnnotation

List of usage examples for org.eclipse.jdt.core.dom AST newSingleMemberAnnotation

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.dom AST newSingleMemberAnnotation.

Prototype

public SingleMemberAnnotation newSingleMemberAnnotation() 

Source Link

Document

Creates and returns a new unparented single member annotation node with an unspecified type name and value.

Usage

From source file:ac.at.tuwien.dsg.utest.transformation.umlclassdiagram2javadb.id.rules.UMLClassDiagram2JavaDBTransformationRule.java

License:Open Source License

public Object createTarget(ITransformContext context) {

    ClassImpl source = (ClassImpl) context.getSource();

    Document document = new Document("@NodeType \n public class " + source.getName() + "{ \n");

    //below helper classes toi generate our desired .java file
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setSource(document.get().toCharArray());
    CompilationUnit cu = (CompilationUnit) parser.createAST(null);
    cu.recordModifications();/*from   w  w w.j a  v a  2  s  . c  o m*/
    AST ast = cu.getAST();

    ASTRewrite rewriter = ASTRewrite.create(ast);

    ListRewrite listRewrite = rewriter.getListRewrite(cu, CompilationUnit.TYPES_PROPERTY);

    //TODO: here we take each property introduced by each Stereotype

    for (Stereotype stereotype : source.getAppliedStereotypes()) {

        //get all properties
        for (Property attribute : stereotype.getAllAttributes()) {

            //todo
        }
    }

    for (Property property : source.getAllAttributes()) {
        System.out.println(property.getName());

        Association assoc = property.getAssociation();

        if (assoc == null) {
            System.out.format("this is simple %s \n", property.getName());

            VariableDeclarationFragment varDecl = ast.newVariableDeclarationFragment();
            varDecl.setName(ast.newSimpleName(property.getName()));

            FieldDeclaration propertyField = ast.newFieldDeclaration(varDecl);
            propertyField.setType(ast.newSimpleType(ast.newName(property.getType().getName())));

            final SingleMemberAnnotation annot = ast.newSingleMemberAnnotation();
            annot.setTypeName(ast.newName("Property"));

            StringLiteral st = ast.newStringLiteral();
            st.setLiteralValue("type=\"variable\"");

            annot.setValue(st);

            listRewrite.insertLast(annot, null);
            listRewrite.insertLast(propertyField, null);

        } else {
            System.out.format("this is complex %s \n", property.getName());
            Type type = assoc.getEndTypes().stream().filter(a -> !a.equals(source)).findFirst().get();
            System.out.format("Association end is   %s \n", type.getName());

            AggregationKind kind = property.getAggregation();
            if (kind.equals(AggregationKind.COMPOSITE)) {
                System.out.format("Composition \n");
            } else if (kind.equals(AggregationKind.SHARED)) {
                System.out.format("Aggregation \n");
            } else if (kind.equals(AggregationKind.NONE)) {
                System.out.format("Association \n");
            }

        }

    }

    TextEdit edits = rewriter.rewriteAST(document, null);
    try {
        UndoEdit undo = edits.apply(document);
    } catch (MalformedTreeException | BadLocationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    System.out.println(document.get());

    return null;
}

From source file:com.android.icu4j.srcgen.RunWithAnnotator.java

License:Apache License

private boolean addRunWithAnnotation(CompilationUnit cu, ASTRewrite rewrite, TypeDeclaration type,
        String runnerClass, boolean imported) {

    AST ast = cu.getAST();

    QualifiedName qRunWith = (QualifiedName) ast.newName(RUN_WITH_CLASS_NAME);
    QualifiedName qRunner = (QualifiedName) ast.newName(runnerClass);
    if (!imported) {
        appendImport(cu, rewrite, qRunWith);
        appendImport(cu, rewrite, qRunner);
    }/*from ww w .ja v  a2  s.c  o  m*/
    String runWithName = qRunWith.getName().getIdentifier();
    String runnerName = qRunner.getName().getIdentifier();

    SingleMemberAnnotation annotation = ast.newSingleMemberAnnotation();
    annotation.setTypeName(ast.newSimpleName(runWithName));

    TypeLiteral junit4Literal = ast.newTypeLiteral();
    junit4Literal.setType(ast.newSimpleType(ast.newSimpleName(runnerName)));
    annotation.setValue(junit4Literal);

    ListRewrite lrw = rewrite.getListRewrite(type, type.getModifiersProperty());
    lrw.insertFirst(annotation, null);

    return imported;
}

From source file:com.android.ide.eclipse.adt.internal.lint.AddSuppressAnnotation.java

License:Open Source License

@SuppressWarnings({ "rawtypes" }) // Java AST API has raw types
private MultiTextEdit addSuppressAnnotation(IDocument document, ICompilationUnit compilationUnit,
        BodyDeclaration declaration) throws CoreException {
    List modifiers = declaration.modifiers();
    SingleMemberAnnotation existing = null;
    for (Object o : modifiers) {
        if (o instanceof SingleMemberAnnotation) {
            SingleMemberAnnotation annotation = (SingleMemberAnnotation) o;
            String type = annotation.getTypeName().getFullyQualifiedName();
            if (type.equals(FQCN_SUPPRESS_LINT) || type.endsWith(SUPPRESS_LINT)) {
                existing = annotation;/*w  ww . j a v  a 2 s . c  o  m*/
                break;
            }
        }
    }

    ImportRewrite importRewrite = ImportRewrite.create(compilationUnit, true);
    String local = importRewrite.addImport(FQCN_SUPPRESS_LINT);
    AST ast = declaration.getAST();
    ASTRewrite rewriter = ASTRewrite.create(ast);
    if (existing == null) {
        SingleMemberAnnotation newAnnotation = ast.newSingleMemberAnnotation();
        newAnnotation.setTypeName(ast.newSimpleName(local));
        StringLiteral value = ast.newStringLiteral();
        value.setLiteralValue(mId);
        newAnnotation.setValue(value);
        ListRewrite listRewrite = rewriter.getListRewrite(declaration, declaration.getModifiersProperty());
        listRewrite.insertFirst(newAnnotation, null);
    } else {
        Expression existingValue = existing.getValue();
        if (existingValue instanceof StringLiteral) {
            StringLiteral stringLiteral = (StringLiteral) existingValue;
            if (mId.equals(stringLiteral.getLiteralValue())) {
                // Already contains the id
                return null;
            }
            // Create a new array initializer holding the old string plus the new id
            ArrayInitializer array = ast.newArrayInitializer();
            StringLiteral old = ast.newStringLiteral();
            old.setLiteralValue(stringLiteral.getLiteralValue());
            array.expressions().add(old);
            StringLiteral value = ast.newStringLiteral();
            value.setLiteralValue(mId);
            array.expressions().add(value);
            rewriter.set(existing, VALUE_PROPERTY, array, null);
        } else if (existingValue instanceof ArrayInitializer) {
            // Existing array: just append the new string
            ArrayInitializer array = (ArrayInitializer) existingValue;
            List expressions = array.expressions();
            if (expressions != null) {
                for (Object o : expressions) {
                    if (o instanceof StringLiteral) {
                        if (mId.equals(((StringLiteral) o).getLiteralValue())) {
                            // Already contains the id
                            return null;
                        }
                    }
                }
            }
            StringLiteral value = ast.newStringLiteral();
            value.setLiteralValue(mId);
            ListRewrite listRewrite = rewriter.getListRewrite(array, EXPRESSIONS_PROPERTY);
            listRewrite.insertLast(value, null);
        } else {
            assert false : existingValue;
            return null;
        }
    }

    TextEdit importEdits = importRewrite.rewriteImports(new NullProgressMonitor());
    TextEdit annotationEdits = rewriter.rewriteAST(document, null);

    // Apply to the document
    MultiTextEdit edit = new MultiTextEdit();
    // Create the edit to change the imports, only if
    // anything changed
    if (importEdits.hasChildren()) {
        edit.addChild(importEdits);
    }
    edit.addChild(annotationEdits);

    return edit;
}

From source file:com.android.ide.eclipse.adt.internal.lint.AddSuppressAnnotation.java

License:Open Source License

@SuppressWarnings({ "rawtypes" }) // Java AST API has raw types
private MultiTextEdit addTargetApiAnnotation(IDocument document, ICompilationUnit compilationUnit,
        BodyDeclaration declaration) throws CoreException {
    List modifiers = declaration.modifiers();
    SingleMemberAnnotation existing = null;
    for (Object o : modifiers) {
        if (o instanceof SingleMemberAnnotation) {
            SingleMemberAnnotation annotation = (SingleMemberAnnotation) o;
            String type = annotation.getTypeName().getFullyQualifiedName();
            if (type.equals(FQCN_TARGET_API) || type.endsWith(TARGET_API)) {
                existing = annotation;//from   w w  w  .  j ava2 s.com
                break;
            }
        }
    }

    ImportRewrite importRewrite = ImportRewrite.create(compilationUnit, true);
    importRewrite.addImport("android.os.Build"); //$NON-NLS-1$
    String local = importRewrite.addImport(FQCN_TARGET_API);
    AST ast = declaration.getAST();
    ASTRewrite rewriter = ASTRewrite.create(ast);
    if (existing == null) {
        SingleMemberAnnotation newAnnotation = ast.newSingleMemberAnnotation();
        newAnnotation.setTypeName(ast.newSimpleName(local));
        Expression value = createLiteral(ast);
        newAnnotation.setValue(value);
        ListRewrite listRewrite = rewriter.getListRewrite(declaration, declaration.getModifiersProperty());
        listRewrite.insertFirst(newAnnotation, null);
    } else {
        Expression value = createLiteral(ast);
        rewriter.set(existing, VALUE_PROPERTY, value, null);
    }

    TextEdit importEdits = importRewrite.rewriteImports(new NullProgressMonitor());
    TextEdit annotationEdits = rewriter.rewriteAST(document, null);
    MultiTextEdit edit = new MultiTextEdit();
    if (importEdits.hasChildren()) {
        edit.addChild(importEdits);
    }
    edit.addChild(annotationEdits);

    return edit;
}

From source file:com.android.ide.eclipse.auidt.internal.lint.AddSuppressAnnotation.java

License:Open Source License

@SuppressWarnings({ "rawtypes" }) // Java AST API has raw types
private MultiTextEdit addSuppressAnnotation(IDocument document, ICompilationUnit compilationUnit,
        BodyDeclaration declaration) throws CoreException {
    List modifiers = declaration.modifiers();
    SingleMemberAnnotation existing = null;
    for (Object o : modifiers) {
        if (o instanceof SingleMemberAnnotation) {
            SingleMemberAnnotation annotation = (SingleMemberAnnotation) o;
            String type = annotation.getTypeName().getFullyQualifiedName();
            if (type.equals(FQCN_SUPPRESS_LINT) || type.endsWith(SUPPRESS_LINT)) {
                existing = annotation;/*from   w w w .j  a  v a 2  s . c  o  m*/
                break;
            }
        }
    }

    ImportRewrite importRewrite = ImportRewrite.create(compilationUnit, true);
    String local = importRewrite.addImport(FQCN_SUPPRESS_LINT);
    AST ast = declaration.getAST();
    ASTRewrite rewriter = ASTRewrite.create(ast);
    if (existing == null) {
        SingleMemberAnnotation newAnnotation = ast.newSingleMemberAnnotation();
        newAnnotation.setTypeName(ast.newSimpleName(local));
        StringLiteral value = ast.newStringLiteral();
        value.setLiteralValue(mId);
        newAnnotation.setValue(value);
        ListRewrite listRewrite = rewriter.getListRewrite(declaration, declaration.getModifiersProperty());
        listRewrite.insertFirst(newAnnotation, null);
    } else {
        Expression existingValue = existing.getValue();
        if (existingValue instanceof StringLiteral) {
            // Create a new array initializer holding the old string plus the new id
            ArrayInitializer array = ast.newArrayInitializer();
            StringLiteral old = ast.newStringLiteral();
            StringLiteral stringLiteral = (StringLiteral) existingValue;
            old.setLiteralValue(stringLiteral.getLiteralValue());
            array.expressions().add(old);
            StringLiteral value = ast.newStringLiteral();
            value.setLiteralValue(mId);
            array.expressions().add(value);
            rewriter.set(existing, VALUE_PROPERTY, array, null);
        } else if (existingValue instanceof ArrayInitializer) {
            // Existing array: just append the new string
            ArrayInitializer array = (ArrayInitializer) existingValue;
            StringLiteral value = ast.newStringLiteral();
            value.setLiteralValue(mId);
            ListRewrite listRewrite = rewriter.getListRewrite(array, EXPRESSIONS_PROPERTY);
            listRewrite.insertLast(value, null);
        } else {
            assert false : existingValue;
            return null;
        }
    }

    TextEdit importEdits = importRewrite.rewriteImports(new NullProgressMonitor());
    TextEdit annotationEdits = rewriter.rewriteAST(document, null);

    // Apply to the document
    MultiTextEdit edit = new MultiTextEdit();
    // Create the edit to change the imports, only if
    // anything changed
    if (importEdits.hasChildren()) {
        edit.addChild(importEdits);
    }
    edit.addChild(annotationEdits);

    return edit;
}

From source file:com.android.ide.eclipse.auidt.internal.lint.AddSuppressAnnotation.java

License:Open Source License

@SuppressWarnings({ "rawtypes" }) // Java AST API has raw types
private MultiTextEdit addTargetApiAnnotation(IDocument document, ICompilationUnit compilationUnit,
        BodyDeclaration declaration) throws CoreException {
    List modifiers = declaration.modifiers();
    SingleMemberAnnotation existing = null;
    for (Object o : modifiers) {
        if (o instanceof SingleMemberAnnotation) {
            SingleMemberAnnotation annotation = (SingleMemberAnnotation) o;
            String type = annotation.getTypeName().getFullyQualifiedName();
            if (type.equals(FQCN_TARGET_API) || type.endsWith(TARGET_API)) {
                existing = annotation;/*from   w w  w . j av  a2  s. co m*/
                break;
            }
        }
    }

    ImportRewrite importRewrite = ImportRewrite.create(compilationUnit, true);
    String local = importRewrite.addImport(FQCN_TARGET_API);
    AST ast = declaration.getAST();
    ASTRewrite rewriter = ASTRewrite.create(ast);
    if (existing == null) {
        SingleMemberAnnotation newAnnotation = ast.newSingleMemberAnnotation();
        newAnnotation.setTypeName(ast.newSimpleName(local));
        NumberLiteral value = ast.newNumberLiteral(Integer.toString(mTargetApi));
        //value.setLiteralValue(mId);
        newAnnotation.setValue(value);
        ListRewrite listRewrite = rewriter.getListRewrite(declaration, declaration.getModifiersProperty());
        listRewrite.insertFirst(newAnnotation, null);
    } else {
        Expression existingValue = existing.getValue();
        if (existingValue instanceof NumberLiteral) {
            // Change the value to the new value
            NumberLiteral value = ast.newNumberLiteral(Integer.toString(mTargetApi));
            rewriter.set(existing, VALUE_PROPERTY, value, null);
        } else {
            assert false : existingValue;
            return null;
        }
    }

    TextEdit importEdits = importRewrite.rewriteImports(new NullProgressMonitor());
    TextEdit annotationEdits = rewriter.rewriteAST(document, null);
    MultiTextEdit edit = new MultiTextEdit();
    if (importEdits.hasChildren()) {
        edit.addChild(importEdits);
    }
    edit.addChild(annotationEdits);

    return edit;
}

From source file:com.crispico.flower.mp.codesync.code.java.adapter.JavaAbstractAstNodeModelAdapter.java

License:Open Source License

@Override
public Object createChildOnContainmentFeature(Object element, Object feature, Object correspondingChild) {
    if (AstCacheCodePackage.eINSTANCE.getModifiableElement_Modifiers().equals(feature)) {
        if (!(element instanceof BodyDeclaration || element instanceof SingleVariableDeclaration)) {
            return null;
        } else {/*  w w w  .j  ava2s .  c om*/
            IExtendedModifier extendedModifier = null;

            if (correspondingChild instanceof com.crispico.flower.mp.model.astcache.code.Modifier) {
                ASTNode parent = (ASTNode) element;
                AST ast = parent.getAST();
                com.crispico.flower.mp.model.astcache.code.Modifier modifier = (com.crispico.flower.mp.model.astcache.code.Modifier) correspondingChild;

                extendedModifier = ast.newModifier(Modifier.ModifierKeyword.fromFlagValue(modifier.getType()));
                if (parent instanceof BodyDeclaration) {
                    ((BodyDeclaration) parent).modifiers().add(extendedModifier);
                } else {
                    ((SingleVariableDeclaration) parent).modifiers().add(extendedModifier);
                }
            }

            if (correspondingChild instanceof com.crispico.flower.mp.model.astcache.code.Annotation) {
                ASTNode parent = (ASTNode) element;
                AST ast = parent.getAST();
                com.crispico.flower.mp.model.astcache.code.Annotation annotation = (com.crispico.flower.mp.model.astcache.code.Annotation) correspondingChild;
                if (annotation.getValues().size() == 0) {
                    MarkerAnnotation markerAnnotation = ast.newMarkerAnnotation();
                    extendedModifier = markerAnnotation;
                }
                if (annotation.getValues().size() == 1) {
                    SingleMemberAnnotation singleMemberAnnotation = ast.newSingleMemberAnnotation();
                    extendedModifier = singleMemberAnnotation;
                } else {
                    NormalAnnotation normalAnnotation = ast.newNormalAnnotation();
                    extendedModifier = normalAnnotation;
                }
                if (parent instanceof BodyDeclaration) {
                    ((BodyDeclaration) parent).modifiers().add(extendedModifier);
                } else {
                    ((SingleVariableDeclaration) parent).modifiers().add(extendedModifier);
                }
            }
            return extendedModifier;
        }
    }

    return null;
}

From source file:com.crispico.flower.mp.metamodel.codesyncjava.algorithm.JavaSyncUtils.java

License:Open Source License

/**
 * Creates a new appropriate {@link Annotation java Annotation} from the
 * given {@link EAnnotation modelEAnnotation}. The returned
 * {@link Annotation} can be a {@link MarkerAnnotation}, a
 * {@link SingleMemberAnnotation} or a {@link NormalAnnotation} according to
 * the <code>modelEAnnotation</code> features.
 * /*from  w w w. j a va  2  s .c o  m*/
 * @param ast
 *            the parent {@link AST} used to create the new
 *            {@link Annotation}
 * @param modelEAnnotation
 *            the model element {@link EAnnotation}
 * @return a new unparented {@link Annotation}
 * 
 * @author Luiza
 */
@SuppressWarnings("unchecked")
public static Annotation createNewJavaAnnotationFromModelEAnnotation(AST ast, EAnnotation modelEAnnotation) {
    EMap<String, String> detailsMap = modelEAnnotation.getDetails();
    Annotation newAnnotation = null;

    if (detailsMap.size() == 0) {
        newAnnotation = ast.newMarkerAnnotation();
    } else if (detailsMap.size() == 1 && detailsMap.get("") != null) {
        String value = detailsMap.get("");
        newAnnotation = ast.newSingleMemberAnnotation();
        ((SingleMemberAnnotation) newAnnotation).setValue(makeExpression(ast, value));
    } else {
        newAnnotation = ast.newNormalAnnotation();
        for (Entry<String, String> mapEntry : detailsMap) {
            MemberValuePair mvp = ast.newMemberValuePair();
            mvp.setName(ast.newSimpleName(mapEntry.getKey()));
            mvp.setValue(makeExpression(ast, mapEntry.getValue()));
            ((NormalAnnotation) newAnnotation).values().add(mvp);
        }
    }
    newAnnotation.setTypeName(ast.newName(modelEAnnotation.getSource()));
    return newAnnotation;
}

From source file:com.google.gwt.eclipse.core.clientbundle.ClientBundleResource.java

License:Open Source License

public MethodDeclaration createMethodDeclaration(IType clientBundle, ASTRewrite astRewrite,
        ImportRewrite importRewrite, boolean addComments) throws CoreException {
    AST ast = astRewrite.getAST();
    MethodDeclaration methodDecl = ast.newMethodDeclaration();

    // Method is named after the resource it accesses
    methodDecl.setName(ast.newSimpleName(getMethodName()));

    // Method return type is a ResourcePrototype subtype
    ITypeBinding resourceTypeBinding = JavaASTUtils.resolveType(clientBundle.getJavaProject(),
            getReturnTypeName());//  www  .j  a  v a2s.  c  om
    Type resourceType = importRewrite.addImport(resourceTypeBinding, ast);
    methodDecl.setReturnType2(resourceType);

    // Add @Source annotation if necessary
    String sourceAnnotationValue = getSourceAnnotationValue(clientBundle);
    if (sourceAnnotationValue != null) {
        // Build the annotation
        SingleMemberAnnotation sourceAnnotation = ast.newSingleMemberAnnotation();
        sourceAnnotation.setTypeName(ast.newName("Source"));
        StringLiteral annotationValue = ast.newStringLiteral();
        annotationValue.setLiteralValue(sourceAnnotationValue);
        sourceAnnotation.setValue(annotationValue);

        // Add the annotation to the method
        ChildListPropertyDescriptor modifiers = methodDecl.getModifiersProperty();
        ListRewrite modifiersRewriter = astRewrite.getListRewrite(methodDecl, modifiers);
        modifiersRewriter.insertFirst(sourceAnnotation, null);
    }

    return methodDecl;
}

From source file:com.halware.nakedide.eclipse.ext.annot.ast.AbstractAnnotationEvaluatorOrModifier.java

License:Open Source License

private void updateSingleMemberAnnotation(ICompilationUnit compilationUnit, BodyDeclaration declaration,
        Object value) throws JavaModelException, MalformedTreeException, BadLocationException {

    SingleMemberAnnotation singleMemberAnnotation = annotation(declaration, SingleMemberAnnotation.class);
    if (singleMemberAnnotation != null) {
        AST ast = singleMemberAnnotation.getAST();
        if (value != QualifiedNameValue.DEFAULT_VALUE) {
            Expression replacement = value != null ? AstUtils.createExpression(ast, value) : null;

            AstUtils.rewriteReplace(compilationUnit, singleMemberAnnotation.getValue(), replacement);
            return;
        } else {/*from  www .j  a v  a  2  s.  c  o  m*/
            MarkerAnnotation replacementAnnotation = ast.newMarkerAnnotation();
            replacementAnnotation
                    .setTypeName(ast.newName(singleMemberAnnotation.getTypeName().getFullyQualifiedName()));
            AstUtils.rewriteReplace(compilationUnit, singleMemberAnnotation, replacementAnnotation);
            return;
        }
    }
    MarkerAnnotation markerAnnotation = annotation(declaration, MarkerAnnotation.class);
    if (markerAnnotation != null) {
        AST ast = markerAnnotation.getAST();
        if (value != QualifiedNameValue.DEFAULT_VALUE) {
            SingleMemberAnnotation replacementAnnotation = ast.newSingleMemberAnnotation();
            replacementAnnotation
                    .setTypeName(ast.newName(markerAnnotation.getTypeName().getFullyQualifiedName()));
            Expression memberValueExpression = value != null ? AstUtils.createExpression(ast, value) : null;
            replacementAnnotation.setValue(memberValueExpression);
            AstUtils.rewriteReplace(compilationUnit, markerAnnotation, replacementAnnotation);
        } else {
            // nothing to do
        }
    }

}