Example #1
0
 private void searchForTypesUsed(
     SearchEngine engine, IJavaElement parent, IType[] types, IJavaSearchScope scope)
     throws CoreException {
   for (int i = 0; i < types.length; i++) {
     if (types[i].isAnonymous()) continue;
     TypeReferenceSearchRequestor requestor = new TypeReferenceSearchRequestor();
     engine.search(
         SearchPattern.createPattern(types[i], IJavaSearchConstants.REFERENCES),
         new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()},
         scope,
         requestor,
         null);
     if (requestor.containMatches()) {
       TypeDeclarationSearchRequestor decRequestor = new TypeDeclarationSearchRequestor();
       engine.search(
           SearchPattern.createPattern(types[i], IJavaSearchConstants.DECLARATIONS),
           new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()},
           SearchEngine.createJavaSearchScope(new IJavaElement[] {parent}),
           decRequestor,
           null);
       Match match = decRequestor.getMatch();
       if (match != null) fSearchResult.addMatch(match);
     }
   }
 }
 private String handleBrowse(String filter) {
   IJavaSearchScope scope = null;
   if (_project == null) {
     scope = SearchEngine.createWorkspaceScope();
   } else {
     scope = SearchEngine.createJavaSearchScope(new IJavaElement[] {_project});
   }
   try {
     SelectionDialog dialog =
         JavaUI.createTypeDialog(
             Display.getCurrent().getActiveShell(),
             null,
             scope,
             IJavaElementSearchConstants.CONSIDER_CLASSES,
             false,
             filter.isEmpty() ? "* " : filter);
     if (dialog.open() == SelectionDialog.OK) {
       Object[] result = dialog.getResult();
       if (result.length > 0 && result[0] instanceof IType) {
         return ((IType) result[0]).getFullyQualifiedName();
       }
     }
   } catch (JavaModelException e) {
     e.printStackTrace();
   }
   return null;
 }
  /*
   * Ensures that searching takes the owner's working copies into account.
   */
  public void testSearch2() throws CoreException {
    ICompilationUnit cu = getCompilationUnit("P/X.java");
    TestWorkingCopyOwner owner = new TestWorkingCopyOwner();
    this.workingCopy = cu.getWorkingCopy(owner, null);

    // remove type X
    this.workingCopy.getBuffer().setContents("");
    this.workingCopy.makeConsistent(null);

    SearchPattern pattern =
        SearchPattern.createPattern(
            "X",
            IJavaSearchConstants.TYPE,
            IJavaSearchConstants.DECLARATIONS,
            SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE);
    JavaSearchTests.JavaSearchResultCollector resultCollector =
        new JavaSearchTests.JavaSearchResultCollector();
    new SearchEngine(owner)
        .search(
            pattern,
            new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()},
            SearchEngine.createWorkspaceScope(),
            resultCollector,
            null);
    assertEquals(
        "", // should not find any in the owner's context
        resultCollector.toString());
  }
Example #4
0
  /**
   * Performs a search using the given pattern, scope and handler. The search will abort if it takes
   * longer than {@link #SEARCH_TIMEOUT_MS} milliseconds.
   */
  private static void search(
      SearchRequestor requestor, IJavaProject javaProject, SearchPattern pattern)
      throws CoreException {
    // Find the package fragment specified in the manifest; the activities should
    // live there.
    IJavaSearchScope scope = createPackageScope(javaProject);

    SearchParticipant[] participants =
        new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()};
    SearchEngine engine = new SearchEngine();

    final long searchStart = System.currentTimeMillis();
    NullProgressMonitor monitor =
        new NullProgressMonitor() {
          private boolean mCancelled;

          @Override
          public void internalWorked(double work) {
            long searchEnd = System.currentTimeMillis();
            if (searchEnd - searchStart > SEARCH_TIMEOUT_MS) {
              mCancelled = true;
            }
          }

          @Override
          public boolean isCanceled() {
            return mCancelled;
          }
        };
    engine.search(pattern, participants, scope, requestor, monitor);
  }
  /** This method is extremely expensive. */
  @OnEclipseVersionUpgrade("Replace monitor.newChild(1) by monitor.split(1)")
  private boolean isMethodUsedInItsPackage(IMethodBinding methodBinding, MethodDeclaration node) {
    final IPackageBinding methodPackage = methodBinding.getDeclaringClass().getPackage();

    final AtomicBoolean methodIsUsedInPackage = new AtomicBoolean(false);
    final SearchRequestor requestor =
        new SearchRequestor() {
          @Override
          public void acceptSearchMatch(SearchMatch match) {
            methodIsUsedInPackage.set(true);
          }
        };

    final SubMonitor subMonitor = SubMonitor.convert(ctx.getProgressMonitor(), 1);
    final SubMonitor childMonitor = subMonitor.newChild(1);
    try {
      final SearchEngine searchEngine = new SearchEngine();
      searchEngine.search(
          createPattern(methodBinding.getJavaElement(), REFERENCES, R_EXACT_MATCH),
          new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()},
          SearchEngine.createJavaSearchScope(new IJavaElement[] {methodPackage.getJavaElement()}),
          requestor,
          childMonitor);
      return methodIsUsedInPackage.get();
    } catch (CoreException e) {
      throw new UnhandledException(node, e);
    } finally {
      childMonitor.done();
    }
  }
  /*
   * Ensures that searching takes the primary owner's working copies into account only if the working copy
   * is not saved.
   */
  public void testSearch3() throws CoreException {
    try {
      createFile("/P/Y.java", "");
      this.workingCopy = getCompilationUnit("P/Y.java");
      this.workingCopy.becomeWorkingCopy(null);

      // create type Y in working copy
      this.workingCopy.getBuffer().setContents("public class Y {}");
      this.workingCopy.makeConsistent(null);

      JavaSearchTests.JavaSearchResultCollector resultCollector =
          new JavaSearchTests.JavaSearchResultCollector();
      search(
          "Y",
          IJavaSearchConstants.TYPE,
          IJavaSearchConstants.DECLARATIONS,
          SearchEngine.createWorkspaceScope(),
          resultCollector);
      assertEquals("Y.java Y [Y]", resultCollector.toString());

      //	commit new type
      this.workingCopy.commitWorkingCopy(false, null);
      resultCollector = new JavaSearchTests.JavaSearchResultCollector();
      search(
          "Y",
          IJavaSearchConstants.TYPE,
          IJavaSearchConstants.DECLARATIONS,
          SearchEngine.createWorkspaceScope(),
          resultCollector);
      assertEquals("Y.java Y [Y]", resultCollector.toString());
    } finally {
      deleteFile("/P/Y.java");
    }
  }
Example #7
0
 /**
  * @param packageNames
  * @return
  */
 private List getPackageFragments(List packageNames) {
   monitor.subTask("Finding Packages in tangle");
   SearchEngine searchEngine = new SearchEngine();
   IJavaSearchScope scope = SearchEngine.createWorkspaceScope();
   SearchPattern pattern =
       SearchPattern.createPattern(
           "*",
           IJavaSearchConstants.PACKAGE,
           IJavaSearchConstants.DECLARATIONS,
           SearchPattern.R_PATTERN_MATCH);
   PackageCollector c = new PackageCollector(packageNames);
   try {
     searchEngine.search(
         pattern,
         new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()},
         scope,
         c,
         monitor);
     monitor.worked(100);
     return c.getResult();
   } catch (CoreException e) {
     e.printStackTrace();
     return new ArrayList();
   }
 }
Example #8
0
  /** Creates a package search scope for the first package root in the given java project */
  private static IJavaSearchScope createPackageScope(IJavaProject javaProject) {
    IPackageFragmentRoot packageRoot = getSourcePackageRoot(javaProject);

    IJavaSearchScope scope;
    if (packageRoot != null) {
      IJavaElement[] scopeElements = new IJavaElement[] {packageRoot};
      scope = SearchEngine.createJavaSearchScope(scopeElements);
    } else {
      scope = SearchEngine.createWorkspaceScope();
    }
    return scope;
  }
 private void searchPackage(String matchString, IJavaSearchScope scope, SearchRequestor requestor)
     throws CoreException {
   SearchPattern pattern =
       SearchPattern.createPattern(
           matchString + "*",
           IJavaSearchConstants.PACKAGE,
           IJavaSearchConstants.DECLARATIONS,
           SearchPattern.R_PREFIX_MATCH);
   SearchEngine searchEngine = new SearchEngine();
   searchEngine.search(
       pattern,
       new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()},
       scope,
       requestor,
       null);
 }
Example #10
0
 private RefactoringStatus checkAccessorDeclarations(IProgressMonitor pm, IMethod existingAccessor)
     throws CoreException {
   RefactoringStatus result = new RefactoringStatus();
   SearchPattern pattern =
       SearchPattern.createPattern(
           existingAccessor,
           IJavaSearchConstants.DECLARATIONS,
           SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
   IJavaSearchScope scope = SearchEngine.createHierarchyScope(fField.getDeclaringType());
   SearchResultGroup[] groupDeclarations =
       RefactoringSearchEngine.search(pattern, scope, pm, result);
   Assert.isTrue(groupDeclarations.length > 0);
   if (groupDeclarations.length != 1) {
     String message =
         Messages.format(
             RefactoringCoreMessages.RenameFieldRefactoring_overridden,
             JavaElementUtil.createMethodSignature(existingAccessor));
     result.addError(message);
   } else {
     SearchResultGroup group = groupDeclarations[0];
     Assert.isTrue(group.getSearchResults().length > 0);
     if (group.getSearchResults().length != 1) {
       String message =
           Messages.format(
               RefactoringCoreMessages.RenameFieldRefactoring_overridden_or_overrides,
               JavaElementUtil.createMethodSignature(existingAccessor));
       result.addError(message);
     }
   }
   return result;
 }
 private void proposePackage(
     final ContentAssistRequest contentAssistRequest,
     IJavaProject project,
     String matchString,
     final int start,
     final int length)
     throws CoreException {
   final List<ICompletionProposal> results = new ArrayList<ICompletionProposal>();
   final Set<String> foundPkgs = new HashSet<String>();
   int includeMask = IJavaSearchScope.SOURCES | IJavaSearchScope.REFERENCED_PROJECTS;
   // Include application libraries only when package is specified (for better performance).
   boolean pkgSpecified = matchString != null && matchString.indexOf('.') > 0;
   if (pkgSpecified)
     includeMask |= IJavaSearchScope.APPLICATION_LIBRARIES | IJavaSearchScope.SYSTEM_LIBRARIES;
   IJavaSearchScope scope =
       SearchEngine.createJavaSearchScope(new IJavaProject[] {project}, includeMask);
   SearchRequestor requestor =
       new SearchRequestor() {
         @Override
         public void acceptSearchMatch(SearchMatch match) throws CoreException {
           PackageFragment element = (PackageFragment) match.getElement();
           String pkg = element.getElementName();
           if (pkg != null && pkg.length() > 0 && !foundPkgs.contains(pkg)) {
             foundPkgs.add(pkg);
             results.add(
                 new CompletionProposal(
                     pkg, start, length, pkg.length(), Activator.getIcon(), pkg, null, null));
           }
         }
       };
   searchPackage(matchString, scope, requestor);
   addProposals(contentAssistRequest, results);
 }
  protected Object createFromElement(Element type) {
    String handle = type.getAttribute(NODE_HANDLE);
    if (handle == null) return null;

    IJavaElement element = JavaCore.create(handle);
    if (!(element instanceof IType)) return null;

    int modifiers = 0;
    try {
      modifiers = Integer.parseInt(type.getAttribute(NODE_MODIFIERS));
    } catch (NumberFormatException e) {
      // take zero
    }
    TypeNameMatch info = SearchEngine.createTypeNameMatch((IType) element, modifiers);
    long timestamp = IResource.NULL_STAMP;
    String timestampValue = type.getAttribute(NODE_TIMESTAMP);
    if (timestampValue != null && timestampValue.length() > 0) {
      try {
        timestamp = Long.parseLong(timestampValue);
      } catch (NumberFormatException e) {
        // take null stamp
      }
    }
    if (timestamp != IResource.NULL_STAMP) {
      fTimestampMapping.put(info, new Long(timestamp));
    }
    return info;
  }
 /**
  * Creates a new search scope with all projects possibly referenced from the given <code>
  * javaElements</code>.
  *
  * @param javaElements the java elements
  * @return the search scope
  */
 public static IJavaSearchScope createReferencedScope(IJavaElement[] javaElements) {
   Set<IJavaProject> projects = new HashSet<IJavaProject>();
   for (int i = 0; i < javaElements.length; i++) {
     projects.add(javaElements[i].getJavaProject());
   }
   IJavaProject[] prj = projects.toArray(new IJavaProject[projects.size()]);
   return SearchEngine.createJavaSearchScope(prj, true);
 }
Example #14
0
 /**
  * @param shell Shell for the window
  * @param superTypeName supertype to search for
  * @param project project to look in
  * @return IType the type created
  * @throws JavaModelException exception thrown
  */
 public IType selectType(Shell shell, String superTypeName, IProject project)
     throws JavaModelException {
   IJavaSearchScope searchScope = null;
   if (project == null) {
     ISelection selection =
         PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().getSelection();
     IStructuredSelection selectionToPass = StructuredSelection.EMPTY;
     if (selection instanceof IStructuredSelection) {
       selectionToPass = (IStructuredSelection) selection;
       if (selectionToPass.getFirstElement() instanceof IFile) {
         project = ((IFile) selectionToPass.getFirstElement()).getProject();
       }
     }
   }
   if (superTypeName != null && !superTypeName.equals("java.lang.Object")) { // $NON-NLS-1$
     if (project == null) {
       project = model.getProject();
     }
     IJavaProject javaProject = JavaCore.create(project);
     IType superType = javaProject.findType(superTypeName);
     if (superType != null) {
       searchScope =
           SearchEngine.createStrictHierarchyScope(javaProject, superType, true, false, null);
     }
   } else {
     searchScope = SearchEngine.createWorkspaceScope();
   }
   SelectionDialog dialog =
       JavaUI.createTypeDialog(
           shell,
           new ProgressMonitorDialog(shell),
           searchScope,
           IJavaElementSearchConstants.CONSIDER_CLASSES_AND_INTERFACES,
           false);
   dialog.setTitle("Select Class");
   dialog.setMessage("Matching items");
   if (dialog.open() == IDialogConstants.CANCEL_ID) {
     return null;
   }
   Object[] types = dialog.getResult();
   if (types == null || types.length == 0) {
     return null;
   }
   return (IType) types[0];
 }
  /*
   * Ensures that searching takes the primary owner's working copies and the given working copies into account.
   * (regression test for bug 43300 SearchEngine(IWorkingCopy[] workingCopies) not backward compatible)
   */
  public void testSearch4() throws CoreException {
    ICompilationUnit primaryWorkingCopy = null;
    try {
      createFolder("P/p");
      createFile("/P/p/Y.java", "");
      primaryWorkingCopy = getCompilationUnit("P/p/Y.java");
      primaryWorkingCopy.becomeWorkingCopy(null);

      // create type Y in working copy
      primaryWorkingCopy.getBuffer().setContents("package p;\n" + "public class Y {\n" + "}");
      primaryWorkingCopy.makeConsistent(null);

      // create new working copy on X.java and add type X
      this.workingCopy = getCompilationUnit("P/p/X.java").getWorkingCopy(null);
      this.workingCopy.getBuffer().setContents("package p;\n" + "public class X {\n" + "}");
      this.workingCopy.makeConsistent(null);

      JavaSearchTests.JavaSearchResultCollector resultCollector =
          new JavaSearchTests.JavaSearchResultCollector();
      IJavaSearchScope scope =
          SearchEngine.createJavaSearchScope(new IJavaElement[] {primaryWorkingCopy.getParent()});
      SearchPattern pattern =
          SearchPattern.createPattern(
              "*",
              IJavaSearchConstants.TYPE,
              IJavaSearchConstants.DECLARATIONS,
              SearchPattern.R_PATTERN_MATCH | SearchPattern.R_CASE_SENSITIVE);
      new SearchEngine(new ICompilationUnit[] {this.workingCopy})
          .search(
              pattern,
              new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()},
              scope,
              resultCollector,
              null);
      assertEquals("p/X.java p.X [X]\n" + "p/Y.java p.Y [Y]", resultCollector.toString());

    } finally {
      if (primaryWorkingCopy != null) {
        primaryWorkingCopy.discardWorkingCopy();
      }
      deleteFile("/P/p/Y.java");
    }
  }
  /** Handle browse package. */
  private void handleBrowsePackage() {

    IPackageFragment[] packages = null;
    IJavaProject javaProject = JavaCore.create(project);
    IJavaElement javaElementArray[] = null;
    ArrayList<IJavaElement> javaElementsList = new ArrayList<IJavaElement>();

    // Si el projecto no esta abierto se cancela el proceso
    if (javaProject.isOpen() == false) {
      MessageDialog.openError(
          getShell(),
          Messages.WizardPageChooseSourceFolderAndPackage_29,
          Messages.WizardPageChooseSourceFolderAndPackage_30);
      return;
    }

    // Lee los paquetes solo del proyecto
    try {
      packages = javaProject.getPackageFragments();

      for (IPackageFragment iPackageFragment : packages) {
        if (iPackageFragment.getKind() == IPackageFragmentRoot.K_SOURCE) {
          javaElementsList.add(iPackageFragment);
        }
      }
      if (javaElementsList.size() > 0) {
        javaElementArray = new IJavaElement[javaElementsList.size()];
        javaElementArray = javaElementsList.toArray(javaElementArray);
      }
    } catch (JavaModelException e) {
      MessageDialog.openError(
          getShell(), Messages.WizardPageChooseSourceFolderAndPackage_31, e.getMessage());
    }

    Shell shell = getShell();
    IJavaSearchScope iJavaSearchScope = SearchEngine.createJavaSearchScope(javaElementArray, false);
    PackageSelectionDialog packageSelectionDialog =
        new PackageSelectionDialog(
            shell,
            new ProgressMonitorDialog(shell),
            PackageSelectionDialog.F_REMOVE_DUPLICATES | PackageSelectionDialog.F_HIDE_EMPTY_INNER,
            iJavaSearchScope);

    packageSelectionDialog.setTitle(Messages.WizardPageChooseSourceFolderAndPackage_32);
    packageSelectionDialog.setMessage(Messages.WizardPageChooseSourceFolderAndPackage_33);

    if (packageSelectionDialog.open() == Window.OK) {
      Object results[] = packageSelectionDialog.getResult();
      if (results != null && results.length > 0) {
        PackageFragment packageFragment = (PackageFragment) results[0];
        txtPackage.setText(packageFragment.getElementName());
        EclipseGeneratorUtil.javaEntityPackage = packageFragment.getElementName();
      }
    }
  }
Example #17
0
  public static IJavaElement searchForClass(IJavaProject javaProject, String className)
      throws JavaModelException {
    // Get the search pattern
    SearchPattern pattern =
        SearchPattern.createPattern(
            className,
            IJavaSearchConstants.TYPE,
            IJavaSearchConstants.DECLARATIONS,
            SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE);
    // Get the search scope
    IJavaSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaElement[] {javaProject});

    final List<SearchMatch> matches = new ArrayList<SearchMatch>(INITIAL_CAPACITY);
    // Get the search requestor
    SearchRequestor requestor =
        new SearchRequestor() {
          public void acceptSearchMatch(SearchMatch match) throws CoreException {
            matches.add(match);
          }
        };

    // Search
    SearchEngine searchEngine = new SearchEngine();
    try {
      searchEngine.search(
          pattern,
          new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()},
          scope,
          requestor,
          null);
    } catch (CoreException ex) {
      JspEditorPlugin.getPluginLog().logError(ex);
    }
    for (SearchMatch match : matches) {
      IJavaElement element = (IJavaElement) match.getElement();
      if (element instanceof IType
          && className.equals(((IType) element).getFullyQualifiedName('.'))) {
        return element;
      }
    }
    return javaProject.findType(className, new NullProgressMonitor());
  }
  @NotNull
  private List<IType> findAllTypes(@NotNull String typeName) {
    IJavaSearchScope scope = SearchEngine.createWorkspaceScope();
    List<IType> searchCollector = new ArrayList<IType>();
    TypeNameMatchRequestor requestor = new KotlinSearchTypeRequestor(searchCollector);
    try {
      searchEngine.searchAllTypeNames(
          null,
          SearchPattern.R_EXACT_MATCH,
          typeName.toCharArray(),
          SearchPattern.R_EXACT_MATCH,
          IJavaSearchConstants.TYPE,
          scope,
          requestor,
          IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
          null);
    } catch (CoreException e) {
      KotlinLogger.logAndThrow(e);
    }

    return searchCollector;
  }
  /**
   * Creates a new search scope with all compilation units possibly referencing <code>javaElement
   * </code>.
   *
   * @param javaElement the java element
   * @param considerVisibility consider visibility of javaElement iff <code>true</code>
   * @param sourceReferencesOnly consider references in source only (no references in binary)
   * @return the search scope
   * @throws JavaModelException if an error occurs
   */
  public static IJavaSearchScope create(
      IJavaElement javaElement, boolean considerVisibility, boolean sourceReferencesOnly)
      throws JavaModelException {
    if (considerVisibility & javaElement instanceof IMember) {
      IMember member = (IMember) javaElement;
      if (JdtFlags.isPrivate(member)) {
        if (member.getCompilationUnit() != null)
          return SearchEngine.createJavaSearchScope(
              new IJavaElement[] {member.getCompilationUnit()});
        else return SearchEngine.createJavaSearchScope(new IJavaElement[] {member});
      }
      // Removed code that does some optimizations regarding package visible members. The problem is
      // that
      // there can be a package fragment with the same name in a different source folder or project.
      // So we
      // have to treat package visible members like public or protected members.
    }

    IJavaProject javaProject = javaElement.getJavaProject();
    return SearchEngine.createJavaSearchScope(
        getAllScopeElements(javaProject, sourceReferencesOnly), false);
  }
Example #20
0
 /**
  * @param packages
  * @return
  */
 private void getDependencies(List packages) {
   try {
     SearchEngine searchEngine = new SearchEngine();
     // fill in the packageName->{IType}* map by getting all type declarations in scope
     IJavaElement[] packs = (IJavaElement[]) packages.toArray(new IJavaElement[] {});
     IJavaSearchScope scope = SearchEngine.createJavaSearchScope(packs);
     SearchPattern pattern =
         SearchPattern.createPattern(
             "*",
             IJavaSearchConstants.TYPE,
             IJavaSearchConstants.DECLARATIONS,
             SearchPattern.R_PATTERN_MATCH);
     TypeCollector c = new TypeCollector(result);
     monitor.subTask("Collecting types in packages");
     searchEngine.search(
         pattern,
         new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()},
         scope,
         c,
         monitor);
     if (monitor.isCanceled()) return;
     // get all type references to these types.
     // Have to do multiple searches to get proper relationship :-(
     Set typesInScope = result.keySet();
     monitor.worked(400);
     monitor.subTask("Collecting type dependencies");
     int scale = 500 / typesInScope.size();
     for (Iterator i = typesInScope.iterator(); i.hasNext(); ) {
       if (monitor.isCanceled()) return;
       String handle = (String) i.next();
       IJavaElement type = JavaCore.create(handle);
       searchEngine.searchDeclarationsOfReferencedTypes(
           type, new RefCollector((Set) result.get(handle), typesInScope, type), monitor);
       monitor.worked(scale);
     }
   } catch (CoreException e) {
     e.printStackTrace();
   }
 }
 public void waitForIndexer() throws JavaModelException {
   new SearchEngine()
       .searchAllTypeNames(
           null,
           null,
           SearchPattern.R_EXACT_MATCH,
           IJavaSearchConstants.CLASS,
           SearchEngine.createJavaSearchScope(new IJavaElement[0]),
           new TypeNameRequestor() {
             // nothing needs to be done here...we accept everything
           },
           IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
           null);
 }
  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());
      }
    }
  }
 public static void performDummySearch() throws JavaModelException {
   new SearchEngine()
       .searchAllTypeNames(
           null,
           SearchPattern.R_EXACT_MATCH,
           "XXXXXXXXX"
               .toCharArray(), // make sure we search a concrete name. This is faster according to
                               // Kent
           SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE,
           IJavaSearchConstants.CLASS,
           SearchEngine.createJavaSearchScope(new IJavaElement[0]),
           new Requestor(),
           IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
           null);
 }
  /*
   * Ensures that searching takes the owner's working copies into account.
   */
  public void testSearch1() throws CoreException {
    ICompilationUnit cu = getCompilationUnit("P/Y.java");
    TestWorkingCopyOwner owner = new TestWorkingCopyOwner();
    this.workingCopy = cu.getWorkingCopy(owner, null);
    this.workingCopy.getBuffer().setContents("public class Y {\n" + "  X field;\n" + "}");
    this.workingCopy.makeConsistent(null);

    SearchPattern pattern =
        SearchPattern.createPattern(
            "X",
            IJavaSearchConstants.TYPE,
            IJavaSearchConstants.REFERENCES,
            SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE);
    JavaSearchTests.JavaSearchResultCollector resultCollector =
        new JavaSearchTests.JavaSearchResultCollector();
    new SearchEngine(owner)
        .search(
            pattern,
            new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()},
            SearchEngine.createWorkspaceScope(),
            resultCollector,
            null);
    assertEquals("Y.java Y.field [X]", resultCollector.toString());
  }
  void goToErrorLine(String choice) {
    try {
      String msg = mLogPanel.getSelectedErrorLineMessage();
      if (msg != null) {
        String error_line_matcher_string = "\\s*at\\ (.*)\\((.*)\\.java\\:(\\d+)\\)";
        Matcher error_line_matcher = Pattern.compile(error_line_matcher_string).matcher(msg);

        if (error_line_matcher.find()) {
          String class_name_method = error_line_matcher.group(1);

          // TODO: Search currently only matches the class declaration (using
          // IJavaSearchConstants.DECLARATIONS). We may want to jump to the
          // "reference" of the class instead (IJavaSearchConstants.REFERENCES)
          // using the filename and line number to disambiguate the search results.
          String class_name_line = error_line_matcher.group(2);
          int line_number = Integer.parseInt(error_line_matcher.group(3));

          SearchEngine se = new SearchEngine();
          if (CHOICE_ERROR_LINE.equals(choice)) {
            se.search(
                SearchPattern.createPattern(
                    class_name_line,
                    IJavaSearchConstants.CLASS,
                    IJavaSearchConstants.DECLARATIONS,
                    SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE),
                new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()},
                SearchEngine.createWorkspaceScope(),
                new LogCatViewSearchRequestor(CHOICE_ERROR_LINE, line_number),
                new NullProgressMonitor());
          } else if (CHOICE_METHOD_DECLARATION.equals(choice)) {
            se.search(
                SearchPattern.createPattern(
                    class_name_method,
                    IJavaSearchConstants.METHOD,
                    IJavaSearchConstants.DECLARATIONS,
                    SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE),
                new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()},
                SearchEngine.createWorkspaceScope(),
                new LogCatViewSearchRequestor(CHOICE_METHOD_DECLARATION, 0),
                new NullProgressMonitor());
          }
        }
      }
    } catch (Exception e) {
      Status s = new Status(Status.ERROR, DdmsPlugin.PLUGIN_ID, e.getMessage(), e);
      DdmsPlugin.getDefault().getLog().log(s);
    }
  }
 /* (non-Javadoc)
  * @see org.eclipse.jdt.debug.ui.launchConfigurations.JavaLaunchShortcut#findTypes(java.lang.Object[], org.eclipse.jface.operation.IRunnableContext)
  */
 @Override
 protected IType[] findTypes(Object[] elements, IRunnableContext context)
     throws InterruptedException, CoreException {
   try {
     if (elements.length == 1) {
       IType type = isMainMethod(elements[0]);
       if (type != null) {
         return new IType[] {type};
       }
     }
     IJavaElement[] javaElements = getJavaElements(elements);
     MainMethodSearchEngine engine = new MainMethodSearchEngine();
     int constraints = IJavaSearchScope.SOURCES;
     constraints |= IJavaSearchScope.APPLICATION_LIBRARIES;
     IJavaSearchScope scope = SearchEngine.createJavaSearchScope(javaElements, constraints);
     return engine.searchMainMethods(context, scope, true);
   } catch (InvocationTargetException e) {
     throw (CoreException) e.getTargetException();
   }
 }
  /**
   * Adds an import for type with type name <code>type</code> if possible. Returns a string which
   * can be used to reference the type.
   *
   * @param type the fully qualified name of the type to import
   * @return returns a type to which the type binding can be assigned to. The returned type contains
   *     is unqualified when an import could be added or was already known. It is fully qualified,
   *     if an import conflict prevented the import.
   * @since 3.4
   */
  public String addImport(String type) {
    if (isReadOnly()) return type;

    ICompilationUnit cu = getCompilationUnit();
    if (cu == null) return type;

    try {
      boolean qualified = type.indexOf('.') != -1;
      if (!qualified) {
        IJavaSearchScope searchScope =
            SearchEngine.createJavaSearchScope(new IJavaElement[] {cu.getJavaProject()});
        SimpleName nameNode = null;
        TypeNameMatch[] matches = findAllTypes(type, searchScope, nameNode, null, cu);
        if (matches.length != 1) // only add import if we have a single match
        return type;
        type = matches[0].getFullyQualifiedName();
      }

      CompilationUnit root = getASTRoot(cu);
      if (fImportRewrite == null) {
        if (root == null) {
          fImportRewrite = StubUtility.createImportRewrite(cu, true);
        } else {
          fImportRewrite = StubUtility.createImportRewrite(root, true);
        }
      }

      ImportRewriteContext context;
      if (root == null) context = null;
      else
        context =
            new ContextSensitiveImportRewriteContext(root, getCompletionOffset(), fImportRewrite);

      return fImportRewrite.addImport(type, context);
    } catch (JavaModelException e) {
      handleException(null, e);
      return type;
    }
  }
  public String chooseClass() {
    SelectionDialog dialog;

    try {
      dialog =
          JavaUI.createTypeDialog(
              shell,
              new ProgressMonitorDialog(shell),
              SearchEngine.createWorkspaceScope(),
              IJavaElementSearchConstants.CONSIDER_CLASSES,
              false);
    } catch (Exception e) {
      Activator.logError(e);

      return null;
    }

    if (dialog.open() != SelectionDialog.OK) {
      return null;
    }

    Object[] result = dialog.getResult();
    String clazz = ((IType) result[0]).getFullyQualifiedName();
    IJavaProject containerProject = ((IType) result[0]).getJavaProject();

    DiagramEditor diagramEditor = Bpmn2Editor.getActiveEditor();

    IProject currentProject =
        getProjectFromDiagram(diagramEditor.getDiagramTypeProvider().getDiagram());

    try {
      doProjectReferenceChange(currentProject, containerProject, clazz);
    } catch (Exception e) {
      return null;
    }

    return clazz;
  }
Example #29
0
  public static Set<IType> searchForJavaConfigs(SearchPattern pattern, IJavaSearchScope scope) {
    final Set<IType> annotatedTypes = new HashSet<IType>();
    SearchRequestor requestor =
        new SearchRequestor() {
          @Override
          public void acceptSearchMatch(SearchMatch match) throws CoreException {
            if (match.getAccuracy() == SearchMatch.A_ACCURATE && !match.isInsideDocComment()) {
              Object element = match.getElement();
              if (element instanceof IType) {
                annotatedTypes.add((IType) element);
              } else if (element instanceof IMethod) {
                IType type = ((IMethod) element).getDeclaringType();
                if (type != null) {
                  annotatedTypes.add(type);
                }
              }
            }
          }
        };

    try {
      new SearchEngine()
          .search(
              pattern,
              new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()},
              scope,
              requestor,
              null);
    } catch (CoreException e) {
      StatusHandler.log(
          new Status(
              IStatus.ERROR,
              SpringCore.PLUGIN_ID,
              "An error occurred while searching for Java config files.",
              e));
    }
    return annotatedTypes;
  }
 private synchronized void internalCheckConsistency(IProgressMonitor monitor)
     throws OperationCanceledException {
   // Setting fNeedsConsistencyCheck is necessary here since
   // markAsInconsistent isn't synchronized.
   fNeedsConsistencyCheck = true;
   List typesToCheck = new ArrayList(getKeys());
   monitor.beginTask(CorextMessages.TypeInfoHistory_consistency_check, typesToCheck.size());
   monitor.setTaskName(CorextMessages.TypeInfoHistory_consistency_check);
   for (Iterator iter = typesToCheck.iterator(); iter.hasNext(); ) {
     TypeNameMatch type = (TypeNameMatch) iter.next();
     long currentTimestamp = getContainerTimestamp(type);
     Long lastTested = (Long) fTimestampMapping.get(type);
     if (lastTested != null
         && currentTimestamp != IResource.NULL_STAMP
         && currentTimestamp == lastTested.longValue()
         && !isContainerDirty(type)) continue;
     try {
       IType jType = type.getType();
       if (jType == null || !jType.exists()) {
         remove(type);
       } else {
         // copy over the modifiers since they may have changed
         int modifiers = jType.getFlags();
         if (modifiers != type.getModifiers()) {
           replace(type, SearchEngine.createTypeNameMatch(jType, modifiers));
         } else {
           fTimestampMapping.put(type, new Long(currentTimestamp));
         }
       }
     } catch (JavaModelException e) {
       remove(type);
     }
     if (monitor.isCanceled()) throw new OperationCanceledException();
     monitor.worked(1);
   }
   monitor.done();
   fNeedsConsistencyCheck = false;
 }