Esempio n. 1
0
 private static void checkHierarchyOfEnclosedTypes(
     IType destinationType, RefactoringStatus result, IType type) throws JavaModelException {
   IType[] enclosedTypes = getAllEnclosedTypes(type);
   for (int i = 0; i < enclosedTypes.length; i++) {
     IType enclosedType = enclosedTypes[i];
     if (destinationType.getElementName().equals(enclosedType.getElementName())) {
       String message =
           Messages.format(
               RefactoringCoreMessages.MemberCheckUtil_type_name_conflict3,
               new String[] {getQualifiedLabel(enclosedType), getQualifiedLabel(type)});
       RefactoringStatusContext context =
           JavaStatusContext.create(
               destinationType.getCompilationUnit(), destinationType.getNameRange());
       result.addError(message, context);
     }
     if (typeNameExistsInEnclosingTypeChain(destinationType, enclosedType.getElementName())) {
       String message =
           Messages.format(
               RefactoringCoreMessages.MemberCheckUtil_type_name_conflict4,
               new String[] {getQualifiedLabel(enclosedType), getQualifiedLabel(type)});
       RefactoringStatusContext context =
           JavaStatusContext.create(
               destinationType.getCompilationUnit(), destinationType.getNameRange());
       result.addError(message, context);
     }
   }
 }
Esempio n. 2
0
 @Override
 protected IType createType() throws JavaModelException {
   IType result = null;
   if (isPopupView) {
     result = createClass("PopupViewImpl", presenter.getElementName() + ".MyView");
     workingCopy.createImport(C_POPUP_VIEW_IMPL, null, new NullProgressMonitor());
   } else {
     result = createClass("ViewImpl", presenter.getElementName() + ".MyView");
     workingCopy.createImport(C_VIEW_IMPL, null, new NullProgressMonitor());
   }
   return result;
 }
  @Override
  protected boolean initialize(Object element) {
    if (element instanceof IType) {
      IType type = (IType) element;
      IJavaProject javaProject = (IJavaProject) type.getAncestor(IJavaElement.JAVA_PROJECT);
      mProject = javaProject.getProject();
      IResource manifestResource =
          mProject.findMember(AdtConstants.WS_SEP + SdkConstants.FN_ANDROID_MANIFEST_XML);

      if (manifestResource == null
          || !manifestResource.exists()
          || !(manifestResource instanceof IFile)) {
        RefactoringUtil.logInfo(
            "Invalid or missing the "
                + SdkConstants.FN_ANDROID_MANIFEST_XML
                + " in the "
                + mProject.getName()
                + " project.");
        return false;
      }
      mManifestFile = (IFile) manifestResource;
      ManifestData manifestData;
      manifestData = AndroidManifestHelper.parseForData(mManifestFile);
      if (manifestData == null) {
        return false;
      }
      mAppPackage = manifestData.getPackage();
      mOldFqcn = type.getFullyQualifiedName();
      Object destination = getArguments().getDestination();
      if (destination instanceof IPackageFragment) {
        IPackageFragment packageFragment = (IPackageFragment) destination;
        mNewFqcn = packageFragment.getElementName() + "." + type.getElementName();
      } else if (destination instanceof IResource) {
        try {
          IPackageFragment[] fragments = javaProject.getPackageFragments();
          for (IPackageFragment fragment : fragments) {
            IResource resource = fragment.getResource();
            if (resource.equals(destination)) {
              mNewFqcn = fragment.getElementName() + '.' + type.getElementName();
              break;
            }
          }
        } catch (JavaModelException e) {
          // pass
        }
      }
      return mOldFqcn != null && mNewFqcn != null;
    }

    return false;
  }
 public boolean visit(TypeDeclaration node) {
   if (null != m_typeFilter) {
     return node.getName().getIdentifier().equals(m_typeFilter.getElementName());
   } else {
     return true;
   }
 }
Esempio n. 5
0
 public synchronized void clearCache(IType elementType) {
   clearApiForElementType(elementType);
   String elementName = elementType.getElementName();
   if (elementName != null) {
     _elementNameToTypeCache.remove(elementName);
   }
 }
Esempio n. 6
0
  public CodeInsertionDialog(Shell shell, IType type) throws JavaModelException {
    super(shell);

    insertPositions = new ArrayList<IJavaElement>();
    fLabels = new ArrayList<String>();

    System.out.println(type.getElementName() + type.getElementType());

    IJavaElement[] members = type.getChildren();

    insertPositions.add(members.length > 0 ? members[0] : null); // first
    insertPositions.add(null); // last

    fLabels.add(CodeInsertionDialog.firstElement);
    fLabels.add(CodeInsertionDialog.secondElement);

    for (int i = 0; i < members.length; i++) {
      IJavaElement curr = members[i];
      String methodLabel =
          JavaElementLabels.getElementLabel(curr, JavaElementLabels.M_PARAMETER_TYPES);
      // System.out.println(MessageFormat.format(afterElement, methodLabel));
      fLabels.add(MessageFormat.format(afterElement, methodLabel));
      insertPositions.add(findSibling(curr, members));
    }
    insertPositions.add(null); // null indicate we want to insert into the last position
  }
Esempio n. 7
0
 private static boolean typeNameExistsInEnclosingTypeChain(IType type, String typeName) {
   IType enclosing = type.getDeclaringType();
   while (enclosing != null) {
     if (enclosing.getElementName().equals(typeName)) return true;
     enclosing = enclosing.getDeclaringType();
   }
   return false;
 }
 private boolean processCompilerError(RefactoringStatus result, ASTNode node) {
   Message[] messages = ASTNodes.getMessages(node, ASTNodes.INCLUDE_ALL_PARENTS);
   if (messages.length == 0) return false;
   result.addFatalError(
       Messages.format(
           "Compiler errors with the class to be refactored",
           new String[] {targetClass.getElementName(), messages[0].getMessage()}));
   return true;
 }
 private void createSymbol(IType primaryType) {
   final IBeanInstanceSymbol bean = SymbolFactory.eINSTANCE.createIBeanInstanceSymbol();
   bean.setName(getBeanName(primaryType.getElementName()));
   IJavaTypeDescriptor2 beanJavaTypeDescriptor =
       SymbolFactory.eINSTANCE.createIJavaTypeDescriptor2();
   beanJavaTypeDescriptor.setType(primaryType);
   bean.setJavaTypeDescriptor(beanJavaTypeDescriptor);
   symbols.add(bean);
 }
 public UpdateRetentionAnnotationValueMarkerResolution(IType type) {
   super(type.getCompilationUnit());
   this.type = type;
   label =
       NLS.bind(
           JaxrsQuickFixMessages.UPDATE_RETENTION_ANNOTATION_VALUE_MARKER_RESOLUTION_TITLE,
           type.getElementName());
   init();
 }
Esempio n. 11
0
 /**
  * Searches for the method with the given binary name.
  *
  * @param name binary method name
  * @param signature binary method signature
  * @return method or <code>null</code>
  */
 public IMethod findMethod(String name, String signature) {
   if ("<init>".equals(name)) { // $NON-NLS-1$
     name = type.getElementName();
   }
   final String paramCountKey = createParamCountKey(name, signature);
   if (ambiguous.contains(paramCountKey)) {
     return indexParamSignature.get(createParamSignatureKey(name, signature));
   } else {
     return indexParamCount.get(paramCountKey);
   }
 }
 public static IType[] findTypes(IType[] types, String[] namesOfTypesToPullUp) {
   List found = new ArrayList(types.length);
   for (int i = 0; i < types.length; i++) {
     IType type = types[i];
     for (int j = 0; j < namesOfTypesToPullUp.length; j++) {
       String name = namesOfTypesToPullUp[j];
       if (type.getElementName().equals(name)) found.add(type);
     }
   }
   return (IType[]) found.toArray(new IType[found.size()]);
 }
Esempio n. 13
0
 private static void checkTypeInType(IType destinationType, RefactoringStatus result, IType type)
     throws JavaModelException {
   String typeName = type.getElementName();
   IType destinationTypeType = destinationType.getType(typeName);
   if (destinationTypeType.exists()) {
     String message =
         Messages.format(
             RefactoringCoreMessages.MemberCheckUtil_type_name_conflict0,
             new String[] {
               BasicElementLabels.getJavaElementName(typeName), getQualifiedLabel(destinationType)
             });
     RefactoringStatusContext context =
         JavaStatusContext.create(
             destinationType.getCompilationUnit(), destinationTypeType.getNameRange());
     result.addError(message, context);
   } else {
     // need to check the hierarchy of enclosing and enclosed types
     if (destinationType.getElementName().equals(typeName)) {
       String message =
           Messages.format(
               RefactoringCoreMessages.MemberCheckUtil_type_name_conflict1,
               getQualifiedLabel(type));
       RefactoringStatusContext context =
           JavaStatusContext.create(
               destinationType.getCompilationUnit(), destinationType.getNameRange());
       result.addError(message, context);
     }
     if (typeNameExistsInEnclosingTypeChain(destinationType, typeName)) {
       String message =
           Messages.format(
               RefactoringCoreMessages.MemberCheckUtil_type_name_conflict2,
               getQualifiedLabel(type));
       RefactoringStatusContext context =
           JavaStatusContext.create(
               destinationType.getCompilationUnit(), destinationType.getNameRange());
       result.addError(message, context);
     }
     checkHierarchyOfEnclosedTypes(destinationType, result, type);
   }
 }
Esempio n. 14
0
 private boolean hasMember(IType type, String name) {
   boolean result = false;
   try {
     for (IMethod method : type.getMethods()) {
       result |= name.equals(method.getElementName());
     }
   } catch (JavaModelException jamox) {
     // defensive: assume the method is there, try another combination
     result = true;
     trace(jamox, type.getElementName());
   }
   return result;
 }
  /** @see IJavaElementRequestor */
  public void acceptType(IType type) {
    try {
      if (this.unitToSkip != null && this.unitToSkip.equals(type.getCompilationUnit())) {
        return;
      }
      char[] packageName = type.getPackageFragment().getElementName().toCharArray();
      boolean isBinary = type instanceof BinaryType;

      // determine associated access restriction
      AccessRestriction accessRestriction = null;

      if (this.checkAccessRestrictions
          && (isBinary || !type.getJavaProject().equals(this.project))) {
        PackageFragmentRoot root =
            (PackageFragmentRoot) type.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
        ClasspathEntry entry = (ClasspathEntry) this.nameLookup.rootToResolvedEntries.get(root);
        if (entry != null) { // reverse map always contains resolved CP entry
          AccessRuleSet accessRuleSet = entry.getAccessRuleSet();
          if (accessRuleSet != null) {
            // TODO (philippe) improve char[] <-> String conversions to avoid performing them on the
            // fly
            char[][] packageChars = CharOperation.splitOn('.', packageName);
            char[] fileWithoutExtension = type.getElementName().toCharArray();
            accessRestriction =
                accessRuleSet.getViolatedRestriction(
                    CharOperation.concatWith(packageChars, fileWithoutExtension, '/'));
          }
        }
      }
      this.requestor.acceptType(
          packageName,
          type.getElementName().toCharArray(),
          null,
          type.getFlags(),
          accessRestriction);
    } catch (JavaModelException jme) {
      // ignore
    }
  }
Esempio n. 16
0
 private void printFileInternals(ICompilationUnit unit, StringBuilder sb)
     throws JavaModelException {
   IType[] allTypes = unit.getAllTypes();
   if (allTypes.length > 0) {
     sb.append("<TYPES>");
     for (IType type : allTypes) {
       sb.append("<TYPE NAME=\"" + type.getElementName() + "\">");
       printSuperclassAndInterfaces(type, sb);
       printMethods(type, sb);
       sb.append("</TYPE>");
     }
     sb.append("</TYPES>");
   }
 }
 /**
  * Runs the stub generation on the specified class file.
  *
  * @param file the class file
  * @param parent the parent store
  * @param monitor the progress monitor to use
  * @throws CoreException if an error occurs
  */
 protected void run(final IClassFile file, final IFileStore parent, final IProgressMonitor monitor)
     throws CoreException {
   try {
     monitor.beginTask(RefactoringCoreMessages.StubCreationOperation_creating_type_stubs, 2);
     SubProgressMonitor subProgressMonitor = new SubProgressMonitor(monitor, 1);
     final IType type = file.getType();
     if (type.isAnonymous() || type.isLocal() || type.isMember()) return;
     String source = new StubCreator(fStubInvisible).createStub(type, subProgressMonitor);
     createCompilationUnit(
         parent, type.getElementName() + JavaModelUtil.DEFAULT_CU_SUFFIX, source, monitor);
   } finally {
     monitor.done();
   }
 }
  private void createModel() {
    //
    // Initialize m_classes
    //
    Set<String> packageSet = Sets.newHashSet();
    List<IType> types = Utils.findTypes(Utils.getSelectedJavaElements(), Utils.CONVERSION_FILTER);
    for (IType type : types) {
      String packageName = type.getPackageFragment().getElementName();
      String className = type.getElementName();
      if (className != null) {
        XmlClass c = new XmlClass(packageName + "." + className, false /* don't resolve */);
        p("Adding class " + c);
        m_classes.add(c);
        packageSet.add(packageName);
      } else {
        p("Adding type " + type);
        m_classes.add(new XmlClass(type.getFullyQualifiedName(), false /* don't resolve */));
        packageSet.add(packageName);
      }
    }
    //    for (JavaElement element : m_selectedElements) {
    //      if (element.getClassName() != null) {
    //        XmlClass c = new XmlClass(element.getPackageName() + "." + element.getClassName(),
    //            false /* don't resolve */);
    //        p("Adding class " + c);
    //        m_classes.add(c);
    //        packageSet.add(element.getPackageName());
    //      } else {
    //        for (IType type : types) {
    //          p("Adding type " + type);
    //          m_classes.add(new XmlClass(type.getFullyQualifiedName(), false /* don't resolve
    // */));
    //          packageSet.add(type.getPackageFragment().getElementName());
    //        }
    //      }
    //    }

    //
    // Initialize m_packages
    //
    for (String p : packageSet) {
      XmlPackage pkg = new XmlPackage();
      pkg.setName(p);
      p("Adding package " + p);
      m_packages.add(pkg);
    }

    m_xmlSuite = createXmlSuite();
  }
  public void build(boolean computeSubtypes) {
    JavaModelManager manager = JavaModelManager.getJavaModelManager();
    try {
      // optimize access to zip files while building hierarchy
      manager.cacheZipFiles(this);

      if (computeSubtypes) {
        // Note by construction there always is a focus type here
        IType focusType = getType();
        boolean focusIsObject =
            focusType.getElementName().equals(new String(IIndexConstants.OBJECT));
        int amountOfWorkForSubtypes =
            focusIsObject ? 5 : 80; // percentage of work needed to get possible subtypes
        IProgressMonitor possibleSubtypesMonitor =
            this.hierarchy.progressMonitor == null
                ? null
                : new SubProgressMonitor(this.hierarchy.progressMonitor, amountOfWorkForSubtypes);
        HashSet localTypes =
            new HashSet(
                10); // contains the paths that have potential subtypes that are local/anonymous
                     // types
        String[] allPossibleSubtypes;
        if (((Member) focusType).getOuterMostLocalContext() == null) {
          // top level or member type
          allPossibleSubtypes = determinePossibleSubTypes(localTypes, possibleSubtypesMonitor);
        } else {
          // local or anonymous type
          allPossibleSubtypes = CharOperation.NO_STRINGS;
        }
        if (allPossibleSubtypes != null) {
          IProgressMonitor buildMonitor =
              this.hierarchy.progressMonitor == null
                  ? null
                  : new SubProgressMonitor(
                      this.hierarchy.progressMonitor, 100 - amountOfWorkForSubtypes);
          this.hierarchy.initialize(allPossibleSubtypes.length);
          buildFromPotentialSubtypes(allPossibleSubtypes, localTypes, buildMonitor);
        }
      } else {
        this.hierarchy.initialize(1);
        buildSupertypes();
      }
    } finally {
      manager.flushZipFiles(this);
    }
  }
 /**
  * Runs the stub generation on the specified class file.
  *
  * @param file the class file
  * @param parent the parent store
  * @param monitor the progress monitor to use
  * @throws CoreException if an error occurs
  */
 @Override
 protected void run(final IClassFile file, final IFileStore parent, final IProgressMonitor monitor)
     throws CoreException {
   try {
     monitor.beginTask(getOperationLabel(), 2);
     final IType type = file.getType();
     if (type.isAnonymous() || type.isLocal() || type.isMember()) return;
     final String source = file.getSource();
     createCompilationUnit(
         parent,
         type.getElementName() + JavaModelUtil.DEFAULT_CU_SUFFIX,
         source != null ? source : "",
         monitor); //$NON-NLS-1$
   } finally {
     monitor.done();
   }
 }
Esempio n. 21
0
 public IType getTypeForName(String typeName) throws JavaModelException {
   // long a = System.currentTimeMillis();
   IType type;
   if ("void".equals(typeName) || (typeName != null && typeName.length() == 1)) {
     // ignore primitives
     type = null;
   } else {
     synchronized (_nextTypeCache) {
       type = _nextTypeCache.get(typeName);
     }
     if (type == null) {
       // long t = System.currentTimeMillis();
       // MS: This call right here is the DEVIL.  This is BY FAR where the
       // majority of time is spent during component validation.  It's also
       // unfortunately completely necessary, but caching should focus on
       // this in the future.
       // String resolvedNextTypeName = JavaModelUtil.getResolvedTypeName(typeName, _type);
       type = resolveType(typeName, _type);
       if (type == null) {
         // We are going to hit KVCProtectedAccessor a LOT, and in most cases, it's just not
         // going to exist, so let's save us all some trouble and skip it ...
         if (!"QKeyValueCodingProtectedAccessor;".equals(typeName)) {
           System.out.println(
               "TypeCacheEntry.getTypeForName: Failed to resolve type name "
                   + typeName
                   + " in component "
                   + _type.getElementName());
         } else if (BindingReflectionUtils.isPrimitive(typeName)) {
           // ignore primitives if we get this far
         }
       } else {
         synchronized (_nextTypeCache) {
           _nextTypeCache.put(typeName, type);
         }
       }
     }
     // System.out.println("TypeCacheEntry.getTypeForName:   " + typeName + " => " +
     // (System.currentTimeMillis() - t) + " => " + type);
   }
   // if (System.currentTimeMillis() -a > 0) {
   //	System.out.println("TypeCache.TypeCacheEntry.getTypeForName: " + type.getElementName() + "
   // " + (System.currentTimeMillis() - a));
   // }
   return type;
 }
 public static IType[] getMemberTypes(IType type, String[] names) {
   if (names == null) return new IType[0];
   Set memberTypes = new HashSet();
   for (int i = 0; i < names.length; i++) {
     IType memberType;
     if (names[i].indexOf('.') != -1) {
       String[] path = names[i].split("\\.");
       memberType = type.getType(path[0]);
       for (int j = 1; j < path.length; j++) {
         memberType = memberType.getType(path[j]);
       }
     } else memberType = type.getType(names[i]);
     assertTrue(
         "member type " + memberType.getElementName() + " does not exist", memberType.exists());
     memberTypes.add(memberType);
   }
   return (IType[]) memberTypes.toArray(new IType[memberTypes.size()]);
 }
 protected ILaunchConfiguration createConfiguration(IType type) {
   ILaunchConfiguration config = null;
   ILaunchConfigurationWorkingCopy wc = null;
   try {
     ILaunchConfigurationType configType = getAJConfigurationType();
     wc =
         configType.newInstance(
             null, getLaunchManager().generateLaunchConfigurationName(type.getElementName()));
     wc.setAttribute(
         IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME,
         type.getJavaProject().getElementName());
     wc.setAttribute(
         IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, type.getFullyQualifiedName());
     config = wc.doSave();
   } catch (CoreException exception) {
     reportErorr(exception);
   }
   return config;
 }
Esempio n. 24
0
  /** @see net.sf.commonclipse.Generator#createMethod(org.eclipse.jdt.core.IType) */
  @Override
  protected String createMethod(IType type) throws JavaModelException {

    StringBuffer buffer = new StringBuffer();

    buffer.append(getJavadoc());

    String className = type.getElementName();

    if (CCPluginPreferences.getPreferences().addOverrideAnnotation()) {
      buffer.append("@Override\n"); // $NON-NLS-1$
    }

    buffer.append("public boolean equals("); // $NON-NLS-1$

    if (CCPluginPreferences.getPreferences().useFinalParameters()) {
      buffer.append("final "); // $NON-NLS-1$
    }

    buffer.append("Object object) {\n"); // $NON-NLS-1$

    if (CCPluginPreferences.getPreferences().addInstanceCheckToEquals()) {
      buffer.append("if (object == this) {\nreturn true;\n}\n"); // $NON-NLS-1$
    }

    buffer.append("if ( !(object instanceof "); // $NON-NLS-1$
    buffer.append(className);
    buffer.append(") ) {\nreturn false;\n}\n"); // $NON-NLS-1$
    buffer.append(className);
    buffer.append(" rhs = ("); // $NON-NLS-1$
    buffer.append(className);
    buffer.append(") object;\nreturn new EqualsBuilder()\n"); // $NON-NLS-1$

    if (CCPluginPreferences.getPreferences().appendSuperToEquals()) {
      buffer.append(".appendSuper(super.equals(object))\n"); // $NON-NLS-1$
    }

    buffer.append(buildAppenderList(type));

    buffer.append(".isEquals();\n}\n"); // $NON-NLS-1$
    return buffer.toString();
  }
 /** Renames the main type in <code>cu</code>. */
 private void updateTypeName(
     ICompilationUnit cu,
     CompilationUnit astCU,
     String oldName,
     String newName,
     ASTRewrite rewriter)
     throws JavaModelException {
   if (newName != null) {
     String oldTypeName = Util.getNameWithoutJavaLikeExtension(oldName);
     String newTypeName = Util.getNameWithoutJavaLikeExtension(newName);
     AST ast = astCU.getAST();
     // update main type name
     IType[] types = cu.getTypes();
     for (int i = 0, max = types.length; i < max; i++) {
       IType currentType = types[i];
       if (currentType.getElementName().equals(oldTypeName)) {
         AbstractTypeDeclaration typeNode =
             (AbstractTypeDeclaration) ((JavaElement) currentType).findNode(astCU);
         if (typeNode != null) {
           // rename type
           rewriter.replace(typeNode.getName(), ast.newSimpleName(newTypeName), null);
           // rename constructors
           Iterator bodyDeclarations = typeNode.bodyDeclarations().iterator();
           while (bodyDeclarations.hasNext()) {
             Object bodyDeclaration = bodyDeclarations.next();
             if (bodyDeclaration instanceof MethodDeclaration) {
               MethodDeclaration methodDeclaration = (MethodDeclaration) bodyDeclaration;
               if (methodDeclaration.isConstructor()) {
                 SimpleName methodName = methodDeclaration.getName();
                 if (methodName.getIdentifier().equals(oldTypeName)) {
                   rewriter.replace(methodName, ast.newSimpleName(newTypeName), null);
                 }
               }
             }
           }
         }
       }
     }
   }
 }
Esempio n. 26
0
  /** Launch a compilation unit (a source file) based test. */
  public static void launchCompilationUnitConfiguration(
      IJavaProject ijp, ICompilationUnit icu, String mode) {
    IType[] types = null;
    try {
      types = icu.getTypes();
    } catch (JavaModelException jme) {
      TestNGPlugin.log(
          new Status(
              IStatus.ERROR,
              TestNGPlugin.PLUGIN_ID,
              TestNGPluginConstants.LAUNCH_ERROR,
              "No types in compilation unit " + icu.getElementName(),
              jme));
    }

    if (null == types) return;

    IType mainType = icu.findPrimaryType();
    final String confName = mainType != null ? mainType.getElementName() : icu.getElementName();

    launchTypeBasedConfiguration(ijp, confName, types, mode);
  }
  private void process() {
    try {
      IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore();

      String basepackage =
          preferenceStore.getString(JsfcaPerferenceConstants.PROP_KEY_BASE_PACKAGE);
      String regEx = preferenceStore.getString(JsfcaPerferenceConstants.PROP_KEY_FILE_PATTERN);

      if (basepackage == null || basepackage.isEmpty()) {
        return;
      }

      if (regEx == null || regEx.isEmpty()) {
        return;
      }

      Pattern classPattern = Pattern.compile(regEx);

      IPackageFragment[] packageFragments = javaProject.getPackageFragments();
      for (IPackageFragment packageFragment : packageFragments) {
        if (packageFragment.getElementName().startsWith(basepackage.toLowerCase())) {
          if (packageFragment.containsJavaResources()) {
            ICompilationUnit[] compilationUnits = packageFragment.getCompilationUnits();
            for (ICompilationUnit compUnit : compilationUnits) {
              IType primaryType = compUnit.findPrimaryType();
              if (primaryType != null
                  && classPattern.matcher(primaryType.getElementName()).matches()) {
                createSymbol(primaryType);
              }
            }
          }
        }
      }

    } catch (JavaModelException e) {
      e.printStackTrace();
    }
  }
  protected void browseForAccessorClass() {
    IProgressService service = PlatformUI.getWorkbench().getProgressService();
    IPackageFragmentRoot root = fAccessorPackage.getSelectedFragmentRoot();

    IJavaSearchScope scope =
        root != null
            ? SearchEngine.createJavaSearchScope(new IJavaElement[] {root})
            : SearchEngine.createWorkspaceScope();

    FilteredTypesSelectionDialog dialog =
        new FilteredTypesSelectionDialog(
            getShell(), false, service, scope, IJavaSearchConstants.CLASS);
    dialog.setTitle(NLSUIMessages.NLSAccessorConfigurationDialog_Accessor_Selection);
    dialog.setMessage(NLSUIMessages.NLSAccessorConfigurationDialog_Choose_the_accessor_file);
    dialog.setInitialPattern("*Messages"); // $NON-NLS-1$
    if (dialog.open() == Window.OK) {
      IType selectedType = (IType) dialog.getFirstResult();
      if (selectedType != null) {
        fAccessorClassName.setText(selectedType.getElementName());
        fAccessorPackage.setSelected(selectedType.getPackageFragment());
      }
    }
  }
Esempio n. 29
0
  /**
   * Constructs a compilation unit relative name for the supplied type.
   *
   * <p>If the type is imported, in java.lang, or in the same package as the source file, then the
   * type name returned is unqualified, otherwise the name returned is the fully qualified type
   * name.
   *
   * @param src The compilation unit.
   * @param type The type.
   * @return The relative type name.
   */
  public static String getCompilationUnitRelativeTypeName(ICompilationUnit src, IType type)
      throws Exception {
    String typeName = type.getFullyQualifiedName().replace('$', '.');
    if (JavaUtils.containsImport(src, type)) {
      typeName = type.getElementName();

      int parentType = type.getParent().getElementType();
      if (parentType == IJavaElement.TYPE) {
        typeName = type.getParent().getElementName() + '.' + typeName;
      } else if (parentType == IJavaElement.CLASS_FILE) {
        String parentName = type.getParent().getElementName();
        int index = parentName.indexOf('$');
        if (index != -1) {
          parentName = parentName.substring(0, index);
          typeName = parentName + '.' + typeName;
        }
      }
    } else {
      typeName = type.getFullyQualifiedName().replace('$', '.');
    }

    return typeName;
  }
  /**
   * 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();
    }
  }