Exemple #1
0
 private static void populateClasses(
     final Shell shell, final IParent parent, final List<IType> types, final Filter filter) {
   try {
     for (final IJavaElement element : parent.getChildren()) {
       if (element instanceof IType) {
         final IType type = (IType) element;
         if (type.isClass()
             && type.isStructureKnown()
             && !type.isAnonymous()
             && !type.isLocal()
             && !Flags.isAbstract(type.getFlags())
             && Flags.isPublic(type.getFlags())
             && (filter == null || filter.accept(type))) {
           types.add(type);
         }
       } else if (element instanceof IParent
           && !element.getPath().toString().contains("/test/")
           && (!(element instanceof IPackageFragmentRoot)
               || !((IPackageFragmentRoot) element).isExternal())) {
         populateClasses(shell, (IParent) element, types, filter);
       }
     }
   } catch (final JavaModelException e) {
     Activator.error(e);
   }
 }
Exemple #2
0
 /**
  * This method asks the specified <code>IType</code> if it has a main method, if not it recurses
  * through all of its children When recursing we only care about child <code>IType</code>s that
  * are static.
  *
  * @param type the <code>IType</code> to inspect for a main method
  * @return true if a main method was found in specified <code>IType</code>, false otherwise
  * @throws CoreException
  * @since 3.3
  */
 private boolean hasMainInChildren(IType type) throws CoreException {
   if (type.isClass() & Flags.isStatic(type.getFlags())) {
     if (hasMainMethod(type)) {
       return true;
     } else {
       IJavaElement[] children = type.getChildren();
       for (int i = 0; i < children.length; i++) {
         if (children[i].getElementType() == IJavaElement.TYPE) {
           return hasMainInChildren((IType) children[i]);
         }
       }
     }
   }
   return false;
 }
 /**
  * Method validates GenericGenerator.strategy. Generator strategy either a predefined Hibernate
  * strategy or a fully qualified class name.
  *
  * @param messages
  * @param reporter
  * @param astRoot
  */
 protected void validateStrategy(
     List<IMessage> messages, IReporter reporter, CompilationUnit astRoot) {
   if (this.strategy != null) {
     TextRange range =
         getStrategyTextRange(astRoot) == null
             ? TextRange.Empty.instance()
             : getStrategyTextRange(astRoot);
     if (this.strategy.trim().length() == 0) {
       messages.add(
           HibernateJpaValidationMessage.buildMessage(
               IMessage.HIGH_SEVERITY, STRATEGY_CANT_BE_EMPTY, getResource(), range));
     } else if (!generatorClasses.contains(this.strategy)) {
       IType lwType = null;
       try {
         lwType = getJpaProject().getJavaProject().findType(this.strategy);
         if (lwType == null || !lwType.isClass()) {
           messages.add(
               HibernateJpaValidationMessage.buildMessage(
                   IMessage.HIGH_SEVERITY,
                   STRATEGY_CLASS_NOT_FOUND,
                   new String[] {this.strategy},
                   getResource(),
                   range));
         } else {
           if (!JpaUtil.isTypeImplementsInterface(
               getJpaProject().getJavaProject(),
               lwType,
               "org.hibernate.id.IdentifierGenerator")) { //$NON-NLS-1$
             messages.add(
                 HibernateJpaValidationMessage.buildMessage(
                     IMessage.HIGH_SEVERITY,
                     STRATEGY_INTERFACE,
                     new String[] {this.strategy},
                     getResource(),
                     range));
           }
         }
       } catch (JavaModelException e) {
         // just ignore it!
       }
     }
   }
 }
  /**
   * Find the set of candidate subtypes of a given type.
   *
   * <p>The requestor is notified of super type references (with actual path of its occurrence) for
   * all types which are potentially involved inside a particular hierarchy. The match locator is
   * not used here to narrow down the results, the type hierarchy resolver is rather used to compute
   * the whole hierarchy at once.
   *
   * @param type
   * @param scope
   * @param binariesFromIndexMatches
   * @param pathRequestor
   * @param waitingPolicy
   * @param progressMonitor
   */
  public static void searchAllPossibleSubTypes(
      IType type,
      IJavaSearchScope scope,
      final Map binariesFromIndexMatches,
      final IPathRequestor pathRequestor,
      int waitingPolicy, // WaitUntilReadyToSearch | ForceImmediateSearch | CancelIfNotReadyToSearch
      final IProgressMonitor progressMonitor) {

    /* embed constructs inside arrays so as to pass them to (inner) collector */
    final Queue queue = new Queue();
    final HashtableOfObject foundSuperNames = new HashtableOfObject(5);

    IndexManager indexManager = JavaModelManager.getIndexManager();

    /* use a special collector to collect paths and queue new subtype names */
    IndexQueryRequestor searchRequestor =
        new IndexQueryRequestor() {
          public boolean acceptIndexMatch(
              String documentPath,
              SearchPattern indexRecord,
              SearchParticipant participant,
              AccessRuleSet access) {
            SuperTypeReferencePattern record = (SuperTypeReferencePattern) indexRecord;
            boolean isLocalOrAnonymous = record.enclosingTypeName == IIndexConstants.ONE_ZERO;
            pathRequestor.acceptPath(documentPath, isLocalOrAnonymous);
            char[] typeName = record.simpleName;
            if (documentPath.toLowerCase().endsWith(SUFFIX_STRING_class)) {
              int suffix = documentPath.length() - SUFFIX_STRING_class.length();
              HierarchyBinaryType binaryType =
                  (HierarchyBinaryType) binariesFromIndexMatches.get(documentPath);
              if (binaryType == null) {
                char[] enclosingTypeName = record.enclosingTypeName;
                if (isLocalOrAnonymous) {
                  int lastSlash = documentPath.lastIndexOf('/');
                  int lastDollar = documentPath.lastIndexOf('$');
                  if (lastDollar == -1) {
                    // malformed local or anonymous type: it doesn't contain a $ in its name
                    // treat it as a top level type
                    enclosingTypeName = null;
                    typeName = documentPath.substring(lastSlash + 1, suffix).toCharArray();
                  } else {
                    enclosingTypeName =
                        documentPath.substring(lastSlash + 1, lastDollar).toCharArray();
                    typeName = documentPath.substring(lastDollar + 1, suffix).toCharArray();
                  }
                }
                binaryType =
                    new HierarchyBinaryType(
                        record.modifiers,
                        record.pkgName,
                        typeName,
                        enclosingTypeName,
                        record.typeParameterSignatures,
                        record.classOrInterface);
                binariesFromIndexMatches.put(documentPath, binaryType);
              }
              binaryType.recordSuperType(
                  record.superSimpleName, record.superQualification, record.superClassOrInterface);
            }
            if (!isLocalOrAnonymous // local or anonymous types cannot have subtypes outside the cu
                                    // that define them
                && !foundSuperNames.containsKey(typeName)) {
              foundSuperNames.put(typeName, typeName);
              queue.add(typeName);
            }
            return true;
          }
        };

    int superRefKind;
    try {
      superRefKind =
          type.isClass()
              ? SuperTypeReferencePattern.ONLY_SUPER_CLASSES
              : SuperTypeReferencePattern.ALL_SUPER_TYPES;
    } catch (JavaModelException e) {
      superRefKind = SuperTypeReferencePattern.ALL_SUPER_TYPES;
    }
    SuperTypeReferencePattern pattern =
        new SuperTypeReferencePattern(
            null, null, superRefKind, SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE);
    MatchLocator.setFocus(pattern, type);
    SubTypeSearchJob job =
        new SubTypeSearchJob(
            pattern,
            new JavaSearchParticipant(), // java search only
            scope,
            searchRequestor);

    int ticks = 0;
    queue.add(type.getElementName().toCharArray());
    try {
      while (queue.start <= queue.end) {
        if (progressMonitor != null && progressMonitor.isCanceled()) return;

        // all subclasses of OBJECT are actually all types
        char[] currentTypeName = queue.retrieve();
        if (CharOperation.equals(currentTypeName, IIndexConstants.OBJECT)) currentTypeName = null;

        // search all index references to a given supertype
        pattern.superSimpleName = currentTypeName;
        indexManager.performConcurrentJob(
            job,
            waitingPolicy,
            progressMonitor == null
                ? null
                : new NullProgressMonitor() {
                  // don't report progress since this is too costly for deep hierarchies (see
                  // https://bugs.eclipse.org/bugs/show_bug.cgi?id=34078 )
                  // just handle isCanceled() (see
                  // https://bugs.eclipse.org/bugs/show_bug.cgi?id=179511 )
                  public void setCanceled(boolean value) {
                    progressMonitor.setCanceled(value);
                  }

                  public boolean isCanceled() {
                    return progressMonitor.isCanceled();
                  }
                  // and handle subTask(...) (see
                  // https://bugs.eclipse.org/bugs/show_bug.cgi?id=34078 )
                  public void subTask(String name) {
                    progressMonitor.subTask(name);
                  }
                });
        if (progressMonitor != null && ++ticks <= MAXTICKS) progressMonitor.worked(1);

        // in case, we search all subtypes, no need to search further
        if (currentTypeName == null) break;
      }
    } finally {
      job.finished();
    }
  }
  private void extractIType(IType type) {
    try {
      String fqn = type.getFullyQualifiedName();

      // Write the entity
      if (type.isClass()) {
        entityWriter.writeClass(fqn, type.getFlags(), path);

        // Write the superclass
        String superSig = type.getSuperclassTypeSignature();
        if (superSig != null) {
          relationWriter.writeExtends(fqn, typeSignatureToFqn(superSig), path);
        }
      } else if (type.isAnnotation()) {
        entityWriter.writeAnnotation(fqn, type.getFlags(), path);
      } else if (type.isInterface()) {
        entityWriter.writeInterface(fqn, type.getFlags(), path);
      } else if (type.isEnum()) {
        entityWriter.writeEnum(fqn, type.getFlags(), path);
      }

      // Write the superinterfaces
      for (String superIntSig : type.getSuperInterfaceTypeSignatures()) {
        relationWriter.writeImplements(fqn, typeSignatureToFqn(superIntSig), path);
      }

      if (!fqnStack.isEmpty()) {
        relationWriter.writeInside(type.getFullyQualifiedName(), fqnStack.peek(), path);
      }

      fqnStack.push(type.getFullyQualifiedName());

      for (IType child : type.getTypes()) {
        extractIType(child);
      }

      for (IField field : type.getFields()) {
        if (!Flags.isSynthetic(field.getFlags())) {
          extractIField(field);
        }
      }

      for (IMethod method : type.getMethods()) {
        if (!Flags.isSynthetic(method.getFlags())
            || (Flags.isSynthetic(method.getFlags())
                && method.isConstructor()
                && method.getParameterTypes().length == 0)) {
          extractIMethod(method, type.isAnnotation());
        }
      }

      int pos = 0;
      for (ITypeParameter param : type.getTypeParameters()) {
        relationWriter.writeParametrizedBy(fqn, getTypeParam(param), pos++, path);
      }

      fqnStack.pop();
    } catch (Exception e) {
      logger.log(Level.SEVERE, "Error in extracting class file", e);
    }
  }