private IJavaProject xtendProject(final String name, final IJavaProject... upstreamProjects) {
   try {
     final IJavaProject result = JavaProjectSetupUtil.createJavaProject(name);
     IProject _project = result.getProject();
     IResourcesSetupUtil.addNature(_project, XtextProjectHelper.NATURE_ID);
     this.xtendLibs.addLibsToClasspath(result, null);
     final Procedure1<IJavaProject> _function =
         new Procedure1<IJavaProject>() {
           @Override
           public void apply(final IJavaProject it) {
             try {
               IPath _path = it.getPath();
               IClasspathEntry _newProjectEntry = JavaCore.newProjectEntry(_path, true);
               JavaProjectSetupUtil.addToClasspath(result, _newProjectEntry);
             } catch (Throwable _e) {
               throw Exceptions.sneakyThrow(_e);
             }
           }
         };
     IterableExtensions.<IJavaProject>forEach(
         ((Iterable<IJavaProject>) Conversions.doWrapArray(upstreamProjects)), _function);
     return result;
   } catch (Throwable _e) {
     throw Exceptions.sneakyThrow(_e);
   }
 }
  public static void fixAsEJB(ILaunchConfiguration config) {
    try {
      LaunchConfigurationInfo info =
          (LaunchConfigurationInfo) BeanUtils.invokeMethod(config, "getInfo");
      Map map = (Map) BeanUtils.getFieldValue(info, "fAttributes");

      String projectName = (String) map.get(ATTR_PROJECT_NAME);
      IJavaModel jModel = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot());
      IJavaProject jp = jModel.getJavaProject(projectName);
      Assert.notNull(jp);

      File root = jp.getProject().getLocation().toFile();
      map.put("org.eclipse.jdt.launching.MAIN_TYPE", "jef.database.JefClassLoader");

      String arg = (String) map.get(ATTR_PROGRAM_ARGUMENTS);
      if (arg == null) {
        File openEjbFolder = findOpenEjbFolder();
        String projectPath = root.getAbsolutePath();
        String openEjbPath = openEjbFolder.getAbsolutePath();
        map.put(
            ATTR_PROGRAM_ARGUMENTS,
            "jef.ejb.server.OpenejbServer " + projectPath + " " + openEjbPath);
      }

    } catch (ReflectionException e) {
      e.printStackTrace();
    }
  }
  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();
    }
  }
  private static IJavaProject[] getProjectSearchOrder(String projectName) {

    ArrayList<String> projectNames = new ArrayList<String>();
    projectNames.add(projectName);

    int nextProject = 0;
    while (nextProject < projectNames.size()) {
      String nextProjectName = projectNames.get(nextProject);
      IJavaProject jproject = getJavaProject(nextProjectName);

      if (jproject != null) {
        try {
          String[] childProjectNames = jproject.getRequiredProjectNames();
          for (int i = 0; i < childProjectNames.length; i++) {
            if (!projectNames.contains(childProjectNames[i])) {
              projectNames.add(childProjectNames[i]);
            }
          }
        } catch (JavaModelException e) {
          JavaPlugin.log(e);
        }
      }
      nextProject += 1;
    }

    ArrayList<IJavaProject> result = new ArrayList<IJavaProject>();
    for (int i = 0, size = projectNames.size(); i < size; i++) {
      String name = projectNames.get(i);
      IJavaProject project = getJavaProject(name);
      if (project != null) result.add(project);
    }

    return result.toArray(new IJavaProject[result.size()]);
  }
 public void changeControlPressed(DialogField field) {
   IJavaProject jproject = chooseProject();
   if (jproject != null) {
     IPath path = jproject.getProject().getFullPath().makeRelative();
     projectField.setText(path.toString());
   }
 }
  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 testJUnitWithCloneNotRaw() throws Exception {
    fAssumeCloneReturnsSameType = true;
    fLeaveUnconstrainedRaw = false;

    IJavaProject javaProject = JavaProjectHelper.createJavaProject("InferTypeArguments", "bin");
    try {
      IPackageFragmentRoot jdk = JavaProjectHelper.addRTJar(javaProject);
      Assert.assertNotNull(jdk);

      File junitSrcArchive =
          JavaTestPlugin.getDefault().getFileInPlugin(JavaProjectHelper.JUNIT_SRC_381);
      Assert.assertTrue(junitSrcArchive != null && junitSrcArchive.exists());

      IPackageFragmentRoot src =
          JavaProjectHelper.addSourceContainerWithImport(
              javaProject, "src", junitSrcArchive, JavaProjectHelper.JUNIT_SRC_ENCODING);

      boolean performed =
          perform(new IJavaElement[] {javaProject}, RefactoringStatus.OK, RefactoringStatus.OK);
      assertTrue(performed);

      compareWithZipFile(src, "junit381-noUI-clone-not-raw-src.zip");
    } finally {
      if (javaProject != null && javaProject.exists()) JavaProjectHelper.delete(javaProject);
    }
  }
  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);
  }
  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 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 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;
  }
  // 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");
  }
  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);
          }
        }
      }
    }
  }
 /**
  * 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 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);
  }
  @Override
  public boolean performFinish() {
    if (!super.performFinish()) {
      return false;
    }

    IProject newProject = getNewProject();

    try {

      IProjectDescription description = newProject.getDescription();
      String[] newNatures = new String[2];
      newNatures[0] = JavaCore.NATURE_ID;
      newNatures[1] = ActivitiConstants.NATURE_ID;
      description.setNatureIds(newNatures);
      newProject.setDescription(description, null);

      IJavaProject javaProject = JavaCore.create(newProject);

      createSourceFolders(newProject);
      createOutputLocation(javaProject);

      IClasspathEntry[] entries = createClasspathEntries(javaProject);

      javaProject.setRawClasspath(entries, null);
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }

    return 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);
  }
  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);
    }
  }
  /* (non-Javadoc)
   * @see org.eclipse.jdt.core.IClasspathContainer#getClasspathEntries()
   */
  @Override
  public IClasspathEntry[] getClasspathEntries() {
    Set<IClasspathEntry> entries = new HashSet<IClasspathEntry>();
    if (project != null && project.exists()) {
      File projectFolder = project.getProject().getLocation().toFile();
      File libFolder = new File(projectFolder, "lib");
      if (libFolder.exists()) {
        File[] listFiles =
            libFolder.listFiles(
                new FileFilter() {

                  @Override
                  public boolean accept(File file) {
                    return file.getName().endsWith(".jar");
                  }
                });
        if (listFiles != null) {
          for (File f : listFiles) {
            entries.add(
                JavaCore.newLibraryEntry(Path.fromOSString(f.getAbsolutePath()), null, null, true));
          }
        }
      }
    }
    return entries.toArray(new IClasspathEntry[entries.size()]);
  }
Example #21
0
  /**
   * Obtain the Git respository that contains the specified project. The repository can either be in
   * the project's directory or in its hierarchy.
   *
   * @param project
   * @return
   * @throws IOException
   */
  private static Git getGitRepository(final IJavaProject project) throws IOException {
    Git returnValue;
    File gitDirectory;
    File currentDirectory;
    Repository repository;
    FileRepositoryBuilder repositoryBuilder;

    // Check whether the project or one of its ancestors hosts a Git
    // repository
    returnValue = null;
    if (project.getProject().getRawLocation() != null) {
      repositoryBuilder = new FileRepositoryBuilder();
      currentDirectory = project.getProject().getRawLocation().toFile();
      repository =
          repositoryBuilder.setGitDir(currentDirectory).readEnvironment().findGitDir().build();
      while (currentDirectory != null) {
        gitDirectory = new File(currentDirectory, ".git");
        if (gitDirectory.exists()) {
          repositoryBuilder = new FileRepositoryBuilder();
          repository =
              repositoryBuilder.setGitDir(gitDirectory).readEnvironment().findGitDir().build();
          break;
        } else {
          currentDirectory = currentDirectory.getParentFile();
        }
      }

      // If possible, reference the Git repository
      if (repository != null) {
        returnValue = new Git(repository);
      }
    }

    return returnValue;
  }
Example #22
0
  /**
   * Returns all activities found in the given project (including those in libraries, except for
   * android.jar itself)
   *
   * @param project the project
   * @return a list of activity classes as fully qualified class names
   */
  @SuppressWarnings("restriction") // BinaryType
  @NonNull
  public static List<String> getProjectActivities(IProject project) {
    final List<String> activities = new ArrayList<String>();
    try {
      final IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);
      if (javaProject != null) {
        IType[] activityTypes = new IType[0];
        IType activityType = javaProject.findType(SdkConstants.CLASS_ACTIVITY);
        if (activityType != null) {
          ITypeHierarchy hierarchy =
              activityType.newTypeHierarchy(javaProject, new NullProgressMonitor());
          activityTypes = hierarchy.getAllSubtypes(activityType);
          for (IType type : activityTypes) {
            if (type instanceof BinaryType
                && (type.getClassFile() == null || type.getClassFile().getResource() == null)) {
              continue;
            }
            activities.add(type.getFullyQualifiedName());
          }
        }
      }
    } catch (CoreException e) {
      AdtPlugin.log(e, null);
    }

    return activities;
  }
  private IJavaProject chooseProject() {
    IJavaProject[] projects;
    try {
      projects = JavaCore.create(Util.getWorkspaceRoot()).getJavaProjects();
    } catch (JavaModelException e) {
      JavaPlugin.log(e);
      projects = new IJavaProject[0];
    }

    // Filter the list to only show GWT projects
    List<IJavaProject> gwtProjects = new ArrayList<IJavaProject>();
    for (IJavaProject project : projects) {
      if (GWTNature.isGWTProject(project.getProject())) {
        gwtProjects.add(project);
      }
    }

    // TODO: refactor this into utility function
    ILabelProvider labelProvider =
        new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT);
    ElementListSelectionDialog dialog = new ElementListSelectionDialog(getShell(), labelProvider);
    dialog.setTitle("Project Selection");
    dialog.setMessage("Choose a project for the new HTML page");
    dialog.setElements(gwtProjects.toArray(new IJavaProject[0]));
    dialog.setInitialSelections(new Object[] {getJavaProject()});
    dialog.setHelpAvailable(false);
    if (dialog.open() == Window.OK) {
      return (IJavaProject) dialog.getFirstResult();
    }
    return null;
  }
  public void createProjectControls(Composite parent, int nColumns) {

    Label locationLabel = new Label(parent, SWT.NONE);
    locationLabel.setText("Project:");
    locationLabel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false));

    projectCombo = new Combo(parent, SWT.BORDER | SWT.READ_ONLY);
    GridData data = new GridData(SWT.FILL, SWT.CENTER, true, false);
    data.horizontalSpan = 2;
    projectCombo.setLayoutData(data);
    projectCombo.addSelectionListener(
        new SelectionAdapter() {
          public void widgetSelected(SelectionEvent e) {
            projectText = projectCombo.getText();
            projectChanged();
          }
        });
    gwtProjects = Util.getGwtProjects();
    for (int i = 0; i < gwtProjects.length; i++) {
      IJavaProject gwtProject = gwtProjects[i];
      String name = gwtProject.getProject().getName();
      projectCombo.add(name);
      if (name.equals(selectedProject)) projectCombo.select(i);
    }
    if (projectCombo.getSelectionIndex() == -1) projectCombo.select(0);

    new Label(parent, SWT.NONE);
  }
 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);
 }
  protected void projectChanged() {

    projectText = projectCombo.getText();
    IJavaProject selectedProject = null;
    for (int i = 0; i < gwtProjects.length; i++) {
      IJavaProject gwtProject = gwtProjects[i];
      if (projectText.equals(gwtProject.getProject().getName())) {
        selectedProject = gwtProject;
        break;
      }
    }

    if (selectedProject != null) {
      try {
        moduleCombo.removeAll();
        List modulesList = Util.findModules(selectedProject);
        for (Iterator i = modulesList.iterator(); i.hasNext(); ) {
          IFile file = (IFile) i.next();
          IPath projectRelativePath = file.getProjectRelativePath();
          String fileName = file.getName();
          String moduleName =
              fileName.substring(0, fileName.length() - Constants.GWT_XML_EXT.length() - 1);
          moduleCombo.add(projectRelativePath.toString());
          moduleCombo.setData(moduleName, file);
        }
        int i = modulesList.indexOf(selectedModule);
        if (i == -1) i = 0;
        moduleCombo.select(i);
        moduleText = moduleCombo.getText();
      } catch (CoreException e) {
        Activator.logException(e);
      }
    }
    doStatusUpdate();
  }
  /**
   * 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;
  }
 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;
 }
  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();
    }
  }
 @SuppressWarnings("deprecation")
 private boolean isParameterNamesAvailable() throws Exception {
   ASTParser parser = ASTParser.newParser(AST.JLS3);
   parser.setIgnoreMethodBodies(true);
   IJavaProject javaProject = projectProvider.getJavaProject(resourceSet);
   parser.setProject(javaProject);
   IType type = javaProject.findType("org.eclipse.xtext.common.types.testSetups.TestEnum");
   IBinding[] bindings = parser.createBindings(new IJavaElement[] {type}, null);
   ITypeBinding typeBinding = (ITypeBinding) bindings[0];
   IMethodBinding[] methods = typeBinding.getDeclaredMethods();
   for (IMethodBinding method : methods) {
     if (method.isConstructor()) {
       IMethod element = (IMethod) method.getJavaElement();
       if (element.exists()) {
         String[] parameterNames = element.getParameterNames();
         if (parameterNames.length == 1 && parameterNames[0].equals("string")) {
           return true;
         }
       } else {
         return false;
       }
     }
   }
   return false;
 }