Search in sources :

Example 1 with NormalAnnotation

use of org.eclipse.jdt.core.dom.NormalAnnotation in project che by eclipse.

the class UnresolvedElementsSubProcessor method getAnnotationMemberProposals.

public static void getAnnotationMemberProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) throws CoreException {
    CompilationUnit astRoot = context.getASTRoot();
    ICompilationUnit cu = context.getCompilationUnit();
    ASTNode selectedNode = problem.getCoveringNode(astRoot);
    Annotation annotation;
    String memberName;
    if (selectedNode.getLocationInParent() == MemberValuePair.NAME_PROPERTY) {
        if (selectedNode.getParent().getLocationInParent() != NormalAnnotation.VALUES_PROPERTY) {
            return;
        }
        annotation = (Annotation) selectedNode.getParent().getParent();
        memberName = ((SimpleName) selectedNode).getIdentifier();
    } else if (selectedNode.getLocationInParent() == SingleMemberAnnotation.VALUE_PROPERTY) {
        annotation = (Annotation) selectedNode.getParent();
        //$NON-NLS-1$
        memberName = "value";
    } else {
        return;
    }
    ITypeBinding annotBinding = annotation.resolveTypeBinding();
    if (annotBinding == null) {
        return;
    }
    if (annotation instanceof NormalAnnotation) {
        // similar names
        IMethodBinding[] otherMembers = annotBinding.getDeclaredMethods();
        for (int i = 0; i < otherMembers.length; i++) {
            IMethodBinding binding = otherMembers[i];
            String curr = binding.getName();
            int relevance = NameMatcher.isSimilarName(memberName, curr) ? IProposalRelevance.CHANGE_TO_ATTRIBUTE_SIMILAR_NAME : IProposalRelevance.CHANGE_TO_ATTRIBUTE;
            String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_UnresolvedElementsSubProcessor_changetoattribute_description, BasicElementLabels.getJavaElementName(curr));
            proposals.add(new RenameNodeCorrectionProposal(label, cu, problem.getOffset(), problem.getLength(), curr, relevance));
        }
    }
    if (annotBinding.isFromSource()) {
        ICompilationUnit targetCU = ASTResolving.findCompilationUnitForBinding(cu, astRoot, annotBinding);
        if (targetCU != null) {
            String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_UnresolvedElementsSubProcessor_createattribute_description, BasicElementLabels.getJavaElementName(memberName));
            Image image = JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC);
            proposals.add(new NewAnnotationMemberProposal(label, targetCU, selectedNode, annotBinding, IProposalRelevance.CREATE_ATTRIBUTE, image));
        }
    }
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) Image(org.eclipse.swt.graphics.Image) NormalAnnotation(org.eclipse.jdt.core.dom.NormalAnnotation) SingleMemberAnnotation(org.eclipse.jdt.core.dom.SingleMemberAnnotation) Annotation(org.eclipse.jdt.core.dom.Annotation) RenameNodeCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.RenameNodeCorrectionProposal) NewAnnotationMemberProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.NewAnnotationMemberProposal) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) NormalAnnotation(org.eclipse.jdt.core.dom.NormalAnnotation)

Example 2 with NormalAnnotation

use of org.eclipse.jdt.core.dom.NormalAnnotation in project buck by facebook.

the class JavaFileParser method extractFeaturesFromJavaCode.

public JavaFileFeatures extractFeaturesFromJavaCode(String code) {
    // For now, we will harcode this. Ultimately, we probably want to make this configurable via
    // .buckconfig. For example, the Buck project itself is diligent about disallowing wildcard
    // imports, but the one exception is the Java code generated via Thrift in src-gen.
    final boolean shouldThrowForUnsupportedWildcardImport = false;
    final AtomicBoolean isPoisonedByUnsupportedWildcardImport = new AtomicBoolean(false);
    final CompilationUnit compilationUnit = makeCompilationUnitFromSource(code);
    final ImmutableSortedSet.Builder<String> providedSymbols = ImmutableSortedSet.naturalOrder();
    final ImmutableSortedSet.Builder<String> requiredSymbols = ImmutableSortedSet.naturalOrder();
    final ImmutableSortedSet.Builder<String> exportedSymbols = ImmutableSortedSet.naturalOrder();
    final ImmutableSortedSet.Builder<String> requiredSymbolsFromExplicitImports = ImmutableSortedSet.naturalOrder();
    compilationUnit.accept(new ASTVisitor() {

        @Nullable
        private String packageName;

        /** Maps simple name to fully-qualified name. */
        private Map<String, String> simpleImportedTypes = new HashMap<>();

        /**
       * Maps wildcard import prefixes, such as {@code "java.util"} to the types in the respective
       * package if a wildcard import such as {@code import java.util.*} is used.
       */
        private Map<String, ImmutableSet<String>> wildcardImports = new HashMap<>();

        @Override
        public boolean visit(PackageDeclaration node) {
            Preconditions.checkState(packageName == null, "There should be at most one package declaration");
            packageName = node.getName().getFullyQualifiedName();
            return false;
        }

        // providedSymbols
        @Override
        public boolean visit(TypeDeclaration node) {
            // Local classes can be declared inside of methods. Skip over these.
            if (node.getParent() instanceof TypeDeclarationStatement) {
                return true;
            }
            String fullyQualifiedName = getFullyQualifiedTypeName(node);
            if (fullyQualifiedName != null) {
                providedSymbols.add(fullyQualifiedName);
            }
            @SuppressWarnings("unchecked") List<Type> interfaceTypes = node.superInterfaceTypes();
            for (Type interfaceType : interfaceTypes) {
                tryAddType(interfaceType, DependencyType.EXPORTED);
            }
            Type superclassType = node.getSuperclassType();
            if (superclassType != null) {
                tryAddType(superclassType, DependencyType.EXPORTED);
            }
            return true;
        }

        @Override
        public boolean visit(EnumDeclaration node) {
            String fullyQualifiedName = getFullyQualifiedTypeName(node);
            if (fullyQualifiedName != null) {
                providedSymbols.add(fullyQualifiedName);
            }
            return true;
        }

        @Override
        public boolean visit(AnnotationTypeDeclaration node) {
            String fullyQualifiedName = getFullyQualifiedTypeName(node);
            if (fullyQualifiedName != null) {
                providedSymbols.add(fullyQualifiedName);
            }
            return true;
        }

        // requiredSymbols
        /**
       * Uses heuristics to try to figure out what type of QualifiedName this is. Returns a non-null
       * value if this is believed to be a reference that qualifies as a "required symbol"
       * relationship.
       */
        @Override
        public boolean visit(QualifiedName node) {
            QualifiedName ancestor = findMostQualifiedAncestor(node);
            ASTNode parent = ancestor.getParent();
            if (!(parent instanceof PackageDeclaration) && !(parent instanceof ImportDeclaration)) {
                String symbol = ancestor.getFullyQualifiedName();
                // lookup.
                if (CharMatcher.javaUpperCase().matches(symbol.charAt(0))) {
                    addTypeFromDotDelimitedSequence(symbol, DependencyType.REQUIRED);
                }
            }
            return false;
        }

        /**
       * @param expr could be "Example", "Example.field", "com.example.Example". Note it could also
       *     be a built-in type, such as "java.lang.Integer", in which case it will not be added to
       *     the set of required symbols.
       */
        private void addTypeFromDotDelimitedSequence(String expr, DependencyType dependencyType) {
            // check it against JAVA_LANG_TYPES.
            if (startsWithUppercaseChar(expr)) {
                int index = expr.indexOf('.');
                if (index >= 0) {
                    String leftmostComponent = expr.substring(0, index);
                    if (JAVA_LANG_TYPES.contains(leftmostComponent)) {
                        return;
                    }
                }
            }
            expr = qualifyWithPackageNameIfNecessary(expr);
            addSymbol(expr, dependencyType);
        }

        @Override
        public boolean visit(ImportDeclaration node) {
            String fullyQualifiedName = node.getName().getFullyQualifiedName();
            // third-party code. As such, we will tolerate these for some of the common cases.
            if (node.isOnDemand()) {
                ImmutableSet<String> value = SUPPORTED_WILDCARD_IMPORTS.get(fullyQualifiedName);
                if (value != null) {
                    wildcardImports.put(fullyQualifiedName, value);
                    return false;
                } else if (shouldThrowForUnsupportedWildcardImport) {
                    throw new RuntimeException(String.format("Use of wildcard 'import %s.*' makes it impossible to statically determine " + "required symbols in this file. Please enumerate explicit imports.", fullyQualifiedName));
                } else {
                    isPoisonedByUnsupportedWildcardImport.set(true);
                    return false;
                }
            }
            // Only worry about the dependency on the enclosing type.
            Optional<String> simpleName = getSimpleNameFromFullyQualifiedName(fullyQualifiedName);
            if (simpleName.isPresent()) {
                String name = simpleName.get();
                int index = fullyQualifiedName.indexOf("." + name);
                String enclosingType = fullyQualifiedName.substring(0, index + name.length() + 1);
                requiredSymbolsFromExplicitImports.add(enclosingType);
                simpleImportedTypes.put(name, enclosingType);
            } else {
                LOG.warn("Suspicious import lacks obvious enclosing type: %s", fullyQualifiedName);
                // The one example we have seen of this in the wild is
                // "org.whispersystems.curve25519.java.curve_sigs". In practice, we still need to add it
                // as a required symbol in this case.
                requiredSymbols.add(fullyQualifiedName);
            }
            return false;
        }

        @Override
        public boolean visit(MethodInvocation node) {
            if (node.getExpression() == null) {
                return true;
            }
            String receiver = node.getExpression().toString();
            if (looksLikeAType(receiver)) {
                addTypeFromDotDelimitedSequence(receiver, DependencyType.REQUIRED);
            }
            return true;
        }

        /** An annotation on a member with zero arguments. */
        @Override
        public boolean visit(MarkerAnnotation node) {
            DependencyType dependencyType = findDependencyTypeForAnnotation(node);
            addSimpleTypeName(node.getTypeName(), dependencyType);
            return true;
        }

        /** An annotation on a member with named arguments. */
        @Override
        public boolean visit(NormalAnnotation node) {
            DependencyType dependencyType = findDependencyTypeForAnnotation(node);
            addSimpleTypeName(node.getTypeName(), dependencyType);
            return true;
        }

        /** An annotation on a member with a single, unnamed argument. */
        @Override
        public boolean visit(SingleMemberAnnotation node) {
            DependencyType dependencyType = findDependencyTypeForAnnotation(node);
            addSimpleTypeName(node.getTypeName(), dependencyType);
            return true;
        }

        private DependencyType findDependencyTypeForAnnotation(Annotation annotation) {
            ASTNode parentNode = annotation.getParent();
            if (parentNode == null) {
                return DependencyType.REQUIRED;
            }
            if (parentNode instanceof BodyDeclaration) {
                // Note that BodyDeclaration is an abstract class. Its subclasses are things like
                // FieldDeclaration and MethodDeclaration. We want to be sure that an annotation on any
                // non-private declaration is considered an exported symbol.
                BodyDeclaration declaration = (BodyDeclaration) parentNode;
                int modifiers = declaration.getModifiers();
                if ((modifiers & Modifier.PRIVATE) == 0) {
                    return DependencyType.EXPORTED;
                }
            }
            return DependencyType.REQUIRED;
        }

        @Override
        public boolean visit(SimpleType node) {
            // This method is responsible for finding the overwhelming majority of the required symbols
            // in the AST.
            tryAddType(node, DependencyType.REQUIRED);
            return true;
        }

        // exportedSymbols
        @Override
        public boolean visit(MethodDeclaration node) {
            // Types from private method signatures need not be exported.
            if ((node.getModifiers() & Modifier.PRIVATE) != 0) {
                return true;
            }
            Type returnType = node.getReturnType2();
            if (returnType != null) {
                tryAddType(returnType, DependencyType.EXPORTED);
            }
            @SuppressWarnings("unchecked") List<SingleVariableDeclaration> params = node.parameters();
            for (SingleVariableDeclaration decl : params) {
                tryAddType(decl.getType(), DependencyType.EXPORTED);
            }
            @SuppressWarnings("unchecked") List<Type> exceptions = node.thrownExceptionTypes();
            for (Type exception : exceptions) {
                tryAddType(exception, DependencyType.EXPORTED);
            }
            return true;
        }

        @Override
        public boolean visit(FieldDeclaration node) {
            // Types from private fields need not be exported.
            if ((node.getModifiers() & Modifier.PRIVATE) == 0) {
                tryAddType(node.getType(), DependencyType.EXPORTED);
            }
            return true;
        }

        private void tryAddType(Type type, DependencyType dependencyType) {
            if (type.isSimpleType()) {
                SimpleType simpleType = (SimpleType) type;
                Name simpleTypeName = simpleType.getName();
                String simpleName = simpleTypeName.toString();
                // rather than simply required.
                if (!CharMatcher.javaUpperCase().matchesAllOf(simpleName) || (dependencyType == DependencyType.EXPORTED && simpleImportedTypes.containsKey(simpleName))) {
                    addSimpleTypeName(simpleTypeName, dependencyType);
                }
            } else if (type.isArrayType()) {
                ArrayType arrayType = (ArrayType) type;
                tryAddType(arrayType.getElementType(), dependencyType);
            } else if (type.isParameterizedType()) {
                ParameterizedType parameterizedType = (ParameterizedType) type;
                tryAddType(parameterizedType.getType(), dependencyType);
                @SuppressWarnings("unchecked") List<Type> argTypes = parameterizedType.typeArguments();
                for (Type argType : argTypes) {
                    tryAddType(argType, dependencyType);
                }
            }
        }

        private void addSimpleTypeName(Name simpleTypeName, DependencyType dependencyType) {
            String simpleName = simpleTypeName.toString();
            if (JAVA_LANG_TYPES.contains(simpleName)) {
                return;
            }
            String fullyQualifiedNameForSimpleName = simpleImportedTypes.get(simpleName);
            if (fullyQualifiedNameForSimpleName != null) {
                // May need to promote from required to exported in this case.
                if (dependencyType == DependencyType.EXPORTED) {
                    addSymbol(fullyQualifiedNameForSimpleName, DependencyType.EXPORTED);
                }
                return;
            }
            // the iterator most of the time.
            if (!wildcardImports.isEmpty()) {
                for (Map.Entry<String, ImmutableSet<String>> entry : wildcardImports.entrySet()) {
                    Set<String> types = entry.getValue();
                    if (types.contains(simpleName)) {
                        String packageName = entry.getKey();
                        addSymbol(packageName + "." + simpleName, dependencyType);
                        return;
                    }
                }
            }
            String symbol = simpleTypeName.getFullyQualifiedName();
            symbol = qualifyWithPackageNameIfNecessary(symbol);
            addSymbol(symbol, dependencyType);
        }

        private void addSymbol(String symbol, DependencyType dependencyType) {
            ((dependencyType == DependencyType.REQUIRED) ? requiredSymbols : exportedSymbols).add(symbol);
        }

        private String qualifyWithPackageNameIfNecessary(String symbol) {
            if (!startsWithUppercaseChar(symbol)) {
                return symbol;
            }
            // If the symbol starts with a capital letter, then we assume that it is a reference to
            // a type in the same package.
            int index = symbol.indexOf('.');
            if (index >= 0) {
                symbol = symbol.substring(0, index);
            }
            if (packageName != null) {
                symbol = packageName + "." + symbol;
            }
            return symbol;
        }
    });
    // TODO(bolinfest): Special treatment for exportedSymbols when poisoned by wildcard import.
    ImmutableSortedSet<String> totalExportedSymbols = exportedSymbols.build();
    // If we were poisoned by an unsupported wildcard import, then we should rely exclusively on
    // the explicit imports to determine the required symbols.
    Set<String> totalRequiredSymbols = new HashSet<>();
    if (isPoisonedByUnsupportedWildcardImport.get()) {
        totalRequiredSymbols.addAll(requiredSymbolsFromExplicitImports.build());
    } else {
        totalRequiredSymbols.addAll(requiredSymbolsFromExplicitImports.build());
        totalRequiredSymbols.addAll(requiredSymbols.build());
    }
    // Make sure that required and exported symbols are disjoint sets.
    totalRequiredSymbols.removeAll(totalExportedSymbols);
    return new JavaFileFeatures(providedSymbols.build(), ImmutableSortedSet.copyOf(totalRequiredSymbols), totalExportedSymbols);
}
Also used : ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) HashSet(java.util.HashSet) ImmutableSortedSet(com.google.common.collect.ImmutableSortedSet) HashMap(java.util.HashMap) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) Name(org.eclipse.jdt.core.dom.Name) ArrayType(org.eclipse.jdt.core.dom.ArrayType) ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) SimpleType(org.eclipse.jdt.core.dom.SimpleType) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableSortedSet(com.google.common.collect.ImmutableSortedSet) ASTNode(org.eclipse.jdt.core.dom.ASTNode) NormalAnnotation(org.eclipse.jdt.core.dom.NormalAnnotation) List(java.util.List) LinkedList(java.util.LinkedList) PackageDeclaration(org.eclipse.jdt.core.dom.PackageDeclaration) HashSet(java.util.HashSet) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) Optional(java.util.Optional) SingleMemberAnnotation(org.eclipse.jdt.core.dom.SingleMemberAnnotation) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) AnnotationTypeDeclaration(org.eclipse.jdt.core.dom.AnnotationTypeDeclaration) SingleMemberAnnotation(org.eclipse.jdt.core.dom.SingleMemberAnnotation) MarkerAnnotation(org.eclipse.jdt.core.dom.MarkerAnnotation) Annotation(org.eclipse.jdt.core.dom.Annotation) NormalAnnotation(org.eclipse.jdt.core.dom.NormalAnnotation) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor) EnumDeclaration(org.eclipse.jdt.core.dom.EnumDeclaration) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ArrayType(org.eclipse.jdt.core.dom.ArrayType) ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) SimpleType(org.eclipse.jdt.core.dom.SimpleType) Type(org.eclipse.jdt.core.dom.Type) MarkerAnnotation(org.eclipse.jdt.core.dom.MarkerAnnotation) TypeDeclarationStatement(org.eclipse.jdt.core.dom.TypeDeclarationStatement) ImportDeclaration(org.eclipse.jdt.core.dom.ImportDeclaration) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration) AnnotationTypeDeclaration(org.eclipse.jdt.core.dom.AnnotationTypeDeclaration) TypeDeclaration(org.eclipse.jdt.core.dom.TypeDeclaration) Nullable(javax.annotation.Nullable)

Example 3 with NormalAnnotation

use of org.eclipse.jdt.core.dom.NormalAnnotation in project liferay-ide by liferay.

the class NewLiferayModuleProjectOpMethods method addProperties.

@SuppressWarnings("unchecked")
public static boolean addProperties(File dest, List<String> properties) throws Exception {
    if (ListUtil.isEmpty(properties)) {
        return false;
    }
    try {
        ASTParser parser = ASTParser.newParser(AST.JLS8);
        String readContents = FileUtil.readContents(dest, true);
        parser.setSource(readContents.toCharArray());
        parser.setKind(ASTParser.K_COMPILATION_UNIT);
        parser.setResolveBindings(true);
        CompilationUnit cu = (CompilationUnit) parser.createAST(new NullProgressMonitor());
        cu.recordModifications();
        Document document = new Document(new String(readContents));
        cu.accept(new ASTVisitor() {

            @Override
            public boolean visit(NormalAnnotation node) {
                String qualifiedName = node.getTypeName().getFullyQualifiedName();
                if (qualifiedName.equals("Component")) {
                    ASTRewrite rewrite = ASTRewrite.create(cu.getAST());
                    AST ast = cu.getAST();
                    List<ASTNode> values = node.values();
                    boolean hasProperty = false;
                    for (ASTNode astNode : values) {
                        if (astNode instanceof MemberValuePair) {
                            MemberValuePair pairNode = (MemberValuePair) astNode;
                            String fullQualifiedName = pairNode.getName().getFullyQualifiedName();
                            if (fullQualifiedName.equals("property")) {
                                Expression express = pairNode.getValue();
                                if (express instanceof ArrayInitializer) {
                                    ListRewrite lrw = rewrite.getListRewrite(express, ArrayInitializer.EXPRESSIONS_PROPERTY);
                                    ArrayInitializer initializer = (ArrayInitializer) express;
                                    List<ASTNode> expressions = initializer.expressions();
                                    ASTNode propertyNode = null;
                                    for (int i = properties.size() - 1; i >= 0; i--) {
                                        StringLiteral stringLiteral = ast.newStringLiteral();
                                        stringLiteral.setLiteralValue(properties.get(i));
                                        if (ListUtil.isNotEmpty(expressions)) {
                                            propertyNode = expressions.get(expressions.size() - 1);
                                            lrw.insertAfter(stringLiteral, propertyNode, null);
                                        } else {
                                            lrw.insertFirst(stringLiteral, null);
                                        }
                                    }
                                }
                                hasProperty = true;
                            }
                        }
                    }
                    if (hasProperty == false) {
                        ListRewrite clrw = rewrite.getListRewrite(node, NormalAnnotation.VALUES_PROPERTY);
                        ASTNode lastNode = values.get(values.size() - 1);
                        ArrayInitializer newArrayInitializer = ast.newArrayInitializer();
                        MemberValuePair propertyMemberValuePair = ast.newMemberValuePair();
                        propertyMemberValuePair.setName(ast.newSimpleName("property"));
                        propertyMemberValuePair.setValue(newArrayInitializer);
                        clrw.insertBefore(propertyMemberValuePair, lastNode, null);
                        ListRewrite newLrw = rewrite.getListRewrite(newArrayInitializer, ArrayInitializer.EXPRESSIONS_PROPERTY);
                        for (String property : properties) {
                            StringLiteral stringLiteral = ast.newStringLiteral();
                            stringLiteral.setLiteralValue(property);
                            newLrw.insertAt(stringLiteral, 0, null);
                        }
                    }
                    try (OutputStream fos = Files.newOutputStream(dest.toPath())) {
                        TextEdit edits = rewrite.rewriteAST(document, null);
                        edits.apply(document);
                        fos.write(document.get().getBytes());
                        fos.flush();
                    } catch (Exception e) {
                        ProjectCore.logError(e);
                    }
                }
                return super.visit(node);
            }
        });
        return true;
    } catch (Exception e) {
        ProjectCore.logError("error when adding properties to " + dest.getAbsolutePath(), e);
        return false;
    }
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) AST(org.eclipse.jdt.core.dom.AST) OutputStream(java.io.OutputStream) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) Document(org.eclipse.jface.text.Document) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor) MemberValuePair(org.eclipse.jdt.core.dom.MemberValuePair) StringLiteral(org.eclipse.jdt.core.dom.StringLiteral) Expression(org.eclipse.jdt.core.dom.Expression) TextEdit(org.eclipse.text.edits.TextEdit) ASTNode(org.eclipse.jdt.core.dom.ASTNode) NormalAnnotation(org.eclipse.jdt.core.dom.NormalAnnotation) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) ArrayList(java.util.ArrayList) List(java.util.List) ElementList(org.eclipse.sapphire.ElementList) ASTParser(org.eclipse.jdt.core.dom.ASTParser) ArrayInitializer(org.eclipse.jdt.core.dom.ArrayInitializer)

Example 4 with NormalAnnotation

use of org.eclipse.jdt.core.dom.NormalAnnotation in project jbosstools-hibernate by jbosstools.

the class CollectEntityInfo method processAnnotation.

public boolean processAnnotation(Annotation node, String mappedBy) {
    String fullyQualifiedName = node.getTypeName().getFullyQualifiedName();
    if (JPAConst.isAnnotationEntity(fullyQualifiedName)) {
        ITypeBinding tb = node.resolveTypeBinding();
        CompilationUnit cu = getCUFromTypeDeclaration(node);
        if (cu != null) {
            if (tb == null) {
                entityInfo.addRequiredImport(JPAConst.IMPORT_ENTITY);
            }
            entityInfo.setAddEntityFlag(false);
        }
    } else if (JPAConst.isAnnotationId(fullyQualifiedName)) {
        ITypeBinding tb = node.resolveTypeBinding();
        CompilationUnit cu = getCUFromFieldMethod(node);
        if (cu != null) {
            if (tb == null) {
                entityInfo.addRequiredImport(JPAConst.IMPORT_ID);
            }
            entityInfo.setAddPrimaryIdFlag(false);
        }
    } else if (JPAConst.isAnnotationGeneratedValue(fullyQualifiedName)) {
        ITypeBinding tb = node.resolveTypeBinding();
        CompilationUnit cu = getCUFromFieldMethod(node);
        if (cu != null) {
            if (tb == null) {
                entityInfo.addRequiredImport(JPAConst.IMPORT_GENERATED_VALUE);
            }
            entityInfo.setAddGeneratedValueFlag(false);
        }
    } else if (JPAConst.isAnnotationOne2One(fullyQualifiedName)) {
        updateAnnotationRelInfo(node, mappedBy, fullyQualifiedName, RefType.ONE2ONE, JPAConst.ANNOTATION_ONE2ONE, JPAConst.IMPORT_ONE2ONE);
    } else if (JPAConst.isAnnotationOne2Many(fullyQualifiedName)) {
        updateAnnotationRelInfo(node, mappedBy, fullyQualifiedName, RefType.ONE2MANY, JPAConst.ANNOTATION_ONE2MANY, JPAConst.IMPORT_ONE2MANY);
    } else if (JPAConst.isAnnotationMany2One(fullyQualifiedName)) {
        updateAnnotationRelInfo(node, mappedBy, fullyQualifiedName, RefType.MANY2ONE, JPAConst.ANNOTATION_MANY2ONE, JPAConst.IMPORT_MANY2ONE);
    } else if (JPAConst.isAnnotationMany2Many(fullyQualifiedName)) {
        updateAnnotationRelInfo(node, mappedBy, fullyQualifiedName, RefType.MANY2MANY, JPAConst.ANNOTATION_MANY2MANY, JPAConst.IMPORT_MANY2MANY);
    } else if (JPAConst.isAnnotationEnumerated(fullyQualifiedName)) {
        updateAnnotationRelInfo(node, mappedBy, fullyQualifiedName, RefType.ENUMERATED, JPAConst.ANNOTATION_ENUMERATED, JPAConst.IMPORT_ENUMERATED);
    } else if (JPAConst.isAnnotationMappedSuperclass(fullyQualifiedName)) {
        ITypeBinding tb = node.resolveTypeBinding();
        CompilationUnit cu = getCUFromTypeDeclaration(node);
        if (cu != null) {
            if (tb == null) {
                entityInfo.addRequiredImport(JPAConst.IMPORT_MAPPEDSUPERCLASS);
            }
            entityInfo.setAddEntityFlag(false);
            entityInfo.setAddMappedSuperclassFlag(false);
            entityInfo.setHasMappedSuperclassAnnotation(true);
        }
    } else if (JPAConst.isAnnotationVersion(fullyQualifiedName)) {
        ITypeBinding tb = node.resolveTypeBinding();
        CompilationUnit cu = getCUFromFieldMethod(node);
        if (cu != null) {
            if (tb == null) {
                entityInfo.addRequiredImport(JPAConst.IMPORT_VERSION);
            }
            entityInfo.setHasVersionAnnotation(true);
        }
    } else if (JPAConst.isAnnotationColumn(fullyQualifiedName) && node instanceof NormalAnnotation) {
        updateAnnotationColumn((NormalAnnotation) node, mappedBy, fullyQualifiedName);
    }
    return true;
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) NormalAnnotation(org.eclipse.jdt.core.dom.NormalAnnotation)

Example 5 with NormalAnnotation

use of org.eclipse.jdt.core.dom.NormalAnnotation in project jbosstools-hibernate by jbosstools.

the class ProcessEntityInfo method addComplexNormalAnnotation.

@SuppressWarnings("unchecked")
public boolean addComplexNormalAnnotation(BodyDeclaration node, String name, RefEntityInfo rei) {
    if (name == null || name.length() == 0) {
        return false;
    }
    NormalAnnotation natd = rewriter.getAST().newNormalAnnotation();
    MemberValuePair mvp = null;
    if (rei.mappedBy != null && (rei.owner == OwnerType.YES || rei.owner == OwnerType.UNDEF)) {
        mvp = rewriter.getAST().newMemberValuePair();
        // $NON-NLS-1$
        mvp.setName(rewriter.getAST().newSimpleName("mappedBy"));
        StringLiteral sl = rewriter.getAST().newStringLiteral();
        sl.setLiteralValue(rei.mappedBy);
        mvp.setValue(sl);
    }
    natd.setTypeName(rewriter.getAST().newSimpleName(name));
    if (mvp != null) {
        natd.values().add(mvp);
    }
    NormalAnnotation natd2 = null;
    /**
     * /
     *		if (rei.owner == OwnerType.NO) {
     *			natd2 = rewriter.getAST().newNormalAnnotation();
     *			natd2.setTypeName(rewriter.getAST().newSimpleName(JPAConst.ANNOTATION_JOINCOLUMN));
     *			mvp = null;
     *			String fullyQualifiedName2 = rei.fullyQualifiedName;
     *			EntityInfo entryInfo2 = entities.get(fullyQualifiedName2);
     *			if (entryInfo2 != null) {
     *				mvp = rewriter.getAST().newMemberValuePair();
     *				mvp.setName(rewriter.getAST().newSimpleName("name")); //$NON-NLS-1$
     *				StringLiteral sl = rewriter.getAST().newStringLiteral();
     *				sl.setLiteralValue(entryInfo2.getPrimaryIdName());
     *				mvp.setValue(sl);
     *			}
     *			if (mvp != null) {
     *				natd2.values().add(mvp);
     *			}
     *		}
     *		/*
     */
    ListRewrite lrw = null;
    if (node instanceof FieldDeclaration) {
        lrw = rewriter.getListRewrite(node, FieldDeclaration.MODIFIERS2_PROPERTY);
    } else if (node instanceof MethodDeclaration) {
        lrw = rewriter.getListRewrite(node, MethodDeclaration.MODIFIERS2_PROPERTY);
    }
    if (lrw != null) {
        if (natd2 != null) {
            lrw.insertFirst(natd2, null);
        }
        lrw.insertFirst(natd, null);
    }
    return true;
}
Also used : MemberValuePair(org.eclipse.jdt.core.dom.MemberValuePair) StringLiteral(org.eclipse.jdt.core.dom.StringLiteral) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) NormalAnnotation(org.eclipse.jdt.core.dom.NormalAnnotation) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration)

Aggregations

NormalAnnotation (org.eclipse.jdt.core.dom.NormalAnnotation)22 MemberValuePair (org.eclipse.jdt.core.dom.MemberValuePair)13 SingleMemberAnnotation (org.eclipse.jdt.core.dom.SingleMemberAnnotation)9 ASTNode (org.eclipse.jdt.core.dom.ASTNode)8 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)7 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)7 Expression (org.eclipse.jdt.core.dom.Expression)6 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)6 AST (org.eclipse.jdt.core.dom.AST)5 Annotation (org.eclipse.jdt.core.dom.Annotation)5 StringLiteral (org.eclipse.jdt.core.dom.StringLiteral)5 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)4 HashSet (java.util.HashSet)3 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)3 ASTVisitor (org.eclipse.jdt.core.dom.ASTVisitor)3 FieldDeclaration (org.eclipse.jdt.core.dom.FieldDeclaration)3 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)3 ImportDeclaration (org.eclipse.jdt.core.dom.ImportDeclaration)3 PackageDeclaration (org.eclipse.jdt.core.dom.PackageDeclaration)3 ArrayList (java.util.ArrayList)2