private static void convertContainer(
      IClasspathEntry entry, IJavaProject project, Map<IPath, String> oldLocationMap) {
    try {
      IClasspathContainer container = JavaCore.getClasspathContainer(entry.getPath(), project);
      if (container == null) {
        return;
      }

      IClasspathEntry[] entries = container.getClasspathEntries();
      boolean hasChange = false;
      for (int i = 0; i < entries.length; i++) {
        IClasspathEntry curr = entries[i];
        IClasspathEntry updatedEntry = getConvertedEntry(curr, project, oldLocationMap);
        if (updatedEntry != null) {
          entries[i] = updatedEntry;
          hasChange = true;
        }
      }
      if (hasChange) {
        BuildPathSupport.requestContainerUpdate(project, container, entries);
      }
    } catch (CoreException e) {
      // ignore
    }
  }
  /**
   * Processes a {@link IClasspathEntry} and add it to one of the list if applicable.
   *
   * @param entry the entry to process
   * @param javaProject the {@link IJavaProject} from which this entry came.
   * @param wsRoot the {@link IWorkspaceRoot}
   * @param projects the project list to add to
   * @param jarFiles the jar list to add to
   * @param includeJarFiles whether to include jar files or just projects. This is useful when
   *     calling on an Android project (value should be <code>false</code>)
   */
  private static void processCPE(
      IClasspathEntry entry,
      IJavaProject javaProject,
      IWorkspaceRoot wsRoot,
      Set<IProject> projects,
      Set<File> jarFiles,
      boolean includeJarFiles) {

    // if this is a classpath variable reference, we resolve it.
    if (entry.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
      entry = JavaCore.getResolvedClasspathEntry(entry);
    }

    if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
      IProject refProject = wsRoot.getProject(entry.getPath().lastSegment());
      try {
        // ignore if it's an Android project, or if it's not a Java Project
        if (refProject.hasNature(JavaCore.NATURE_ID)
            && refProject.hasNature(AndmoreAndroidConstants.NATURE_DEFAULT) == false) {
          // add this project to the list
          projects.add(refProject);

          // also get the dependency from this project.
          getDependencyListFromClasspath(refProject, projects, jarFiles, true /*includeJarFiles*/);
        }
      } catch (CoreException exception) {
        // can't query the project nature? ignore
      }
    } else if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
      if (includeJarFiles) {
        handleClasspathLibrary(entry, wsRoot, jarFiles);
      }
    } else if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
      // get the container and its content
      try {
        IClasspathContainer container =
            JavaCore.getClasspathContainer(entry.getPath(), javaProject);
        // ignore the system and default_system types as they represent
        // libraries that are part of the runtime.
        if (container != null && container.getKind() == IClasspathContainer.K_APPLICATION) {
          IClasspathEntry[] entries = container.getClasspathEntries();
          for (IClasspathEntry cpe : entries) {
            processCPE(cpe, javaProject, wsRoot, projects, jarFiles, includeJarFiles);
          }
        }
      } catch (JavaModelException jme) {
        // can't resolve the container? ignore it.
        AndmoreAndroidPlugin.log(jme, "Failed to resolve ClasspathContainer: %s", entry.getPath());
      }
    }
  }
  /* (non-Javadoc)
   * @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object)
   */
  public String getText(Object element) {
    IRuntimeClasspathEntry entry = (IRuntimeClasspathEntry) element;
    switch (entry.getType()) {
      case IRuntimeClasspathEntry.PROJECT:
        IResource res = entry.getResource();
        IJavaElement proj = JavaCore.create(res);
        if (proj == null) {
          return entry.getPath().lastSegment();
        } else {
          return lp.getText(proj);
        }
      case IRuntimeClasspathEntry.ARCHIVE:
        IPath path = entry.getPath();
        if (path == null) {
          return MessageFormat.format("Invalid path: {0}", new Object[] {"null"}); // $NON-NLS-1$
        }
        if (!path.isAbsolute() || !path.isValidPath(path.toString())) {
          return MessageFormat.format("Invalid path: {0}", new Object[] {path.toOSString()});
        }
        String[] segments = path.segments();
        StringBuffer displayPath = new StringBuffer();
        if (segments.length > 0) {
          String device = path.getDevice();
          if (device != null) {
            displayPath.append(device);
            displayPath.append(File.separator);
          }
          for (int i = 0; i < segments.length - 1; i++) {
            displayPath.append(segments[i]).append(File.separator);
          }
          displayPath.append(segments[segments.length - 1]);

          // getDevice means that's a absolute path.
          if (path.getDevice() != null && !path.toFile().exists()) {
            displayPath.append(" (missing) ");
          }
        } else {
          displayPath.append(path.toOSString());
        }
        return displayPath.toString();
      case IRuntimeClasspathEntry.VARIABLE:
        path = entry.getPath();
        IPath srcPath = entry.getSourceAttachmentPath();
        StringBuffer buf = new StringBuffer(path.toString());
        if (srcPath != null) {
          buf.append(" ["); // $NON-NLS-1$
          buf.append(srcPath.toString());
          IPath rootPath = entry.getSourceAttachmentRootPath();
          if (rootPath != null) {
            buf.append(IPath.SEPARATOR);
            buf.append(rootPath.toString());
          }
          buf.append(']');
        }
        // append JRE name if we can compute it
        if (path.equals(new Path(JavaRuntime.JRELIB_VARIABLE)) && fLaunchConfiguration != null) {
          try {
            IVMInstall vm = JavaRuntime.computeVMInstall(fLaunchConfiguration);
            buf.append(" - "); // $NON-NLS-1$
            buf.append(vm.getName());
          } catch (CoreException e) {
          }
        }
        return buf.toString();
      case IRuntimeClasspathEntry.CONTAINER:
        path = entry.getPath();
        if (fLaunchConfiguration != null) {
          try {
            IJavaProject project = null;
            try {
              project = JavaRuntime.getJavaProject(fLaunchConfiguration);
            } catch (CoreException e) {
            }
            if (project == null) {
            } else {
              IClasspathContainer container =
                  JavaCore.getClasspathContainer(entry.getPath(), project);
              if (container != null) {
                if (container.getDescription().startsWith("Persisted container")) {
                  return container.getPath().toString();
                } else {
                  return container.getDescription();
                }
              }
            }
          } catch (CoreException e) {
          }
        }
        return entry.getPath().toString();
      case IRuntimeClasspathEntry.OTHER:
        IRuntimeClasspathEntry delegate = entry;
        if (entry instanceof ClasspathEntry) {
          delegate = ((ClasspathEntry) entry).getDelegate();
        }
        String name = lp.getText(delegate);
        if (name == null || name.length() == 0) {
          return ((IRuntimeClasspathEntry2) delegate).getName();
        }
        return name;
    }
    return ""; //$NON-NLS-1$
  }
  @Override
  public void requestClasspathContainerUpdate(
      IPath containerPath, IJavaProject project, IClasspathContainer containerSuggestion)
      throws CoreException {

    final String key =
        SDKClasspathContainer.getDecorationManagerKey(
            project.getProject(), containerPath.toString());

    final IClasspathEntry[] entries = containerSuggestion.getClasspathEntries();

    cpDecorations.clearAllDecorations(key);

    for (int i = 0; i < entries.length; i++) {
      final IClasspathEntry entry = entries[i];

      final IPath srcpath = entry.getSourceAttachmentPath();
      final IPath srcrootpath = entry.getSourceAttachmentRootPath();
      final IClasspathAttribute[] attrs = entry.getExtraAttributes();

      if (srcpath != null || attrs.length > 0) {
        final String eid = entry.getPath().toString();
        final ClasspathDecorations dec = new ClasspathDecorations();

        dec.setSourceAttachmentPath(srcpath);
        dec.setSourceAttachmentRootPath(srcrootpath);
        dec.setExtraAttributes(attrs);

        cpDecorations.setDecorations(key, eid, dec);
      }
    }

    cpDecorations.save();

    IPath portalDir = null;
    IPath portalGlobalDir = null;
    String javadocURL = null;
    IPath sourceLocation = null;
    IPath bundleDir = null;
    IPath[] bundleLibDependencyPath = null;

    if (containerSuggestion instanceof SDKClasspathContainer) {
      portalDir = ((SDKClasspathContainer) containerSuggestion).getPortalDir();
      bundleDir = ((SDKClasspathContainer) containerSuggestion).getBundleDir();
      portalGlobalDir = ((SDKClasspathContainer) containerSuggestion).getPortalGlobalDir();
      javadocURL = ((SDKClasspathContainer) containerSuggestion).getJavadocURL();
      sourceLocation = ((SDKClasspathContainer) containerSuggestion).getSourceLocation();
      bundleLibDependencyPath =
          ((SDKClasspathContainer) containerSuggestion).getBundleLibDependencyPath();
    } else {
      PortalBundle bundle = ServerUtil.getPortalBundle(project.getProject());

      if (bundle == null) {
        final String msg = "Invalid sdk properties setting.";
        throw new CoreException(ProjectCore.createErrorStatus(msg));
      }

      portalDir = bundle.getAppServerPortalDir();
      portalGlobalDir = bundle.getAppServerLibGlobalDir();
      bundleLibDependencyPath = bundle.getBundleDependencyJars();
    }

    if (portalDir != null && portalGlobalDir != null) {
      IClasspathContainer newContainer =
          new SDKClasspathContainer(
              containerPath,
              project,
              portalDir,
              javadocURL,
              sourceLocation,
              portalGlobalDir,
              bundleDir,
              bundleLibDependencyPath);

      JavaCore.setClasspathContainer(
          containerPath,
          new IJavaProject[] {project},
          new IClasspathContainer[] {newContainer},
          null);
    }
  }
示例#5
0
  /**
   * Add a path to current java search scope or all project fragment roots if null. Use project
   * resolved classpath to retrieve and store access restriction on each classpath entry. Recurse if
   * dependent projects are found.
   *
   * @param javaProject Project used to get resolved classpath entries
   * @param pathToAdd Path to add in case of single element or null if user want to add all project
   *     package fragment roots
   * @param includeMask Mask to apply on classpath entries
   * @param projectsToBeAdded Set to avoid infinite recursion
   * @param visitedProjects Set to avoid adding twice the same project
   * @param referringEntry Project raw entry in referring project classpath
   * @throws JavaModelException May happen while getting java model info
   */
  void add(
      JavaProject javaProject,
      IPath pathToAdd,
      int includeMask,
      HashSet projectsToBeAdded,
      HashSet visitedProjects,
      IClasspathEntry referringEntry)
      throws JavaModelException {
    IProject project = javaProject.getProject();
    if (!project.isAccessible() || !visitedProjects.add(project)) return;

    IPath projectPath = project.getFullPath();
    String projectPathString = projectPath.toString();
    addEnclosingProjectOrJar(projectPath);

    IClasspathEntry[] entries = javaProject.getResolvedClasspath();
    IJavaModel model = javaProject.getJavaModel();
    JavaModelManager.PerProjectInfo perProjectInfo = javaProject.getPerProjectInfo();
    for (int i = 0, length = entries.length; i < length; i++) {
      IClasspathEntry entry = entries[i];
      AccessRuleSet access = null;
      ClasspathEntry cpEntry = (ClasspathEntry) entry;
      if (referringEntry != null) {
        // Add only exported entries.
        // Source folder are implicitly exported.
        if (!entry.isExported() && entry.getEntryKind() != IClasspathEntry.CPE_SOURCE) {
          continue;
        }
        cpEntry = cpEntry.combineWith((ClasspathEntry) referringEntry);
        //				cpEntry = ((ClasspathEntry)referringEntry).combineWith(cpEntry);
      }
      access = cpEntry.getAccessRuleSet();
      switch (entry.getEntryKind()) {
        case IClasspathEntry.CPE_LIBRARY:
          IClasspathEntry rawEntry = null;
          Map rootPathToRawEntries = perProjectInfo.rootPathToRawEntries;
          if (rootPathToRawEntries != null) {
            rawEntry = (IClasspathEntry) rootPathToRawEntries.get(entry.getPath());
          }
          if (rawEntry == null) break;
          rawKind:
          switch (rawEntry.getEntryKind()) {
            case IClasspathEntry.CPE_LIBRARY:
            case IClasspathEntry.CPE_VARIABLE:
              if ((includeMask & APPLICATION_LIBRARIES) != 0) {
                IPath path = entry.getPath();
                if (pathToAdd == null || pathToAdd.equals(path)) {
                  Object target = JavaModel.getTarget(path, false /*don't check existence*/);
                  if (target instanceof IFolder) // case of an external folder
                  path = ((IFolder) target).getFullPath();
                  String pathToString =
                      path.getDevice() == null ? path.toString() : path.toOSString();
                  add(
                      projectPath.toString(),
                      "",
                      pathToString,
                      false /*not a package*/,
                      access); //$NON-NLS-1$
                  addEnclosingProjectOrJar(entry.getPath());
                }
              }
              break;
            case IClasspathEntry.CPE_CONTAINER:
              IClasspathContainer container =
                  JavaCore.getClasspathContainer(rawEntry.getPath(), javaProject);
              if (container == null) break;
              switch (container.getKind()) {
                case IClasspathContainer.K_APPLICATION:
                  if ((includeMask & APPLICATION_LIBRARIES) == 0) break rawKind;
                  break;
                case IClasspathContainer.K_SYSTEM:
                case IClasspathContainer.K_DEFAULT_SYSTEM:
                  if ((includeMask & SYSTEM_LIBRARIES) == 0) break rawKind;
                  break;
                default:
                  break rawKind;
              }
              IPath path = entry.getPath();
              if (pathToAdd == null || pathToAdd.equals(path)) {
                Object target = JavaModel.getTarget(path, false /*don't check existence*/);
                if (target instanceof IFolder) // case of an external folder
                path = ((IFolder) target).getFullPath();
                String pathToString =
                    path.getDevice() == null ? path.toString() : path.toOSString();
                add(
                    projectPath.toString(),
                    "",
                    pathToString,
                    false /*not a package*/,
                    access); //$NON-NLS-1$
                addEnclosingProjectOrJar(entry.getPath());
              }
              break;
          }
          break;
        case IClasspathEntry.CPE_PROJECT:
          if ((includeMask & REFERENCED_PROJECTS) != 0) {
            IPath path = entry.getPath();
            if (pathToAdd == null || pathToAdd.equals(path)) {
              JavaProject referencedProject = (JavaProject) model.getJavaProject(path.toOSString());
              if (!projectsToBeAdded.contains(
                  referencedProject)) { // do not recurse if depending project was used to create
                                        // the scope
                add(
                    referencedProject,
                    null,
                    includeMask,
                    projectsToBeAdded,
                    visitedProjects,
                    cpEntry);
              }
            }
          }
          break;
        case IClasspathEntry.CPE_SOURCE:
          if ((includeMask & SOURCES) != 0) {
            IPath path = entry.getPath();
            if (pathToAdd == null || pathToAdd.equals(path)) {
              add(
                  projectPath.toString(),
                  Util.relativePath(path, projectPath.segmentCount() /*remove project segment*/),
                  projectPathString,
                  false /*not a package*/,
                  access);
            }
          }
          break;
      }
    }
  }
  /**
   * Initialize the container with the "persisted" classpath entries, and then schedule the refresh.
   */
  public void initialize(IPath containerPath, final IJavaProject project) throws CoreException {
    int size = containerPath.segmentCount();
    if (size > 0) {
      if (containerPath.segment(0).equals(CeylonProjectModulesContainer.CONTAINER_ID)) {
        ceylonModel().addProject(project.getProject());
        IClasspathContainer c = getClasspathContainer(containerPath, project);
        CeylonProjectModulesContainer container;
        if (c instanceof CeylonProjectModulesContainer) {
          container = (CeylonProjectModulesContainer) c;
        } else {
          IClasspathEntry entry = getCeylonClasspathEntry(containerPath, project);
          IClasspathAttribute[] attributes =
              entry == null ? new IClasspathAttribute[0] : entry.getExtraAttributes();
          if (c == null) {
            container =
                new CeylonProjectModulesContainer(
                    project, containerPath, new IClasspathEntry[0], attributes);
          } else {
            // this might be the persisted one: reuse the persisted entries
            container =
                new CeylonProjectModulesContainer(
                    project, containerPath, c.getClasspathEntries(), attributes);
          }
        }

        setClasspathContainer(
            containerPath,
            new IJavaProject[] {project},
            new IClasspathContainer[] {container},
            null);

        final Job initDependenciesJob =
            new InitDependenciesJob(
                "Initializing dependencies for project " + project.getElementName(), container);
        initDependenciesJob.setUser(false);
        initDependenciesJob.setPriority(Job.BUILD);
        initDependenciesJob.setRule(getWorkspace().getRoot());

        // Before scheduling the InitDependenciesJob, we will wait for the end of the Java Tooling
        // initialization Job
        final long waitUntil = System.currentTimeMillis() + 120000;

        Job initDependenciesWhenJavaToolingIsInitialized =
            new Job(
                "Waiting for the end of the Java Tooling Initialization before initializing Ceylon dependencies for project "
                    + project.getElementName()
                    + " ...") {
              private Job initJavaToolingJob = null;

              @Override
              protected IStatus run(IProgressMonitor monitor) {
                if (initJavaToolingJob == null) {
                  Job[] jobs = getJobManager().find(JavaUI.ID_PLUGIN);
                  for (Job job : jobs) {
                    if (job.getClass().getEnclosingClass().equals(InitializeAfterLoadJob.class)) {
                      initJavaToolingJob = job;
                    }
                  }
                }

                if (initJavaToolingJob != null) {
                  if (initJavaToolingJob.getState() == Job.WAITING
                      || initJavaToolingJob.getState() == Job.RUNNING) {
                    if (System.currentTimeMillis() < waitUntil) {
                      //                                    System.out.println("Waiting 1 seconde
                      // more for the end of the Java Tooling Initialization before initializing
                      // Ceylon dependencies for project " + project.getElementName() + " ...");
                      schedule(1000);
                      return Status.OK_STATUS;
                    } else {
                      //                                    System.out.println("The Java Tooling is
                      // not initialized after 2 minutes, so start initializing Ceylon dependencies
                      // for project " + project.getElementName() + " anyway !");
                    }
                  }
                }

                boolean shouldSchedule = true;
                for (Job job : getJobManager().find(initDependenciesJob)) {
                  if (job.getState() == Job.WAITING) {
                    //                                System.out.println("An InitDependenciesJob for
                    // project " + project.getElementName() + " is already scheduled. Finally don't
                    // schedule a new one after the Java Tooling has initialized");
                    shouldSchedule = false;
                    break;
                  }
                }

                if (shouldSchedule) {
                  //                            System.out.println("Scheduling the initialization of
                  // the Ceylon dependencies for project " + project.getElementName() + " after the
                  // Java Tooling has been initialized");
                  initDependenciesJob.schedule();
                }
                return Status.OK_STATUS;
              }
            };

        initDependenciesWhenJavaToolingIsInitialized.setPriority(Job.BUILD);
        initDependenciesWhenJavaToolingIsInitialized.setSystem(true);
        initDependenciesWhenJavaToolingIsInitialized.schedule();
      }
    }
  }
 protected static IClasspathEntry[] getClassPathEntries(IProject project) throws Exception {
   IJavaProject javaProject = JavaCore.create(project);
   IClasspathContainer container = BuildPathManager.getMaven2ClasspathContainer(javaProject);
   return container.getClasspathEntries();
 }