Esempio n. 1
0
 /* (non-Javadoc)
  * @see org.eclipse.jdt.core.search.SearchRequestor#acceptSearchMatch(org.eclipse.jdt.core.search.SearchMatch)
  */
 public void acceptSearchMatch(SearchMatch match) {
   IJavaElement enclosingElement = (IJavaElement) match.getElement();
   if ((enclosingElement != null)
       && (packageNames.contains(enclosingElement.getElementName()))) {
     packages.add(enclosingElement);
   }
 }
  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;
  }
 protected IPackageFragmentRoot getFragmentRoot(IJavaElement elem) {
   IPackageFragmentRoot initRoot = null;
   if (elem != null) {
     initRoot = (IPackageFragmentRoot) elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
     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) {
       // TODO
       e.printStackTrace();
     }
   }
   return initRoot;
 }
Esempio n. 4
0
 private char[][][] getQualifiedNames(ObjectVector types) {
   final int size = types.size;
   char[][][] focusQualifiedNames = null;
   IJavaElement javaElement = this.pattern.focus;
   int index = 0;
   while (javaElement != null && !(javaElement instanceof ITypeRoot)) {
     javaElement = javaElement.getParent();
   }
   if (javaElement != null) {
     IType primaryType = ((ITypeRoot) javaElement).findPrimaryType();
     if (primaryType != null) {
       focusQualifiedNames = new char[size + 1][][];
       focusQualifiedNames[index++] =
           CharOperation.splitOn('.', primaryType.getFullyQualifiedName().toCharArray());
     }
   }
   if (focusQualifiedNames == null) {
     focusQualifiedNames = new char[size][][];
   }
   for (int i = 0; i < size; i++) {
     focusQualifiedNames[index++] =
         CharOperation.splitOn(
             '.', ((IType) (types.elementAt(i))).getFullyQualifiedName().toCharArray());
   }
   return focusQualifiedNames.length == 0
       ? null
       : ReferenceCollection.internQualifiedNames(focusQualifiedNames, true);
 }
 @Override
 public void addPages() {
   super.addPages();
   if (page == null) {
     IJavaElement selectedElement = getSelectedJavaElement(selection);
     String repoPath = null;
     IProject project = null;
     if (selectedElement != null) {
       project = selectedElement.getJavaProject().getProject();
       /*List<String> paths = getCeylonRepositories(project.getProject());
       if (paths!=null) {
           for (int i=paths.size()-1; i>=0; i--) {
               String path = paths.get(i);
               if (!path.startsWith("http://")) {
                   repoPath = path;
                   break;
               }
           }
       }*/
     }
     if (repoPath == null) repoPath = getDefaultRepositoryPath();
     page = new ExportModuleWizardPage(repoPath, project, selectedElement);
     // page.init(selection);
   }
   addPage(page);
 }
 private void processJavaDelta(WorkingSetDelta result, IJavaElementDelta delta) {
   IJavaElement jElement = delta.getElement();
   int index = result.indexOf(jElement);
   int type = jElement.getElementType();
   int kind = delta.getKind();
   int flags = delta.getFlags();
   if (type == IJavaElement.JAVA_PROJECT && kind == IJavaElementDelta.CHANGED) {
     if (index != -1 && (flags & IJavaElementDelta.F_CLOSED) != 0) {
       result.set(index, ((IJavaProject) jElement).getProject());
     } else if ((flags & IJavaElementDelta.F_OPENED) != 0) {
       index = result.indexOf(((IJavaProject) jElement).getProject());
       if (index != -1) result.set(index, jElement);
     }
   }
   if (index != -1) {
     if (kind == IJavaElementDelta.REMOVED) {
       if ((flags & IJavaElementDelta.F_MOVED_TO) != 0) {
         result.set(index, delta.getMovedToElement());
       } else {
         result.remove(index);
       }
     }
   }
   IResourceDelta[] resourceDeltas = delta.getResourceDeltas();
   if (resourceDeltas != null) {
     for (int i = 0; i < resourceDeltas.length; i++) {
       processResourceDelta(result, resourceDeltas[i]);
     }
   }
   IJavaElementDelta[] children = delta.getAffectedChildren();
   for (int i = 0; i < children.length; i++) {
     processJavaDelta(result, children[i]);
   }
 }
Esempio n. 7
0
 @Override
 protected List<? extends IRenameElementContext> createRenameElementContexts(Object element) {
   if (element instanceof IJavaElement) {
     IJavaElement javaElement = (IJavaElement) element;
     EClass expectedJvmType = getExpectedJvmType(javaElement);
     if (expectedJvmType != null) {
       IJavaProject javaProject = javaElement.getJavaProject();
       IProject project = javaProject.getProject();
       ResourceSet resourceSet = resourceSetProvider.get(project);
       EObject directJvmElement =
           jvmElementFinder.getCorrespondingJvmElement(javaElement, resourceSet);
       if (directJvmElement != null && expectedJvmType.isSuperTypeOf(directJvmElement.eClass())) {
         EObject indexedJvmElement =
             jvmElementFinder.findJvmElementDeclarationInIndex(directJvmElement, project);
         if (indexedJvmElement != null)
           // jvmElement is indexed, thus contained in an XtextResurce and likely inferred from
           // some Xtext-based elements
           return getContextFactory(indexedJvmElement)
               .createJdtParticipantXtextSourceContexts(indexedJvmElement);
         else if (directJvmElement instanceof JvmMember)
           // jvmElement is only cross referenced by Xtext-based elements
           return createJdtRenameParticipantContext((JvmMember) directJvmElement, javaElement);
       }
     }
   }
   return null;
 }
 /** {@inheritDoc} */
 @Override
 public final List<ICompletionProposal> computeCompletionProposals(
     final ContentAssistInvocationContext context, final IProgressMonitor monitor) {
   JavaContentAssistInvocationContext javaContext = (JavaContentAssistInvocationContext) context;
   try {
     CompilationUnit compilationUnit = resolveContextualCompilationUnit(monitor, javaContext);
     IJavaElement invocationElement =
         javaContext.getCompilationUnit().getElementAt(context.getInvocationOffset());
     if (invocationElement.getElementType() == IJavaElement.METHOD) {
       IAnnotationBinding annotationBinding =
           resolveContextualAnnotationBinding(javaContext, compilationUnit);
       // completion proposal on @PathParam method annotation
       if (annotationBinding != null
           && PathParam.class
               .getName()
               .equals(JdtUtils.resolveAnnotationFullyQualifiedName(annotationBinding))) {
         return internalComputePathParamProposals(
             javaContext, annotationBinding, (IMethod) invocationElement, compilationUnit);
       }
     }
   } catch (Exception e) {
     Logger.error("Failed to compute completion proposal", e);
   }
   return Collections.emptyList();
 }
 protected String buildPackageName_() {
   IJavaElement javaElement = JavaCore.create(this.file.getParent());
   if ((javaElement != null) && (javaElement.getElementType() == IJavaElement.PACKAGE_FRAGMENT)) {
     return ((IPackageFragment) javaElement).getElementName();
   }
   return null;
 }
 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;
 }
Esempio n. 11
0
  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;
  }
Esempio n. 12
0
 public ASTReader(IJavaProject iJavaProject, IProgressMonitor monitor) {
   if (monitor != null)
     monitor.beginTask("Parsing selected Java Project", getNumberOfCompilationUnits(iJavaProject));
   systemObject = new SystemObject();
   examinedProject = iJavaProject;
   try {
     IPackageFragmentRoot[] iPackageFragmentRoots = iJavaProject.getPackageFragmentRoots();
     for (IPackageFragmentRoot iPackageFragmentRoot : iPackageFragmentRoots) {
       IJavaElement[] children = iPackageFragmentRoot.getChildren();
       for (IJavaElement child : children) {
         if (child.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
           IPackageFragment iPackageFragment = (IPackageFragment) child;
           ICompilationUnit[] iCompilationUnits = iPackageFragment.getCompilationUnits();
           for (ICompilationUnit iCompilationUnit : iCompilationUnits) {
             if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException();
             systemObject.addClasses(parseAST(iCompilationUnit));
             if (monitor != null) monitor.worked(1);
           }
         }
       }
     }
   } catch (JavaModelException e) {
     e.printStackTrace();
   }
   if (monitor != null) monitor.done();
 }
  /*
   * Ensures that getPrimaryElement() on an element of primary working copy returns the same handle.
   */
  public void testGetPrimaryElement2() throws CoreException {
    this.workingCopy = getCompilationUnit("P/X.java");
    this.workingCopy.becomeWorkingCopy(null);
    IJavaElement element = this.workingCopy.getType("X");

    assertEquals("Unexpected element", element, element.getPrimaryElement());
  }
 @Override
 public List<ICompletionProposal> computeCompletionProposals(
     ContentAssistInvocationContext context, IProgressMonitor monitor) {
   final List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>();
   if (context instanceof JavaContentAssistInvocationContext) {
     final JavaContentAssistInvocationContext javaContext =
         (JavaContentAssistInvocationContext) context;
     final IJavaProject javaProject = javaContext.getProject();
     try {
       final IJaxrsMetamodel metamodel = JaxrsMetamodelLocator.get(javaProject);
       // skip if the JAX-RS Nature is not configured for this project
       if (metamodel == null) {
         return Collections.emptyList();
       }
       final IJavaElement invocationElement =
           javaContext.getCompilationUnit().getElementAt(context.getInvocationOffset());
       if (invocationElement.getElementType() == IJavaElement.TYPE) {
         final ITypedRegion region = new TypedRegion(javaContext.getInvocationOffset(), 0, null);
         // proposals.add(new MethodParametersCompletionProposal("Foo !", new StyledString("Foo!"),
         // region, icon, (IMember) invocationElement));
       }
     } catch (CoreException e) {
       Logger.error("Failed to compute completion proposal", e);
     }
   }
   return proposals;
 }
Esempio n. 15
0
  private static String getRenameKind(IJavaElement e) {
    switch (e.getElementType()) {
      case IJavaElement.COMPILATION_UNIT:
        return IJavaRefactorings.RENAME_COMPILATION_UNIT;

      case IJavaElement.FIELD:
        return IJavaRefactorings.RENAME_FIELD;

      case IJavaElement.LOCAL_VARIABLE:
        return IJavaRefactorings.RENAME_LOCAL_VARIABLE;

      case IJavaElement.METHOD:
        return IJavaRefactorings.RENAME_METHOD;

      case IJavaElement.TYPE:
        return IJavaRefactorings.RENAME_TYPE;

      case IJavaElement.TYPE_PARAMETER:
        return IJavaRefactorings.RENAME_TYPE_PARAMETER;

      case IJavaElement.PACKAGE_FRAGMENT:
        return IJavaRefactorings.RENAME_PACKAGE;

      case IJavaElement.PACKAGE_FRAGMENT_ROOT:
        return IJavaRefactorings.RENAME_PACKAGE;

      default:
        throw new RuntimeException("Unexpected object `" + e.getClass() + "' to rename");
    }
  }
Esempio n. 16
0
 private static void populateClasses(
     final Shell shell, final IParent parent, final List<IType> types, final Filter filter) {
   try {
     for (final IJavaElement element : parent.getChildren()) {
       if (element instanceof IType) {
         final IType type = (IType) element;
         if (type.isClass()
             && type.isStructureKnown()
             && !type.isAnonymous()
             && !type.isLocal()
             && !Flags.isAbstract(type.getFlags())
             && Flags.isPublic(type.getFlags())
             && (filter == null || filter.accept(type))) {
           types.add(type);
         }
       } else if (element instanceof IParent
           && !element.getPath().toString().contains("/test/")
           && (!(element instanceof IPackageFragmentRoot)
               || !((IPackageFragmentRoot) element).isExternal())) {
         populateClasses(shell, (IParent) element, types, filter);
       }
     }
   } catch (final JavaModelException e) {
     Activator.error(e);
   }
 }
  /** @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;
 }
Esempio n. 19
0
  /**
   * @see
   *     edu.buffalo.cse.green.RefactorHandler#handleMove(edu.buffalo.cse.green.editor.model.RootModel,
   *     org.eclipse.jdt.core.IJavaElement, org.eclipse.jdt.core.IJavaElement)
   */
  public void handleMove(RootModel root, E sourceElement, E targetElement) {
    // get all types represented in the diagram
    String scuId = sourceElement.getHandleIdentifier();
    String tcuId = targetElement.getHandleIdentifier();

    String scuName = scuId.substring(scuId.indexOf('{') + 1, scuId.indexOf(".java"));
    String tcuName = tcuId.substring(tcuId.indexOf('{') + 1, tcuId.indexOf(".java"));

    List<IJavaElement> cuTypes = root.getElementsOfKind(TYPE);

    // see if any types belong to the compilation unit
    // that is undergoing the move event
    for (IJavaElement oType : cuTypes) {
      if (JavaModelListener.sameElements(sourceElement, oType.getAncestor(COMPILATION_UNIT))) {
        String oId = oType.getHandleIdentifier();
        String oName = oId.substring(oId.indexOf('['));

        oName = oName.replaceAll("\\[" + scuName, "[" + tcuName);

        IJavaElement nType = JavaCore.create(tcuId + oName);
        TypeModel oModel = (TypeModel) root.getModelFromElement(oType);

        TypeModel nModel = root.createTypeModel((IType) nType);
        if (oModel != null) {
          // TODO We tried to catch a ResourceException,
          // but it is caught in MemberModel
          oModel.removeFromParent();
          nModel.setLocation(oModel.getLocation());
          nModel.setSize(oModel.getSize());
        }
      }
    }
  }
  public void search(
      ISearchRequestor requestor, QuerySpecification querySpecification, IProgressMonitor monitor)
      throws CoreException {

    if (querySpecification.getLimitTo() != S_LIMIT_REF
        && querySpecification.getLimitTo() != S_LIMIT_ALL) return;

    String search;
    if (querySpecification instanceof ElementQuerySpecification) {
      IJavaElement element = ((ElementQuerySpecification) querySpecification).getElement();
      if (element instanceof IType) search = ((IType) element).getFullyQualifiedName('.');
      else search = element.getElementName();
      int type = element.getElementType();
      if (type == IJavaElement.TYPE) fSearchFor = S_FOR_TYPES;
      else if (type == IJavaElement.PACKAGE_FRAGMENT || type == IJavaElement.PACKAGE_FRAGMENT_ROOT)
        fSearchFor = S_FOR_PACKAGES;
    } else {
      fSearchFor = ((PatternQuerySpecification) querySpecification).getSearchFor();
      search = ((PatternQuerySpecification) querySpecification).getPattern();
    }
    if (fSearchFor != S_FOR_TYPES && fSearchFor != S_FOR_PACKAGES) return;
    fSearchPattern = PatternConstructor.createPattern(search, true);
    fSearchRequestor = requestor;

    IPath[] enclosingPaths = querySpecification.getScope().enclosingProjectsAndJars();
    IPluginModelBase[] pluginModels = PluginRegistry.getWorkspaceModels();
    monitor.beginTask(PDEUIMessages.ClassSearchParticipant_taskMessage, pluginModels.length);
    for (int i = 0; i < pluginModels.length; i++) {
      IProject project = pluginModels[i].getUnderlyingResource().getProject();
      if (!monitor.isCanceled() && encloses(enclosingPaths, project.getFullPath()))
        searchProject(project, monitor);
    }
  }
Esempio n. 21
0
 /* (non-Javadoc)
  * @see IJavaSearchScope#encloses(IJavaElement)
  */
 public boolean encloses(IJavaElement element) {
   if (this.elements != null) {
     for (int i = 0, length = this.elements.size(); i < length; i++) {
       IJavaElement scopeElement = (IJavaElement) this.elements.get(i);
       IJavaElement searchedElement = element;
       while (searchedElement != null) {
         if (searchedElement.equals(scopeElement)) return true;
         searchedElement = searchedElement.getParent();
       }
     }
     return false;
   }
   IPackageFragmentRoot root =
       (IPackageFragmentRoot) element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
   if (root != null && root.isArchive()) {
     // external or internal jar
     IPath rootPath = root.getPath();
     String rootPathToString =
         rootPath.getDevice() == null ? rootPath.toString() : rootPath.toOSString();
     IPath relativePath = getPath(element, true /*relative path*/);
     return indexOf(rootPathToString, relativePath.toString()) >= 0;
   }
   // resource in workspace
   String fullResourcePathString = getPath(element, false /*full path*/).toString();
   return indexOf(fullResourcePathString) >= 0;
 }
Esempio n. 22
0
  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. 23
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();
    }
  }
  public void elementChanged(ElementChangedEvent event) {
    IJavaElementDelta[] children = event.getDelta().getChangedChildren(); // children = IProjects
    for (IJavaElementDelta child : children) {
      IProject project = child.getElement().getJavaProject().getProject();
      int size = child.getAffectedChildren().length; // .getChangedElement() = JavaProject
      if (size == 1) {
        IJavaElementDelta elementDelta =
            child.getAffectedChildren()[0]; // if it is only 1, name is ".tmp"
        // and elementDelta.kind = 4
        // (CHANGED)
        IJavaElement changedElement = elementDelta.getElement();
        if (changedElement
            .getElementName()
            .equals(ImportUtils.getImportPref(ResourceBuilder.LOCALE_INTERFACES_FOLDER_NAME))) {
          _changedBuildClasspath.put(project.getName(), Boolean.FALSE);
          break;
        }
      }
      if (isClasspathChange(
          child)) { // adding classpath entries might induce reordering the classpath entries
        _changedBuildClasspath.put(project.getName(), Boolean.TRUE);
        // notify the listeners
        EJDEEventNotifier.getInstance()
            .notifyClassPathChanged(child.getElement().getJavaProject(), hasCPRemoved(child));
        // validate the project
        ValidationManager.getInstance()
            .validateProjects(
                ProjectUtils.getAllReferencingProjects(
                    new IProject[] {child.getElement().getJavaProject().getProject()}),
                null);
      }
      if ((child.getFlags() & IJavaElementDelta.F_CLASSPATH_CHANGED) != 0
          || (child.getFlags() & IJavaElementDelta.F_RESOLVED_CLASSPATH_CHANGED) != 0) {
        IJavaElement javaElement = child.getElement();
        final IJavaProject javaProject = javaElement.getJavaProject();
        classPathChanged(javaProject, child);
      }
      checkSourceAttachement(child.getAffectedChildren());
    }

    for (final IJavaElementDelta addedElemDelta : event.getDelta().getAddedChildren()) {
      final IJavaProject javaProject = addedElemDelta.getElement().getJavaProject();
      try {
        if (javaProject.getProject().hasNature(BlackBerryProjectCoreNature.NATURE_ID)) {
          if (addedElemDelta.getAffectedChildren().length == 0) {
            final IJavaElement addedElement = addedElemDelta.getElement();
            if (addedElement instanceof IJavaProject) {
              final IJavaProject addedJavaProj = (IJavaProject) addedElement;
              if (addedJavaProj.equals(javaProject)) {
                projectCreated(javaProject);
              }
            }
          }
        }
      } catch (final CoreException ce) {
        _log.error("", ce);
      }
    }
  }
  /*
   * Ensures that getPrimaryElement() on an element of a non-primary working copy returns
   * an element ofthe primary compilation unit.
   */
  public void testGetPrimaryElement1() throws CoreException {
    ICompilationUnit cu = getCompilationUnit("P/X.java");
    TestWorkingCopyOwner owner = new TestWorkingCopyOwner();
    this.workingCopy = cu.getWorkingCopy(owner, null);
    IJavaElement element = this.workingCopy.getType("X");

    assertEquals("Unexpected element", cu.getType("X"), element.getPrimaryElement());
  }
Esempio n. 26
0
 private IPackageFragmentRoot getPackageFragmentRoot(IJavaElement ele) {
   IJavaElement current = ele;
   while (current != null) {
     if (current instanceof IPackageFragmentRoot) return (IPackageFragmentRoot) current;
     current = current.getParent();
   }
   return null;
 }
Esempio n. 27
0
 /**
  * Gets the primary element (compilation unit or class file) for the supplied element.
  *
  * @param element The element.
  * @return The primary element.
  */
 public static IJavaElement getPrimaryElement(IJavaElement element) {
   IJavaElement parent = element;
   while (parent.getElementType() != IJavaElement.COMPILATION_UNIT
       && parent.getElementType() != IJavaElement.CLASS_FILE) {
     parent = parent.getParent();
   }
   return parent;
 }
Esempio n. 28
0
 private IType getMainClass(Element element) {
   String handleId = element.getAttribute("mainClassHandleIdentifier"); // $NON-NLS-1$
   if (handleId.equals("")) // $NON-NLS-1$
   return null; // Main-Class entry is optional or can be empty
   IJavaElement je = JavaCore.create(handleId);
   if (je != null && je.getElementType() == IJavaElement.TYPE) return (IType) je;
   addWarning(JarPackagerMessages.JarPackageReader_warning_mainClassDoesNotExist, null);
   return null;
 }
Esempio n. 29
0
  /**
   * Called when an IJavaElement changes. Used to reflect changes in the editor, which has a view
   * that is based on the <code>JavaModel</code>.
   *
   * @param event - The change that occurred to the <code>JavaModel</code>.
   */
  @SuppressWarnings("unchecked")
  public void elementChanged(ElementChangedEvent event) {
    try {
      /* Goes through these classes looking for any that are added, moved
       * or removed. Calls methods that updates the editor to reflect any
       * changes found.
       */
      for (Class type : map.keySet()) {
        List<IJavaElementDelta> added = findAddedElements(event.getDelta(), type);
        List<IJavaElementDelta> removed = findRemovedElements(event.getDelta(), type);
        List<IJavaElementDelta> changed = findChangedElements(event.getDelta(), type);
        HashMap<IJavaElement, IJavaElement> moved = extractMovedElements(added, removed);

        // ignore updating the editors if no changes occurred
        if (added.size() == 0 && removed.size() == 0 && moved.size() == 0 && changed.size() == 0) {
          continue;
        }

        List<DiagramEditor> editors = new ArrayList<DiagramEditor>(DiagramEditor.getEditors());

        // handle changes
        for (DiagramEditor editor : editors) {
          RootModel root = editor.getRootModel();

          // handle moves
          for (IJavaElement sourceElement : moved.keySet()) {
            IJavaElement targetElement = moved.get(sourceElement);
            map.get(sourceElement.getClass()).handleMove(root, sourceElement, targetElement);
          }

          // handle removes
          for (IJavaElementDelta removedElement : removed) {
            map.get(removedElement.getElement().getClass())
                .handleRemove(root, removedElement.getElement());
          }

          // handle adds
          for (IJavaElementDelta addedElement : added) {
            map.get(addedElement.getElement().getClass())
                .handleAdd(root, addedElement.getElement());
          }

          // handle changes (to modifiers, etc.)
          for (IJavaElementDelta changedElement : changed) {
            handleElementChange(changedElement);
          }

          editor.forceRefreshRelationships();
        }
      }
    } catch (Throwable t) {
      // TODO Incremental exploration throws Null Pointer.  Virtually unreproduceable.
      GreenException.critical(t);
    } finally {
      TypeRefactorHandler.REMOVED_TYPE = null;
    }
  }
Esempio n. 30
0
  /**
   * @see
   *     edu.buffalo.cse.green.RefactorHandler#handleRemove(edu.buffalo.cse.green.editor.model.RootModel,
   *     org.eclipse.jdt.core.IJavaElement)
   */
  public void handleRemove(RootModel root, E element) {
    List<IJavaElement> cus = root.getElementsOfKind(COMPILATION_UNIT);

    for (IJavaElement cu : cus) {
      if (JavaModelListener.sameElements(cu.getAncestor(PACKAGE_FRAGMENT), element)) {
        CompilationUnitRefactorHandler.instance().handleRemove(root, (ICompilationUnit) cu);
      }
    }
  }