protected List<String> getSourceFolders(IProject project) {
    List<String> result = new ArrayList<String>();
    IJavaProject javaProject = JavaCore.create(project);
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();

    try {
      for (IPackageFragmentRoot packageFragmentRoot : javaProject.getPackageFragmentRoots()) {
        if (packageFragmentRoot.getKind() == IPackageFragmentRoot.K_SOURCE) {
          IPath path = packageFragmentRoot.getPath();
          IFolder folder = root.getFolder(path);
          String location = folder.getLocation().toString();

          if (!location.contains("src-gen")) {
            result.add(location);
          }
        }
      }

      for (IProject referencedProject : javaProject.getProject().getReferencedProjects()) {
        if (referencedProject.isAccessible() && referencedProject.hasNature(JavaCore.NATURE_ID)) {
          result.addAll(getSourceFolders(referencedProject));
        }
      }

    } catch (JavaModelException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();

    } catch (CoreException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return result;
  }
  private static Change createPackageFragmentRootDeleteChange(IPackageFragmentRoot root)
      throws JavaModelException {
    IResource resource = root.getResource();
    if (resource != null && resource.isLinked()) {
      // XXX using this code is a workaround for jcore bug 31998
      // jcore cannot handle linked stuff
      // normally, we should always create DeletePackageFragmentRootChange
      CompositeChange composite =
          new DynamicValidationStateChange(
              RefactoringCoreMessages.DeleteRefactoring_delete_package_fragment_root);

      ClasspathChange change =
          ClasspathChange.removeEntryChange(root.getJavaProject(), root.getRawClasspathEntry());
      if (change != null) {
        composite.add(change);
      }
      Assert.isTrue(!Checks.isClasspathDelete(root)); // checked in preconditions
      composite.add(createDeleteChange(resource));

      return composite;
    } else {
      Assert.isTrue(!root.isExternal());
      // TODO remove the query argument
      return new DeletePackageFragmentRootChange(root, true, null);
    }
  }
 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;
 }
 /**
  * Write all state to persistent properties in the given project
  *
  * @param p
  */
 public void persistState() {
   TableTreeItem[] items = getItems();
   for (TableTreeItem item : items) {
     String id = (String) item.getData("id");
     String val = (item.getChecked()) ? "true" : "false";
     String mPatterns = item.getText(1);
     try {
       project.setPersistentProperty(
           new QualifiedName(Constants.PLUGIN_ID, id + ".enabled"), val);
       project.setPersistentProperty(
           new QualifiedName(Constants.PLUGIN_ID, id + ".patterns"), mPatterns);
       TableTreeItem[] folders = item.getItems();
       for (TableTreeItem folder : folders) {
         IPackageFragmentRoot f = (IPackageFragmentRoot) folder.getData("element");
         String handle = f.getHandleIdentifier();
         String fVal = (folder.getChecked()) ? "true" : "false";
         String fPatterns = folder.getText(1);
         project.setPersistentProperty(
             new QualifiedName(Constants.PLUGIN_ID, id + "_" + handle + ".enabled"), fVal);
         project.setPersistentProperty(
             new QualifiedName(Constants.PLUGIN_ID, id + "_" + handle + ".patterns"), fPatterns);
       }
     } catch (CoreException e) {
       Log.logError("Could not persist property", e);
     }
   }
 }
  /**
   * Adds a source container to a IJavaProject.
   *
   * @param jproject The parent project
   * @param containerName The name of the new source container
   * @param inclusionFilters Inclusion filters to set
   * @param exclusionFilters Exclusion filters to set
   * @param outputLocation The location where class files are written to, <b>null</b> for project
   *     output folder
   * @return The handle to the new source container
   * @throws CoreException Creation failed
   */
  public static IPackageFragmentRoot addSourceContainer(
      IJavaProject jproject,
      String containerName,
      IPath[] inclusionFilters,
      IPath[] exclusionFilters,
      String outputLocation)
      throws CoreException {
    IProject project = jproject.getProject();
    IContainer container = null;
    if (containerName == null || containerName.length() == 0) {
      container = project;
    } else {
      IFolder folder = project.getFolder(containerName);
      if (!folder.exists()) {
        CoreUtility.createFolder(folder, false, true, null);
      }
      container = folder;
    }
    IPackageFragmentRoot root = jproject.getPackageFragmentRoot(container);

    IPath outputPath = null;
    if (outputLocation != null) {
      IFolder folder = project.getFolder(outputLocation);
      if (!folder.exists()) {
        CoreUtility.createFolder(folder, false, true, null);
      }
      outputPath = folder.getFullPath();
    }
    IClasspathEntry cpe =
        JavaCore.newSourceEntry(root.getPath(), inclusionFilters, exclusionFilters, outputPath);
    addToClasspath(jproject, cpe);
    return root;
  }
  /**
   * Tests that the output folder settings for a source folder cause the class file containers to be
   * updated
   */
  public void testWPUpdateOutputFolderSrcFolderChanged() throws Exception {
    IJavaProject project = getTestingProject();
    IApiComponent component = getWorkspaceBaseline().getApiComponent(project.getElementName());
    assertNotNull("the workspace component must exist", component);
    int before = component.getApiTypeContainers().length;

    ProjectUtils.addFolderToProject(project.getProject(), "bin3");
    IContainer container = ProjectUtils.addFolderToProject(project.getProject(), "src2");
    // add to bundle class path
    IBundleProjectService service = ProjectUtils.getBundleProjectService();
    IBundleClasspathEntry next =
        service.newBundleClasspathEntry(new Path("src2"), new Path("bin3"), new Path("next.jar"));
    ProjectUtils.addBundleClasspathEntry(project.getProject(), next);
    waitForAutoBuild();

    // retrieve updated component
    component = getWorkspaceBaseline().getApiComponent(project.getElementName());
    assertTrue(
        "there must be one more container after the change",
        before < component.getApiTypeContainers().length);
    IPackageFragmentRoot root = project.getPackageFragmentRoot(container);
    assertTrue(
        "the class file container for src2 must be 'bin3'",
        "bin3".equals(root.getRawClasspathEntry().getOutputLocation().toFile().getName()));
  }
 public void selectionChanged(IAction action, ISelection sel) {
   boolean enable = false;
   if (sel instanceof IStructuredSelection) {
     IStructuredSelection selection = (IStructuredSelection) sel;
     Object element = selection.getFirstElement();
     try {
       if (element instanceof IPackageFragmentRoot) {
         IPackageFragmentRoot root = (IPackageFragmentRoot) element;
         project = root.getJavaProject().getProject();
         cpEntry = root.getRawClasspathEntry();
         if (cpEntry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
           fileName = root.getElementName();
           enable = AspectJCorePreferences.isOnInpath(cpEntry);
         } else {
           fileName = null;
           cpEntry = null;
           project = null;
           enable = false;
         }
       } else {
         enable = false;
       }
     } catch (JavaModelException e) {
     }
     action.setEnabled(enable);
   }
 }
 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);
   }
 }
  /**
   * Ensures that creating a DOM AST and computing the bindings takes the owner's working copies
   * into account.
   *
   * @deprecated using deprecated code
   */
  public void testParseCompilationUnit3() throws CoreException {
    try {
      createJavaProject("P1", new String[] {"src"}, new String[] {"JCL_LIB", "lib"}, "bin");

      // create X.class in lib folder
      /* Evaluate the following in a scrapbook:
      	org.eclipse.jdt.core.tests.model.ModifyingResourceTests.generateClassFile(
      		"X",
      		"public class X {\n" +
      		"}")
      */
      byte[] bytes =
          new byte[] {
            -54, -2, -70, -66, 0, 3, 0, 45, 0, 13, 1, 0, 1, 88, 7, 0, 1, 1, 0, 16, 106, 97, 118, 97,
                47, 108, 97, 110, 103, 47, 79, 98, 106, 101, 99, 116, 7, 0, 3, 1, 0, 6, 60, 105,
                110, 105, 116, 62, 1, 0, 3, 40, 41, 86, 1, 0, 4, 67, 111, 100, 101, 12, 0, 5, 0, 6,
                10, 0, 4, 0, 8, 1, 0, 15, 76, 105, 110, 101, 78, 117,
            109, 98, 101, 114, 84, 97, 98, 108, 101, 1, 0, 10, 83, 111, 117, 114, 99, 101, 70, 105,
                108, 101, 1, 0, 6, 88, 46, 106, 97, 118, 97, 0, 33, 0, 2, 0, 4, 0, 0, 0, 0, 0, 1, 0,
                1, 0, 5, 0, 6, 0, 1, 0, 7, 0, 0, 0, 29, 0, 1, 0, 1, 0, 0, 0, 5, 42, -73, 0, 9, -79,
                0, 0, 0, 1, 0, 10, 0, 0, 0, 6,
            0, 1, 0, 0, 0, 1, 0, 1, 0, 11, 0, 0, 0, 2, 0, 12,
          };
      this.createFile("P1/lib/X.class", bytes);

      // create libsrc and attach source
      createFolder("P1/libsrc");
      createFile("P1/libsrc/X.java", "public class X extends Y {\n" + "}");
      IPackageFragmentRoot lib = getPackageFragmentRoot("P1/lib");
      lib.attachSource(new Path("/P1/libsrc"), null, null);

      // create Y.java in src folder
      createFile("P1/src/Y.java", "");

      // create working copy on Y.java
      TestWorkingCopyOwner owner = new TestWorkingCopyOwner();
      this.workingCopy = getCompilationUnit("P1/src/Y.java").getWorkingCopy(owner, null);
      this.workingCopy.getBuffer().setContents("public class Y {\n" + "}");
      this.workingCopy.makeConsistent(null);

      // parse and resolve class file
      IClassFile classFile = getClassFile("P1/lib/X.class");
      ASTParser parser = ASTParser.newParser(AST.JLS2);
      parser.setSource(classFile);
      parser.setResolveBindings(true);
      parser.setWorkingCopyOwner(owner);
      CompilationUnit cu = (CompilationUnit) parser.createAST(null);
      List types = cu.types();
      assertEquals("Unexpected number of types in AST", 1, types.size());
      TypeDeclaration type = (TypeDeclaration) types.get(0);
      ITypeBinding typeBinding = type.resolveBinding();
      ITypeBinding superType = typeBinding.getSuperclass();
      assertEquals(
          "Unexpected super type",
          "Y",
          superType == null ? "<null>" : superType.getQualifiedName());
    } finally {
      deleteProject("P1");
    }
  }
  public void testEditOutputFolder01SetOutputFolderForSourceFolder() throws Exception {
    fJavaProject = createProject(DEFAULT_OUTPUT_FOLDER_NAME);
    IPackageFragmentRoot src = JavaProjectHelper.addSourceContainer(fJavaProject, "src");

    IPath projectPath = fJavaProject.getProject().getFullPath();
    IPath outputPath = projectPath.append("srcbin");

    CPJavaProject cpProject = CPJavaProject.createFromExisting(fJavaProject);
    CPListElement element =
        cpProject.getCPElement(
            CPListElement.createFromExisting(src.getRawClasspathEntry(), fJavaProject));
    IStatus status =
        ClasspathModifier.checkSetOutputLocationPrecondition(element, outputPath, false, cpProject);
    assertTrue(status.getMessage(), status.getSeverity() != IStatus.ERROR);

    BuildpathDelta delta =
        ClasspathModifier.setOutputLocation(element, outputPath, false, cpProject);
    assertDeltaResources(delta, new IPath[] {outputPath}, new IPath[0], new IPath[0], new IPath[0]);
    assertDeltaDefaultOutputFolder(delta, fJavaProject.getOutputLocation());
    assertDeltaAddedEntries(delta, new IPath[0]);
    assertDeltaRemovedEntries(delta, new IPath[0]);

    ClasspathModifier.commitClassPath(cpProject, null);

    IClasspathEntry[] classpathEntries = fJavaProject.getRawClasspath();
    assertNumberOfEntries(classpathEntries, 2);
    IClasspathEntry entry = classpathEntries[1];
    assertTrue(src.getRawClasspathEntry() == entry);
    IPath location = entry.getOutputLocation();
    assertTrue(
        "Output path is " + location + " expected was " + outputPath, outputPath.equals(location));
  }
 /**
  * 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);
 }
  public void testRemoveFromBuildpathBug153299Lib() throws Exception {
    fJavaProject = createProject(null);
    IPackageFragmentRoot p01 =
        JavaProjectHelper.addSourceContainer(fJavaProject, null, new IPath[] {new Path("src1/")});

    CPJavaProject cpProject = CPJavaProject.createFromExisting(fJavaProject);
    IPath[] jarPaths = new IPath[] {JavaProjectHelper.MYLIB.makeAbsolute()};

    ClasspathModifier.addExternalJars(jarPaths, cpProject);
    ClasspathModifier.commitClassPath(cpProject, null);

    cpProject = CPJavaProject.createFromExisting(fJavaProject);

    BuildpathDelta delta =
        ClasspathModifier.removeFromBuildpath(
            new CPListElement[] {
              CPListElement.createFromExisting(p01.getRawClasspathEntry(), fJavaProject)
            },
            cpProject);
    assertDeltaResources(delta, new IPath[0], new IPath[] {}, new IPath[0], new IPath[0]);
    assertDeltaDefaultOutputFolder(delta, fJavaProject.getPath());
    assertDeltaRemovedEntries(delta, new IPath[] {p01.getPath()});
    assertDeltaAddedEntries(delta, new IPath[0]);

    ClasspathModifier.commitClassPath(cpProject, null);

    IClasspathEntry[] classpathEntries = fJavaProject.getRawClasspath();
    assertNumberOfEntries(classpathEntries, 2);
  }
 /**
  * Tests that making Javadoc changes to the source file TestClass2 cause the workspace baseline to
  * be updated.
  *
  * <p>This test adds a @noinstantiate tag to the source file TestClass2
  */
 public void testWPUpdateSourceTypeChanged() throws Exception {
   IJavaProject project = getTestingProject();
   assertNotNull("The testing project must exist", project);
   IPackageFragmentRoot root =
       project.findPackageFragmentRoot(
           new Path(project.getElementName()).append(ProjectUtils.SRC_FOLDER).makeAbsolute());
   assertNotNull("the 'src' package fragment root must exist", root);
   NullProgressMonitor monitor = new NullProgressMonitor();
   IPackageFragment fragment = root.getPackageFragment("a.b.c");
   FileUtils.importFileFromDirectory(
       SRC_LOC.append("TestClass2.java").toFile(), fragment.getPath(), monitor);
   ICompilationUnit element =
       (ICompilationUnit) project.findElement(new Path("a/b/c/TestClass2.java"));
   assertNotNull("TestClass2 must exist in the test project", element);
   updateTagInSource(element, "TestClass2", null, "@noinstantiate", false);
   IApiDescription desc = getTestProjectApiDescription();
   assertNotNull("the testing project api description must exist", desc);
   IApiAnnotations annot = desc.resolveAnnotations(Factory.typeDescriptor("a.b.c.TestClass2"));
   assertNotNull("the annotations for a.b.c.TestClass2 cannot be null", annot);
   assertTrue(
       "there must be a noinstantiate setting for TestClass2",
       (annot.getRestrictions() & RestrictionModifiers.NO_INSTANTIATE) != 0);
   assertTrue(
       "there must be a noextend setting for TestClass2",
       (annot.getRestrictions() & RestrictionModifiers.NO_EXTEND) != 0);
 }
Пример #14
0
  /**
   * 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;
  }
Пример #15
0
  /*
   * (non-Javadoc)
   *
   * @see org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator#
   * isSelectedValid(java.lang.Object)
   */
  @Override
  public boolean isSelectedValid(Object element) {
    boolean isValid = false;
    try {
      if (element instanceof IJavaProject) {
        IJavaProject jproject = (IJavaProject) element;
        IPath path = jproject.getProject().getFullPath();
        isValid = (jproject.findPackageFragmentRoot(path) != null);
      } else if (element instanceof IPackageFragmentRoot) {
        IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) element;

        boolean isSrc = (packageFragmentRoot.getKind() == IPackageFragmentRoot.K_SOURCE);
        boolean isGen =
            packageFragmentRoot.getElementName().equals(IAndroidConstants.GEN_SRC_FOLDER)
                && (packageFragmentRoot.getParent() instanceof IJavaProject);

        isValid = isSrc && !isGen;
      } else {
        isValid = true;
      }
    } catch (JavaModelException e) {
      AndmoreLogger.error(ElementTreeValidator.class, e.getLocalizedMessage(), e);
    }
    return isValid;
  }
 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;
 }
Пример #17
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();
 }
  private IPackageFragment[] createDestination(
      IPackageFragmentRoot root, IPackageFragment destination, IProgressMonitor pm)
      throws JavaModelException {
    String packageName = destination.getElementName();
    String[] split = packageName.split("\\."); // $NON-NLS-1$

    ArrayList<IPackageFragment> created = new ArrayList<IPackageFragment>();

    StringBuffer name = new StringBuffer();
    name.append(split[0]);
    for (int i = 0; i < split.length; i++) {
      IPackageFragment fragment = root.getPackageFragment(name.toString());
      if (!fragment.exists()) {
        created.add(fragment);
      }

      if (fragment.equals(destination)) {
        root.createPackageFragment(name.toString(), true, pm);
        return created.toArray(new IPackageFragment[created.size()]);
      }

      name.append("."); // $NON-NLS-1$
      name.append(split[i + 1]);
    }

    return null;
  }
  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;
  }
Пример #20
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;
 }
 /**
  * Returns the Java project of the currently selected package fragment root or <code>null</code>
  * if no package fragment root is configured.
  *
  * @return The current Java project or <code>null</code>.
  * @since 3.3
  */
 public IJavaProject getJavaProject() {
   IPackageFragmentRoot root = getPackageFragmentRoot();
   if (root != null) {
     return root.getJavaProject();
   }
   return null;
 }
  public void testRemoveFromBuildpathBug153299Src() throws Exception {
    fJavaProject = createProject(null);

    // Use the old behavior in order to test the fallback code. Set to ERROR since 3.8.
    fJavaProject.setOption(
        JavaCore.CORE_OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE, JavaCore.IGNORE);

    IPackageFragmentRoot p01 =
        JavaProjectHelper.addSourceContainer(fJavaProject, null, new IPath[] {new Path("src1/")});
    JavaProjectHelper.addSourceContainer(fJavaProject, "src1");

    CPJavaProject cpProject = CPJavaProject.createFromExisting(fJavaProject);

    BuildpathDelta delta =
        ClasspathModifier.removeFromBuildpath(
            new CPListElement[] {
              CPListElement.createFromExisting(p01.getRawClasspathEntry(), fJavaProject)
            },
            cpProject);
    assertDeltaResources(delta, new IPath[0], new IPath[] {}, new IPath[0], new IPath[0]);
    assertDeltaDefaultOutputFolder(
        delta, fJavaProject.getPath().append(DEFAULT_OUTPUT_FOLDER_NAME));
    assertDeltaRemovedEntries(delta, new IPath[] {p01.getPath()});
    assertDeltaAddedEntries(delta, new IPath[0]);

    ClasspathModifier.commitClassPath(cpProject, null);

    IClasspathEntry[] classpathEntries = fJavaProject.getRawClasspath();
    assertNumberOfEntries(classpathEntries, 2);
  }
Пример #23
0
  public static URL getJavadocBaseLocation(IJavaElement element) throws JavaModelException {
    if (element.getElementType() == IJavaElement.JAVA_PROJECT) {
      return getProjectJavadocLocation((IJavaProject) element);
    }

    IPackageFragmentRoot root = JavaModelUtil.getPackageFragmentRoot(element);
    if (root == null) {
      return null;
    }

    if (root.getKind() == IPackageFragmentRoot.K_BINARY) {
      IClasspathEntry entry = root.getResolvedClasspathEntry();
      URL javadocLocation = getLibraryJavadocLocation(entry);
      if (javadocLocation != null) {
        return getLibraryJavadocLocation(entry);
      }
      entry = root.getRawClasspathEntry();
      switch (entry.getEntryKind()) {
        case IClasspathEntry.CPE_LIBRARY:
        case IClasspathEntry.CPE_VARIABLE:
          return getLibraryJavadocLocation(entry);
        default:
          return null;
      }
    } else {
      return getProjectJavadocLocation(root.getJavaProject());
    }
  }
Пример #24
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;
 }
Пример #26
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();
   }
 }
Пример #27
0
 /**
  * Adds a new source container specified by the container name to the source path of the specified
  * project
  *
  * @param jproject
  * @param containerName
  * @return the package fragment root of the container name
  * @throws CoreException
  */
 public static IPackageFragmentRoot addSourceContainer(IJavaProject jproject, String containerName)
     throws CoreException {
   IProject project = jproject.getProject();
   IPackageFragmentRoot root =
       jproject.getPackageFragmentRoot(addFolderToProject(project, containerName));
   IClasspathEntry cpe = JavaCore.newSourceEntry(root.getPath());
   addToClasspath(jproject, cpe);
   return root;
 }
Пример #28
0
 public Type(IType type) {
   if (type == null) throw new IllegalArgumentException("Invalid argument: JDT Type is null");
   this.type = type;
   packageName = type.getPackageFragment().getElementName();
   IPackageFragmentRoot packageRoot = (IPackageFragmentRoot) type.getPackageFragment().getParent();
   IFolder folder = (IFolder) packageRoot.getResource();
   sourceFolder = folder.getName();
   // sourceFolder = type.getfo
 }
 /**
  * Adds the package with the given name to the given package fragment root
  *
  * @param the project to add the package to
  * @param srcroot the absolute path to the package fragment root to add the new package to
  * @param packagename the name of the new package
  * @return the new {@link IPackageFragment} or <code>null</code>
  */
 public IPackageFragment assertTestPackage(IJavaProject project, IPath srcroot, String packagename)
     throws JavaModelException {
   IPackageFragment fragment = null;
   IPackageFragmentRoot root = project.findPackageFragmentRoot(srcroot);
   assertNotNull("the 'src' package fragment root must exist", root);
   fragment = root.createPackageFragment(packagename, true, new NullProgressMonitor());
   assertNotNull("the new package '" + packagename + "' should have been created", fragment);
   return fragment;
 }
 private void collectCompilationUnits(IPackageFragmentRoot root, Collection result)
     throws JavaModelException {
   if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
     IJavaElement[] children = root.getChildren();
     for (int i = 0; i < children.length; i++) {
       collectCompilationUnits((IPackageFragment) children[i], result);
     }
   }
 }