private Set<String> outputFoldersForProject(final IJavaProject project) {
    final Set<String> outputFolders = new HashSet<String>();
    final IPath projectLocation = projectLocationPath(project);

    try {
      final IPath defaultOutputLocation = project.getOutputLocation();
      if (defaultOutputLocation != null) {
        final IPath fullPath = appendPathTo(projectLocation, defaultOutputLocation);
        if (fullPath.toFile().exists()) {
          outputFolders.add(fullPath.toOSString());
        }
      }
      for (final IClasspathEntry entry : project.getRawClasspath()) {
        if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
          final IPath outputLocation = entry.getOutputLocation();
          if (outputLocation != null) {
            final IPath fullPath = appendPathTo(projectLocation, outputLocation);
            if (fullPath.toFile().exists()) {
              outputFolders.add(fullPath.toOSString());
            }
          }
        }
      }
    } catch (final JavaModelException ex) {
      FeatureEditorPlugin.instance()
          .warn("Could not get output folder location for project " + project.getElementName());
    }

    return outputFolders;
  }
  public static void addServletLibToWebInf(IProject project, IProgressMonitor monitor) {

    monitor = Util.getNonNullMonitor(monitor);

    try {
      monitor.beginTask("", 1);

      IJavaProject javaProject = JavaCore.create(project);
      IClasspathEntry[] oldClasspath = javaProject.getRawClasspath();
      IClasspathEntry[] newClasspath = new IClasspathEntry[oldClasspath.length + 1];
      System.arraycopy(oldClasspath, 0, newClasspath, 0, oldClasspath.length);
      IClasspathEntry gwtServletJarEntry =
          JavaCore.newVariableEntry(Util.getGwtServletLibPath(), null, null);
      IClasspathAttribute attr =
          JavaCore.newClasspathAttribute("org.eclipse.jst.component.dependency", "/WEB-INF/lib");
      gwtServletJarEntry =
          JavaCore.newVariableEntry(
              gwtServletJarEntry.getPath(),
              null,
              null,
              new IAccessRule[0],
              new IClasspathAttribute[] {attr},
              false);
      newClasspath[oldClasspath.length] = gwtServletJarEntry;
      javaProject.setRawClasspath(newClasspath, monitor);

    } catch (JavaModelException e) {
      // the jar is already in the classpath.
      Activator.logException(e);
    } finally {
      monitor.done();
    }
  }
 protected void updateContainerAttributes(
     IProject project,
     IClasspathAttribute attributeToAdd,
     String attributeToDelete,
     IProgressMonitor monitor)
     throws JavaModelException {
   IJavaProject javaProject = JavaCore.create(project);
   if (javaProject == null) return;
   IClasspathEntry[] cp = javaProject.getRawClasspath();
   for (int i = 0; i < cp.length; i++) {
     if (IClasspathEntry.CPE_CONTAINER == cp[i].getEntryKind()
         && BuildPathManager.isMaven2ClasspathContainer(cp[i].getPath())) {
       LinkedHashMap<String, IClasspathAttribute> attrs =
           new LinkedHashMap<String, IClasspathAttribute>();
       for (IClasspathAttribute attr : cp[i].getExtraAttributes()) {
         if (!attr.getName().equals(attributeToDelete)) {
           attrs.put(attr.getName(), attr);
         }
       }
       attrs.put(attributeToAdd.getName(), attributeToAdd);
       IClasspathAttribute[] newAttrs =
           attrs.values().toArray(new IClasspathAttribute[attrs.size()]);
       cp[i] =
           JavaCore.newContainerEntry(
               cp[i].getPath(), cp[i].getAccessRules(), newAttrs, cp[i].isExported());
       break;
     }
   }
   javaProject.setRawClasspath(cp, monitor);
 }
  public void testConfigureSetsIgnoreWarningsForGenFolder() throws Exception {
    IJavaProject project = JavaCore.create(importAndroidProject("ignore-gen-warnings"));
    IClasspathEntry gen = findSourceEntry(project.getRawClasspath(), "gen");

    assertTrue(
        "external assets folder isn't linked", booleanAttribute(IGNORE_OPTIONAL_PROBLEMS, gen));
  }
  public static void addUserLibToClassPath(IProject project, IProgressMonitor monitor) {

    monitor = Util.getNonNullMonitor(monitor);
    try {

      IJavaProject javaProject = JavaCore.create(project);
      IClasspathEntry[] oldClasspath = javaProject.getRawClasspath();
      IClasspathEntry[] newClasspath = new IClasspathEntry[oldClasspath.length + 1];
      System.arraycopy(oldClasspath, 0, newClasspath, 0, oldClasspath.length);
      IClasspathEntry gwtuserJarEntry =
          JavaCore.newVariableEntry(Util.getGwtUserLibPath(), null, null);
      gwtuserJarEntry =
          JavaCore.newVariableEntry(
              gwtuserJarEntry.getPath(),
              null,
              null,
              new IAccessRule[0],
              new IClasspathAttribute[0],
              false);
      newClasspath[oldClasspath.length] = gwtuserJarEntry;
      javaProject.setRawClasspath(newClasspath, monitor);

    } catch (CoreException e) {
      // the jar is already in the classpath.
      Activator.logException(e);
    } finally {
      monitor.done();
    }
  }
 /**
  * Checks if all source files are existing. If not, create them.
  *
  * @param javaProj
  */
 private void checkSourceFolders(final IJavaProject javaProj) {
   if (javaProj == null) return;
   if (javaProj.exists()) {
     try {
       if (!javaProj.isOpen()) {
         javaProj.open(new NullProgressMonitor());
       }
       IClasspathEntry[] entries = javaProj.getRawClasspath();
       for (IClasspathEntry entry : entries) {
         if (IClasspathEntry.CPE_SOURCE == entry.getEntryKind()) {
           IPath path = entry.getPath();
           final IPath folderPath = path.removeFirstSegments(1);
           if (!folderPath.isEmpty()) {
             Display.getDefault()
                 .asyncExec(
                     new Runnable() {
                       public void run() {
                         try {
                           ImportUtils.createFolders(
                               javaProj.getProject(), folderPath, IResource.FORCE);
                         } catch (CoreException e) {
                           _log.error(e.getMessage());
                         }
                       }
                     });
           }
         }
       }
     } catch (JavaModelException e) {
       _log.error("findProjectSources: Could not retrieve project sources:", e); // $NON-NLS-1$
     }
   }
 }
  public void testRemoveFromBuildpath01RemoveLibs() throws Exception {
    fJavaProject = createProject(DEFAULT_OUTPUT_FOLDER_NAME);

    IPath[] jarPaths =
        new IPath[] {
          JavaProjectHelper.MYLIB.makeAbsolute(), JavaProjectHelper.JUNIT_SRC_381.makeAbsolute()
        };

    CPJavaProject cpProject = CPJavaProject.createFromExisting(fJavaProject);
    BuildpathDelta delta = ClasspathModifier.addExternalJars(jarPaths, cpProject);
    ClasspathModifier.commitClassPath(cpProject, null);

    CPListElement[] toRemove = {delta.getAddedEntries().get(0), delta.getAddedEntries().get(1)};

    delta = ClasspathModifier.removeFromBuildpath(toRemove, cpProject);
    assertDeltaResources(delta, new IPath[0], new IPath[0], new IPath[0], new IPath[0]);
    assertDeltaDefaultOutputFolder(
        delta, fJavaProject.getPath().append(DEFAULT_OUTPUT_FOLDER_NAME));
    assertDeltaRemovedEntries(delta, new IPath[] {toRemove[0].getPath(), toRemove[1].getPath()});
    assertDeltaAddedEntries(delta, new IPath[0]);

    ClasspathModifier.commitClassPath(cpProject, null);

    IClasspathEntry[] classpathEntries = fJavaProject.getRawClasspath();
    assertNumberOfEntries(classpathEntries, 1);
  }
  public void testAddExternalJarBug132827() throws Exception {
    fJavaProject = createProject(DEFAULT_OUTPUT_FOLDER_NAME);

    IPath[] jarPaths = new IPath[] {JavaProjectHelper.MYLIB.makeAbsolute()};

    CPJavaProject cpProject = CPJavaProject.createFromExisting(fJavaProject);
    ClasspathModifier.addExternalJars(jarPaths, cpProject);
    ClasspathModifier.commitClassPath(cpProject, null);

    cpProject = CPJavaProject.createFromExisting(fJavaProject);
    IStatus status = ClasspathModifier.checkAddExternalJarsPrecondition(jarPaths, cpProject);
    assertTrue(status.getSeverity() == IStatus.INFO);

    BuildpathDelta delta = ClasspathModifier.addExternalJars(jarPaths, cpProject);
    assertDeltaResources(delta, new IPath[0], new IPath[0], new IPath[0], new IPath[0]);
    assertDeltaDefaultOutputFolder(delta, fJavaProject.getOutputLocation());
    assertDeltaRemovedEntries(delta, new IPath[0]);
    assertDeltaAddedEntries(delta, new IPath[0]);

    ClasspathModifier.commitClassPath(cpProject, null);

    IClasspathEntry[] classpathEntries = fJavaProject.getRawClasspath();
    assertNumberOfEntries(classpathEntries, 2);
    assertIsOnBuildpath(classpathEntries, JavaProjectHelper.MYLIB.makeAbsolute());
  }
  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);
  }
  public void testRemoveFromBuildpath01() throws Exception {
    fJavaProject = createProject(DEFAULT_OUTPUT_FOLDER_NAME);
    IPackageFragmentRoot src1 = JavaProjectHelper.addSourceContainer(fJavaProject, "src1");
    IPackageFragmentRoot src2 = JavaProjectHelper.addSourceContainer(fJavaProject, "src2");

    CPJavaProject cpProject = CPJavaProject.createFromExisting(fJavaProject);
    CPListElement[] toRemove = new CPListElement[2];
    toRemove[0] = CPListElement.createFromExisting(src1.getRawClasspathEntry(), fJavaProject);
    toRemove[1] = CPListElement.createFromExisting(src2.getRawClasspathEntry(), fJavaProject);

    BuildpathDelta delta = ClasspathModifier.removeFromBuildpath(toRemove, cpProject);
    assertDeltaResources(
        delta,
        new IPath[0],
        new IPath[] {src1.getPath(), src2.getPath()},
        new IPath[0],
        new IPath[0]);
    assertDeltaDefaultOutputFolder(
        delta, fJavaProject.getPath().append(DEFAULT_OUTPUT_FOLDER_NAME));
    assertDeltaRemovedEntries(delta, new IPath[] {src1.getPath(), src2.getPath()});
    assertDeltaAddedEntries(delta, new IPath[0]);

    ClasspathModifier.commitClassPath(cpProject, null);

    IClasspathEntry[] classpathEntries = fJavaProject.getRawClasspath();
    assertNumberOfEntries(classpathEntries, 1);
  }
  // test that after a source folder is deleted, all
  // class files nd resources are removed from the
  // output folder
  public void testDeleteSourceFolder() throws Exception {
    IProject proj = createPredefinedProject("CopyDerived1");
    getWorkspace().build(IncrementalProjectBuilder.FULL_BUILD, null);

    IJavaProject jProj = JavaCore.create(proj);
    IClasspathEntry[] classpath = jProj.getRawClasspath();
    IClasspathEntry[] newClasspath = new IClasspathEntry[classpath.length - 1];

    // remove the classpath entry corresponding to src
    for (int i = 0, j = 0; i < classpath.length; i++, j++) {
      if (classpath[i].getPath().lastSegment().toString().equals("src")) {
        j--;
        continue;
      }
      newClasspath[j] = classpath[i];
    }

    jProj.setRawClasspath(newClasspath, true, null);

    proj.build(IncrementalProjectBuilder.FULL_BUILD, null);

    IFolder out = proj.getFolder("bin");
    checkFolderIsNotDerived(out, "");
    checkFileNoExist(out, "file.txt");
    checkFileNoExist(out, "Nothing.class");
    checkFileNoExist(out, "Nothing2.class");
    checkFolderNoExist(out, "package1");
    checkFileNoExist(out, "package1/file.txt");
    checkFileNoExist(out, "package1/Nothing.class");
    checkFileNoExist(out, "package1/Nothing2.class");
  }
  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));
  }
 private void addSystemLibraries() throws JavaModelException {
   IClasspathEntry[] oldEntries = javaProject.getRawClasspath();
   IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1];
   System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length);
   newEntries[oldEntries.length] = JavaRuntime.getDefaultJREContainerEntry();
   javaProject.setRawClasspath(newEntries, null);
 }
 public static boolean hasProjectDependencyProblem(IJavaProject javaProject) {
   IProject project = javaProject.getProject();
   try {
     ResourceBuilderUtils.cleanProblemMarkers(
         project,
         new String[] {IRIMMarker.PROJECT_DEPENDENCY_PROBLEM_MARKER},
         IResource.DEPTH_ONE);
   } catch (CoreException e) {
     _log.error(e);
   }
   IClasspathEntry[] classpathEntries = null;
   try {
     classpathEntries = javaProject.getRawClasspath();
   } catch (JavaModelException e) {
     _log.error(e);
     return true;
   }
   IProject dependentProject = null;
   String projectName = null;
   boolean hasDependencyError = false;
   for (IClasspathEntry entry : classpathEntries) {
     if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
       projectName = entry.getPath().lastSegment();
       dependentProject = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
       if (!isValidDependency(javaProject.getProject(), dependentProject) && !hasDependencyError) {
         hasDependencyError = true;
       }
     }
   }
   return hasDependencyError;
 }
  private void restoreTestProject() throws Exception {
    IJavaProject javaProject = getRoot().getJavaProject();
    if (javaProject.exists()) {
      IClasspathEntry srcEntry = getRoot().getRawClasspathEntry();
      IClasspathEntry jreEntry = RefactoringTestSetup.getJRELibrary().getRawClasspathEntry();
      IClasspathEntry[] cpes = javaProject.getRawClasspath();
      ArrayList newCPEs = new ArrayList();
      boolean cpChanged = false;
      for (int i = 0; i < cpes.length; i++) {
        IClasspathEntry cpe = cpes[i];
        if (cpe.equals(srcEntry) || cpe.equals(jreEntry)) {
          newCPEs.add(cpe);
        } else {
          cpChanged = true;
        }
      }
      if (cpChanged) {
        IClasspathEntry[] newCPEsArray =
            (IClasspathEntry[]) newCPEs.toArray(new IClasspathEntry[newCPEs.size()]);
        javaProject.setRawClasspath(newCPEsArray, null);
      }

      Object[] nonJavaResources = javaProject.getNonJavaResources();
      for (int i = 0; i < nonJavaResources.length; i++) {
        Object kid = nonJavaResources[i];
        if (kid instanceof IResource) {
          IResource resource = (IResource) kid;
          if (!PROJECT_RESOURCE_CHILDREN.contains(resource.getName())) {
            JavaProjectHelper.delete(resource);
          }
        }
      }
    }
  }
  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);
  }
  private static ClassFileReader getClassFileReaderForClassName(String className, IProject project)
      throws JavaModelException, MalformedURLException {
    IJavaProject jp = JavaCore.create(project);

    File outputDirectory = convertPathToFile(project, jp.getOutputLocation());
    File classFile = new File(outputDirectory, ClassUtils.getClassFileName(className));
    if (classFile.exists() && classFile.canRead()) {
      try {
        return ClassFileReader.read(classFile);
      } catch (ClassFormatException e) {
      } catch (IOException e) {
      }
    }

    IClasspathEntry[] classpath = jp.getRawClasspath();
    for (int i = 0; i < classpath.length; i++) {
      IClasspathEntry path = classpath[i];
      if (path.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
        outputDirectory = convertPathToFile(project, path.getOutputLocation());
        classFile = new File(outputDirectory, ClassUtils.getClassFileName(className));
        if (classFile.exists() && classFile.canRead()) {
          try {
            return ClassFileReader.read(classFile);
          } catch (ClassFormatException e) {
          } catch (IOException e) {
          }
        }
      }
    }
    return null;
  }
  public void testCuGetClass2() throws Exception {
    // Test for https://bugs.eclipse.org/bugs/show_bug.cgi?id=211037
    // In 1.6, Object#getClass() declares return type Class<?>, but in 1.5, it's Class<? extends
    // Object>.
    performCuOK();

    // Test the same with 1.5:
    IJavaProject project = RefactoringTestSetup.getProject();

    ArrayList classpath = new ArrayList(Arrays.asList(project.getRawClasspath()));
    IClasspathEntry jreEntry = RefactoringTestSetup.getJRELibrary().getRawClasspathEntry();
    classpath.remove(jreEntry);
    IClasspathEntry[] noRTJarCPEs =
        (IClasspathEntry[]) classpath.toArray(new IClasspathEntry[classpath.size()]);

    project.setRawClasspath(noRTJarCPEs, new NullProgressMonitor());
    JavaProjectHelper.addRTJar15(project);

    try {
      performCuOK();
    } finally {
      project.setRawClasspath(noRTJarCPEs, new NullProgressMonitor());
      JavaProjectHelper.addRTJar16(project);
    }
  }
  public void newResource(final IResource resource) {
    if (resource instanceof IFile
        && resource.getName().endsWith(".groovy")
        && !resource.getName().endsWith("Tests.groovy")) {
      // Only open resource if is in any source folder
      IJavaProject jp = JdtUtils.getJavaProject(project);
      if (jp != null) {
        try {
          for (IClasspathEntry entry : jp.getRawClasspath()) {
            if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
              if (entry.getPath() != null && entry.getPath().isPrefixOf(resource.getFullPath())) {
                Display.getDefault()
                    .asyncExec(
                        new Runnable() {

                          public void run() {
                            SpringUIUtils.openInEditor((IFile) resource, -1);
                          }
                        });
                break;
              }
            }
          }
        } catch (JavaModelException e) {
        }
      }
    }
  }
  protected void changeToExistingLibrary(
      Shell shell, IPath path, boolean isNew, final IJavaProject project) {
    try {
      IClasspathEntry[] entries = project.getRawClasspath();
      int idx = indexOfClasspath(entries, path);
      if (idx == -1) {
        return;
      }
      IClasspathEntry[] res;
      if (isNew) {
        res = BuildPathDialogAccess.chooseContainerEntries(shell, project, entries);
        if (res == null) {
          return;
        }
      } else {
        IClasspathEntry resEntry =
            BuildPathDialogAccess.configureContainerEntry(shell, entries[idx], project, entries);
        if (resEntry == null) {
          return;
        }
        res = new IClasspathEntry[] {resEntry};
      }
      final IClasspathEntry[] newEntries = new IClasspathEntry[entries.length - 1 + res.length];
      System.arraycopy(entries, 0, newEntries, 0, idx);
      System.arraycopy(res, 0, newEntries, idx, res.length);
      System.arraycopy(entries, idx + 1, newEntries, idx + res.length, entries.length - idx - 1);

      IRunnableContext context = JavaPlugin.getActiveWorkbenchWindow();
      if (context == null) {
        context = PlatformUI.getWorkbench().getProgressService();
      }
      context.run(
          true,
          true,
          new IRunnableWithProgress() {
            public void run(IProgressMonitor monitor)
                throws InvocationTargetException, InterruptedException {
              try {
                project.setRawClasspath(newEntries, project.getOutputLocation(), monitor);
              } catch (CoreException e) {
                throw new InvocationTargetException(e);
              }
            }
          });
    } catch (JavaModelException e) {
      String title = NewWizardMessages.UserLibraryMarkerResolutionGenerator_error_title;
      String message =
          NewWizardMessages.UserLibraryMarkerResolutionGenerator_error_creationfailed_message;
      ExceptionHandler.handle(e, shell, title, message);
    } catch (InvocationTargetException e) {
      String title = NewWizardMessages.UserLibraryMarkerResolutionGenerator_error_title;
      String message =
          NewWizardMessages.UserLibraryMarkerResolutionGenerator_error_applyingfailed_message;
      ExceptionHandler.handle(e, shell, title, message);
    } catch (InterruptedException e) {
      // user cancelled
    }
  }
 public void testConfigureNonAndroidProjectDoesAddGenFolder() throws Exception {
   IProject project = importAndroidProject(SIMPLE_PROJECT_NAME);
   IJavaProject javaProject = JavaCore.create(project);
   for (IClasspathEntry entry : javaProject.getRawClasspath()) {
     assertFalse(
         "classpath contains reference to gen directory",
         entry.getPath().toOSString().contains("gen"));
   }
 }
 public void addJar(Plugin plugin, String jar)
     throws MalformedURLException, IOException, JavaModelException {
   Path result = findFileInPlugin(plugin, jar);
   IClasspathEntry[] oldEntries = javaProject.getRawClasspath();
   IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1];
   System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length);
   newEntries[oldEntries.length] = JavaCore.newLibraryEntry(result, null, null);
   javaProject.setRawClasspath(newEntries, null);
 }
Example #23
0
  public static IResource getSourceResource(IResource classFile) {
    try {
      if (isJavaProject(classFile) && classFile.getName().endsWith(CLASS_FILE_EXTENSION)) {
        IPath classFilePath = classFile.getFullPath();
        String classFileName = null;

        IJavaProject project = getJavaProject(classFile);
        IPath defaultOutput = project.getOutputLocation();

        if (defaultOutput.isPrefixOf(classFilePath)) {
          classFileName =
              classFilePath.removeFirstSegments(defaultOutput.segmentCount()).toString();
        } else {
          for (IClasspathEntry entry : project.getRawClasspath()) {
            if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
              IPath output = entry.getOutputLocation();
              if (output != null) {
                if (classFilePath.isPrefixOf(output)) {
                  classFileName =
                      classFilePath.removeFirstSegments(output.segmentCount()).toString();
                }
              }
            }
          }
        }

        if (classFileName != null) {
          // Replace file extension
          String sourceFileName = classFileName.replace(".class", ".java");
          for (IClasspathEntry entry : project.getRawClasspath()) {
            if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
              IPath path = entry.getPath().append(sourceFileName).removeFirstSegments(1);
              IResource resource = project.getProject().findMember(path);
              if (resource != null) {
                return resource;
              }
            }
          }
        }
      }
    } catch (JavaModelException e) {
    }
    return null;
  }
Example #24
0
 public static Optional<IClasspathEntry> getModelPathClasspathEntry(IJavaProject javaProject) {
   try {
     return Arrays.stream(javaProject.getRawClasspath())
         .filter(classpathEntry -> classpathEntry.getEntryKind() == IClasspathEntry.CPE_CONTAINER)
         .filter(classpathEntry -> classpathEntry.getPath().equals(Constants.MODELPATH))
         .findFirst();
   } catch (JavaModelException e) {
     return Optional.empty();
   }
 }
Example #25
0
 /**
  * @param project
  * @return
  */
 public static IClasspathEntry[] getClasspathEntries(IProject project) {
   if (project != null) {
     IJavaProject javaProject = JavaCore.create(project);
     try {
       IClasspathEntry[] classPathEntries = javaProject.getRawClasspath();
       return classPathEntries;
     } catch (JavaModelException e) {
     }
   }
   return null;
 }
  private IPackageFragmentRoot createSourceFolder() throws CoreException {
    IFolder folder = project.getFolder("src");
    folder.create(false, true, null);
    IPackageFragmentRoot root = javaProject.getPackageFragmentRoot(folder);

    IClasspathEntry[] oldEntries = javaProject.getRawClasspath();
    IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1];
    System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length);
    newEntries[oldEntries.length] = JavaCore.newSourceEntry(root.getPath());
    javaProject.setRawClasspath(newEntries, null);
    return root;
  }
 protected static IClasspathContainer getWebLibClasspathContainer(IJavaProject project)
     throws JavaModelException {
   IClasspathEntry[] entries = project.getRawClasspath();
   for (int i = 0; i < entries.length; i++) {
     IClasspathEntry entry = entries[i];
     if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER
         && "org.eclipse.jst.j2ee.internal.web.container".equals(entry.getPath().segment(0))) {
       return JavaCore.getClasspathContainer(entry.getPath(), project);
     }
   }
   return null;
 }
Example #28
0
  /**
   * @param javaProject
   * @param newEntry
   * @throws JavaModelException
   */
  public static final void addToClasspath(IJavaProject javaProject, IClasspathEntry newEntry)
      throws JavaModelException {
    if (newEntry == null) {
      return;
    }
    IClasspathEntry[] oldEntries = javaProject.getRawClasspath();
    IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1];
    System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length);

    newEntries[oldEntries.length] = newEntry;
    javaProject.setRawClasspath(newEntries, null);
  }
  public void testEditOutputFolder04RemoveProjectAndExcludeOutput() 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);

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

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

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

    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.getPath().append(DEFAULT_OUTPUT_FOLDER_NAME));
    assertDeltaRemovedEntries(delta, new IPath[] {fJavaProject.getPath()});
    assertDeltaAddedEntries(delta, new IPath[0]);

    ClasspathModifier.commitClassPath(cpProject, null);

    assertTrue(
        "Default output folder was not set to bin",
        fJavaProject
            .getOutputLocation()
            .equals(fJavaProject.getPath().append(DEFAULT_OUTPUT_FOLDER_NAME)));

    IClasspathEntry[] classpathEntries = fJavaProject.getRawClasspath();
    assertNumberOfEntries(classpathEntries, 3);
    IClasspathEntry entry = classpathEntries[1];
    assertTrue(src1.getRawClasspathEntry() == entry);
    IPath location = entry.getOutputLocation();
    assertTrue(
        "Output path is " + location + " expected was " + outputPath, outputPath.equals(location));

    entry = classpathEntries[2];
    assertTrue(src2.getRawClasspathEntry() == entry);
    IPath[] exclusionPatterns = entry.getExclusionPatterns();
    assertTrue(exclusionPatterns.length == 1);
    assertTrue(exclusionPatterns[0].toString().equals("bin/"));
  }
  private static IClasspathContainer allocateContainer(
      IJavaProject javaProject, List<IClasspathEntry> entries, IPath id, String description) {

    if (AndmoreAndroidPlugin.getDefault()
        == null) { // This is totally weird, but I've seen it happen!
      return null;
    }

    // First check that the project has a library-type container.
    try {
      IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
      final IClasspathEntry[] oldRawClasspath = rawClasspath;

      boolean foundContainer = false;
      for (IClasspathEntry entry : rawClasspath) {
        // get the entry and kind
        final int kind = entry.getEntryKind();

        if (kind == IClasspathEntry.CPE_CONTAINER) {
          String path = entry.getPath().toString();
          String idString = id.toString();
          if (idString.equals(path)) {
            foundContainer = true;
            break;
          }
        }
      }

      // if there isn't any, add it.
      if (foundContainer == false) {
        // add the android container to the array
        rawClasspath =
            ProjectHelper.addEntryToClasspath(
                rawClasspath, JavaCore.newContainerEntry(id, true /*isExported*/));
      }

      // set the new list of entries to the project
      if (rawClasspath != oldRawClasspath) {
        javaProject.setRawClasspath(rawClasspath, new NullProgressMonitor());
      }
    } catch (JavaModelException e) {
      // This really shouldn't happen, but if it does, simply return null (the calling
      // method will fails as well)
      return null;
    }

    return new AndroidClasspathContainer(
        entries.toArray(new IClasspathEntry[entries.size()]),
        id,
        description,
        IClasspathContainer.K_APPLICATION);
  }