/** @see MultiOperation */
  protected void verify(IJavaElement element) throws JavaModelException {
    if (element == null || !element.exists())
      error(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, element);

    if (element.isReadOnly() && (isRename() || isMove()))
      error(IJavaModelStatusConstants.READ_ONLY, element);

    IResource resource = ((JavaElement) element).resource();
    if (resource instanceof IFolder) {
      if (resource.isLinked()) {
        error(IJavaModelStatusConstants.INVALID_RESOURCE, element);
      }
    }

    int elementType = element.getElementType();

    if (elementType == IJavaElement.COMPILATION_UNIT) {
      org.eclipse.jdt.internal.core.CompilationUnit compilationUnit =
          (org.eclipse.jdt.internal.core.CompilationUnit) element;
      if (isMove() && compilationUnit.isWorkingCopy() && !compilationUnit.isPrimary())
        error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element);
    } else if (elementType != IJavaElement.PACKAGE_FRAGMENT) {
      error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element);
    }

    JavaElement dest = (JavaElement) getDestinationParent(element);
    verifyDestination(element, dest);
    if (this.renamings != null) {
      verifyRenaming(element);
    }
  }
 @Override
 public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException {
   pm.beginTask("", 2); // $NON-NLS-1$
   RefactoringStatus result;
   try {
     result = new RefactoringStatus();
     IJavaElement element = (IJavaElement) getModifiedElement();
     // don't check for read-only since we don't go through
     // validate edit.
     result.merge(super.isValid(new SubProgressMonitor(pm, 1)));
     if (result.hasFatalError()) return result;
     if (element != null && element.exists() && element instanceof IPackageFragment) {
       IPackageFragment pack = (IPackageFragment) element;
       if (fRenameSubpackages) {
         IPackageFragment[] allPackages = JavaElementUtil.getPackageAndSubpackages(pack);
         SubProgressMonitor subPm = new SubProgressMonitor(pm, 1);
         subPm.beginTask("", allPackages.length); // $NON-NLS-1$
         for (int i = 0; i < allPackages.length; i++) {
           // don't check for read-only since we don't go through
           // validate edit.
           checkIfModifiable(result, allPackages[i].getResource(), VALIDATE_NOT_DIRTY);
           if (result.hasFatalError()) return result;
           isValid(result, allPackages[i], new SubProgressMonitor(subPm, 1));
         }
       } else {
         isValid(result, pack, new SubProgressMonitor(pm, 1));
       }
     }
   } finally {
     pm.done();
   }
   return result;
 }
 private long getContainerTimestamp(TypeNameMatch match) {
   try {
     IType type = match.getType();
     IResource resource = type.getResource();
     if (resource != null) {
       URI location = resource.getLocationURI();
       if (location != null) {
         IFileInfo info = EFS.getStore(location).fetchInfo();
         if (info.exists()) {
           // The element could be removed from the build path. So check
           // if the Java element still exists.
           IJavaElement element = JavaCore.create(resource);
           if (element != null && element.exists()) return info.getLastModified();
         }
       }
     } else { // external JAR
       IPackageFragmentRoot root = match.getPackageFragmentRoot();
       if (root.exists()) {
         IFileInfo info = EFS.getLocalFileSystem().getStore(root.getPath()).fetchInfo();
         if (info.exists()) {
           return info.getLastModified();
         }
       }
     }
   } catch (CoreException e) {
     // Fall through
   }
   return IResource.NULL_STAMP;
 }
  private ISelection restoreSelectionState(IMemento memento) {
    if (memento == null) return null;

    IMemento childMem;
    childMem = memento.getChild(TAG_SELECTED_ELEMENTS);
    if (childMem != null) {
      ArrayList<Object> list = new ArrayList<>();
      IMemento[] elementMem = childMem.getChildren(TAG_SELECTED_ELEMENT);
      for (int i = 0; i < elementMem.length; i++) {
        String javaElementHandle = elementMem[i].getString(TAG_SELECTED_ELEMENT_PATH);
        if (javaElementHandle == null) {
          // logical package
          IMemento[] packagesMem = elementMem[i].getChildren(TAG_LOGICAL_PACKAGE);
          LogicalPackage lp = null;
          for (int j = 0; j < packagesMem.length; j++) {
            javaElementHandle = packagesMem[j].getString(TAG_SELECTED_ELEMENT_PATH);
            Object pack = JavaCore.create(javaElementHandle);
            if (pack instanceof IPackageFragment && ((IPackageFragment) pack).exists()) {
              if (lp == null) lp = new LogicalPackage((IPackageFragment) pack);
              else lp.add((IPackageFragment) pack);
            }
          }
          if (lp != null) list.add(lp);
        } else {
          IJavaElement element = JavaCore.create(javaElementHandle);
          if (element != null && element.exists()) list.add(element);
        }
      }
      return new StructuredSelection(list);
    }
    return null;
  }
  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 = (IJavaElement) adaptable.getAdapter(IJavaElement.class);
        if (jelem == null || !jelem.exists()) {
          jelem = null;
          IResource resource = (IResource) adaptable.getAdapter(IResource.class);
          if (resource != null && resource.getType() != IResource.ROOT) {
            while (jelem == null && resource.getType() != IResource.PROJECT) {
              resource = resource.getParent();
              jelem = (IJavaElement) resource.getAdapter(IJavaElement.class);
            }
            if (jelem == null) {
              jelem = JavaCore.create(resource); // java project
            }
          }
        }
      }
    }

    return jelem;
  }
  void adjustInputAndSetSelection(Object o) {
    if (!(o instanceof IJavaElement)) {
      if (o == null) setInput(null);
      setSelection(StructuredSelection.EMPTY, true);
      return;
    }

    IJavaElement je = (IJavaElement) o;
    IJavaElement elementToSelect = findElementToSelect(je);
    IJavaElement newInput = findInputForJavaElement(je);
    IJavaElement oldInput = null;
    if (getInput() instanceof IJavaElement) oldInput = (IJavaElement) getInput();

    if (elementToSelect == null
        && !isValidInput(newInput)
        && (newInput == null && !isAncestorOf(je, oldInput)))
      // Clear input
      setInput(null);
    else if (mustSetNewInput(elementToSelect, oldInput, newInput)) {
      // Adjust input to selection
      setInput(newInput);
    }

    if (elementToSelect != null && elementToSelect.exists())
      setSelection(new StructuredSelection(elementToSelect), true);
    else setSelection(StructuredSelection.EMPTY, true);
  }
Esempio n. 7
0
  private void addTextMatches(IResource resource, IProgressMonitor pm) throws JavaModelException {
    try {
      String task = RefactoringCoreMessages.TextMatchUpdater_searching + resource.getFullPath();
      if (resource instanceof IFile) {
        IJavaElement element = JavaCore.create(resource);
        // don't start pm task (flickering label updates; finally {pm.done()} is enough)
        if (!(element instanceof ICompilationUnit)) return;
        if (!element.exists()) return;
        if (!fScope.encloses(element)) return;
        addCuTextMatches((ICompilationUnit) element);

      } else if (resource instanceof IContainer) {
        IResource[] members = ((IContainer) resource).members();
        pm.beginTask(task, members.length);
        pm.subTask(task);
        for (int i = 0; i < members.length; i++) {
          if (pm.isCanceled()) throw new OperationCanceledException();

          addTextMatches(members[i], new SubProgressMonitor(pm, 1));
        }
      }
    } catch (JavaModelException e) {
      throw e;
    } catch (CoreException e) {
      throw new JavaModelException(e);
    } finally {
      pm.done();
    }
  }
  /**
   * 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;
  }
Esempio n. 9
0
 private RefactoringStatus initialize(JavaRefactoringArguments extended) {
   final String handle = extended.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT);
   if (handle != null) {
     final IJavaElement element =
         JavaRefactoringDescriptorUtil.handleToElement(extended.getProject(), handle, false);
     if (element == null || !element.exists() || element.getElementType() != IJavaElement.FIELD)
       return JavaRefactoringDescriptorUtil.createInputFatalStatus(
           element, getProcessorName(), IJavaRefactorings.RENAME_FIELD);
     else fField = (IField) element;
   } else
     return RefactoringStatus.createFatalErrorStatus(
         Messages.format(
             RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
             JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT));
   final String name = extended.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_NAME);
   if (name != null && !"".equals(name)) // $NON-NLS-1$
   setNewElementName(name);
   else
     return RefactoringStatus.createFatalErrorStatus(
         Messages.format(
             RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
             JavaRefactoringDescriptorUtil.ATTRIBUTE_NAME));
   final String references =
       extended.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_REFERENCES);
   if (references != null) {
     fUpdateReferences = Boolean.valueOf(references).booleanValue();
   } else
     return RefactoringStatus.createFatalErrorStatus(
         Messages.format(
             RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
             JavaRefactoringDescriptorUtil.ATTRIBUTE_REFERENCES));
   final String matches = extended.getAttribute(ATTRIBUTE_TEXTUAL_MATCHES);
   if (matches != null) {
     fUpdateTextualMatches = Boolean.valueOf(matches).booleanValue();
   } else
     return RefactoringStatus.createFatalErrorStatus(
         Messages.format(
             RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
             ATTRIBUTE_TEXTUAL_MATCHES));
   final String getters = extended.getAttribute(ATTRIBUTE_RENAME_GETTER);
   if (getters != null) fRenameGetter = Boolean.valueOf(getters).booleanValue();
   else fRenameGetter = false;
   final String setters = extended.getAttribute(ATTRIBUTE_RENAME_SETTER);
   if (setters != null) fRenameSetter = Boolean.valueOf(setters).booleanValue();
   else fRenameSetter = false;
   final String delegate = extended.getAttribute(ATTRIBUTE_DELEGATE);
   if (delegate != null) {
     fDelegateUpdating = Boolean.valueOf(delegate).booleanValue();
   } else fDelegateUpdating = false;
   final String deprecate = extended.getAttribute(ATTRIBUTE_DEPRECATE);
   if (deprecate != null) {
     fDelegateDeprecation = Boolean.valueOf(deprecate).booleanValue();
   } else fDelegateDeprecation = false;
   return new RefactoringStatus();
 }
  private void validatePropertyPackage() {

    IPackageFragmentRoot root = fResourceBundlePackage.getSelectedFragmentRoot();
    if ((root == null) || !root.exists()) {
      setInvalid(
          IDX_BUNDLE_PACKAGE,
          NLSUIMessages.NLSAccessorConfigurationDialog_property_package_root_invalid);
      return;
    }

    IPackageFragment fragment = fResourceBundlePackage.getSelected();
    if ((fragment == null) || !fragment.exists()) {
      setInvalid(
          IDX_BUNDLE_PACKAGE,
          NLSUIMessages.NLSAccessorConfigurationDialog_property_package_invalid);
      return;
    }

    String pkgName = fragment.getElementName();

    IStatus status = JavaConventionsUtil.validatePackageName(pkgName, root);
    if ((pkgName.length() > 0) && (status.getSeverity() == IStatus.ERROR)) {
      setInvalid(IDX_BUNDLE_PACKAGE, status.getMessage());
      return;
    }

    IPath pkgPath = new Path(pkgName.replace('.', IPath.SEPARATOR)).makeRelative();

    IJavaProject project = fRefactoring.getCu().getJavaProject();
    try {
      IJavaElement element = project.findElement(pkgPath);
      if (element == null || !element.exists()) {
        setInvalid(IDX_BUNDLE_PACKAGE, NLSUIMessages.NLSAccessorConfigurationDialog_must_exist);
        return;
      }
      IPackageFragment fPkgFragment = (IPackageFragment) element;
      if (!PackageBrowseAdapter.canAddPackage(fPkgFragment)) {
        setInvalid(
            IDX_BUNDLE_PACKAGE, NLSUIMessages.NLSAccessorConfigurationDialog_incorrect_package);
        return;
      }
      if (!PackageBrowseAdapter.canAddPackageRoot(
          (IPackageFragmentRoot) fPkgFragment.getParent())) {
        setInvalid(
            IDX_BUNDLE_PACKAGE, NLSUIMessages.NLSAccessorConfigurationDialog_incorrect_package);
        return;
      }
    } catch (JavaModelException e) {
      setInvalid(IDX_BUNDLE_PACKAGE, e.getStatus().getMessage());
      return;
    }

    setValid(IDX_BUNDLE_PACKAGE);
  }
 private void checkElementExistence(IWorkingSet workingSet) {
   List<IAdaptable> elements = new ArrayList<>(Arrays.asList(workingSet.getElements()));
   boolean changed = false;
   for (Iterator<IAdaptable> iter = elements.iterator(); iter.hasNext(); ) {
     IAdaptable element = iter.next();
     boolean remove = false;
     if (element instanceof IJavaElement) {
       IJavaElement jElement = (IJavaElement) element;
       // If we have directly a project then remove it when it
       // doesn't exist anymore. However if we have a sub element
       // under a project only remove the element if the parent
       // project is open. Otherwise we would remove all elements
       // in closed projects.
       if (jElement instanceof IJavaProject) {
         remove = !jElement.exists();
       } else {
         final IJavaProject javaProject = jElement.getJavaProject();
         final boolean isProjectOpen =
             javaProject != null ? javaProject.getProject().isOpen() : true;
         remove = isProjectOpen && !jElement.exists();
       }
     } else if (element instanceof IResource) {
       IResource resource = (IResource) element;
       // See comments above
       if (resource instanceof IProject) {
         remove = !resource.exists();
       } else {
         IProject project = resource.getProject();
         remove = (project != null ? project.isOpen() : true) && !resource.exists();
       }
     }
     if (remove) {
       iter.remove();
       changed = true;
     }
   }
   if (changed) {
     workingSet.setElements(elements.toArray(new IAdaptable[elements.size()]));
   }
 }
Esempio n. 12
0
 /**
  * Method runs the tests defined from extension points for Run As... and Debug As... menu items.
  * Currently this test optimistically considers everything not a source file. In this context we
  * consider an optimistic approach to mean that the test will always return true.
  *
  * <p>There are many reasons for the optimistic choice some of them are outlined below.
  *
  * <ul>
  *   <li>Performance (in terms of time needed to display menu) cannot be preserved. To know what
  *       to allow in any one of the menus we would have to search all of the children of the
  *       container to determine what it contains and what can be launched by what.
  *   <li>If inspection of children of containers were done, a user might want to choose a
  *       different launch type, even though our tests filter it out.
  * </ul>
  *
  * @see org.eclipse.core.expressions.IPropertyTester#test(java.lang.Object, java.lang.String,
  *     java.lang.Object[], java.lang.Object)
  * @since 3.2
  * @return true if the specified tests pass, or the context is a container, false otherwise
  */
 public boolean test(Object receiver, String property, Object[] args, Object expectedValue) {
   if (PROPERTY_IS_CONTAINER.equals(property)) {
     if (receiver instanceof IAdaptable) {
       IResource resource = (IResource) ((IAdaptable) receiver).getAdapter(IResource.class);
       if (resource != null) {
         return resource instanceof IContainer;
       }
     }
     return false;
   }
   IJavaElement element = null;
   if (receiver instanceof IAdaptable) {
     element = (IJavaElement) ((IAdaptable) receiver).getAdapter(IJavaElement.class);
     if (element != null) {
       if (!element.exists()) {
         return false;
       }
     }
   }
   if (PROPERTY_HAS_MAIN.equals(property)) {
     return hasMain(element);
   }
   if (PROPERTY_HAS_METHOD.equals(property)) {
     return hasMethod(element, args);
   }
   if (PROPERTY_HAS_METHOD_WITH_ANNOTATION.equals(property)) {
     return hasMethodWithAnnotation(element, args);
   }
   if (PROPERTY_HAS_TYPE_WITH_ANNOTATION.equals(property)) {
     return hasTypeWithAnnotation(element, (String) args[0]);
   }
   if (PROPERTY_BUILDPATH_REFERENCE.equals(property)) {
     return hasItemOnBuildPath(element, args);
   }
   if (PROPERTY_EXTENDS_CLASS.equals(property)) {
     return hasSuperclass(element, (String) args[0]);
   }
   if (PROPERTY_PROJECT_NATURE.equals(property)) {
     return hasProjectNature(element, (String) args[0]);
   }
   if (PROPERTY_EXTENDS_INTERFACE.equals(property)) {
     return implementsInterface(element, (String) args[0]);
   }
   if (PROPERTY_IS_PACKAGE_FRAGMENT.equals(property)) {
     return element instanceof IPackageFragment;
   }
   if (PROPERTY_IS_PACKAGE_FRAGMENT_ROOT.equals(property)) {
     return element instanceof IPackageFragmentRoot;
   }
   return false;
 }
Esempio n. 13
0
 private static ISourceRange getOldSourceRange(SearchMatch newMatch) {
   // cannot transfom offset in preview to offset in original -> just show enclosing method
   IJavaElement newMatchElement = (IJavaElement) newMatch.getElement();
   IJavaElement primaryElement = newMatchElement.getPrimaryElement();
   ISourceRange range = null;
   if (primaryElement.exists() && primaryElement instanceof ISourceReference) {
     try {
       range = ((ISourceReference) primaryElement).getSourceRange();
     } catch (JavaModelException e) {
       // can live without source range
     }
   }
   return range;
 }
Esempio n. 14
0
 private void collectCompilationUnits(Object element, Collection<IJavaElement> result) {
   try {
     if (element instanceof IJavaElement) {
       IJavaElement elem = (IJavaElement) element;
       if (elem.exists()) {
         switch (elem.getElementType()) {
           case IJavaElement.TYPE:
             if (elem.getParent().getElementType() == IJavaElement.COMPILATION_UNIT) {
               result.add(elem.getParent());
             }
             break;
           case IJavaElement.COMPILATION_UNIT:
             result.add(elem);
             break;
           case IJavaElement.IMPORT_CONTAINER:
             result.add(elem.getParent());
             break;
           case IJavaElement.PACKAGE_FRAGMENT:
             collectCompilationUnits((IPackageFragment) elem, result);
             break;
           case IJavaElement.PACKAGE_FRAGMENT_ROOT:
             collectCompilationUnits((IPackageFragmentRoot) elem, result);
             break;
           case IJavaElement.JAVA_PROJECT:
             IPackageFragmentRoot[] roots = ((IJavaProject) elem).getPackageFragmentRoots();
             for (int k = 0; k < roots.length; k++) {
               collectCompilationUnits(roots[k], result);
             }
             break;
         }
       }
     } else if (element instanceof LogicalPackage) {
       IPackageFragment[] packageFragments = ((LogicalPackage) element).getFragments();
       for (int k = 0; k < packageFragments.length; k++) {
         IPackageFragment pack = packageFragments[k];
         if (pack.exists()) {
           collectCompilationUnits(pack, result);
         }
       }
     } else if (element instanceof IWorkingSet) {
       IWorkingSet workingSet = (IWorkingSet) element;
       IAdaptable[] elements = workingSet.getElements();
       for (int j = 0; j < elements.length; j++) {
         collectCompilationUnits(elements[j], result);
       }
     }
   } catch (JavaModelException e) {
     if (JavaModelUtil.isExceptionToBeLogged(e)) JavaPlugin.log(e);
   }
 }
  private ICompilationUnit[] getCompilationUnits(IStructuredSelection selection) {
    HashSet result = new HashSet();
    Object[] selected = selection.toArray();
    for (int i = 0; i < selected.length; i++) {
      try {
        if (selected[i] instanceof IJavaElement) {
          IJavaElement elem = (IJavaElement) selected[i];
          if (elem.exists()) {

            switch (elem.getElementType()) {
              case IJavaElement.TYPE:
                if (elem.getParent().getElementType() == IJavaElement.COMPILATION_UNIT) {
                  result.add(elem.getParent());
                }
                break;
              case IJavaElement.COMPILATION_UNIT:
                result.add(elem);
                break;
              case IJavaElement.IMPORT_CONTAINER:
                result.add(elem.getParent());
                break;
              case IJavaElement.PACKAGE_FRAGMENT:
                collectCompilationUnits((IPackageFragment) elem, result);
                break;
              case IJavaElement.PACKAGE_FRAGMENT_ROOT:
                collectCompilationUnits((IPackageFragmentRoot) elem, result);
                break;
              case IJavaElement.JAVA_PROJECT:
                IPackageFragmentRoot[] roots = ((IJavaProject) elem).getPackageFragmentRoots();
                for (int k = 0; k < roots.length; k++) {
                  collectCompilationUnits(roots[k], result);
                }
                break;
            }
          }
        } else if (selected[i] instanceof LogicalPackage) {
          IPackageFragment[] packageFragments = ((LogicalPackage) selected[i]).getFragments();
          for (int k = 0; k < packageFragments.length; k++) {
            IPackageFragment pack = packageFragments[k];
            if (pack.exists()) {
              collectCompilationUnits(pack, result);
            }
          }
        }
      } catch (JavaModelException e) {
        if (JavaModelUtil.isExceptionToBeLogged(e)) JavaPlugin.log(e);
      }
    }
    return (ICompilationUnit[]) result.toArray(new ICompilationUnit[result.size()]);
  }
 @Override
 public void run() {
   TreeViewer viewer = fPackageExplorer.getTreeViewer();
   GotoResourceDialog dialog =
       new GotoResourceDialog(
           fPackageExplorer.getSite().getShell(),
           ResourcesPlugin.getWorkspace().getRoot(),
           viewer);
   dialog.open();
   Object[] result = dialog.getResult();
   if (result == null || result.length == 0 || !(result[0] instanceof IResource)) return;
   StructuredSelection selection = null;
   IJavaElement element = JavaCore.create((IResource) result[0]);
   if (element != null && element.exists()) selection = new StructuredSelection(element);
   else selection = new StructuredSelection(result[0]);
   viewer.setSelection(selection, true);
 }
Esempio n. 17
0
 /**
  * Returns the {@link IJavaElement} associated with the given source element or <code>null</code>
  * if none.
  *
  * @param sourceElement a java element, object that adapts to a java element, or a resource
  * @return corresponding {@link IJavaElement} or <code>null</code>
  * @since 3.4.0
  */
 public static IJavaElement getJavaElement(Object sourceElement) {
   IJavaElement javaElement = null;
   if (sourceElement instanceof IJavaElement) {
     javaElement = (IJavaElement) sourceElement;
   } else if (sourceElement instanceof IAdaptable) {
     javaElement = (IJavaElement) ((IAdaptable) sourceElement).getAdapter(IJavaElement.class);
   }
   if (javaElement == null && sourceElement instanceof IResource) {
     javaElement = JavaCore.create((IResource) sourceElement);
   }
   if (javaElement == null) {
     return null;
   }
   if (!javaElement.exists()) {
     return null;
   }
   return javaElement;
 }
Esempio n. 18
0
 private boolean isEnabled(IStructuredSelection selection) {
   Object[] selected = selection.toArray();
   for (int i = 0; i < selected.length; i++) {
     try {
       if (selected[i] instanceof IJavaElement) {
         IJavaElement elem = (IJavaElement) selected[i];
         if (elem.exists()) {
           switch (elem.getElementType()) {
             case IJavaElement.TYPE:
               return elem.getParent().getElementType()
                   == IJavaElement.COMPILATION_UNIT; // for browsing perspective
             case IJavaElement.COMPILATION_UNIT:
               return true;
             case IJavaElement.IMPORT_CONTAINER:
               return true;
             case IJavaElement.PACKAGE_FRAGMENT:
             case IJavaElement.PACKAGE_FRAGMENT_ROOT:
               IPackageFragmentRoot root =
                   (IPackageFragmentRoot) elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
               return (root.getKind() == IPackageFragmentRoot.K_SOURCE);
             case IJavaElement.JAVA_PROJECT:
               // https://bugs.eclipse.org/bugs/show_bug.cgi?id=65638
               return true;
           }
         }
       } else if (selected[i] instanceof LogicalPackage) {
         return true;
       } else if (selected[i] instanceof IWorkingSet) {
         IWorkingSet workingSet = (IWorkingSet) selected[i];
         return IWorkingSetIDs.JAVA.equals(workingSet.getId());
       }
     } catch (JavaModelException e) {
       if (!e.isDoesNotExist()) {
         JavaPlugin.log(e);
       }
     }
   }
   return false;
 }
Esempio n. 19
0
 /**
  * Finds the closest Java element which can be used as input for this part and has the given Java
  * element as child
  *
  * @param je the Java element for which to search the closest input
  * @return the closest Java element used as input for this part
  */
 protected IJavaElement findInputForJavaElement(IJavaElement je) {
   if (je == null || !je.exists()) return null;
   if (isValidInput(je)) return je;
   return findInputForJavaElement(je.getParent());
 }
 private RefactoringStatus initialize(JavaRefactoringArguments arguments) {
   final String selection =
       arguments.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION);
   if (selection != null) {
     int offset = -1;
     int length = -1;
     final StringTokenizer tokenizer = new StringTokenizer(selection);
     if (tokenizer.hasMoreTokens()) offset = Integer.valueOf(tokenizer.nextToken()).intValue();
     if (tokenizer.hasMoreTokens()) length = Integer.valueOf(tokenizer.nextToken()).intValue();
     if (offset >= 0 && length >= 0) {
       fSelectionStart = offset;
       fSelectionLength = length;
     } else
       return RefactoringStatus.createFatalErrorStatus(
           Messages.format(
               RefactoringCoreMessages.InitializableRefactoring_illegal_argument,
               new Object[] {selection, JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION}));
   } else
     return RefactoringStatus.createFatalErrorStatus(
         Messages.format(
             RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
             JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION));
   final String handle = arguments.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT);
   if (handle != null) {
     final IJavaElement element =
         JavaRefactoringDescriptorUtil.handleToElement(arguments.getProject(), handle, false);
     if (element == null
         || !element.exists()
         || element.getElementType() != IJavaElement.COMPILATION_UNIT)
       return JavaRefactoringDescriptorUtil.createInputFatalStatus(
           element, getName(), IJavaRefactorings.EXTRACT_CONSTANT);
     else fCu = (ICompilationUnit) element;
   } else
     return RefactoringStatus.createFatalErrorStatus(
         Messages.format(
             RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
             JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT));
   final String visibility = arguments.getAttribute(ATTRIBUTE_VISIBILITY);
   if (visibility != null && !"".equals(visibility)) { // $NON-NLS-1$
     int flag = 0;
     try {
       flag = Integer.parseInt(visibility);
     } catch (NumberFormatException exception) {
       return RefactoringStatus.createFatalErrorStatus(
           Messages.format(
               RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
               ATTRIBUTE_VISIBILITY));
     }
     fVisibility = JdtFlags.getVisibilityString(flag);
   }
   final String name = arguments.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_NAME);
   if (name != null && !"".equals(name)) // $NON-NLS-1$
   fConstantName = name;
   else
     return RefactoringStatus.createFatalErrorStatus(
         Messages.format(
             RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
             JavaRefactoringDescriptorUtil.ATTRIBUTE_NAME));
   final String replace = arguments.getAttribute(ATTRIBUTE_REPLACE);
   if (replace != null) {
     fReplaceAllOccurrences = Boolean.valueOf(replace).booleanValue();
   } else
     return RefactoringStatus.createFatalErrorStatus(
         Messages.format(
             RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
             ATTRIBUTE_REPLACE));
   final String declareFinal = arguments.getAttribute(ATTRIBUTE_QUALIFY);
   if (declareFinal != null) {
     fQualifyReferencesWithDeclaringClassName = Boolean.valueOf(declareFinal).booleanValue();
   } else
     return RefactoringStatus.createFatalErrorStatus(
         Messages.format(
             RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
             ATTRIBUTE_QUALIFY));
   return new RefactoringStatus();
 }
 /**
  * Throws a <code>ParameterValueConversionException</code> if the java element reference string
  * identifies an element that does not exist.
  *
  * @param javaElement an element to check for existence
  * @throws ParameterValueConversionException
  */
 private void assertExists(IJavaElement javaElement) throws ParameterValueConversionException {
   if ((javaElement == null) || (!javaElement.exists())) {
     throw new ParameterValueConversionException(
         "parameterValue must reference an existing IJavaElement"); //$NON-NLS-1$
   }
 }