Example usage for org.eclipse.jdt.core.dom Annotation setTypeName

List of usage examples for org.eclipse.jdt.core.dom Annotation setTypeName

Introduction

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

Prototype

public void setTypeName(Name typeName) 

Source Link

Document

Sets the annotation type name of this annotation.

Usage

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

License:Open Source License

@Override
public void setValueFeatureValue(Object element, Object feature, Object value) {
    if (AstCacheCodePackage.eINSTANCE.getAnnotation_Name().equals(feature)) {
        if (element instanceof Annotation) {
            Annotation annotation = (Annotation) element;
            String name = (String) value;
            annotation.setTypeName(annotation.getAST().newName(name));
        }//from   w  w w .  ja  va2 s. c om
        return;
    }
    super.setValueFeatureValue(element, feature, value);
}

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.
 * /*  w w w  . ja v a 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:jmockit.assist.ASTUtil.java

License:Open Source License

public static void addAnnotation(final String annotation, final IJavaProject project, final ASTRewrite rewrite,
        final MethodDeclaration decl, final IMethodBinding binding) {
    String version = project.getOption(JavaCore.COMPILER_COMPLIANCE, true);

    if (!binding.getDeclaringClass().isInterface()
            || !JavaModelUtil.isVersionLessThan(version, JavaCore.VERSION_1_6)) {
        final Annotation marker = rewrite.getAST().newMarkerAnnotation();
        marker.setTypeName(rewrite.getAST().newSimpleName(annotation)); //$NON-NLS-1$
        rewrite.getListRewrite(decl, MethodDeclaration.MODIFIERS2_PROPERTY).insertFirst(marker, null);
    }//from  w  w  w . ja  v a2  s. co m
}

From source file:org.eclipse.jdt.core.dom.ASTConverter.java

License:Open Source License

protected void setTypeNameForAnnotation(org.eclipse.jdt.internal.compiler.ast.Annotation compilerAnnotation,
        Annotation annotation) {
    TypeReference typeReference = compilerAnnotation.type;
    if (typeReference instanceof QualifiedTypeReference) {
        QualifiedTypeReference qualifiedTypeReference = (QualifiedTypeReference) typeReference;
        char[][] tokens = qualifiedTypeReference.tokens;
        long[] positions = qualifiedTypeReference.sourcePositions;
        // QualifiedName
        annotation.setTypeName(setQualifiedNameNameAndSourceRanges(tokens, positions, typeReference));
    } else {//from  w  w w  .  j  a v  a  2 s.c  o m
        SingleTypeReference singleTypeReference = (SingleTypeReference) typeReference;
        final SimpleName name = new SimpleName(this.ast);
        name.internalSetIdentifier(new String(singleTypeReference.token));
        int start = singleTypeReference.sourceStart;
        int end = singleTypeReference.sourceEnd;
        name.setSourceRange(start, end - start + 1);
        name.index = 1;
        annotation.setTypeName(name);
        if (this.resolveBindings) {
            recordNodes(name, typeReference);
        }
    }
}

From source file:org.eclipse.jpt.common.core.internal.utility.jdt.AbstractDeclarationAnnotationAdapter.java

License:Open Source License

/**
 * Add the appropriate import statement, then shorten the annotation's
 * name before adding it to the declaration.
 *///www  . j  a  v  a 2  s  .  c  om
protected void addAnnotationAndImport(ModifiedDeclaration declaration, Annotation annotation) {
    annotation.setTypeName(declaration.getAst().newName(this.getSourceCodeAnnotationName(declaration)));
    this.addAnnotation(declaration, annotation);
}

From source file:org.eclipse.objectteams.otdt.internal.ui.assist.CompletionAdaptor.OverrideRoleCompletionProposal.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
    @Override/*w  ww  . j av a2s . com*/
    protected boolean updateReplacementString(IDocument document, char trigger, int offset,
            ImportRewrite importRewrite) throws CoreException, BadLocationException {
        Document recoveredDocument = new Document();
        CompilationUnit unit = getRecoveredAST(document, offset, recoveredDocument);

        // find enclosing team type:
        ASTNode node = NodeFinder.perform(unit, fReplaceStart, 0);
        while (node != null && !(node instanceof AbstractTypeDeclaration)) {
            node = node.getParent();
        }

        if (node != null) {
            AbstractTypeDeclaration teamDecl = ((AbstractTypeDeclaration) node);

            // create and setup the rewrite:
            AST ast = unit.getAST();
            ASTRewrite rewrite = ASTRewrite.create(ast);
            rewrite.setToOTJ();

            // create type
            TypeDeclaration newType = ast.newTypeDeclaration();
            newType.setName(ast.newSimpleName(this.fRoleName));
            newType.setInterface(Flags.isInterface(this.fModifiers));
            newType.setTeam(Flags.isTeam(this.fModifiers));
            // add @Override:
            Annotation overrideAnnotation = ast.newMarkerAnnotation();
            overrideAnnotation.setTypeName(ast.newSimpleName("Override")); //$NON-NLS-1$
            List modifiers = newType.modifiers();
            modifiers.add(overrideAnnotation);
            // add protected or public
            modifiers.add(ast.newModifier(Flags.isPublic(this.fModifiers) ? ModifierKeyword.PUBLIC_KEYWORD
                    : ModifierKeyword.PROTECTED_KEYWORD));
            // add team keyword?
            if (Flags.isTeam(this.fModifiers))
                modifiers.add(ast.newModifier(ModifierKeyword.TEAM_KEYWORD));

            insertStub(rewrite, teamDecl, teamDecl.getBodyDeclarationsProperty(), this.fReplaceStart, newType);

            // create the replacementString from the rewrite:
            ITrackedNodePosition position = rewrite.track(newType);
            try {
                rewrite.rewriteAST(recoveredDocument, fJavaProject.getOptions(true)).apply(recoveredDocument);

                String generatedCode = recoveredDocument.get(position.getStartPosition(), position.getLength());
                CodeGenerationSettings settings = JavaPreferencesSettings.getCodeGenerationSettings(fJavaProject);
                int generatedIndent = IndentManipulation.measureIndentUnits(
                        getIndentAt(recoveredDocument, position.getStartPosition(), settings), settings.tabWidth,
                        settings.indentWidth);

                String indent = getIndentAt(document, getReplacementOffset(), settings);
                setReplacementString(
                        IndentManipulation.changeIndent(generatedCode, generatedIndent, settings.tabWidth,
                                settings.indentWidth, indent, TextUtilities.getDefaultLineDelimiter(document)));

            } catch (MalformedTreeException exception) {
                JavaPlugin.log(exception);
            } catch (BadLocationException exception) {
                JavaPlugin.log(exception);
            }
        }
        return true;
    }

From source file:org.evosuite.eclipse.quickfixes.ResolutionMarkerEvoIgnoreForClass.java

License:Open Source License

@Override
public void run(IMarker marker) {
    IResource res = marker.getResource();

    try {// w w  w  .  j a v  a 2 s  .  co  m

        CompilationUnit compunit = CompilationUnitManager.getCompilationUnit(res);

        int position = marker.getAttribute(IMarker.CHAR_START, 0) + 1;
        if (position == 0) {
            int line = marker.getAttribute(IMarker.LINE_NUMBER, 0);
            position = compunit.getPosition(line, 0);
        }

        AST ast = compunit.getAST();

        ASTRewrite rewriter = ASTRewrite.create(ast);

        Annotation annotation = ast.newNormalAnnotation();
        annotation.setTypeName(ast.newName("EvoIgnore"));
        ImportDeclaration id = ast.newImportDeclaration();
        id.setName(ast.newName("org.evosuite.quickfixes.annotations.EvoIgnore"));
        ListRewrite lr = rewriter.getListRewrite(compunit, CompilationUnit.TYPES_PROPERTY);

        //lr.insertFirst(annotation, null);
        lr.insertAt(annotation, 0, null);
        lr.insertAt(id, 0, null);
        ITextFileBufferManager bm = FileBuffers.getTextFileBufferManager();
        IPath path = compunit.getJavaElement().getPath();
        try {
            bm.connect(path, null, null);
            ITextFileBuffer textFileBuffer = bm.getTextFileBuffer(path, null);
            IDocument document = textFileBuffer.getDocument();
            TextEdit edits = rewriter.rewriteAST(document, null);
            edits.apply(document);
            textFileBuffer.commit(null, false);

        } catch (CoreException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MalformedTreeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadLocationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                bm.disconnect(path, null, null);
            } catch (CoreException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } // (4)
        }
        System.out
                .println(lr.getRewrittenList() + "\nPosition: " + position + "\nEdits: " + rewriter.toString());
    } catch (JavaModelException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        marker.delete();
    } catch (CoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.evosuite.eclipse.quickfixes.ResolutionMarkerEvoIgnoreForMethod.java

License:Open Source License

@Override
public void run(IMarker marker) {
    // TODO Auto-generated method stub
    IResource res = marker.getResource();

    try {/*from   www  .  j  a va2s .c  o m*/

        ICompilationUnit icomp = CompilationUnitManager.getICompilationUnit(res);

        CompilationUnit compunit = CompilationUnitManager.getCompilationUnit(res);

        int position = marker.getAttribute(IMarker.CHAR_START, 0) + 1;
        if (position == 1) {
            int line = marker.getAttribute(IMarker.LINE_NUMBER, 0);
            position = compunit.getPosition(line, 0);
        }

        AST ast = compunit.getAST();
        ASTRewrite rewriter = ASTRewrite.create(ast);

        IJavaElement element = icomp.getElementAt(position);
        IJavaElement method = getMethod(element);

        //         TypeDeclaration td = (TypeDeclaration) compunit.types().get(0);
        TypeDeclaration td = (TypeDeclaration) compunit.types().get(0);

        MethodDeclaration md = td.getMethods()[0];

        int counter = 1;
        while (!md.getName().getFullyQualifiedName().equals(method.getElementName())
                && counter < td.getMethods().length) {
            md = td.getMethods()[counter];
            System.out.println(md.getName().getFullyQualifiedName() + " " + method.getElementName());
            counter++;
        }

        Annotation annotation = ast.newNormalAnnotation();
        annotation.setTypeName(ast.newName("EvoIgnore"));
        ImportDeclaration id = ast.newImportDeclaration();

        id.setName(ast.newName("org.evosuite.quickfixes.annotations.EvoIgnore"));
        ListRewrite lr = rewriter.getListRewrite(md.getParent(), TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
        ListRewrite lr2 = rewriter.getListRewrite(compunit, CompilationUnit.TYPES_PROPERTY);

        //lr.insertFirst(annotation, null);
        lr.insertBefore(annotation, md, null);
        lr2.insertAt(id, 0, null);
        ITextFileBufferManager bm = FileBuffers.getTextFileBufferManager();
        IPath path = compunit.getJavaElement().getPath();
        try {
            bm.connect(path, null, null);
            ITextFileBuffer textFileBuffer = bm.getTextFileBuffer(path, null);
            IDocument document = textFileBuffer.getDocument();
            TextEdit edits = rewriter.rewriteAST(document, null);
            edits.apply(document);
            textFileBuffer.commit(null, false);

        } catch (CoreException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MalformedTreeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadLocationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                bm.disconnect(path, null, null);
            } catch (CoreException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } // (4)
        }
        System.out
                .println(lr.getRewrittenList() + "\nPosition: " + position + "\nEdits: " + rewriter.toString());
    } catch (JavaModelException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        marker.delete();
    } catch (CoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.flowerplatform.codesync.code.java.adapter.JavaAnnotationModelAdapter.java

License:Open Source License

@Override
public void setValueFeatureValue(Object element, Object feature, Object value) {
    if (CoreConstants.NAME.equals(feature)) {
        if (element instanceof Annotation) {
            Annotation annotation = (Annotation) element;
            String name = (String) value;
            annotation.setTypeName(annotation.getAST().newName(name));
        }//from   ww  w.  j a  va  2  s . c  om
        return;
    }
    super.setValueFeatureValue(element, feature, value);
}

From source file:org.jboss.tools.arquillian.ui.internal.refactoring.AddMissingTypeRefactoring.java

License:Open Source License

@Override
public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException {
    message = null;/*w w w  . j  a  v  a  2s .  c  o  m*/
    if (astRoot == null || (abstractMethodBindings == null && deploymentMethodName == null)) {
        message = CANNOT_FIND_A_DEPLOYMENT_METHOD;
        return null;
    }
    MethodDeclaration deploymentMethod = null;
    TextFileChange result = new TextFileChange(file.getName(), file);
    MultiTextEdit rootEdit = new MultiTextEdit();
    importRewrite = CodeStyleConfiguration.createImportRewrite(astRoot, true);
    if (astRoot.getAST().hasResolvedBindings()) {
        importRewrite.setUseContextToFilterImplicitImports(true);
    }
    rewrite = ASTRewrite.create(astRoot.getAST());
    IType fType = cUnit.findPrimaryType();
    if (fType.isAnonymous()) {
        final ClassInstanceCreation creation = (ClassInstanceCreation) ASTNodes
                .getParent(NodeFinder.perform(astRoot, fType.getNameRange()), ClassInstanceCreation.class);
        if (creation != null) {
            final AnonymousClassDeclaration declaration = creation.getAnonymousClassDeclaration();
            if (declaration != null)
                listRewriter = rewrite.getListRewrite(declaration,
                        AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY);
        }
    } else {
        final AbstractTypeDeclaration declaration = (AbstractTypeDeclaration) ASTNodes
                .getParent(NodeFinder.perform(astRoot, fType.getNameRange()), AbstractTypeDeclaration.class);
        if (declaration != null)
            listRewriter = rewrite.getListRewrite(declaration, declaration.getBodyDeclarationsProperty());
    }
    if (listRewriter == null) {
        throw new CoreException(new Status(IStatus.ERROR, ArquillianUIActivator.PLUGIN_ID, IStatus.ERROR,
                "Could not find the type element", null));
    }
    ast = astRoot.getAST();
    ReturnStatement returnStatement;
    if (abstractMethodBindings != null) {
        IMethodBinding abstractMethodBinding = null;
        for (IMethodBinding binding : abstractMethodBindings) {
            if (binding.getName().equals(deploymentMethodName)) {
                abstractMethodBinding = binding;
                break;
            }
        }
        if (abstractMethodBinding == null) {
            message = CANNOT_FIND_A_DEPLOYMENT_METHOD;
            return null;
        }
        deploymentMethod = ast.newMethodDeclaration();
        deploymentMethod.setName(ast.newSimpleName(deploymentMethodName));

        IJavaProject javaProject = abstractMethodBinding.getJavaElement().getJavaProject();
        String archiveTypeName = ArquillianUtility.ORG_JBOSS_SHRINKWRAP_API_SPEC_JAVA_ARCHIVE;
        if (javaProject != null && javaProject.isOpen()) {
            IProject project = javaProject.getProject();
            IFile pomFile = project.getFile(IMavenConstants.POM_FILE_NAME);
            if (pomFile != null && pomFile.exists()) {
                try {
                    IMavenProjectFacade facade = MavenPlugin.getMavenProjectRegistry().create(project,
                            new NullProgressMonitor());
                    MavenProject mavenProject = facade.getMavenProject(new NullProgressMonitor());
                    Model model = mavenProject.getModel();
                    String packaging = model.getPackaging();
                    if (ArquillianConstants.WAR.equals(packaging)) {
                        archiveTypeName = ArquillianUtility.ORG_JBOSS_SHRINKWRAP_API_SPEC_WEB_ARCHIVE;
                    }
                    if (ArquillianConstants.EAR.equals(packaging)) {
                        archiveTypeName = ArquillianUtility.ORG_JBOSS_SHRINKWRAP_API_SPEC_ENTERPRISE_ARCHIVE;
                    }
                    if (ArquillianConstants.RAR.equals(packaging)) {
                        archiveTypeName = ArquillianUtility.ORG_JBOSS_SHRINKWRAP_API_SPEC_RESOURCEADAPTER_ARCHIVE;
                    }
                } catch (CoreException e) {
                    ArquillianUIActivator.log(e);
                }
            }
        }
        int index = archiveTypeName.lastIndexOf("."); //$NON-NLS-1$
        String simpleArchiveName;
        if (index >= 0) {
            simpleArchiveName = archiveTypeName.substring(index + 1);
        } else {
            simpleArchiveName = archiveTypeName;
        }
        SimpleName type2 = ast.newSimpleName(simpleArchiveName);
        importRewrite.addImport(archiveTypeName);
        deploymentMethod.setReturnType2(ast.newSimpleType(type2));
        deploymentMethod.setConstructor(false);
        deploymentMethod.modifiers()
                .addAll(ASTNodeFactory.newModifiers(ast, Modifier.PUBLIC | Modifier.STATIC));

        Annotation marker = rewrite.getAST().newMarkerAnnotation();
        importRewrite.addImport(ArquillianUtility.ORG_JBOSS_ARQUILLIAN_CONTAINER_TEST_API_DEPLOYMENT);
        marker.setTypeName(rewrite.getAST().newSimpleName("Deployment")); //$NON-NLS-1$
        rewrite.getListRewrite(deploymentMethod, MethodDeclaration.MODIFIERS2_PROPERTY).insertFirst(marker,
                null);

        Block body = ast.newBlock();
        deploymentMethod.setBody(body);

        // XXXArchive archive = (XXXArchive) AbstractTest.createDeployment();
        String declaringClassQualifiedName = abstractMethodBinding.getDeclaringClass().getQualifiedName();
        importRewrite.addImport(declaringClassQualifiedName);
        String declaringClassName = abstractMethodBinding.getDeclaringClass().getName();
        MethodInvocation deploymentInvocation = ast.newMethodInvocation();
        deploymentInvocation.setExpression(ast.newName(declaringClassName));
        deploymentInvocation.setName(ast.newSimpleName(deploymentMethodName));
        VariableDeclarationFragment archiveDeclFragment = ast.newVariableDeclarationFragment();
        archiveDeclFragment.setName(ast.newSimpleName(ARCHIVE_VARIABLE));
        ITypeBinding returnType = abstractMethodBinding.getReturnType();
        if (!archiveTypeName.equals(returnType.getQualifiedName())) {
            CastExpression cast = ast.newCastExpression();
            cast.setType(ast.newSimpleType(ast.newName(simpleArchiveName)));
            cast.setExpression(deploymentInvocation);
            archiveDeclFragment.setInitializer(cast);
        } else {
            archiveDeclFragment.setInitializer(deploymentInvocation);
        }
        VariableDeclarationStatement vStatement = ast.newVariableDeclarationStatement(archiveDeclFragment);
        vStatement.setType(ast.newSimpleType(ast.newName(simpleArchiveName)));
        body.statements().add(vStatement);

        //return archive;
        returnStatement = ast.newReturnStatement();
        returnStatement.setExpression(ast.newSimpleName(ARCHIVE_VARIABLE));
        //body.statements().add(returnStatement);
    } else {
        for (MethodDeclaration md : deploymentMethodDeclarations) {
            if (deploymentMethodName.equals(md.getName().getIdentifier())) {
                deploymentMethod = md;
                break;
            }
        }
        if (deploymentMethod == null) {
            message = CANNOT_FIND_A_DEPLOYMENT_METHOD;
            return null;
        }
        returnStatement = getReturnStatement(deploymentMethod);
        ast = deploymentMethod.getAST();
        rewrite = ASTRewrite.create(ast);
    }

    if (returnStatement == null) {
        message = "Cannot find a return statement";
        return null;
    }

    Expression expression = returnStatement.getExpression();

    if (expression instanceof MethodInvocation) {
        int start = expression.getStartPosition();
        int length = expression.getLength();
        selectedExpression = getSelectedExpression(new SourceRange(start, length));
        tempName = ARCHIVE_VARIABLE;
        int i = 0;
        while (!checkTempName(tempName).isOK()) {
            tempName = tempName + i++;
        }
        createAndInsertTempDeclaration(start, length);
        addReplaceExpressionWithTemp();
        createStatements(tempName, className, deploymentMethod, returnStatement, rootEdit, pm);
    }
    if (expression instanceof SimpleName) {
        String name = ((SimpleName) expression).getIdentifier();
        createStatements(name, className, deploymentMethod, returnStatement, rootEdit, pm);
    }

    result.setEdit(rootEdit);
    return result;
}