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;
  }
  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 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 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));
  }
Ejemplo n.º 5
0
  // We need this as a separate method, as we'll put dependent projects' output
  // on the classpath
  private static void addProjectClasspath(
      IWorkspaceRoot root,
      IJavaProject otherJavaProject,
      Set<IJavaProject> projectsProcessed,
      Set<String> classpath) {

    // Check for cycles. If we've already seen this project,
    // no need to go any further.
    if (projectsProcessed.contains(otherJavaProject)) {
      return;
    }
    projectsProcessed.add(otherJavaProject);

    try {
      // Add the output directory first as a binary entry for other projects
      IPath binPath = otherJavaProject.getOutputLocation();
      IResource binPathResource = root.findMember(binPath);
      String binDirString;
      if (binPathResource != null) {
        binDirString = root.findMember(binPath).getLocation().toOSString();
      } else {
        binDirString = binPath.toOSString();
      }
      classpath.add(binDirString);

      // Now the rest of the classpath
      IClasspathEntry[] classpathEntries = otherJavaProject.getResolvedClasspath(true);
      for (IClasspathEntry entry : classpathEntries) {
        if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
          IPath cpPath = entry.getPath();

          IResource res = root.findMember(cpPath);

          // If res is null, the path is absolute (it's an external jar)
          if (res == null) {
            classpath.add(cpPath.toOSString());
          } else {
            // It's relative
            classpath.add(res.getLocation().toOSString());
          }
        } else if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
          IPath otherProjectPath = entry.getPath();
          IProject otherProject = root.getProject(otherProjectPath.segment(0));
          IJavaProject yetAnotherJavaProject = JavaCore.create(otherProject);
          if (yetAnotherJavaProject != null) {
            addProjectClasspath(root, yetAnotherJavaProject, projectsProcessed, classpath);
          }
        }
        // Ignore source types
      }
    } catch (JavaModelException jme) {
      AptPlugin.log(
          jme,
          "Failed to get the classpath for the following project: "
              + otherJavaProject); //$NON-NLS-1$
    }
  }
 public void testConfigureNonAndroidProjectDoesSetOutputLocation() throws Exception {
   IProject project = importAndroidProject(SIMPLE_PROJECT_NAME);
   IJavaProject javaProject = JavaCore.create(project);
   assertFalse(
       "output location set to android value for non-android project",
       javaProject
           .getOutputLocation()
           .toString()
           .equals("/" + SIMPLE_PROJECT_NAME + "/target/android-classes"));
 }
  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 void setClassLoader() {
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    IJavaProject javaProject = getJavaProject();

    try {
      if (javaProject != null) {
        List<URL> entries = new ArrayList<URL>();
        IPath path = javaProject.getOutputLocation();
        IResource iResource = root.findMember(path);
        path = iResource.getLocation();
        path = path.addTrailingSeparator();
        entries.add(path.toFile().toURL());

        IClasspathEntry[] cpEntries = javaProject.getRawClasspath();
        for (IClasspathEntry cpEntry : cpEntries) {
          switch (cpEntry.getEntryKind()) {
            case IClasspathEntry.CPE_SOURCE:
              path = cpEntry.getOutputLocation();
              if (path != null) {
                iResource = root.findMember(path);
                path = iResource.getLocation();
                path = path.addTrailingSeparator();
                entries.add(path.toFile().toURL());
              }
              break;

            case IClasspathEntry.CPE_LIBRARY:
              iResource = root.findMember(cpEntry.getPath());
              if (iResource == null) {
                // resource is not in workspace, must be an external JAR
                path = cpEntry.getPath();
              } else {
                path = iResource.getLocation();
              }
              entries.add(path.toFile().toURL());
              break;
          }
        }

        ClassLoader oldCl = Thread.currentThread().getContextClassLoader();
        URL[] entryArray = new URL[entries.size()];
        entries.toArray(entryArray);
        ClassLoader newCl = new URLClassLoader(entryArray, oldCl);
        Thread.currentThread().setContextClassLoader(newCl);
        oldClassLoader = oldCl;
      }
    } catch (Exception e) {
      // ignore - something too complex is wrong
      ;
    }
  }
Ejemplo n.º 9
0
 public static byte[] getClassContent(IJavaProject javaProject, String className) {
   if (javaProject == null || !javaProject.exists()) return null;
   String resourceName = className.replace('.', '/') + ".class";
   try {
     IPath outPath =
         javaProject
             .getProject()
             .getLocation()
             .removeLastSegments(1)
             .append(javaProject.getOutputLocation());
     outPath = outPath.addTrailingSeparator();
     {
       URL url = toURL(outPath.append(resourceName));
       if (url != null) {
         InputStream inputStream = url.openStream();
         byte[] content = new byte[inputStream.available()];
         inputStream.read(content);
         return content;
       }
       for (IProject project : javaProject.getProject().getReferencedProjects()) {
         if (!project.isOpen()) {
           continue;
         }
         IJavaProject javaReferencedProject = JavaCore.create(project);
         if (javaReferencedProject.exists()) {
           byte[] content = getClassContent(javaReferencedProject, className);
           if (content != null) {
             return content;
           }
         }
       }
     }
     IType type = javaProject.findType(className);
     if (type != null && type.exists()) {
       if (type.isBinary()) {
         return type.getClassFile().getBytes();
       } else {
         IJavaProject typeProject = type.getJavaProject();
         if (!javaProject.equals(typeProject)) {
           return getClassContent(typeProject, className);
         }
       }
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
   return null;
 }
  protected Collection<String> getNonTestSourceOutputLocations() {
    Collection<String> outputs = getSourceOutputLocations(false);
    Set<String> nonTestOutput = new HashSet<String>(outputs);
    // add the Java project default output location as well
    try {
      IPath location = javaProject.getOutputLocation();
      location = getWorkspaceFullPath(location);

      if (location != null) {
        nonTestOutput.add(location.toOSString());
      }
    } catch (JavaModelException e) {
      CloudFoundryPlugin.log(e);
    }
    return nonTestOutput;
  }
  public IArchive createDefaultConfiguration(String projectName, IProgressMonitor monitor) {
    // IPackageType t = this;
    IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
    Assert.isNotNull(project);

    IJavaProject javaProject = JavaCore.create(project);
    Assert.isNotNull(javaProject);

    if (monitor == null) monitor = new NullProgressMonitor();

    monitor.beginTask(
        ArchivesCore.bind(ArchivesCoreMessages.CreatingDefaultJarConfig, project.getName()), 2);

    IPath outputPath;
    try {
      outputPath = javaProject.getOutputLocation();
    } catch (JavaModelException e) {
      ArchivesCore.getInstance().getLogger().log(IStatus.WARNING, e.getMessage(), e);
      return null;
    }

    outputPath = outputPath.removeFirstSegments(1);
    IContainer outputContainer = project.getFolder(outputPath);

    IArchive jar = new ArchiveImpl();

    jar.setDestinationPath(project.getLocation());
    jar.setInWorkspace(true);
    jar.setExploded(false);
    jar.setName(project.getName() + ".jar"); // $NON-NLS-1$
    jar.setArchiveType(this);

    IArchiveStandardFileSet classes = new ArchiveFileSetImpl();
    classes.setIncludesPattern("**/*"); // $NON-NLS-1$
    classes.setRawSourcePath(outputContainer.getFullPath().toString());
    classes.setInWorkspace(true);

    try {
      jar.addChild(classes);
    } catch (ArchivesModelException ame) {
    }

    monitor.worked(1);
    monitor.done();

    return jar;
  }
 /**
  * Tests that changing the output folder settings for a project cause the class file containers to
  * be updated
  */
 public void testWPUpdateDefaultOutputFolderChanged() throws Exception {
   IJavaProject project = getTestingProject();
   assertNotNull("The testing project must exist", project);
   IContainer container = ProjectUtils.addFolderToProject(project.getProject(), "bin2");
   assertNotNull("the new output folder cannot be null", container);
   IApiComponent component = getWorkspaceBaseline().getApiComponent(project.getElementName());
   assertNotNull("the workspace component must exist", component);
   int before = component.getApiTypeContainers().length;
   project.setOutputLocation(container.getFullPath(), new NullProgressMonitor());
   waitForAutoBuild();
   assertTrue(
       "there must be the same number of containers after the change",
       before == component.getApiTypeContainers().length);
   assertTrue(
       "the new output location should be 'bin2'",
       "bin2".equalsIgnoreCase(project.getOutputLocation().toFile().getName()));
 }
  @Test
  public void shouldConfigureJavaSourceAndTarget() throws JavaModelException, IOException {
    IJavaProject project = mock(IJavaProject.class);
    Properties sonarProperties = new Properties();

    when(project.getOption(JavaCore.COMPILER_SOURCE, true)).thenReturn("1.6");
    when(project.getOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, true)).thenReturn("1.6");
    when(project.getResolvedClasspath(true)).thenReturn(new IClasspathEntry[] {});
    when(project.getOutputLocation())
        .thenReturn(new Path(temp.newFolder("output").getAbsolutePath()));

    configurator.configureJavaProject(project, sonarProperties);

    assertTrue(sonarProperties.containsKey("sonar.java.source"));
    assertThat(sonarProperties.getProperty("sonar.java.source"), is("1.6"));
    assertTrue(sonarProperties.containsKey("sonar.java.target"));
    assertThat(sonarProperties.getProperty("sonar.java.target"), is("1.6"));
  }
Ejemplo n.º 14
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;
  }
Ejemplo n.º 15
0
  /**
   * Determine the exposed (exported) dependencies from the project named 'otherProject' and add
   * them to the accumulatedPathEntries String Set. This will include the output location of the
   * project plus other kinds of entry that are re-exported. If dependent on another project and
   * that project is re-exported, the method will recurse.
   *
   * @param baseProject the original project for which the classpath is being computed
   * @param otherProject a project something in the dependency chain for the original project
   * @param accumulatedPathEntries a String set of classpath entries, into which new entries should
   *     be added
   */
  private static void computeDependenciesFromProject(
      IProject baseProject, String otherProject, Set accumulatedPathEntries)
      throws JavaModelException {

    // First the output location for the project:
    IProject iproject = baseProject.getWorkspace().getRoot().getProject(otherProject);
    IJavaProject ijp = JavaCore.create(iproject);
    accumulatedPathEntries.add(pathToString(ijp.getOutputLocation(), iproject));

    // Look for exported entries from otherProject
    IClasspathEntry[] cpes = ijp.getResolvedClasspath(true);
    if (cpes != null) {
      for (int j = 0; j < cpes.length; j++) {
        IClasspathEntry cpe = cpes[j];
        if (cpe.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
          continue;
        }
        if (cpe.isExported()) {
          // TODO should quickly dismiss source entries? others?
          IPath cpePath = cpes[j].getPath();
          String segmentZero = cpePath.segment(0);
          if (segmentZero != null && segmentZero.equals(otherProject)) {
            accumulatedPathEntries.add(
                iproject.getFile(cpePath.removeFirstSegments(1)).getRawLocation().toOSString());
          } else {
            if (cpe.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
              // segmentZero is a project name
              computeDependenciesFromProject(baseProject, segmentZero, accumulatedPathEntries);
            } else {
              String otherPathElement = null;
              if (segmentZero != null && segmentZero.equals(iproject.getName())) {
                otherPathElement =
                    iproject.getFile(cpePath.removeFirstSegments(1)).getRawLocation().toOSString();
              } else {
                otherPathElement = cpePath.toOSString();
              }
              accumulatedPathEntries.add(otherPathElement);
            }
          }
        }
      }
    }
  }
  @Test
  public void shouldConfigureSimpleProject() throws JavaModelException, IOException {
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    File workspaceRoot = root.getFullPath().toFile();
    File projectRoot = new File(workspaceRoot, "myProject");
    projectRoot.mkdir();
    File sourceFolder = new File(projectRoot, "src");
    sourceFolder.mkdir();
    File testFolder = new File(projectRoot, "test");
    testFolder.mkdir();
    File outputFolder = new File(projectRoot, "bin");
    outputFolder.mkdir();

    IJavaProject project = mock(IJavaProject.class);
    Properties sonarProperties = new Properties();

    when(project.getOption(JavaCore.COMPILER_SOURCE, true)).thenReturn("1.6");
    when(project.getOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, true)).thenReturn("1.6");
    when(project.getPath()).thenReturn(new Path(projectRoot.getAbsolutePath()));

    IClasspathEntry[] cpes =
        new IClasspathEntry[] {
          createCPE(IClasspathEntry.CPE_SOURCE, sourceFolder),
          createCPE(IClasspathEntry.CPE_SOURCE, testFolder)
        };

    when(project.getResolvedClasspath(true)).thenReturn(cpes);
    when(project.getOutputLocation()).thenReturn(new Path(outputFolder.getAbsolutePath()));

    configurator.configureJavaProject(project, sonarProperties);

    // TODO Find a way to mock a project inside Eclipse

    // assertTrue(sonarProperties.containsKey("sonar.sources"));
    // assertThat(sonarProperties.getProperty("sonar.sources"), is(sourceFolder.getPath()));
    // assertTrue(sonarProperties.containsKey("sonar.tests"));
    // assertThat(sonarProperties.getProperty("sonar.tests"), is(testFolder.getPath()));
    // assertTrue(sonarProperties.containsKey("sonar.binaries"));
    // assertThat(sonarProperties.getProperty("sonar.binaries"), is(outputFolder.getPath()));
  }
Ejemplo n.º 17
0
 /**
  * This will return the set of output folders name for the given (java) project.
  *
  * <p>For example, if a project has a source folder "src" with its output folder set as "bin" and
  * a source folder "src-gen" with its output folder set as "bin-gen", this will return a
  * LinkedHashSet containing both "bin" and "bin-gen".
  *
  * @param project The project we seek the output folders of.
  * @return The set of output folders name for the given (java) project.
  */
 private static Set<String> getOutputFolders(IProject project) {
   final Set<String> classpathEntries = new CompactLinkedHashSet<String>();
   final IJavaProject javaProject = JavaCore.create(project);
   try {
     for (IClasspathEntry entry : javaProject.getResolvedClasspath(true)) {
       if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
         final IPath output = entry.getOutputLocation();
         if (output != null) {
           classpathEntries.add(output.removeFirstSegments(1).toString());
         }
       }
     }
     /*
      * Add the default output location to the classpath anyway since source folders are not required
      * to have their own
      */
     final IPath output = javaProject.getOutputLocation();
     classpathEntries.add(output.removeFirstSegments(1).toString());
   } catch (JavaModelException e) {
     AcceleoCommonPlugin.log(e, false);
   }
   return classpathEntries;
 }
Ejemplo n.º 18
0
 private static void collectClasspathURLs(
     IJavaProject javaProject, List<URL> urls, Set<IJavaProject> visited, boolean isFirstProject) {
   if (visited.contains(javaProject)) return;
   visited.add(javaProject);
   try {
     IPath outPath =
         javaProject
             .getProject()
             .getWorkspace()
             .getRoot()
             .getFullPath()
             .append(javaProject.getOutputLocation());
     outPath = outPath.addTrailingSeparator();
     URL out = createFileURL(outPath);
     urls.add(out);
     IClasspathEntry[] entries = null;
     entries = javaProject.getResolvedClasspath(true);
     for (IClasspathEntry entry : entries) {
       switch (entry.getEntryKind()) {
         case IClasspathEntry.CPE_LIBRARY:
         case IClasspathEntry.CPE_CONTAINER:
         case IClasspathEntry.CPE_VARIABLE:
           collectClasspathEntryURL(entry, urls);
           break;
         case IClasspathEntry.CPE_PROJECT:
           {
             if (isFirstProject || entry.isExported())
               collectClasspathURLs(getJavaProject(entry), urls, visited, false);
             break;
           }
       }
     }
   } catch (JavaModelException e) {
     return;
   }
 }
Ejemplo n.º 19
0
 private static URL findResourceURL(
     IJavaProject javaProject, Set<IJavaProject> visited, boolean isFirstProject, String name) {
   if (visited.contains(javaProject)) return null;
   visited.add(javaProject);
   try {
     IPath outPath =
         javaProject
             .getProject()
             .getLocation()
             .removeLastSegments(1)
             .append(javaProject.getOutputLocation());
     outPath = outPath.addTrailingSeparator();
     {
       URL url = toURL(outPath.append(name));
       if (url != null) {
         return url;
       }
     }
     for (IPackageFragmentRoot fragment : javaProject.getPackageFragmentRoots()) {
       if (fragment.getKind() == IPackageFragmentRoot.K_SOURCE) {
         URL url = toURL(fragment.getResource().getLocation().append(name));
         if (url != null) {
           return url;
         }
       }
     }
     // urls.add(out);
     IClasspathEntry[] entries = javaProject.getResolvedClasspath(true);
     for (IClasspathEntry entry : entries) {
       switch (entry.getEntryKind()) {
         case IClasspathEntry.CPE_LIBRARY:
           {
             // TODO
             IClasspathEntry resolveEntry = JavaCore.getResolvedClasspathEntry(entry);
             File file = resolveEntry.getPath().toFile();
             IPath path = resolveEntry.getPath();
             if (!file.exists()) {
               String projectName = path.segment(0);
               IProject project =
                   javaProject.getProject().getWorkspace().getRoot().getProject(projectName);
               path = project.getLocation().append(path.removeFirstSegments(1));
             }
             String spec = "jar:file:" + path.toString() + "!/" + name;
             try {
               URL url2 = new URL(spec);
               url2.getContent();
               return url2;
             } catch (Exception e) {
             }
           }
           break;
         case IClasspathEntry.CPE_CONTAINER:
           break;
         case IClasspathEntry.CPE_VARIABLE:
           {
             {
               // TODO
               URL url = toURL(outPath.append(name));
               if (url != null) {
                 return url;
               }
             }
           }
           break;
         case IClasspathEntry.CPE_PROJECT:
           {
             if (isFirstProject || entry.isExported()) {
               URL url = findResourceURL(getJavaProject(entry), visited, false, name);
               if (url != null) {
                 return url;
               }
             }
             break;
           }
       }
     }
   } catch (JavaModelException e) {
     e.printStackTrace();
   }
   return null;
 }
Ejemplo n.º 20
0
  /**
   * Retrieves the Java project output path
   *
   * @return The Java project output path
   * @throws CoreException An error occurred while retrieving project informations
   */
  protected IPath getProjectOutputPath() throws CoreException {

    final IJavaProject javaProject = (IJavaProject) getProject().getNature(JavaCore.NATURE_ID);
    return javaProject.getOutputLocation();
  }
  public List<IResource> exportArtifact(IProject project) {
    List<IResource> exportResources = new ArrayList<IResource>();
    if (!project.isOpen()) {
      return exportResources;
    }

    try {
      ArchiveManipulator archiveManipulator = new ArchiveManipulator();
      NullProgressMonitor nullProgressMonitor = new NullProgressMonitor();
      // cleaning target directory
      clearTarget(project);
      project.build(IncrementalProjectBuilder.FULL_BUILD, nullProgressMonitor);
      IJavaProject javaProject = JavaCore.create(project);

      List<String> exportPac = getExportPackages(javaProject);
      BundleManifest manifest = new BundleManifest();
      manifest.setBundleName(project.getName());
      manifest.setBundleSymbolicName(project.getName());
      manifest.setBundleDescription(project.getName());
      manifest.setBundleVersion("2.0");
      manifest.setExportPackagesList(exportPac);
      // IPath outPutPath = javaProject.getOutputLocation();
      IPath outPutPath =
          ResourcesPlugin.getWorkspace()
              .getRoot()
              .getFolder(javaProject.getOutputLocation())
              .getLocation();
      // Let's create a temp project
      IProject tempProject =
          ResourcesPlugin.getWorkspace().getRoot().getProject(".temp" + System.currentTimeMillis());
      tempProject.create(nullProgressMonitor);
      tempProject.open(nullProgressMonitor);
      tempProject.setHidden(true);
      org.eclipse.osgi.storagemanager.StorageManager manager =
          new StorageManager(tempProject.getLocation().toFile(), "false");

      File validatorResource = manager.createTempFile("validator_resources");
      validatorResource.delete();
      validatorResource.mkdir();
      FileUtils.copyDirectoryContents(outPutPath.toFile(), validatorResource); // copy binaries

      /////////////////////// Create the Bundle*********************************

      File metainfPath = new File(validatorResource, "META-INF");
      metainfPath.mkdir();
      File manifestFile = new File(metainfPath, "MANIFEST.MF");
      FileUtils.createFile(manifestFile, manifest.toString());
      File tmpArchive =
          new File(tempProject.getLocation().toFile(), project.getName().concat(".jar"));
      archiveManipulator.archiveDir(tmpArchive.toString(), validatorResource.toString());
      IFolder binaries = project.getFolder("target");
      if (!binaries.exists()) {
        binaries.create(true, true, nullProgressMonitor);
        binaries.setHidden(true);
      }
      IFile serviceArchive =
          project.getFile("target" + File.separator + project.getName().concat(".jar"));
      FileUtils.copy(tmpArchive, serviceArchive.getLocation().toFile());
      exportResources.add((IResource) serviceArchive);
      // cleaning temp project
      tempProject.delete(true, nullProgressMonitor);

    } catch (Exception e) {
      e.printStackTrace();
    }
    return exportResources;
  }
Ejemplo n.º 22
0
  // public for testing
  public static String calculateClasspath(IJavaProject javaProject) {
    try {
      Set accumulatedPathEntries = new LinkedHashSet();
      IProject project = javaProject.getProject();
      String projectName = project.getName();
      IPath defaultOutputPath = javaProject.getOutputLocation();
      String defaultOutputLocation = pathToString(defaultOutputPath, project);

      IClasspathEntry[] cpes = javaProject.getResolvedClasspath(true);
      if (cpes != null) {
        for (int i = 0, max = cpes.length; i < max; i++) {
          IClasspathEntry cpe = cpes[i];
          if (cpe.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
            continue;
          }
          // Two kinds of entry we are interested in - those relative and those absolute
          // relative example: grails/lib/hibernate3-3.3.1.jar  (where grails is the project name)
          // absolute example: f:/grails-111/dist/grails-core-blah.jar
          // javaProject path is f:\grails\grails
          IPath cpePath = cpe.getPath();
          String pathElement = null;
          String segmentZero = cpePath.segment(0);
          if (segmentZero.equals(projectName)) {
            pathElement =
                project.getFile(cpePath.removeFirstSegments(1)).getRawLocation().toOSString();
          } else {

            // for GRECLIPSE-917.  Entry is something like /SomeOtherProject/foo/bar/doodah.jar
            if (cpe.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
              try {
                IProject iproject = project.getWorkspace().getRoot().getProject(segmentZero);
                if (iproject != null) {
                  IFile ifile = iproject.getFile(cpePath.removeFirstSegments(1));
                  IPath ipath = (ifile == null ? null : ifile.getRawLocation());
                  pathElement = (ipath == null ? null : ipath.toOSString());
                }
              } catch (Throwable t) {
                t.printStackTrace();
              }
            }
            if (cpe.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
              // the classpath entry is a dependency on another project
              computeDependenciesFromProject(project, segmentZero, accumulatedPathEntries);
              // FIXASC this ought to also allow for separate output folders in the project we
              // depend upon *sigh*
              // FIXASC what does all this look like for batch compilation?  Should it be passed in
              // rather than computed here
            } else {
              if (pathElement == null) {
                pathElement = cpe.getPath().toOSString();
              }
            }
          }
          if (pathElement != null) {
            accumulatedPathEntries.add(pathElement);
          }
        }
        accumulatedPathEntries.add(defaultOutputLocation);
        StringBuilder sb = new StringBuilder();
        Iterator iter = accumulatedPathEntries.iterator();
        while (iter.hasNext()) {
          sb.append((String) iter.next());
          sb.append(File.pathSeparator);
        }
        String classpath = sb.toString();
        //				System.out.println("Project classpath for '"+projectName+"' is "+classpath);
        return classpath;
      }
    } catch (JavaModelException jme) {
      System.err.println(
          "Problem trying to determine classpath of project "
              + javaProject.getProject().getName()
              + ":"); //$NON-NLS-1$ //$NON-NLS-2$
      jme.printStackTrace();
    }
    return ""; //$NON-NLS-1$
  }
  /** Filters out every {@link IFile} which is has unknown root elements in its XML content. */
  @Override
  protected Set<IFile> filterMatchingFiles(Set<IFile> files) {
    // if project is a java project remove bin dirs from the list
    Set<String> outputDirectories = new HashSet<String>();
    IJavaProject javaProject = JdtUtils.getJavaProject(project);
    if (javaProject != null) {
      try {
        // add default output directory
        outputDirectories.add(javaProject.getOutputLocation().toString());

        // add source folder specific output directories
        for (IClasspathEntry entry : javaProject.getRawClasspath()) {
          if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE
              && entry.getOutputLocation() != null) {
            outputDirectories.add(entry.getOutputLocation().toString());
          }
        }
      } catch (JavaModelException e) {
        BeansCorePlugin.log(e);
      }
    }

    Set<IFile> detectedFiles = new LinkedHashSet<IFile>();
    for (IFile file : files) {
      boolean skip = false;
      // first check if the file sits in an output directory
      String path = file.getFullPath().toString();
      for (String outputDirectory : outputDirectories) {
        if (path.startsWith(outputDirectory)) {
          skip = true;
        }
      }
      if (skip) {
        continue;
      }

      // check if the file is known Spring xml file
      IStructuredModel model = null;
      try {
        try {
          model = StructuredModelManager.getModelManager().getExistingModelForRead(file);
        } catch (RuntimeException e) {
          // sometimes WTP throws a NPE in concurrency situations
        }
        if (model == null) {
          model = StructuredModelManager.getModelManager().getModelForRead(file);
        }
        if (model != null) {
          IDOMDocument document = ((DOMModelImpl) model).getDocument();
          if (document != null && document.getDocumentElement() != null) {
            String namespaceUri = document.getDocumentElement().getNamespaceURI();
            if (applyNamespaceFilter(file, namespaceUri)) {
              detectedFiles.add(file);
            }
          }
        }
      } catch (IOException e) {
        BeansCorePlugin.log(e);
      } catch (CoreException e) {
        BeansCorePlugin.log(e);
      } finally {
        if (model != null) {
          model.releaseFromRead();
        }
      }
    }
    return detectedFiles;
  }
 protected void collectClasspathURLs(
     final IJavaProject projectToUse,
     final LinkedHashSet<URL> result,
     final boolean includeOutputFolder,
     final Set<IJavaProject> visited)
     throws JavaModelException {
   try {
     boolean _or = false;
     IProject _project = projectToUse.getProject();
     boolean _isAccessible = _project.isAccessible();
     boolean _not = (!_isAccessible);
     if (_not) {
       _or = true;
     } else {
       boolean _add = visited.add(projectToUse);
       boolean _not_1 = (!_add);
       _or = _not_1;
     }
     if (_or) {
       return;
     }
     if (includeOutputFolder) {
       IPath _outputLocation = projectToUse.getOutputLocation();
       IPath path = _outputLocation.addTrailingSeparator();
       String _string = path.toString();
       URI _createPlatformResourceURI = URI.createPlatformResourceURI(_string, true);
       String _string_1 = _createPlatformResourceURI.toString();
       URL url = new URL(_string_1);
       result.add(url);
     }
     final IClasspathEntry[] resolvedClasspath = projectToUse.getResolvedClasspath(true);
     for (final IClasspathEntry entry : resolvedClasspath) {
       {
         URL url_1 = null;
         int _entryKind = entry.getEntryKind();
         switch (_entryKind) {
           case IClasspathEntry.CPE_SOURCE:
             if (includeOutputFolder) {
               final IPath path_1 = entry.getOutputLocation();
               boolean _notEquals = (!Objects.equal(path_1, null));
               if (_notEquals) {
                 IPath _addTrailingSeparator = path_1.addTrailingSeparator();
                 String _string_2 = _addTrailingSeparator.toString();
                 URI _createPlatformResourceURI_1 = URI.createPlatformResourceURI(_string_2, true);
                 String _string_3 = _createPlatformResourceURI_1.toString();
                 URL _uRL = new URL(_string_3);
                 url_1 = _uRL;
               }
             }
             break;
           case IClasspathEntry.CPE_PROJECT:
             IPath path_2 = entry.getPath();
             IWorkspaceRoot _workspaceRoot = this.getWorkspaceRoot(projectToUse);
             final IResource project = _workspaceRoot.findMember(path_2);
             IProject _project_1 = project.getProject();
             final IJavaProject referencedProject = JavaCore.create(_project_1);
             this.collectClasspathURLs(referencedProject, result, true, visited);
             break;
           case IClasspathEntry.CPE_LIBRARY:
             IPath path_3 = entry.getPath();
             IWorkspaceRoot _workspaceRoot_1 = this.getWorkspaceRoot(projectToUse);
             final IResource library = _workspaceRoot_1.findMember(path_3);
             URL _xifexpression = null;
             boolean _notEquals_1 = (!Objects.equal(library, null));
             if (_notEquals_1) {
               java.net.URI _rawLocationURI = library.getRawLocationURI();
               _xifexpression = _rawLocationURI.toURL();
             } else {
               File _file = path_3.toFile();
               java.net.URI _uRI = _file.toURI();
               _xifexpression = _uRI.toURL();
             }
             url_1 = _xifexpression;
             break;
           default:
             {
               IPath path_4 = entry.getPath();
               File _file_1 = path_4.toFile();
               java.net.URI _uRI_1 = _file_1.toURI();
               URL _uRL_1 = _uRI_1.toURL();
               url_1 = _uRL_1;
             }
             break;
         }
         boolean _notEquals_2 = (!Objects.equal(url_1, null));
         if (_notEquals_2) {
           result.add(url_1);
         }
       }
     }
   } catch (Throwable _e) {
     throw Exceptions.sneakyThrow(_e);
   }
 }
Ejemplo n.º 25
0
  /**
   * Initializes the ProjectProperties object.
   *
   * @param project
   * @throws JavaModelException
   * @throws CoreException
   */
  public void refresh() throws JavaModelException, CoreException {

    classPath = new StringBuffer();
    inPath = new StringBuffer();
    sourceFiles = new ArrayList();

    javaProject = JavaCore.create(project);
    String projectLocalPrefix = File.separator + project.getName();

    /*
     * get paths
     */
    this.projectLocation = project.getLocation().removeLastSegments(1).toOSString();
    this.outputPath = javaProject.getOutputLocation().toOSString();
    this.sourcePaths = new ArrayList<String>();

    /*
     * get source files
     */
    IClasspathEntry[] classPathEntries = javaProject.getResolvedClasspath(false);

    for (int i = 0; i < classPathEntries.length; i++) {
      if (classPathEntries[i].getEntryKind() == IClasspathEntry.CPE_SOURCE) {
        // 1st segment of the path has to be removed because it is added
        // again by findMember ending in duplicated first segment in the path
        getAllSourceFiles(
            project.findMember(classPathEntries[i].getPath().removeFirstSegments(1)),
            this.sourceFiles);
        if (!this.sourcePaths.contains(classPathEntries[i].getPath().toOSString())) {
          this.sourcePaths.add(classPathEntries[i].getPath().toOSString());
        }
      } else if (classPathEntries[i].getEntryKind() == IClasspathEntry.CPE_LIBRARY) {

        if (this.classPath.length() > 0) {
          this.classPath.append(File.pathSeparator);
        }

        String cp = classPathEntries[i].getPath().toOSString();
        if (cp.startsWith(projectLocalPrefix)) {
          cp = this.projectLocation + classPathEntries[i].getPath().toOSString();
        }

        // add the lib to inPath if specified in the .classpath file
        // as an inpath resource
        for (IClasspathAttribute attr : classPathEntries[i].getExtraAttributes()) {
          if (attr.getName().equals("inpath") && attr.getValue().equals("true")) {
            if (this.inPath.length() > 0) {
              this.inPath.append(File.pathSeparator);
            }
            this.inPath.append(cp);
            break;
          }
        }

        this.classPath.append(cp);
      }
    }

    //        IFile inpathFile = project.getFile("inpath.properties");
    //        if(inpathFile != null) {
    //        	Properties inpathProp = new Properties();
    //        	try {
    //				inpathProp.load(inpathFile.getContents());
    //				for(Object prop : inpathProp.keySet()) {
    //					if(inPath.length() > 0) {
    //						inPath.append(File.pathSeparator);
    //					}
    //
    //	inPath.append(this.projectLocation).append(projectLocalPrefix).append(File.separator).append(inpathProp.get(prop));
    //				}
    //			} catch (IOException e) {
    //				// TODO Auto-generated catch block
    //				e.printStackTrace();
    //			}
    //        }

  }
Ejemplo n.º 26
0
  /**
   * Get the options that are presented to annotation processors by the
   * AnnotationProcessorEnvironment. Options are key/value pairs which are set in the project
   * properties.
   *
   * <p>Option values can begin with a percent-delimited token representing a classpath variable or
   * one of several predefined values. The token must either be followed by a path delimiter, or be
   * the entire value. Such tokens will be replaced with their resolved value. The predefined values
   * are <code>%ROOT%</code>, which is replaced by the absolute pathname of the workspace root
   * directory, and <code>%PROJECT.DIR%</code>, which will be replaced by the absolute pathname of
   * the project root directory. For example, a value of <code>
   * %ECLIPSE_HOME%/configuration/config.ini</code> might be resolved to <code>
   * d:/eclipse/configuration/config.ini</code>.
   *
   * <p>This method returns some options which are set programmatically but are not directly
   * editable, are not displayed in the configuration GUI, and are not persisted to the preference
   * store. This is meant to emulate the behavior of Sun's apt command-line tool, which passes most
   * of its command line options to the processor environment. The programmatically set options are:
   * <code>-classpath</code> [set to Java build path] <code>-sourcepath</code> [set to Java source
   * path] <code>-s</code> [set to generated src dir] <code>-d</code> [set to binary output dir]
   * <code>-target</code> [set to compiler target version] <code>-source</code> [set to compiler
   * source version]
   *
   * <p>There are some slight differences between the options returned by this method and the
   * options returned from this implementation of @see AnnotationProcessorEnvironment#getOptions().
   * First, that method returns additional options which are only meaningful during a build, such as
   * <code>phase</code>. Second, that method also adds alternate encodings of each option, to be
   * compatible with a bug in Sun's apt implementation: specifically, for each option key="k",
   * value="v", an additional option is created with key="-Ak=v", value=null. This includes the
   * user-created options, but does not include the programmatically defined options listed above.
   *
   * @param jproj a project, or null to query the workspace-wide setting.
   * @return a mutable, possibly empty, map of (key, value) pairs. The value part of a pair may be
   *     null (equivalent to "-Akey" on the Sun apt command line). The value part may contain
   *     spaces.
   */
  public static Map<String, String> getProcessorOptions(IJavaProject jproj) {
    Map<String, String> rawOptions = getRawProcessorOptions(jproj);
    // map is large enough to also include the programmatically generated options
    Map<String, String> options = new HashMap<String, String>(rawOptions.size() + 6);

    // Resolve path metavariables like %ROOT%
    for (Map.Entry<String, String> entry : rawOptions.entrySet()) {
      String resolvedValue = resolveVarPath(jproj, entry.getValue());
      String value = (resolvedValue == null) ? entry.getValue() : resolvedValue;
      options.put(entry.getKey(), value);
    }

    if (jproj == null) {
      // there are no programmatically set options at the workspace level
      return options;
    }

    IWorkspaceRoot root = jproj.getProject().getWorkspace().getRoot();

    // Add sourcepath and classpath variables
    try {
      IClasspathEntry[] classpathEntries = jproj.getResolvedClasspath(true);
      Set<String> classpath = new LinkedHashSet<String>();
      Set<String> sourcepath = new LinkedHashSet<String>();

      // For projects on the classpath, loops can exist; need to make sure we
      // don't loop forever
      Set<IJavaProject> projectsProcessed = new HashSet<IJavaProject>();
      projectsProcessed.add(jproj);
      for (IClasspathEntry entry : classpathEntries) {
        int kind = entry.getEntryKind();
        if (kind == IClasspathEntry.CPE_LIBRARY) {
          IPath cpPath = entry.getPath();

          IResource res = root.findMember(cpPath);

          // If res is null, the path is absolute (it's an external jar)
          if (res == null) {
            classpath.add(cpPath.toOSString());
          } else {
            // It's relative
            classpath.add(res.getLocation().toOSString());
          }
        } else if (kind == IClasspathEntry.CPE_SOURCE) {
          IResource res = root.findMember(entry.getPath());
          if (res == null) {
            continue;
          }
          IPath srcPath = res.getLocation();
          if (srcPath == null) {
            continue;
          }

          sourcepath.add(srcPath.toOSString());
        } else if (kind == IClasspathEntry.CPE_PROJECT) {
          // Add the dependent project's build path and classpath to ours
          IPath otherProjectPath = entry.getPath();
          IProject otherProject = root.getProject(otherProjectPath.segment(0));

          // Note: JavaCore.create() is safe, even if the project is null --
          // in that case, we get null back
          IJavaProject otherJavaProject = JavaCore.create(otherProject);

          // If it doesn't exist, ignore it
          if (otherJavaProject != null && otherJavaProject.isOpen()) {
            addProjectClasspath(root, otherJavaProject, projectsProcessed, classpath);
          }
        }
      }
      // if you add options here, also add them in isAutomaticProcessorOption(),
      // and document them in docs/reference/automatic_processor_options.html.

      // Classpath and sourcepath
      options.put("-classpath", convertPathCollectionToString(classpath)); // $NON-NLS-1$    	
      options.put("-sourcepath", convertPathCollectionToString(sourcepath)); // $NON-NLS-1$

      // Get absolute path for generated source dir
      IFolder genSrcDir = jproj.getProject().getFolder(getGenSrcDir(jproj));
      String genSrcDirString = genSrcDir.getRawLocation().toOSString();
      options.put("-s", genSrcDirString); // $NON-NLS-1$

      // Absolute path for bin dir as well
      IPath binPath = jproj.getOutputLocation();
      IResource binPathResource = root.findMember(binPath);
      String binDirString;
      if (binPathResource != null) {
        binDirString = root.findMember(binPath).getLocation().toOSString();
      } else {
        binDirString = binPath.toOSString();
      }
      options.put("-d", binDirString); // $NON-NLS-1$

      String target = jproj.getOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, true);
      options.put("-target", target); // $NON-NLS-1$

      String source = jproj.getOption(JavaCore.COMPILER_SOURCE, true);
      options.put("-source", source); // $NON-NLS-1$
    } catch (JavaModelException jme) {
      AptPlugin.log(jme, "Could not get the classpath for project: " + jproj); // $NON-NLS-1$
    }

    return options;
  }