public ClasspathFixProcessor getProcessor(IJavaProject project) {
   if (matches(project)) {
     if (fProcessorInstance == null) {
       try {
         Object extension = fConfigurationElement.createExecutableExtension(CLASS);
         if (extension instanceof ClasspathFixProcessor) {
           fProcessorInstance = (ClasspathFixProcessor) extension;
         } else {
           String message =
               "Invalid extension to "
                   + ATT_EXTENSION //$NON-NLS-1$
                   + ". Must extends ClasspathFixProcessor: "
                   + getID(); //$NON-NLS-1$
           JavaPlugin.log(new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, message));
           fStatus = Boolean.FALSE;
           return null;
         }
       } catch (CoreException e) {
         JavaPlugin.log(e);
         fStatus = Boolean.FALSE;
         return null;
       }
     }
     return fProcessorInstance;
   }
   return null;
 }
    /*
     * (non-Javadoc)
     *
     * @see
     * org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter
     * #changeControlPressed(org.eclipse.jdt
     * .internal.ui.wizards.dialogfields.DialogField)
     */
    public void changeControlPressed(DialogField field) {
      final DirectoryDialog dialog = new DirectoryDialog(getShell());
      dialog.setMessage(NewWizardMessages.NewJavaProjectWizardPageOne_directory_message);
      String directoryName = fLocation.getText().trim();
      if (directoryName.length() == 0) {
        String prevLocation =
            JavaPlugin.getDefault().getDialogSettings().get(DIALOGSTORE_LAST_EXTERNAL_LOC);
        if (prevLocation != null) {
          directoryName = prevLocation;
        }
      }

      if (directoryName.length() > 0) {
        final File path = new File(directoryName);
        if (path.exists()) dialog.setFilterPath(directoryName);
      }
      final String selectedDirectory = dialog.open();
      if (selectedDirectory != null) {
        String oldDirectory = new Path(fLocation.getText().trim()).lastSegment();
        fLocation.setText(selectedDirectory);
        String lastSegment = new Path(selectedDirectory).lastSegment();
        if (lastSegment != null
            && (fNameGroup.getName().length() == 0 || fNameGroup.getName().equals(oldDirectory))) {
          fNameGroup.setName(lastSegment);
        }
        JavaPlugin.getDefault()
            .getDialogSettings()
            .put(DIALOGSTORE_LAST_EXTERNAL_LOC, selectedDirectory);
      }
    }
  /*
   * @see org.eclipse.jdt.internal.ui.text.java.LazyJavaCompletionProposal#apply(org.eclipse.jface.text.IDocument, char, int)
   */
  @Override
  public void apply(IDocument document, char trigger, int offset) {
    try {
      boolean insertClosingParenthesis = trigger == '(' && autocloseBrackets();
      if (insertClosingParenthesis) {
        StringBuffer replacement = new StringBuffer(getReplacementString());
        updateReplacementWithParentheses(replacement);
        setReplacementString(replacement.toString());
        trigger = '\0';
      }

      super.apply(document, trigger, offset);

      if (fImportRewrite != null && fImportRewrite.hasRecordedChanges()) {
        int oldLen = document.getLength();
        fImportRewrite
            .rewriteImports(new NullProgressMonitor())
            .apply(document, TextEdit.UPDATE_REGIONS);
        setReplacementOffset(getReplacementOffset() + document.getLength() - oldLen);
      }

      if (insertClosingParenthesis) setUpLinkedMode(document, ')');

      rememberSelection();
    } catch (CoreException e) {
      JavaPlugin.log(e);
    } catch (BadLocationException e) {
      JavaPlugin.log(e);
    }
  }
  public void testSearchNotRunIfViewDeactivated() throws PartInitException, JavaModelException {
    view = (ActiveSearchView) JavaPlugin.getActivePage().showView(ActiveSearchView.ID);
    for (AbstractRelationProvider provider :
        ContextCorePlugin.getDefault().getRelationProviders()) {
      assertTrue(provider.getCurrentDegreeOfSeparation() > 0);
    }
    IViewPart viewPart = JavaPlugin.getActivePage().showView("org.eclipse.ui.views.ProblemView");

    // XXX e4.0 IPerspectiveDescriptor API has changed
    //		IPerspectiveDescriptor perspective = ((WorkbenchPage)
    // JavaPlugin.getActivePage()).getPerspective();
    IViewReference reference = JavaPlugin.getActivePage().findViewReference(ActiveSearchView.ID);
    assertNotNull(reference);
    //		assertTrue(perspective.canCloseView(view));
    //		assertTrue(perspective.hideView(reference));
    JavaPlugin.getActivePage().hideView(viewPart);

    for (AbstractRelationProvider provider :
        ContextCorePlugin.getDefault().getRelationProviders()) {
      assertFalse(provider.isEnabled());
    }

    JavaPlugin.getActivePage().showView(ActiveSearchView.ID);
    for (AbstractRelationProvider provider :
        ContextCorePlugin.getDefault().getRelationProviders()) {
      assertTrue(provider.isEnabled());
    }
  }
 @Override
 public Change createChange(IProgressMonitor monitor) throws CoreException {
   try {
     final TextChange[] changes = fChangeManager.getAllChanges();
     final List<TextChange> list = new ArrayList<>(changes.length);
     list.addAll(Arrays.asList(changes));
     String project = null;
     IJavaProject javaProject = fMethod.getJavaProject();
     if (javaProject != null) project = javaProject.getElementName();
     int flags =
         JavaRefactoringDescriptor.JAR_MIGRATION
             | JavaRefactoringDescriptor.JAR_REFACTORING
             | RefactoringDescriptor.STRUCTURAL_CHANGE;
     try {
       if (!Flags.isPrivate(fMethod.getFlags())) flags |= RefactoringDescriptor.MULTI_CHANGE;
     } catch (JavaModelException exception) {
       JavaPlugin.log(exception);
     }
     final IType declaring = fMethod.getDeclaringType();
     try {
       if (declaring.isAnonymous() || declaring.isLocal())
         flags |= JavaRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
     } catch (JavaModelException exception) {
       JavaPlugin.log(exception);
     }
     final String description =
         Messages.format(
             RefactoringCoreMessages.RenameMethodProcessor_descriptor_description_short,
             BasicElementLabels.getJavaElementName(fMethod.getElementName()));
     final String header =
         Messages.format(
             RefactoringCoreMessages.RenameMethodProcessor_descriptor_description,
             new String[] {
               JavaElementLabels.getTextLabel(fMethod, JavaElementLabels.ALL_FULLY_QUALIFIED),
               BasicElementLabels.getJavaElementName(getNewElementName())
             });
     final String comment = new JDTRefactoringDescriptorComment(project, this, header).asString();
     final RenameJavaElementDescriptor descriptor =
         RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(
             IJavaRefactorings.RENAME_METHOD);
     descriptor.setProject(project);
     descriptor.setDescription(description);
     descriptor.setComment(comment);
     descriptor.setFlags(flags);
     descriptor.setJavaElement(fMethod);
     descriptor.setNewName(getNewElementName());
     descriptor.setUpdateReferences(fUpdateReferences);
     descriptor.setKeepOriginal(fDelegateUpdating);
     descriptor.setDeprecateDelegate(fDelegateDeprecation);
     return new DynamicValidationRefactoringChange(
         descriptor,
         RefactoringCoreMessages.RenameMethodProcessor_change_name,
         list.toArray(new Change[list.size()]));
   } finally {
     monitor.done();
   }
 }
Example #6
0
 /**
  * Overridden by subclasses.
  *
  * @return return the refactoring descriptor for this refactoring
  */
 protected RenameJavaElementDescriptor createRefactoringDescriptor() {
   String project = null;
   IJavaProject javaProject = fField.getJavaProject();
   if (javaProject != null) project = javaProject.getElementName();
   int flags =
       JavaRefactoringDescriptor.JAR_MIGRATION
           | JavaRefactoringDescriptor.JAR_REFACTORING
           | RefactoringDescriptor.STRUCTURAL_CHANGE;
   try {
     if (!Flags.isPrivate(fField.getFlags())) flags |= RefactoringDescriptor.MULTI_CHANGE;
   } catch (JavaModelException exception) {
     JavaPlugin.log(exception);
   }
   final IType declaring = fField.getDeclaringType();
   try {
     if (declaring.isAnonymous() || declaring.isLocal())
       flags |= JavaRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
   } catch (JavaModelException exception) {
     JavaPlugin.log(exception);
   }
   final String description =
       Messages.format(
           RefactoringCoreMessages.RenameFieldRefactoring_descriptor_description_short,
           BasicElementLabels.getJavaElementName(fField.getElementName()));
   final String header =
       Messages.format(
           RefactoringCoreMessages.RenameFieldProcessor_descriptor_description,
           new String[] {
             BasicElementLabels.getJavaElementName(fField.getElementName()),
             JavaElementLabels.getElementLabel(
                 fField.getParent(), JavaElementLabels.ALL_FULLY_QUALIFIED),
             getNewElementName()
           });
   final JDTRefactoringDescriptorComment comment =
       new JDTRefactoringDescriptorComment(project, this, header);
   if (fRenameGetter)
     comment.addSetting(RefactoringCoreMessages.RenameFieldRefactoring_setting_rename_getter);
   if (fRenameSetter)
     comment.addSetting(RefactoringCoreMessages.RenameFieldRefactoring_setting_rename_settter);
   final RenameJavaElementDescriptor descriptor =
       RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(
           IJavaRefactorings.RENAME_FIELD);
   descriptor.setProject(project);
   descriptor.setDescription(description);
   descriptor.setComment(comment.asString());
   descriptor.setFlags(flags);
   descriptor.setJavaElement(fField);
   descriptor.setNewName(getNewElementName());
   descriptor.setUpdateReferences(fUpdateReferences);
   descriptor.setUpdateTextualOccurrences(fUpdateTextualMatches);
   descriptor.setRenameGetters(fRenameGetter);
   descriptor.setRenameSetters(fRenameSetter);
   descriptor.setKeepOriginal(fDelegateUpdating);
   descriptor.setDeprecateDelegate(fDelegateDeprecation);
   return descriptor;
 }
  /**
   * Utility method to inspect a selection to find a Java element.
   *
   * @param selection the selection to be inspected
   * @return a Java element to be used as the initial selection, or <code>null</code>, if no Java
   *     element exists in the given selection
   */
  protected IJavaElement getInitialJavaElement(IStructuredSelection selection) {
    IJavaElement jelem = null;
    if (selection != null && !selection.isEmpty()) {
      Object selectedElement = selection.getFirstElement();
      if (selectedElement instanceof IAdaptable) {
        IAdaptable adaptable = (IAdaptable) selectedElement;

        jelem = adaptable.getAdapter(IJavaElement.class);
        if (jelem == null || !jelem.exists()) {
          jelem = null;
          IResource resource = adaptable.getAdapter(IResource.class);
          if (resource != null && resource.getType() != IResource.ROOT) {
            while (jelem == null && resource.getType() != IResource.PROJECT) {
              resource = resource.getParent();
              jelem = resource.getAdapter(IJavaElement.class);
            }
            if (jelem == null) {
              jelem = JavaCore.create(resource); // java project
            }
          }
        }
      }
    }
    if (jelem == null) {
      IWorkbenchPart part = JavaPlugin.getActivePage().getActivePart();
      if (part instanceof ContentOutline) {
        part = JavaPlugin.getActivePage().getActiveEditor();
      }

      if (part instanceof IViewPartInputProvider) {
        Object elem = ((IViewPartInputProvider) part).getViewPartInput();
        if (elem instanceof IJavaElement) {
          jelem = (IJavaElement) elem;
        }
      }
    }

    if (jelem == null || jelem.getElementType() == IJavaElement.JAVA_MODEL) {
      try {
        IJavaProject[] projects = JavaCore.create(getWorkspaceRoot()).getJavaProjects();
        if (projects.length == 1) {
          IClasspathEntry[] rawClasspath = projects[0].getRawClasspath();
          for (int i = 0; i < rawClasspath.length; i++) {
            if (rawClasspath[i].getEntryKind()
                == IClasspathEntry.CPE_SOURCE) { // add only if the project contains a source folder
              jelem = projects[0];
              break;
            }
          }
        }
      } catch (JavaModelException e) {
        JavaPlugin.log(e);
      }
    }
    return jelem;
  }
Example #8
0
  /**
   * 將所要變更的內容寫回Edit中 (New)
   *
   * @param msg
   */
  protected void applyChange(ASTRewrite rewrite) {
    try {
      // 參考org.eclipse.jdt.internal.ui.text.correction.CorrectionMarkerResolutionGenerator run
      // org.eclipse.jdt.internal.ui.text.correction.ChangeCorrectionProposal apply與performChange
      ICompilationUnit cu = (ICompilationUnit) actOpenable;
      IEditorPart part = EditorUtility.isOpenInEditor(cu);
      IEditorInput input = part.getEditorInput();
      IDocument doc =
          JavaPlugin.getDefault().getCompilationUnitDocumentProvider().getDocument(input);

      performChange(JavaPlugin.getActivePage().getActiveEditor(), doc, rewrite);
    } catch (CoreException e) {
      logger.error("[Core Exception] EXCEPTION ", e);
    }
  }
  private static boolean hasFatalError(CompilationUnit compilationUnit) {
    try {
      if (!((ICompilationUnit) compilationUnit.getJavaElement()).isStructureKnown()) return true;
    } catch (JavaModelException e) {
      JavaPlugin.log(e);
      return true;
    }

    IProblem[] problems = compilationUnit.getProblems();
    for (int i = 0; i < problems.length; i++) {
      if (problems[i].isError()) {
        if (!(problems[i] instanceof CategorizedProblem)) return true;

        CategorizedProblem categorizedProblem = (CategorizedProblem) problems[i];
        int categoryID = categorizedProblem.getCategoryID();

        if (categoryID == CategorizedProblem.CAT_BUILDPATH) return true;
        if (categoryID == CategorizedProblem.CAT_SYNTAX) return true;
        if (categoryID == CategorizedProblem.CAT_IMPORT) return true;
        if (categoryID == CategorizedProblem.CAT_TYPE) return true;
        if (categoryID == CategorizedProblem.CAT_MEMBER) return true;
        if (categoryID == CategorizedProblem.CAT_INTERNAL) return true;
      }
    }

    return false;
  }
 /*
  * @see org.eclipse.jdt.core.IElementChangedListener#elementChanged(org.eclipse.jdt.core.ElementChangedEvent)
  */
 public void elementChanged(ElementChangedEvent event) {
   try {
     processDelta(event.getDelta());
   } catch (JavaModelException e) {
     JavaPlugin.log(e);
   }
 }
 /*
  * @see ViewerFilter#select
  */
 @Override
 public boolean select(Viewer viewer, Object parent, Object element) {
   if (element instanceof IFile) {
     if (fExcludes != null && fExcludes.contains(element)) {
       return false;
     }
     return isArchivePath(((IFile) element).getFullPath(), fAllowAllArchives);
   } else if (element instanceof IContainer) { // IProject, IFolder
     if (!fRecursive) {
       return true;
     }
     // ignore closed projects
     if (element instanceof IProject && !((IProject) element).isOpen()) return false;
     try {
       IResource[] resources = ((IContainer) element).members();
       for (int i = 0; i < resources.length; i++) {
         // recursive! Only show containers that contain an archive
         if (select(viewer, parent, resources[i])) {
           return true;
         }
       }
     } catch (CoreException e) {
       JavaPlugin.log(e.getStatus());
     }
   }
   return false;
 }
 public WorkingSetGroup() {
   String[] workingSetIds = new String[] {IWorkingSetIDs_JAVA, IWorkingSetIDs_RESOURCE};
   fWorkingSetBlock =
       new WorkingSetConfigurationBlock(
           workingSetIds, JavaPlugin.getDefault().getDialogSettings());
   // fWorkingSetBlock.setDialogMessage(NewWizardMessages.NewJavaProjectWizardPageOne_WorkingSetSelection_message);
 }
  private void storeSelectionValue(ComboDialogField combo, String preferenceKey) {
    int index = combo.getSelectionIndex();
    if (index == -1) return;

    String item = combo.getItems()[index];
    JavaPlugin.getDefault().getDialogSettings().put(preferenceKey, item);
  }
  private void doPasteWithImportsOperation() {
    ITextEditor editor = getTextEditor();
    IJavaElement inputElement = JavaUI.getEditorInputTypeRoot(editor.getEditorInput());

    Clipboard clipboard = new Clipboard(getDisplay());
    try {
      ClipboardData importsData = (ClipboardData) clipboard.getContents(fgTransferInstance);
      if (importsData != null
          && inputElement instanceof ICompilationUnit
          && !importsData.isFromSame(inputElement)) {
        // combine operation and adding of imports
        IRewriteTarget target = (IRewriteTarget) editor.getAdapter(IRewriteTarget.class);
        if (target != null) {
          target.beginCompoundChange();
        }
        try {
          fOperationTarget.doOperation(fOperationCode);
          addImports((ICompilationUnit) inputElement, importsData);
        } catch (CoreException e) {
          JavaPlugin.log(e);
        } finally {
          if (target != null) {
            target.endCompoundChange();
          }
        }
      } else {
        fOperationTarget.doOperation(fOperationCode);
      }
    } finally {
      clipboard.dispose();
    }
  }
  /**
   * Evaluates a 'java' template in the context of a compilation unit
   *
   * @param template the template to be evaluated
   * @param compilationUnit the compilation unit in which to evaluate the template
   * @param position the position inside the compilation unit for which to evaluate the template
   * @return the evaluated template
   * @throws CoreException in case the template is of an unknown context type
   * @throws BadLocationException in case the position is invalid in the compilation unit
   * @throws TemplateException in case the evaluation fails
   */
  public static String evaluateTemplate(
      Template template, ICompilationUnit compilationUnit, int position)
      throws CoreException, BadLocationException, TemplateException {

    TemplateContextType contextType =
        JavaPlugin.getDefault()
            .getTemplateContextRegistry()
            .getContextType(template.getContextTypeId());
    if (!(contextType instanceof CompilationUnitContextType))
      throw new CoreException(
          new Status(
              IStatus.ERROR,
              JavaUI.ID_PLUGIN,
              IStatus.ERROR,
              JavaTemplateMessages.JavaContext_error_message,
              null));

    IDocument document = new Document();
    if (compilationUnit != null && compilationUnit.exists())
      document.set(compilationUnit.getSource());

    CompilationUnitContext context =
        ((CompilationUnitContextType) contextType)
            .createContext(document, position, 0, compilationUnit);
    context.setForceEvaluation(true);

    TemplateBuffer buffer = context.evaluate(template);
    if (buffer == null) return null;
    return buffer.getString();
  }
  /**
   * Returns the reason for why the Javadoc of the Java element could not be retrieved.
   *
   * @param element whose Javadoc could not be retrieved
   * @param root the root of the Java element
   * @return the String message for why the Javadoc could not be retrieved for the Java element or
   *     <code>null</code> if the Java element is from a source container
   * @since 3.9
   */
  public static String getExplanationForMissingJavadoc(
      IJavaElement element, IPackageFragmentRoot root) {
    String message = null;
    try {
      boolean isBinary = (root.exists() && root.getKind() == IPackageFragmentRoot.K_BINARY);
      if (isBinary) {
        boolean hasAttachedJavadoc = JavaDocLocations.getJavadocBaseLocation(element) != null;
        boolean hasAttachedSource = root.getSourceAttachmentPath() != null;
        IOpenable openable = element.getOpenable();
        boolean hasSource = openable.getBuffer() != null;

        // Provide hint why there's no Java doc
        if (!hasAttachedSource && !hasAttachedJavadoc)
          message = CorextMessages.JavaDocLocations_noAttachments;
        else if (!hasAttachedJavadoc && !hasSource)
          message = CorextMessages.JavaDocLocations_noAttachedJavadoc;
        else if (!hasAttachedSource) message = CorextMessages.JavaDocLocations_noAttachedSource;
        else if (!hasSource) message = CorextMessages.JavaDocLocations_noInformation;
      }
    } catch (JavaModelException e) {
      message = CorextMessages.JavaDocLocations_error_gettingJavadoc;
      JavaPlugin.log(e);
    }
    return message;
  }
 /**
  * Initializes the source folder field with a valid package fragment root. The package fragment
  * root is computed from the given Java element.
  *
  * @param elem the Java element used to compute the initial package fragment root used as the
  *     source folder
  */
 protected void initContainerPage(IJavaElement elem) {
   IPackageFragmentRoot initRoot = null;
   if (elem != null) {
     initRoot = JavaModelUtil.getPackageFragmentRoot(elem);
     try {
       if (initRoot == null || initRoot.getKind() != IPackageFragmentRoot.K_SOURCE) {
         IJavaProject jproject = elem.getJavaProject();
         if (jproject != null) {
           initRoot = null;
           if (jproject.exists()) {
             IPackageFragmentRoot[] roots = jproject.getPackageFragmentRoots();
             for (int i = 0; i < roots.length; i++) {
               if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE) {
                 initRoot = roots[i];
                 break;
               }
             }
           }
           if (initRoot == null) {
             initRoot = jproject.getPackageFragmentRoot(jproject.getResource());
           }
         }
       }
     } catch (JavaModelException e) {
       JavaPlugin.log(e);
     }
   }
   setPackageFragmentRoot(initRoot, true);
 }
  /**
   * Assert NO proposals on the primitive leaf type of an array type.
   *
   * @throws Exception
   */
  public void testAnnotateParameter_ArrayOfPrimitive() throws Exception {

    String X_PATH = "pack/age/X";
    String[] pathAndContents =
        new String[] {
          X_PATH + ".java",
          "package pack.age;\n"
              + "import java.util.List;\n"
              + "public interface X {\n"
              + "    public String test(int[] ints, List<String> list);\n"
              + "}\n"
        };
    addLibrary(
        fJProject1,
        "lib.jar",
        "lib.zip",
        pathAndContents,
        ANNOTATION_PATH,
        JavaCore.VERSION_1_8,
        null);
    IType type = fJProject1.findType(X_PATH.replace('/', '.'));
    JavaEditor javaEditor = (JavaEditor) JavaUI.openInEditor(type);

    try {
      int offset = pathAndContents[1].indexOf("int[]");

      List<ICompletionProposal> list = collectAnnotateProposals(javaEditor, offset);

      assertNumberOfProposals(list, 0);
    } finally {
      JavaPlugin.getActivePage().closeAllEditors(false);
    }
  }
  public JavaEditor openJavaEditor(IJavaElement javaElement) {
    IEditorPart part = EditorUtility.isOpenInEditor(javaElement);
    if (part == null) {
      try {
        part = JavaUI.openInEditor(javaElement);
      } catch (PartInitException e) {
        // ignore
      } catch (JavaModelException e) {
        // ignore
      }
    }

    IWorkbenchPage page = JavaPlugin.getActivePage();
    if (page != null && part != null) {
      page.bringToTop(part);
    }
    if (part != null) {
      part.setFocus();
    }
    if (part instanceof JavaEditor) {
      return (JavaEditor) part;
    }

    return null;
  }
  private static IJavaProject[] getProjectSearchOrder(String projectName) {

    ArrayList<String> projectNames = new ArrayList<String>();
    projectNames.add(projectName);

    int nextProject = 0;
    while (nextProject < projectNames.size()) {
      String nextProjectName = projectNames.get(nextProject);
      IJavaProject jproject = getJavaProject(nextProjectName);

      if (jproject != null) {
        try {
          String[] childProjectNames = jproject.getRequiredProjectNames();
          for (int i = 0; i < childProjectNames.length; i++) {
            if (!projectNames.contains(childProjectNames[i])) {
              projectNames.add(childProjectNames[i]);
            }
          }
        } catch (JavaModelException e) {
          JavaPlugin.log(e);
        }
      }
      nextProject += 1;
    }

    ArrayList<IJavaProject> result = new ArrayList<IJavaProject>();
    for (int i = 0, size = projectNames.size(); i < size; i++) {
      String name = projectNames.get(i);
      IJavaProject project = getJavaProject(name);
      if (project != null) result.add(project);
    }

    return result.toArray(new IJavaProject[result.size()]);
  }
  private IJavaProject chooseProject() {
    IJavaProject[] projects;
    try {
      projects = JavaCore.create(Util.getWorkspaceRoot()).getJavaProjects();
    } catch (JavaModelException e) {
      JavaPlugin.log(e);
      projects = new IJavaProject[0];
    }

    // Filter the list to only show GWT projects
    List<IJavaProject> gwtProjects = new ArrayList<IJavaProject>();
    for (IJavaProject project : projects) {
      if (GWTNature.isGWTProject(project.getProject())) {
        gwtProjects.add(project);
      }
    }

    // TODO: refactor this into utility function
    ILabelProvider labelProvider =
        new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT);
    ElementListSelectionDialog dialog = new ElementListSelectionDialog(getShell(), labelProvider);
    dialog.setTitle("Project Selection");
    dialog.setMessage("Choose a project for the new HTML page");
    dialog.setElements(gwtProjects.toArray(new IJavaProject[0]));
    dialog.setInitialSelections(new Object[] {getJavaProject()});
    dialog.setHelpAvailable(false);
    if (dialog.open() == Window.OK) {
      return (IJavaProject) dialog.getFirstResult();
    }
    return null;
  }
  public void testSearchAfterDeletion()
      throws JavaModelException, PartInitException, IOException, CoreException {
    view = (ActiveSearchView) JavaPlugin.getActivePage().showView(ActiveSearchView.ID);
    if (view != null) {
      assertEquals(0, view.getViewer().getTree().getItemCount());

      IWorkbenchPart part =
          PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart();
      IMethod m1 = type1.createMethod("void m1() {\n m2() \n}", null, true, null);
      IMethod m2 = type1.createMethod("void m2() { }", null, true, null);
      StructuredSelection sm2 = new StructuredSelection(m2);
      monitor.selectionChanged(part, sm2);
      IInteractionElement node =
          manager.processInteractionEvent(
              mockInterestContribution(m2.getHandleIdentifier(), scaling.getLandmark()));
      assertEquals(1, ContextCore.getContextManager().getActiveLandmarks().size());

      assertEquals(1, search(2, node).size());

      m1.delete(true, null);
      assertFalse(m1.exists());

      assertEquals(0, search(2, node).size());
    }
  }
  public void testViewRecursion() throws JavaModelException, PartInitException {
    view = (ActiveSearchView) JavaPlugin.getActivePage().showView(ActiveSearchView.ID);
    ActiveSearchView.getFromActivePerspective().setSyncExecForTesting(false);

    for (AbstractRelationProvider provider :
        ContextCorePlugin.getDefault().getRelationProviders()) {
      assertTrue(provider.isEnabled());
    }
    assertEquals(0, view.getViewer().getTree().getItemCount());

    IWorkbenchPart part =
        PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart();
    IMethod m1 = type1.createMethod("void m1() {\n m1(); \n}", null, true, null);
    StructuredSelection sm1 = new StructuredSelection(m1);
    monitor.selectionChanged(part, sm1);
    IInteractionElement node =
        manager.processInteractionEvent(
            mockInterestContribution(m1.getHandleIdentifier(), scaling.getLandmark()));

    assertEquals(1, ContextCore.getContextManager().getActiveLandmarks().size());

    assertEquals(1, search(2, node).size());

    List<TreeItem> collectedItems = new ArrayList<TreeItem>();
    UiTestUtil.collectTreeItemsInView(view.getViewer().getTree().getItems(), collectedItems);

    // just make sure that the view didn't blow up.
    assertEquals(1, collectedItems.size());
    monitor.selectionChanged(part, sm1);
    manager.processInteractionEvent(
        mockInterestContribution(m1.getHandleIdentifier(), -scaling.getLandmark()));
  }
  /*
   * @see org.eclipse.swt.dnd.DragSourceListener#dragStart
   */
  @Override
  public void dragStart(DragSourceEvent event) {
    fEditorInputDatas = new ArrayList<EditorInputData>();

    ISelection selection = fProvider.getSelection();
    if (selection instanceof IStructuredSelection) {
      IStructuredSelection structuredSelection = (IStructuredSelection) selection;
      for (Iterator<?> iter = structuredSelection.iterator(); iter.hasNext(); ) {
        Object element = iter.next();
        IEditorInput editorInput = EditorUtility.getEditorInput(element);
        if (editorInput != null && editorInput.getPersistable() != null) {
          try {
            String editorId = EditorUtility.getEditorID(editorInput);
            // see org.eclipse.ui.internal.ide.EditorAreaDropAdapter.openNonExternalEditor(..):
            IEditorRegistry editorReg = PlatformUI.getWorkbench().getEditorRegistry();
            IEditorDescriptor editorDesc = editorReg.findEditor(editorId);
            if (editorDesc != null && !editorDesc.isOpenExternal()) {
              fEditorInputDatas.add(
                  EditorInputTransfer.createEditorInputData(editorId, editorInput));
            }
          } catch (PartInitException e) {
            JavaPlugin.log(e);
          }
        }
      }
    }

    event.doit = fEditorInputDatas.size() > 0;
  }
  /**
   * @param input the editor input
   * @param offset the offset in the file
   * @return the element at the given offset
   */
  protected IJavaElement getElementAt(IEditorInput input, int offset) {
    if (input instanceof IClassFileEditorInput) {
      try {
        return ((IClassFileEditorInput) input).getClassFile().getElementAt(offset);
      } catch (JavaModelException ex) {
        return null;
      }
    }

    IWorkingCopyManager manager = JavaPlugin.getDefault().getWorkingCopyManager();
    ICompilationUnit unit = manager.getWorkingCopy(input);
    if (unit != null)
      try {
        if (unit.isConsistent()) return unit.getElementAt(offset);
        else {
          /*
           * XXX: We should set the selection later when the
           *      CU is reconciled.
           *      see https://bugs.eclipse.org/bugs/show_bug.cgi?id=51290
           */
        }
      } catch (JavaModelException ex) {
        // fall through
      }
    return null;
  }
 private int getLastSelectedJREKind() {
   int kind = PROJECT_RE;
   IDialogSettings settings = JavaPlugin.getDefault().getDialogSettings();
   if (settings.get(LAST_SELECTED_JRE_KIND2_KEY) != null) {
     kind = settings.getInt(LAST_SELECTED_JRE_KIND2_KEY);
   }
   return kind;
 }
 /**
  * Sets the Javadoc location for an archive with the given path.
  *
  * @param project the Java project
  * @param url the Javadoc location
  */
 public static void setProjectJavadocLocation(IJavaProject project, URL url) {
   try {
     String location = url != null ? url.toExternalForm() : null;
     setProjectJavadocLocation(project, location);
   } catch (CoreException e) {
     JavaPlugin.log(e);
   }
 }
 boolean addMatch(Match match, IMatchPresentation participant) {
   Object element = match.getElement();
   if (fElementsToParticipants.get(element) != null) {
     // TODO must access the participant id / label to properly report the error.
     JavaPlugin.log(
         new Status(
             IStatus.WARNING,
             JavaPlugin.getPluginId(),
             0,
             "A second search participant was found for an element",
             null)); //$NON-NLS-1$
     return false;
   }
   fElementsToParticipants.put(element, participant);
   addMatch(match);
   return true;
 }
  public CodeTemplatePreferencePage() {
    setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
    // setDescription(PreferencesMessages.getString("CodeTemplatesPreferencePage.description"));
    // //$NON-NLS-1$

    // only used when page is shown programatically
    setTitle(PreferencesMessages.CodeTemplatesPreferencePage_title);
  }
 /**
  * Returns the {@link File} of a <code>file:</code> URL. This method tries to recover from bad
  * URLs, e.g. the unencoded form we used to use in persistent storage.
  *
  * @param url a <code>file:</code> URL
  * @return the file
  * @since 3.9
  */
 public static File toFile(URL url) {
   try {
     return URIUtil.toFile(url.toURI());
   } catch (URISyntaxException e) {
     JavaPlugin.log(e);
     return new File(url.getFile());
   }
 }