예제 #1
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;
 }
  protected IFile getManifest(IPackageFragmentRoot[] roots, IJavaProject javaProject)
      throws CoreException {

    IFolder metaFolder = null;
    for (IPackageFragmentRoot root : roots) {
      if (!root.isArchive() && !root.isExternal()) {
        IResource resource = root.getResource();
        metaFolder = getMetaFolder(resource);
        if (metaFolder != null) {
          break;
        }
      }
    }

    // Otherwise look for manifest file in the java project:
    if (metaFolder == null) {
      metaFolder = getMetaFolder(javaProject.getProject());
    }

    if (metaFolder != null) {
      IResource[] members = metaFolder.members();
      if (members != null) {
        for (IResource mem : members) {
          if (MANIFEST_FILE.equals(mem.getName().toUpperCase()) && mem instanceof IFile) {
            return (IFile) mem;
          }
        }
      }
    }

    return null;
  }
 public void initFromSelection() {
   IJavaElement je = getSelectedJavaElement(selection);
   if (je instanceof IJavaProject) {
     IJavaProject jp = (IJavaProject) je;
     if (jp.isOpen()) {
       // default to the first source dir
       // we find in the selected project
       try {
         for (IPackageFragmentRoot pfr : jp.getAllPackageFragmentRoots()) {
           if (!pfr.isExternal() && !pfr.isArchive()) {
             je = pfr;
             break;
           }
         }
       } catch (JavaModelException e) {
       }
     }
   }
   if (je instanceof IPackageFragmentRoot) {
     sourceDir = (IPackageFragmentRoot) je;
     packageFragment = sourceDir.getPackageFragment("");
     packageName = packageFragment.getElementName();
   } else if (je instanceof IPackageFragment) {
     packageFragment = (IPackageFragment) je;
     packageName = packageFragment.getElementName();
     sourceDir = (IPackageFragmentRoot) packageFragment.getAncestor(PACKAGE_FRAGMENT_ROOT);
   }
 }
예제 #4
0
  /**
   * Function for traversing the source files in the application under analysis
   *
   * @param astC
   * @return
   */
  public TreeSet analyzeLibraryCode(ASTCrawler astC) {
    IJavaProject libProject = RepositoryAnalyzer.getInstance().getCurrentJProject();
    if (libProject == null) {
      logger.warn("No library project is available as input. Nothing can be done, Sorry!!!!");
      return null;
    }

    try {
      IPackageFragment[] fragments = libProject.getPackageFragments();
      for (int j = 0; j < fragments.length; j++) {
        switch (fragments[j].getKind()) {
          case IPackageFragmentRoot.K_SOURCE:

            /**
             * @todo I'm not sure whether K_SOURCE actually means non-Archive (and therefore further
             *     testing is obsolete)
             */
            IPackageFragmentRoot root =
                (IPackageFragmentRoot) fragments[j].getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);

            if (!root.isArchive()) {
              ICompilationUnit[] units = fragments[j].getCompilationUnits();
              for (ICompilationUnit icu : units) {
                ASTParser parser = ASTParser.newParser(AST.JLS3);
                parser.setProject(libProject);
                parser.setResolveBindings(true);
                parser.setStatementsRecovery(true);

                parser.setSource(icu);
                CompilationUnit cu_java = (CompilationUnit) parser.createAST(null);

                try {
                  // This also clears the class specific data of the previous run
                  String path = icu.getPath().toString();
                  int indexOfLastSlash;
                  if ((indexOfLastSlash = path.lastIndexOf("/")) != -1) {
                    path = path.substring(indexOfLastSlash + 1, path.length());
                  }
                  astC.preProcessClass(cu_java, path);
                  MethodInvocationHolder.MIHKEYGEN = 0;
                  cu_java.accept(astC);
                } catch (Exception ex) {
                  ex.printStackTrace();
                }
              }
            }

            break;

          default:
            break;
        }
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    return astC.postProcess();
  }
 private PackageFragmentRootData getData(IPackageFragmentRoot root) {
   final boolean isCachable = root.isArchive() || root.isExternal();
   if (isCachable) {
     return getCachedData(root);
   }
   PackageFragmentRootData data = initializeData(root);
   return data;
 }
예제 #6
0
 /**
  * A class file has a corresponding resource unless it is contained in a jar.
  *
  * @see IJavaElement
  */
 public IResource getCorrespondingResource() throws JavaModelException {
   IPackageFragmentRoot root = (IPackageFragmentRoot) getParent().getParent();
   if (root.isArchive()) {
     return null;
   } else {
     return getUnderlyingResource();
   }
 }
 /** @since 2.4 */
 @Override
 public Pair<URI, URI> getURIMapping(IPackageFragmentRoot root) throws JavaModelException {
   PackageFragmentRootData data = getData(root);
   if (data.uriPrefix == null) return null;
   IPath path = root.isExternal() ? root.getPath() : root.getUnderlyingResource().getLocation();
   URI physical = null;
   if (root.isArchive()) {
     String archiveScheme =
         "zip".equalsIgnoreCase(root.getPath().getFileExtension()) ? "zip" : "jar";
     physical = URI.createURI(archiveScheme + ":file:" + path.toFile().getPath() + "!/");
   } else {
     physical = URI.createFileURI(path.toFile().getPath() + "/");
   }
   return Tuples.create(data.uriPrefix, physical);
 }
 /** @since 2.4 */
 private void updateCache(IJavaProject project) {
   Set<PackageFragmentRootData> datas = newHashSet();
   try {
     if (project.exists() && project.getProject().isAccessible()) {
       for (IPackageFragmentRoot root : project.getPackageFragmentRoots()) {
         boolean isCachable = root.isArchive() || root.isExternal();
         if (isCachable) datas.add(getCachedData(root));
       }
     }
   } catch (JavaModelException e) {
     if (!e.isDoesNotExist())
       log.error("Error getting package fragments roots of " + project.getElementName(), e);
   } finally {
     clearCache(project, datas);
   }
 }
예제 #9
0
 /* (non-Javadoc)
  * Method declared on ViewerFilter.
  */
 public boolean select(Viewer viewer, Object parentElement, Object element) {
   if (element instanceof IPackageFragmentRoot) {
     IPackageFragmentRoot root = (IPackageFragmentRoot) element;
     if (root.isArchive()) {
       // don't filter out JARs contained in the project itself
       IResource resource = root.getResource();
       if (resource != null) {
         IProject jarProject = resource.getProject();
         IProject container = root.getJavaProject().getProject();
         return container.equals(jarProject);
       }
       return false;
     }
   }
   return true;
 }
 private void initializePackageNames(IPackageFragmentRoot root, HashSetOfArray fragmentsCache) {
   IJavaElement[] frags = null;
   try {
     if (!root.isOpen()) {
       PackageFragmentRootInfo info =
           root.isArchive() ? new JarPackageFragmentRootInfo() : new PackageFragmentRootInfo();
       ((PackageFragmentRoot) root).computeChildren(info, ((JavaElement) root).resource());
       frags = info.children;
     } else frags = root.getChildren();
   } catch (JavaModelException e) {
     // root doesn't exist: ignore
     return;
   }
   for (int j = 0, length = frags.length; j < length; j++) {
     fragmentsCache.add(((PackageFragment) frags[j]).names);
   }
 }
 private static String getAddClasspathLabel(
     IClasspathEntry entry, IPackageFragmentRoot root, IJavaProject project) {
   switch (entry.getEntryKind()) {
     case IClasspathEntry.CPE_LIBRARY:
       if (root.isArchive()) {
         String[] args = {
           JavaElementLabels.getElementLabel(
               root, JavaElementLabels.REFERENCED_ROOT_POST_QUALIFIED),
           BasicElementLabels.getJavaElementName(project.getElementName())
         };
         return Messages.format(
             CorrectionMessages.ReorgCorrectionsSubProcessor_addcp_archive_description, args);
       } else {
         String[] args = {
           JavaElementLabels.getElementLabel(
               root, JavaElementLabels.REFERENCED_ROOT_POST_QUALIFIED),
           BasicElementLabels.getJavaElementName(project.getElementName())
         };
         return Messages.format(
             CorrectionMessages.ReorgCorrectionsSubProcessor_addcp_classfolder_description, args);
       }
     case IClasspathEntry.CPE_VARIABLE:
       {
         String[] args = {
           JavaElementLabels.getElementLabel(root, 0),
           BasicElementLabels.getJavaElementName(project.getElementName())
         };
         return Messages.format(
             CorrectionMessages.ReorgCorrectionsSubProcessor_addcp_variable_description, args);
       }
     case IClasspathEntry.CPE_CONTAINER:
       try {
         String[] args = {
           JavaElementLabels.getContainerEntryLabel(entry.getPath(), root.getJavaProject()),
           BasicElementLabels.getJavaElementName(project.getElementName())
         };
         return Messages.format(
             CorrectionMessages.ReorgCorrectionsSubProcessor_addcp_library_description, args);
       } catch (JavaModelException e) {
         // ignore
       }
       break;
   }
   return null;
 }
예제 #12
0
 /*
  * Create the list of focused jars or projects.
  */
 private static IJavaElement[] getFocusedElementsAndTypes(
     SearchPattern pattern, IJavaElement focusElement, ObjectVector superTypes)
     throws JavaModelException {
   if (pattern instanceof MethodPattern) {
     // For method pattern, it needs to walk along the focus type super hierarchy
     // and add jars/projects of all the encountered types.
     IType type = (IType) pattern.focus.getAncestor(IJavaElement.TYPE);
     MethodPattern methodPattern = (MethodPattern) pattern;
     String selector = new String(methodPattern.selector);
     int parameterCount = methodPattern.parameterCount;
     ITypeHierarchy superHierarchy = type.newSupertypeHierarchy(null);
     IType[] allTypes = superHierarchy.getAllSupertypes(type);
     int length = allTypes.length;
     SimpleSet focusSet = new SimpleSet(length + 1);
     if (focusElement != null) focusSet.add(focusElement);
     for (int i = 0; i < length; i++) {
       IMethod[] methods = allTypes[i].getMethods();
       int mLength = methods.length;
       for (int m = 0; m < mLength; m++) {
         if (parameterCount == methods[m].getNumberOfParameters()
             && methods[m].getElementName().equals(selector)) {
           IPackageFragmentRoot root =
               (IPackageFragmentRoot) allTypes[i].getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
           IJavaElement element = root.isArchive() ? root : root.getParent();
           focusSet.add(element);
           if (superTypes != null) superTypes.add(allTypes[i]);
           break;
         }
       }
     }
     // Rebuilt a contiguous array
     IJavaElement[] focuses = new IJavaElement[focusSet.elementSize];
     Object[] values = focusSet.values;
     int count = 0;
     for (int i = values.length; --i >= 0; ) {
       if (values[i] != null) {
         focuses[count++] = (IJavaElement) values[i];
       }
     }
     return focuses;
   }
   if (focusElement == null) return new IJavaElement[0];
   return new IJavaElement[] {focusElement};
 }
 /** @since 2.5 */
 @Override
 public URI getUri(/* @NonNull */ IStorage storage) {
   if (storage instanceof IJarEntryResource) {
     final IJarEntryResource casted = (IJarEntryResource) storage;
     IPackageFragmentRoot packageFragmentRoot = casted.getPackageFragmentRoot();
     Map<URI, IStorage> data = getAllEntries(packageFragmentRoot);
     for (Map.Entry<URI, IStorage> entry : data.entrySet()) {
       if (entry.getValue().equals(casted)) return entry.getKey();
     }
     if (packageFragmentRoot.exists() && packageFragmentRoot.isArchive()) {
       IPath jarPath = packageFragmentRoot.getPath();
       URI jarURI;
       if (packageFragmentRoot.isExternal()) {
         jarURI = URI.createFileURI(jarPath.toOSString());
       } else {
         jarURI = URI.createPlatformResourceURI(jarPath.toString(), true);
       }
       URI result = URI.createURI("archive:" + jarURI + "!" + storage.getFullPath());
       return result;
     }
   }
   return null;
 }
  /**
   * This method is a hook which gets called after the source folder's text input field has changed.
   * This default implementation updates the model and returns an error status. The underlying model
   * is only valid if the returned status is OK.
   *
   * @return the model's error status
   */
  protected IStatus containerChanged() {
    StatusInfo status = new StatusInfo();

    fCurrRoot = null;
    String str = getPackageFragmentRootText();
    if (str.length() == 0) {
      status.setError(NewWizardMessages.NewContainerWizardPage_error_EnterContainerName);
      return status;
    }
    IPath path = new Path(str);
    IResource res = fWorkspaceRoot.findMember(path);
    if (res != null) {
      int resType = res.getType();
      if (resType == IResource.PROJECT || resType == IResource.FOLDER) {
        IProject proj = res.getProject();
        if (!proj.isOpen()) {
          status.setError(
              Messages.format(
                  NewWizardMessages.NewContainerWizardPage_error_ProjectClosed,
                  BasicElementLabels.getPathLabel(proj.getFullPath(), false)));
          return status;
        }
        IJavaProject jproject = JavaCore.create(proj);
        fCurrRoot = jproject.getPackageFragmentRoot(res);
        if (res.exists()) {
          if (res.isVirtual()) {
            status.setError(NewWizardMessages.NewContainerWizardPage_error_FolderIsVirtual);
            return status;
          }
          try {
            if (!proj.hasNature(JavaCore.NATURE_ID)) {
              if (resType == IResource.PROJECT) {
                status.setError(NewWizardMessages.NewContainerWizardPage_warning_NotAJavaProject);
              } else {
                status.setWarning(
                    NewWizardMessages.NewContainerWizardPage_warning_NotInAJavaProject);
              }
              return status;
            }
            if (fCurrRoot.isArchive()) {
              status.setError(
                  Messages.format(
                      NewWizardMessages.NewContainerWizardPage_error_ContainerIsBinary,
                      BasicElementLabels.getPathLabel(path, false)));
              return status;
            }
            if (fCurrRoot.getKind() == IPackageFragmentRoot.K_BINARY) {
              status.setWarning(
                  Messages.format(
                      NewWizardMessages.NewContainerWizardPage_warning_inside_classfolder,
                      BasicElementLabels.getPathLabel(path, false)));
            } else if (!jproject.isOnClasspath(fCurrRoot)) {
              status.setWarning(
                  Messages.format(
                      NewWizardMessages.NewContainerWizardPage_warning_NotOnClassPath,
                      BasicElementLabels.getPathLabel(path, false)));
            }
          } catch (JavaModelException e) {
            status.setWarning(NewWizardMessages.NewContainerWizardPage_warning_NotOnClassPath);
          } catch (CoreException e) {
            status.setWarning(NewWizardMessages.NewContainerWizardPage_warning_NotAJavaProject);
          }
        }
        return status;
      } else {
        status.setError(
            Messages.format(
                NewWizardMessages.NewContainerWizardPage_error_NotAFolder,
                BasicElementLabels.getPathLabel(path, false)));
        return status;
      }
    } else {
      status.setError(
          Messages.format(
              NewWizardMessages.NewContainerWizardPage_error_ContainerDoesNotExist,
              BasicElementLabels.getPathLabel(path, false)));
      return status;
    }
  }