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;
 }
  /** 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();
    }
  }
 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);
 }
Esempio n. 4
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);
     }
   }
 }
 /**
  * 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);
 }
  /** 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();
      }
    }
  }
Esempio n. 7
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;
  }
  /**
   * 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);
  }
 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);
 }
 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 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");
    }
  }
Esempio n. 12
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());
  }
 /* (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();
   }
 }
Esempio n. 14
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();
   }
 }
  /**
   * 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;
    }
  }
  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());
      }
    }
  }
  private void addType() {
    Shell shell = fAddTypeButton.getDisplay().getActiveShell();
    SelectionDialog dialog = null;
    try {
      dialog =
          JavaUI.createTypeDialog(
              shell,
              PlatformUI.getWorkbench().getProgressService(),
              SearchEngine.createJavaSearchScope(
                  new IJavaElement[] {fEditor.getJavaProject()}, true),
              IJavaElementSearchConstants.CONSIDER_ALL_TYPES,
              false);
    } catch (JavaModelException jme) {
      String title =
          SnippetMessages.getString("SelectImportsDialog.Add_Type_as_Import_12"); // $NON-NLS-1$
      String message =
          SnippetMessages.getString(
              "SelectImportsDialog.Could_not_open_class_selection_dialog_13"); //$NON-NLS-1$
      ExceptionHandler.handle(jme, title, message);
      return;
    }

    dialog.setTitle(
        SnippetMessages.getString("SelectImportsDialog.Add_Type_as_Import_12")); // $NON-NLS-1$
    dialog.setMessage(
        SnippetMessages.getString(
            "SelectImportsDialog.&Select_a_type_to_add_to_add_as_an_import_15")); //$NON-NLS-1$
    if (dialog.open() == IDialogConstants.CANCEL_ID) {
      return;
    }

    Object[] types = dialog.getResult();
    if (types != null && types.length > 0) {
      IType type = (IType) types[0];
      fImportContentProvider.addImport(type.getFullyQualifiedName());
    }
  }
 public static void performDummySearch(IJavaElement element) throws JavaModelException {
   performDummySearch(SearchEngine.createJavaSearchScope(new IJavaElement[] {element}));
 }
 private IJavaSearchScope getSearchScopeFromContext(IPackageFragmentRoot sourceFolder) {
   List<IPackageFragmentRoot> sourceFolderToSearch =
       SourceFolderContext.getInstance().getSourceFolderToSearch(sourceFolder);
   return SearchEngine.createJavaSearchScope(
       sourceFolderToSearch.toArray(new IPackageFragmentRoot[sourceFolderToSearch.size()]));
 }
 /**
  * Creates a new search scope containing all projects which reference or are referenced by the
  * specified project.
  *
  * @param project the project
  * @param includeMask the include mask
  * @return the search scope
  * @throws CoreException if a referenced project could not be determined
  */
 public static IJavaSearchScope createRelatedProjectsScope(IJavaProject project, int includeMask)
     throws CoreException {
   IJavaProject[] projects = getRelatedProjects(project);
   return SearchEngine.createJavaSearchScope(projects, includeMask);
 }
 private IJavaSearchScope createWorkspaceSourceScope() {
   IJavaElement[] project =
       new IJavaElement[] {getMoveProcessor().getDeclaringType().getJavaProject()};
   return SearchEngine.createJavaSearchScope(
       project, IJavaSearchScope.REFERENCED_PROJECTS | IJavaSearchScope.SOURCES);
 }