/*
   * 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");
    }
  }
  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);
    }
  }
 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());
  }
Beispiel #5
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();
   }
 }
Beispiel #6
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;
  }
Beispiel #7
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];
 }
  @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;
  }
  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;
  }
  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());
      }
    }
  }
  protected String[] getPathsOfDeclaringType() {
    if (this.typeQualification == null && this.typeSimpleName == null) return null;

    final PathCollector pathCollector = new PathCollector();
    IJavaSearchScope scope = SearchEngine.createWorkspaceScope();
    IndexManager indexManager = JavaModelManager.getIndexManager();
    SearchPattern searchPattern =
        new TypeDeclarationPattern(
            this.typeSimpleName != null
                ? null
                : this.typeQualification, // use the qualification only if no simple name
            null, // do find member types
            this.typeSimpleName,
            IIndexConstants.TYPE_SUFFIX,
            this.pattern.getMatchRule());
    IndexQueryRequestor searchRequestor =
        new IndexQueryRequestor() {
          public boolean acceptIndexMatch(
              String documentPath,
              SearchPattern indexRecord,
              SearchParticipant participant,
              AccessRuleSet access) {
            TypeDeclarationPattern record = (TypeDeclarationPattern) indexRecord;
            if (record.enclosingTypeNames
                != IIndexConstants.ONE_ZERO_CHAR) { // filter out local and anonymous classes
              pathCollector.acceptIndexMatch(documentPath, indexRecord, participant, access);
            }
            return true;
          }
        };

    indexManager.performConcurrentJob(
        new PatternSearchJob(searchPattern, new JavaSearchParticipant(), scope, searchRequestor),
        IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
        progressMonitor == null ? null : new SubProgressMonitor(progressMonitor, 100));
    return pathCollector.getPaths();
  }
  /*
   * 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());
  }
 public static void performDummySearch() throws JavaModelException {
   performDummySearch(SearchEngine.createWorkspaceScope());
 }
  private void collectProposals(
      IJavaProject project, String name, Collection<DefaultClasspathFixProposal> proposals)
      throws CoreException {
    int idx = name.lastIndexOf('.');
    char[] packageName =
        idx != -1 ? name.substring(0, idx).toCharArray() : null; // no package provided
    char[] typeName = name.substring(idx + 1).toCharArray();

    if (typeName.length == 1 && typeName[0] == '*') {
      typeName = null;
    }

    IJavaSearchScope scope = SearchEngine.createWorkspaceScope();
    ArrayList<TypeNameMatch> res = new ArrayList<TypeNameMatch>();
    TypeNameMatchCollector requestor = new TypeNameMatchCollector(res);
    int matchMode = SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE;
    new SearchEngine()
        .searchAllTypeNames(
            packageName,
            matchMode,
            typeName,
            matchMode,
            IJavaSearchConstants.TYPE,
            scope,
            requestor,
            IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
            null);

    if (res.isEmpty()) {
      return;
    }
    HashSet<Object> addedClaspaths = new HashSet<Object>();
    for (int i = 0; i < res.size(); i++) {
      TypeNameMatch curr = res.get(i);
      IType type = curr.getType();
      if (type != null) {
        IPackageFragmentRoot root =
            (IPackageFragmentRoot) type.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
        try {
          IClasspathEntry entry = root.getRawClasspathEntry();
          if (entry == null) {
            continue;
          }
          IJavaProject other = root.getJavaProject();
          int entryKind = entry.getEntryKind();
          if ((entry.isExported() || entryKind == IClasspathEntry.CPE_SOURCE)
              && addedClaspaths.add(other)) {
            IClasspathEntry newEntry = JavaCore.newProjectEntry(other.getPath());
            Change change = ClasspathFixProposal.newAddClasspathChange(project, newEntry);
            if (change != null) {
              String[] args = {
                BasicElementLabels.getResourceName(other.getElementName()),
                BasicElementLabels.getResourceName(project.getElementName())
              };
              String label =
                  Messages.format(
                      CorrectionMessages.ReorgCorrectionsSubProcessor_addcp_project_description,
                      args);
              String desc = label;
              DefaultClasspathFixProposal proposal =
                  new DefaultClasspathFixProposal(
                      label, change, desc, IProposalRelevance.ADD_PROJECT_TO_BUILDPATH);
              proposals.add(proposal);
            }
          }
          if (entryKind == IClasspathEntry.CPE_CONTAINER) {
            IPath entryPath = entry.getPath();
            if (isNonProjectSpecificContainer(entryPath)) {
              addLibraryProposal(project, root, entry, addedClaspaths, proposals);
            } else {
              try {
                IClasspathContainer classpathContainer =
                    JavaCore.getClasspathContainer(entryPath, root.getJavaProject());
                if (classpathContainer != null) {
                  IClasspathEntry entryInContainer =
                      JavaModelUtil.findEntryInContainer(classpathContainer, root.getPath());
                  if (entryInContainer != null) {
                    addLibraryProposal(project, root, entryInContainer, addedClaspaths, proposals);
                  }
                }
              } catch (CoreException e) {
                // ignore
              }
            }
          } else if ((entryKind == IClasspathEntry.CPE_LIBRARY
              || entryKind == IClasspathEntry.CPE_VARIABLE)) {
            addLibraryProposal(project, root, entry, addedClaspaths, proposals);
          }
        } catch (JavaModelException e) {
          // ignore
        }
      }
    }
  }
 public static void search(String scopeName, IType[] accessorClasses, IFile[] propertieFiles) {
   NLSSearchQuery query =
       new NLSSearchQuery(
           accessorClasses, propertieFiles, SearchEngine.createWorkspaceScope(), scopeName);
   NewSearchUI.runQueryInBackground(query);
 }