예제 #1
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;
 }
  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);
    }
  }
 /**
  * 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$
     }
   }
 }
  /* (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()]);
  }
  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);
          }
        }
      }
    }
  }
 /**
  * Initializes the source folder field with a valid package fragment root. The package fragment
  * root is computed from the given Java element.
  *
  * @param elem the Java element used to compute the initial package fragment root used as the
  *     source folder
  */
 protected void initContainerPage(IJavaElement elem) {
   IPackageFragmentRoot initRoot = null;
   if (elem != null) {
     initRoot = JavaModelUtil.getPackageFragmentRoot(elem);
     try {
       if (initRoot == null || initRoot.getKind() != IPackageFragmentRoot.K_SOURCE) {
         IJavaProject jproject = elem.getJavaProject();
         if (jproject != null) {
           initRoot = null;
           if (jproject.exists()) {
             IPackageFragmentRoot[] roots = jproject.getPackageFragmentRoots();
             for (int i = 0; i < roots.length; i++) {
               if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE) {
                 initRoot = roots[i];
                 break;
               }
             }
           }
           if (initRoot == null) {
             initRoot = jproject.getPackageFragmentRoot(jproject.getResource());
           }
         }
       }
     } catch (JavaModelException e) {
       JavaPlugin.log(e);
     }
   }
   setPackageFragmentRoot(initRoot, true);
 }
 protected IPackageFragmentRoot getFragmentRoot(IJavaElement elem) {
   IPackageFragmentRoot initRoot = null;
   if (elem != null) {
     initRoot = (IPackageFragmentRoot) elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
     try {
       if (initRoot == null || initRoot.getKind() != IPackageFragmentRoot.K_SOURCE) {
         IJavaProject jproject = elem.getJavaProject();
         if (jproject != null) {
           initRoot = null;
           if (jproject.exists()) {
             IPackageFragmentRoot[] roots = jproject.getPackageFragmentRoots();
             for (int i = 0; i < roots.length; i++) {
               if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE) {
                 initRoot = roots[i];
                 break;
               }
             }
           }
           if (initRoot == null) {
             initRoot = jproject.getPackageFragmentRoot(jproject.getResource());
           }
         }
       }
     } catch (JavaModelException e) {
       // TODO
       e.printStackTrace();
     }
   }
   return initRoot;
 }
예제 #8
0
 /**
  * Returns the java project that corresponds to the given path. Returns null if the path doesn't
  * correspond to a project.
  */
 private static IJavaProject getJavaProject(IPath path, IJavaModel model) {
   IJavaProject project = model.getJavaProject(path.lastSegment());
   if (project.exists()) {
     return project;
   }
   return null;
 }
  private static IJavaProject getJavaProject(String projectName) {
    IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
    if (project == null) return null;

    IJavaProject result = JavaCore.create(project);
    if (result == null) return null;

    if (!result.exists()) return null;

    return result;
  }
 /*
  * Adds to <code> projects </code> IJavaProject objects for all projects directly or indirectly referencing focus. @param projects IJavaProjects will be added to this set
  */
 private static void addReferencingProjects(IJavaProject focus, Set<IJavaProject> projects)
     throws JavaModelException {
   IProject[] referencingProjects = focus.getProject().getReferencingProjects();
   for (int i = 0; i < referencingProjects.length; i++) {
     IJavaProject candidate = JavaCore.create(referencingProjects[i]);
     if (candidate == null || projects.contains(candidate) || !candidate.exists())
       continue; // break cycle
     IClasspathEntry entry = getReferencingClassPathEntry(candidate, focus);
     if (entry != null) {
       projects.add(candidate);
       if (entry.isExported()) addReferencingProjects(candidate, projects);
     }
   }
 }
 /** @since 2.4 */
 private void updateCache(IJavaProject project) {
   Set<PackageFragmentRootData> datas = newHashSet();
   try {
     if (project.exists() && project.getProject().isAccessible()) {
       for (IPackageFragmentRoot root : project.getPackageFragmentRoots()) {
         boolean isCachable = root.isArchive() || root.isExternal();
         if (isCachable) datas.add(getCachedData(root));
       }
     }
   } catch (JavaModelException e) {
     if (!e.isDoesNotExist())
       log.error("Error getting package fragments roots of " + project.getElementName(), e);
   } finally {
     clearCache(project, datas);
   }
 }
예제 #12
0
  /**
   * Gets a java project from the supplied IProject.
   *
   * @param project The IProject.
   * @return The java project.
   */
  public static IJavaProject getJavaProject(IProject project) throws Exception {
    if (ProjectUtils.getPath(project) == null) {
      throw new IllegalArgumentException(
          Services.getMessage("project.location.null", project.getName()));
    }

    if (!project.hasNature(PluginResources.NATURE)) {
      throw new IllegalArgumentException(
          Services.getMessage(
              "project.missing.nature",
              project.getName(),
              ProjectNatureFactory.getAliasForNature(PluginResources.NATURE)));
    }

    IJavaProject javaProject = JavaCore.create(project);
    if (javaProject == null || !javaProject.exists()) {
      throw new IllegalArgumentException(Services.getMessage("project.not.found", project));
    }

    return javaProject;
  }
 @Override
 public void mavenProjectChanged(MavenProjectChangedEvent event, IProgressMonitor monitor)
     throws CoreException {
   IPreferenceStore store = Activator.getDefault().getPreferenceStore();
   boolean configureGWT = store.getBoolean(Activator.CONFIGURE_GWT);
   if (configureGWT) {
     Plugin newConfig =
         event.getMavenProject().getMavenProject().getPlugin(GWT_WAR_MAVEN_PLUGIN_KEY);
     if (newConfig != null) {
       IJavaProject javaProject = JavaCore.create(event.getMavenProject().getProject());
       if (javaProject.exists()) {
         List<String> modNames = findModules(newConfig, javaProject);
         try {
           GWTProjectProperties.setEntryPointModules(
               event.getMavenProject().getProject(), modNames);
         } catch (BackingStoreException e) {
           logError("Exception in Maven GWT Configurator, cannot set entry point modules", e);
         }
       }
     }
   }
 }
 /**
  * Resolves the {@link IJavaProject} within the context of the given {@link IJavaStackFrame}
  *
  * @param frame
  * @return the {@link IJavaProject} or <code>null</code>
  * @since 3.8.0
  */
 public static IJavaProject resolveJavaProject(IJavaStackFrame frame) {
   ILaunch launch = frame.getLaunch();
   if (launch != null) {
     try {
       Object sourceElement = resolveSourceElement(frame, JAVA_STRATUM, launch);
       IJavaElement element = getJavaElement(sourceElement);
       if (element != null) {
         return element.getJavaProject();
       }
       // If Source element is not a Java element
       if (sourceElement instanceof IResource) {
         IJavaProject project = JavaCore.create(((IResource) sourceElement).getProject());
         if (project.exists()) {
           return project;
         }
       }
     } catch (CoreException ce) {
       // do nothing, return null
     }
   }
   return null;
 }
예제 #15
0
 private boolean hasItemsOnBuildPath(IJavaProject project, Set searched, Object[] args) {
   try {
     List projects = new ArrayList();
     if (project != null && project.exists()) {
       IClasspathEntry[] entries = project.getResolvedClasspath(true);
       for (int i = 0; i < entries.length; i++) {
         IClasspathEntry entry = entries[i];
         IPath path = entry.getPath();
         String spath = path.toPortableString();
         for (int j = 0; j < args.length; j++) {
           if (spath.lastIndexOf((String) args[j]) != -1) {
             return true;
           }
         }
         if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
           String name = entry.getPath().lastSegment();
           IProject dep = ResourcesPlugin.getWorkspace().getRoot().getProject(name);
           IJavaProject javaProject = JavaCore.create(dep);
           if (!searched.contains(javaProject)) {
             projects.add(javaProject);
           }
         }
       }
     }
     // search referenced projects
     Iterator iterator = projects.iterator();
     while (iterator.hasNext()) {
       IJavaProject jp = (IJavaProject) iterator.next();
       searched.add(jp);
       if (hasItemsOnBuildPath(jp, searched, args)) {
         return true;
       }
     }
   } catch (JavaModelException e) {
   }
   return false;
 }