/**
   * Tests reading a 3.0.2 install with a mix of classic and OSGi plug-ins.
   *
   * @throws Exception
   */
  public void testClassicPlugins() throws Exception {
    // extract the 3.0.2 skeleton
    IPath location = extractClassicPlugins();

    // the new way
    ITargetDefinition definition = getNewTarget();
    ITargetLocation container = getTargetService().newDirectoryLocation(location.toOSString());
    definition.setTargetLocations(new ITargetLocation[] {container});
    Set urls = getAllBundleURLs(definition);
    assertTrue("Must be bundles", urls.size() > 0);

    Preferences store = PDECore.getDefault().getPluginPreferences();
    boolean restore = store.getBoolean(ICoreConstants.TARGET_PLATFORM_REALIZATION);
    try {
      store.setValue(ICoreConstants.TARGET_PLATFORM_REALIZATION, false);
      // the old way
      URL[] pluginPaths = PluginPathFinder.getPluginPaths(location.toOSString());
      for (int i = 0; i < pluginPaths.length; i++) {
        URL url = pluginPaths[i];
        if (!urls.contains(url)) {
          System.err.println(url.toString());
        }
      }
      assertEquals("Wrong number of bundles", pluginPaths.length, urls.size());
    } finally {
      store.setValue(ICoreConstants.TARGET_PLATFORM_REALIZATION, restore);
    }
  }
  /**
   * Tests identification of source bundles in a 3.0.2 install.
   *
   * @throws Exception
   */
  public void testClassicSourcePlugins() throws Exception {
    // extract the 3.0.2 skeleton
    IPath location = extractClassicPlugins();

    // the new way
    ITargetDefinition definition = getNewTarget();
    ITargetLocation container = getTargetService().newDirectoryLocation(location.toOSString());
    definition.setTargetLocations(new ITargetLocation[] {container});

    definition.resolve(null);
    TargetBundle[] bundles = definition.getBundles();
    List source = new ArrayList();
    for (int i = 0; i < bundles.length; i++) {
      TargetBundle sb = bundles[i];
      if (sb.isSourceBundle()) {
        source.add(sb);
      }
    }

    assertEquals("Wrong number of source bundles", 4, source.size());
    Set names = new HashSet();
    for (int i = 0; i < source.size(); i++) {
      names.add(((TargetBundle) source.get(i)).getBundleInfo().getSymbolicName());
    }
    String[] expected =
        new String[] {
          "org.eclipse.platform.source",
          "org.eclipse.jdt.source",
          "org.eclipse.pde.source",
          "org.eclipse.platform.source.win32.win32.x86"
        };
    for (int i = 0; i < expected.length; i++) {
      assertTrue("Missing source for " + expected[i], names.contains(expected[i]));
    }
  }
  protected boolean checkForClassFileChanges(
      IResourceDelta binaryDelta, ClasspathMultiDirectory md, int segmentCount)
      throws CoreException {
    IResource resource = binaryDelta.getResource();
    // remember that if inclusion & exclusion patterns change then a full build is done
    boolean isExcluded =
        (md.exclusionPatterns != null || md.inclusionPatterns != null)
            && Util.isExcluded(resource, md.inclusionPatterns, md.exclusionPatterns);
    switch (resource.getType()) {
      case IResource.FOLDER:
        if (isExcluded && md.inclusionPatterns == null)
          return true; // no need to go further with this delta since its children cannot be
        // included

        IResourceDelta[] children = binaryDelta.getAffectedChildren();
        for (int i = 0, l = children.length; i < l; i++)
          if (!checkForClassFileChanges(children[i], md, segmentCount)) return false;
        return true;
      case IResource.FILE:
        if (!isExcluded
            && org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(resource.getName())) {
          // perform full build if a managed class file has been changed
          IPath typePath =
              resource.getFullPath().removeFirstSegments(segmentCount).removeFileExtension();
          if (this.newState.isKnownType(typePath.toString())) {
            if (JavaBuilder.DEBUG)
              System.out.println(
                  "MUST DO FULL BUILD. Found change to class file " + typePath); // $NON-NLS-1$
            return false;
          }
          return true;
        }
    }
    return true;
  }
  /**
   * Tests a JDT source feature bundle container contains the appropriate bundles
   *
   * @throws Exception
   */
  public void testSourceFeatureBundleContainer() throws Exception {
    // extract the feature
    IPath location = extractModifiedFeatures();

    ITargetDefinition definition = getNewTarget();
    ITargetLocation container =
        getTargetService()
            .newFeatureLocation(location.toOSString(), "org.eclipse.jdt.source", null);
    container.resolve(definition, null);
    TargetBundle[] bundles = container.getBundles();

    List expected = new ArrayList();
    expected.add("org.eclipse.jdt.source");
    expected.add("org.eclipse.jdt.launching.source");
    // There are two versions of junit available, each with source
    expected.add("org.junit.source");
    expected.add("org.junit.source");
    if (Platform.getOS().equals(Platform.OS_MACOSX)) {
      expected.add("org.eclipse.jdt.launching.macosx.source");
    }

    assertEquals("Wrong number of bundles", expected.size(), bundles.length);
    for (int i = 0; i < bundles.length; i++) {
      if (bundles[i].getBundleInfo().getSymbolicName().equals("org.eclipse.jdt.doc.isv")) {
        assertFalse("Should not be a source bundle", bundles[i].isSourceBundle());
      } else {
        assertTrue(expected.remove(bundles[i].getBundleInfo().getSymbolicName()));
        assertTrue("Should be a source bundle", bundles[i].isSourceBundle());
      }
    }
    assertTrue("Wrong bundles in JDT feature", expected.isEmpty());
  }
  protected void finishedWith(
      String sourceLocator,
      CompilationResult result,
      char[] mainTypeName,
      ArrayList definedTypeNames,
      ArrayList duplicateTypeNames) {
    char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(sourceLocator);
    if (previousTypeNames == null) previousTypeNames = new char[][] {mainTypeName};
    IPath packagePath = null;
    next:
    for (int i = 0, l = previousTypeNames.length; i < l; i++) {
      char[] previous = previousTypeNames[i];
      for (int j = 0, m = definedTypeNames.size(); j < m; j++)
        if (CharOperation.equals(previous, (char[]) definedTypeNames.get(j))) continue next;

      SourceFile sourceFile = (SourceFile) result.getCompilationUnit();
      if (packagePath == null) {
        int count = sourceFile.sourceLocation.sourceFolder.getFullPath().segmentCount();
        packagePath =
            sourceFile.resource.getFullPath().removeFirstSegments(count).removeLastSegments(1);
      }
      if (this.secondaryTypesToRemove == null)
        this.secondaryTypesToRemove = new SimpleLookupTable();
      ArrayList types =
          (ArrayList) this.secondaryTypesToRemove.get(sourceFile.sourceLocation.binaryFolder);
      if (types == null) types = new ArrayList(definedTypeNames.size());
      types.add(packagePath.append(new String(previous)));
      this.secondaryTypesToRemove.put(sourceFile.sourceLocation.binaryFolder, types);
    }
    super.finishedWith(sourceLocator, result, mainTypeName, definedTypeNames, duplicateTypeNames);
  }
 /**
  * Returns the file path where the given resolved bundle can be found. Used to group bundles by
  * file path in the tree.
  *
  * @param bundle bundle to lookup parent path for
  * @return path of parent directory, if unknown it will be a path object containing "Unknown"
  */
 private IPath getParentPath(IResolvedBundle bundle) {
   URI location = bundle.getBundleInfo().getLocation();
   if (location == null) {
     return new Path(Messages.TargetContentsGroup_8);
   }
   IPath path = new Path(URIUtil.toUnencodedString(location));
   path = path.removeLastSegments(1);
   return path;
 }
Example #7
0
 /**
  * Returns the existing WebProject corresponding to the provided path, or <code>null</code> if no
  * such project exists.
  *
  * @param path path in the form /file/{workspaceId}/{projectName}/[filePath]
  * @return the web project, or <code>null</code>
  */
 public static ProjectInfo projectFromPath(IPath path) {
   if (path == null || path.segmentCount() < 3) return null;
   String workspaceId = path.segment(1);
   String projectName = path.segment(2);
   try {
     return OrionConfiguration.getMetaStore().readProject(workspaceId, projectName);
   } catch (CoreException e) {
     return null;
   }
 }
  protected long computeModificationStamp(IResource resource) {
    long modificationStamp = resource.getModificationStamp();

    IPath path = resource.getLocation();
    if (path == null) {
      return modificationStamp;
    }

    modificationStamp = path.toFile().lastModified();
    return modificationStamp;
  }
  /**
   * Tests a JDT feature bundle container contains the appropriate bundles for a specific OS.
   *
   * @throws Exception
   */
  public void testMacOSFeatureBundleContainer() throws Exception {
    // extract the feature
    IPath location = extractModifiedFeatures();

    ITargetDefinition definition = getNewTarget();
    definition.setOS(Platform.OS_MACOSX);
    ITargetLocation container =
        getTargetService().newFeatureLocation(location.toOSString(), "org.eclipse.jdt", null);
    container.resolve(definition, null);
    TargetBundle[] bundles = container.getBundles();

    List expected = new ArrayList();
    expected.add("org.eclipse.jdt");
    expected.add("org.eclipse.jdt.launching");
    // 2 versions of JUnit
    expected.add("org.junit");
    expected.add("org.junit");
    expected.add("org.junit4");
    expected.add("org.eclipse.jdt.launching.macosx");

    assertEquals("Wrong number of bundles in JDT feature", expected.size(), bundles.length);
    for (int i = 0; i < bundles.length; i++) {
      String symbolicName = bundles[i].getBundleInfo().getSymbolicName();
      expected.remove(symbolicName);
      if (symbolicName.equals("org.eclipse.jdt.launching.macosx")) {
        // the bundle should be missing unless on Mac
        IStatus status = bundles[i].getStatus();
        if (Platform.getOS().equals(Platform.OS_MACOSX)) {
          assertTrue("Mac bundle should be present", status.isOK());
        } else {
          assertFalse("Mac bundle should be missing", status.isOK());
          assertEquals(
              "Mac bundle should be mssing",
              TargetBundle.STATUS_PLUGIN_DOES_NOT_EXIST,
              status.getCode());
        }
      }
    }
    Iterator iterator = expected.iterator();
    while (iterator.hasNext()) {
      String name = (String) iterator.next();
      System.err.println("Missing: " + name);
    }
    assertTrue("Wrong bundles in JDT feature", expected.isEmpty());

    // should be no source bundles
    for (int i = 0; i < bundles.length; i++) {
      TargetBundle bundle = bundles[i];
      assertFalse("Should be no source bundles", bundle.isSourceBundle());
    }
  }
  /**
   * Tests reading a 3.0 style plug-in that has a MANIFEST file that is not a bundle manifest.
   *
   * @throws Exception
   */
  public void testClassicPluginsWithNonBundleManifest() throws Exception {
    // extract the plug-in
    IPath location = extractClassicNonBundleManifestPlugins();

    // the new way
    ITargetDefinition definition = getNewTarget();
    ITargetLocation container = getTargetService().newDirectoryLocation(location.toOSString());
    definition.setTargetLocations(new ITargetLocation[] {container});
    definition.resolve(null);
    TargetBundle[] bundles = definition.getAllBundles();
    assertEquals("Wrong number of bundles", 1, bundles.length);
    assertEquals(
        "Wrong bundle", "org.eclipse.core.variables", bundles[0].getBundleInfo().getSymbolicName());
  }
 /**
  * Returns the location of the JDT feature in the running host as a path in the local file system.
  *
  * @return path to JDT feature
  */
 protected IPath getJdtFeatureLocation() {
   IPath path = new Path(TargetPlatform.getDefaultLocation());
   path = path.append("features");
   File dir = path.toFile();
   assertTrue("Missing features directory", dir.exists() && !dir.isFile());
   String[] files = dir.list();
   String location = null;
   for (int i = 0; i < files.length; i++) {
     if (files[i].startsWith("org.eclipse.jdt_")) {
       location = path.append(files[i]).toOSString();
       break;
     }
   }
   assertNotNull("Missing JDT feature", location);
   return new Path(location);
 }
Example #12
0
 /**
  * Returns the existing git repositories for the given file path, following the given traversal
  * rule.
  *
  * @param path expected format /file/{Workspace}/{projectName}[/{path}]
  * @return a map of all git repositories found, or <code>null</code> if the provided path format
  *     doesn't match the expected format.
  * @throws CoreException
  */
 public static Map<IPath, File> getGitDirs(IPath path, Traverse traverse) throws CoreException {
   IPath p = path.removeFirstSegments(1); // remove /file
   IFileStore fileStore = NewFileServlet.getFileStore(null, p);
   if (fileStore == null) return null;
   Map<IPath, File> result = new HashMap<IPath, File>();
   File file = fileStore.toLocalFile(EFS.NONE, null);
   // jgit can only handle a local file
   if (file == null) return result;
   switch (traverse) {
     case CURRENT:
       if (RepositoryCache.FileKey.isGitRepository(file, FS.DETECTED)) {
         result.put(new Path(""), file); // $NON-NLS-1$
       } else if (RepositoryCache.FileKey.isGitRepository(
           new File(file, Constants.DOT_GIT), FS.DETECTED)) {
         result.put(new Path(""), new File(file, Constants.DOT_GIT)); // $NON-NLS-1$
       }
       break;
     case GO_UP:
       getGitDirsInParents(file, result);
       break;
     case GO_DOWN:
       getGitDirsInChildren(file, p, result);
       break;
   }
   return result;
 }
  /**
   * Tests setting the target platform to the stored JDT feature test data
   *
   * @throws Exception
   */
  public void testSetTargetPlatformToJdtFeature() throws Exception {
    try {
      // extract the feature
      IPath location = extractModifiedFeatures();
      // org.eclipse.jdt_3.6.0.v20100105-0800-7z8VFR9FMTb52_pOyKHhoek1

      ITargetDefinition target = getNewTarget();
      ITargetLocation container =
          getTargetService()
              .newFeatureLocation(
                  location.toOSString(),
                  "org.eclipse.jdt",
                  "3.6.0.v20100105-0800-7z8VFR9FMTb52_pOyKHhoek1");

      target.setTargetLocations(new ITargetLocation[] {container});

      setTargetPlatform(target);

      List expected = new ArrayList();
      expected.add("org.eclipse.jdt");
      expected.add("org.eclipse.jdt.launching");
      // 2 versions of JUnit
      expected.add("org.junit");
      expected.add("org.junit");
      expected.add("org.junit4");
      if (Platform.getOS().equals(Platform.OS_MACOSX)) {
        expected.add("org.eclipse.jdt.launching.macosx");
      }

      // current platform
      IPluginModelBase[] models = TargetPlatformHelper.getPDEState().getTargetModels();

      assertEquals("Wrong number of bundles in JDT feature", expected.size(), models.length);
      for (int i = 0; i < models.length; i++) {
        expected.remove(models[i].getPluginBase().getId());
        assertTrue(models[i].isEnabled());
      }
      Iterator iterator = expected.iterator();
      while (iterator.hasNext()) {
        String name = (String) iterator.next();
        System.err.println("Missing: " + name);
      }
      assertTrue("Wrong bundles in target platform", expected.isEmpty());
    } finally {
      resetTargetPlatform();
    }
  }
 protected void removeClassFile(IPath typePath, IContainer outputFolder) throws CoreException {
   if (typePath.lastSegment().indexOf('$') == -1) { // is not a nested type
     this.newState.removeQualifiedTypeName(typePath.toString());
     // add dependents even when the type thinks it does not exist to be on the safe side
     if (JavaBuilder.DEBUG) System.out.println("Found removed type " + typePath); // $NON-NLS-1$
     addDependentsOf(
         typePath,
         true); // when member types are removed, their enclosing type is structurally changed
   }
   IFile classFile =
       outputFolder.getFile(typePath.addFileExtension(SuffixConstants.EXTENSION_class));
   if (classFile.exists()) {
     if (JavaBuilder.DEBUG)
       System.out.println("Deleting class file of removed type " + typePath); // $NON-NLS-1$
     classFile.delete(IResource.FORCE, null);
   }
 }
Example #15
0
 /**
  * Completes a move after a file transfer. Returns <code>true</code> if the move was successful,
  * and <code>false</code> otherwise. In case of failure, this method handles setting an
  * appropriate response.
  */
 private boolean completeMove(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException {
   IPath destPath = new Path(getPath()).append(getFileName());
   try {
     IFileStore source = EFS.getStore(new File(getStorageDirectory(), FILE_DATA).toURI());
     IFileStore destination = NewFileServlet.getFileStore(destPath);
     source.move(destination, EFS.OVERWRITE, null);
   } catch (CoreException e) {
     String msg = NLS.bind("Failed to complete file transfer on {0}", destPath.toString());
     statusHandler.handleRequest(
         req,
         resp,
         new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
     return false;
   }
   return true;
 }
  /**
   * Removes path information from the given string containing one or more comma separated osgi
   * bundles. Replaces escaped '\:' with ':'. Removes, reference, platform and file prefixes.
   * Removes any other path information converting the location or the last segment to a bundle id.
   *
   * @param osgiBundles list of bundles to strip path information from (commma separated)
   * @return list of bundles with path information stripped
   */
  public static String stripPathInformation(String osgiBundles) {
    StringBuffer result = new StringBuffer();
    StringTokenizer tokenizer = new StringTokenizer(osgiBundles, ","); // $NON-NLS-1$
    while (tokenizer.hasMoreElements()) {
      String token = tokenizer.nextToken();
      token = token.replaceAll("\\\\:|/:", ":"); // $NON-NLS-1$ //$NON-NLS-2$

      // read up until the first @, if there
      int atIndex = token.indexOf('@');
      String bundle = atIndex > 0 ? token.substring(0, atIndex) : token;
      bundle = bundle.trim();

      // strip [reference:][platform:][file:] prefixes if any
      if (bundle.startsWith(REFERENCE_PREFIX) && bundle.length() > REFERENCE_PREFIX.length())
        bundle = bundle.substring(REFERENCE_PREFIX.length());
      if (bundle.startsWith(PLATFORM_PREFIX) && bundle.length() > PLATFORM_PREFIX.length())
        bundle = bundle.substring(PLATFORM_PREFIX.length());
      if (bundle.startsWith(FILE_URL_PREFIX) && bundle.length() > FILE_URL_PREFIX.length())
        bundle = bundle.substring(FILE_URL_PREFIX.length());

      // if the path is relative, the last segment is the bundle symbolic name
      // Otherwise, we need to retrieve the bundle symbolic name ourselves
      IPath path = new Path(bundle);
      String id = null;
      if (path.isAbsolute()) {
        id = getSymbolicName(bundle);
      }
      if (id == null) {
        id = path.lastSegment();
      }
      if (id != null) {
        int underscoreIndex = id.indexOf('_');
        if (underscoreIndex >= 0) {
          id = id.substring(0, underscoreIndex);
        }
        if (id.endsWith(JAR_EXTENSION)) {
          id = id.substring(0, id.length() - 4);
        }
      }
      if (result.length() > 0) result.append(","); // $NON-NLS-1$
      result.append(id != null ? id : bundle);
      if (atIndex > -1) result.append(token.substring(atIndex).trim());
    }
    return result.toString();
  }
Example #17
0
 boolean filterExtraResource(IResource resource) {
   if (this.extraResourceFileFilters != null) {
     char[] name = resource.getName().toCharArray();
     for (int i = 0, l = this.extraResourceFileFilters.length; i < l; i++)
       if (CharOperation.match(this.extraResourceFileFilters[i], name, true)) return true;
   }
   if (this.extraResourceFolderFilters != null) {
     IPath path = resource.getProjectRelativePath();
     String pathName = path.toString();
     int count = path.segmentCount();
     if (resource.getType() == IResource.FILE) count--;
     for (int i = 0, l = this.extraResourceFolderFilters.length; i < l; i++)
       if (pathName.indexOf(this.extraResourceFolderFilters[i]) != -1)
         for (int j = 0; j < count; j++)
           if (this.extraResourceFolderFilters[i].equals(path.segment(j))) return true;
   }
   return false;
 }
    public boolean include(Object object) {
      if (object instanceof IResource) {
        IResource resource = (IResource) object;
        IPath path =
            IResource.FILE == resource.getType()
                ? resource.getFullPath()
                : resource.getFullPath().addTrailingSeparator();
        object = path.toPortableString();
      }

      for (Iterator iter = filters.iterator(); iter.hasNext(); ) {
        Filter filter = (Filter) iter.next();
        if (filter.matches(object)) {
          return filter.inclusive();
        }
      }
      return default_;
    }
Example #19
0
 private void loadCommentTemplates() {
   IPath pluginStateLocation =
       CVSUIPlugin.getPlugin().getStateLocation().append(COMMENT_TEMPLATES_FILE);
   File file = pluginStateLocation.toFile();
   if (!file.exists()) return;
   try {
     BufferedInputStream is = new BufferedInputStream(new FileInputStream(file));
     try {
       readCommentTemplates(is);
     } finally {
       is.close();
     }
   } catch (IOException e) {
     CVSUIPlugin.log(IStatus.ERROR, CVSUIMessages.RepositoryManager_ioException, e);
   } catch (TeamException e) {
     CVSUIPlugin.log(e);
   }
 }
  protected void deleteGeneratedFiles(IFile[] deletedGeneratedFiles) {
    // delete generated files and recompile any affected source files
    try {
      for (int j = deletedGeneratedFiles.length; --j >= 0; ) {
        IFile deletedFile = deletedGeneratedFiles[j];
        if (deletedFile.exists())
          continue; // only delete .class files for source files that were actually deleted

        SourceFile sourceFile = findSourceFile(deletedFile, false);
        String typeLocator = sourceFile.typeLocator();
        int mdSegmentCount = sourceFile.sourceLocation.sourceFolder.getFullPath().segmentCount();
        IPath typePath =
            sourceFile
                .resource
                .getFullPath()
                .removeFirstSegments(mdSegmentCount)
                .removeFileExtension();
        addDependentsOf(typePath, true); // add dependents of the source file since its now deleted
        this.previousSourceFiles =
            null; // existing source files did not see it as deleted since they were compiled before
        // it was
        char[][] definedTypeNames = this.newState.getDefinedTypeNamesFor(typeLocator);
        if (definedTypeNames == null) { // defined a single type matching typePath
          removeClassFile(typePath, sourceFile.sourceLocation.binaryFolder);
        } else {
          if (definedTypeNames.length > 0) { // skip it if it failed to successfully define a type
            IPath packagePath = typePath.removeLastSegments(1);
            for (int d = 0, l = definedTypeNames.length; d < l; d++)
              removeClassFile(
                  packagePath.append(new String(definedTypeNames[d])),
                  sourceFile.sourceLocation.binaryFolder);
          }
        }
        this.newState.removeLocator(typeLocator);
      }
    } catch (CoreException e) {
      // must continue with compile loop so just log the CoreException
      Util.log(
          e,
          "JavaBuilder logging CompilationParticipant's CoreException to help debugging"); //$NON-NLS-1$
    }
  }
Example #21
0
  /* Return the list of projects for which it requires a resource delta. This builder's project
   * is implicitly included and need not be specified. Builders must re-specify the list
   * of interesting projects every time they are run as this is not carried forward
   * beyond the next build. Missing projects should be specified but will be ignored until
   * they are added to the workspace.
   */
  private IProject[] getRequiredProjects(boolean includeBinaryPrerequisites) {
    if (this.javaProject == null || this.workspaceRoot == null) return new IProject[0];

    ArrayList projects = new ArrayList();
    ExternalFoldersManager externalFoldersManager = JavaModelManager.getExternalManager();
    try {
      IClasspathEntry[] entries = this.javaProject.getExpandedClasspath();
      for (int i = 0, l = entries.length; i < l; i++) {
        IClasspathEntry entry = entries[i];
        IPath path = entry.getPath();
        IProject p = null;
        switch (entry.getEntryKind()) {
          case IClasspathEntry.CPE_PROJECT:
            p =
                this.workspaceRoot.getProject(
                    path.lastSegment()); // missing projects are considered too
            if (((ClasspathEntry) entry).isOptional()
                && !JavaProject.hasJavaNature(p)) // except if entry is optional
            p = null;
            break;
          case IClasspathEntry.CPE_LIBRARY:
            if (includeBinaryPrerequisites && path.segmentCount() > 0) {
              // some binary resources on the class path can come from projects that are not
              // included in the project references
              IResource resource = this.workspaceRoot.findMember(path.segment(0));
              if (resource instanceof IProject) {
                p = (IProject) resource;
              } else {
                resource = externalFoldersManager.getFolder(path);
                if (resource != null) p = resource.getProject();
              }
            }
        }
        if (p != null && !projects.contains(p)) projects.add(p);
      }
    } catch (JavaModelException e) {
      return new IProject[0];
    }
    IProject[] result = new IProject[projects.size()];
    projects.toArray(result);
    return result;
  }
  /**
   * Tests that a target definition equivalent to the default target platform contains the same
   * bundles as the default target platform (this is an explicit location with no target weaving),
   * when created with a variable referencing ${eclipse_home}
   *
   * @throws Exception
   */
  public void testEclipseHomeTargetPlatform() throws Exception {
    // the new way
    ITargetDefinition definition = getNewTarget();
    ITargetLocation container = getTargetService().newProfileLocation("${eclipse_home}", null);
    definition.setTargetLocations(new ITargetLocation[] {container});
    Set urls = getAllBundleURLs(definition);

    // the old way
    IPath location = new Path(TargetPlatform.getDefaultLocation());
    URL[] pluginPaths =
        P2Utils.readBundlesTxt(
            location.toOSString(), location.append("configuration").toFile().toURL());
    // pluginPaths will be null (and NPE) when self-hosting and the target platform is not a real
    // installation
    assertEquals("Should have same number of bundles", pluginPaths.length, urls.size());
    for (int i = 0; i < pluginPaths.length; i++) {
      URL url = pluginPaths[i];
      assertTrue("Missing plug-in " + url.toString(), urls.contains(url));
    }
  }
  private void createParents(IProject fragmentProject, IPath parent) throws CoreException {
    String[] segments = parent.segments();
    String path = new String();

    for (int i = 0; i < segments.length; i++) {
      path += SLASH + segments[i];
      IFolder folder = fragmentProject.getFolder(path);
      if (!folder.exists()) {
        folder.create(true, true, getProgressMonitor());
      }
    }
  }
Example #24
0
 /*
  * Instruct the build manager that this project is involved in a cycle and
  * needs to propagate structural changes to the other projects in the cycle.
  */
 void mustPropagateStructuralChanges() {
   LinkedHashSet cycleParticipants = new LinkedHashSet(3);
   this.javaProject.updateCycleParticipants(
       new ArrayList(), cycleParticipants, this.workspaceRoot, new HashSet(3), null);
   IPath currentPath = this.javaProject.getPath();
   Iterator i = cycleParticipants.iterator();
   while (i.hasNext()) {
     IPath participantPath = (IPath) i.next();
     if (participantPath != currentPath) {
       IProject project = this.workspaceRoot.getProject(participantPath.segment(0));
       if (hasBeenBuilt(project)) {
         if (DEBUG)
           System.out.println(
               "JavaBuilder: Requesting another build iteration since cycle participant "
                   + project.getName() // $NON-NLS-1$
                   + " has not yet seen some structural changes"); //$NON-NLS-1$
         needRebuild();
         return;
       }
     }
   }
 }
Example #25
0
 private void loadState() {
   IPath pluginStateLocation =
       CVSUIPlugin.getPlugin().getStateLocation().append(REPOSITORIES_VIEW_FILE);
   File file = pluginStateLocation.toFile();
   if (file.exists()) {
     try {
       BufferedInputStream is = new BufferedInputStream(new FileInputStream(file));
       try {
         readState(is);
       } finally {
         is.close();
       }
     } catch (IOException e) {
       CVSUIPlugin.log(IStatus.ERROR, CVSUIMessages.RepositoryManager_ioException, e);
     } catch (TeamException e) {
       CVSUIPlugin.log(e);
     }
   } else {
     IPath oldPluginStateLocation = CVSUIPlugin.getPlugin().getStateLocation().append(STATE_FILE);
     file = oldPluginStateLocation.toFile();
     if (file.exists()) {
       try {
         DataInputStream dis = new DataInputStream(new FileInputStream(file));
         try {
           readOldState(dis);
         } finally {
           dis.close();
         }
         saveState();
         file.delete();
       } catch (IOException e) {
         CVSUIPlugin.log(IStatus.ERROR, CVSUIMessages.RepositoryManager_ioException, e);
       } catch (TeamException e) {
         CVSUIPlugin.log(e);
       }
     }
   }
 }
Example #26
0
 protected void saveState() throws TeamException {
   IPath pluginStateLocation = CVSUIPlugin.getPlugin().getStateLocation();
   File tempFile =
       pluginStateLocation.append(REPOSITORIES_VIEW_FILE + ".tmp").toFile(); // $NON-NLS-1$
   File stateFile = pluginStateLocation.append(REPOSITORIES_VIEW_FILE).toFile();
   try {
     XMLWriter writer = new XMLWriter(new BufferedOutputStream(new FileOutputStream(tempFile)));
     try {
       writeState(writer);
     } finally {
       writer.close();
     }
     if (stateFile.exists()) {
       stateFile.delete();
     }
     boolean renamed = tempFile.renameTo(stateFile);
     if (!renamed) {
       throw new TeamException(
           new Status(
               IStatus.ERROR,
               CVSUIPlugin.ID,
               TeamException.UNABLE,
               NLS.bind(
                   CVSUIMessages.RepositoryManager_rename,
                   new String[] {tempFile.getAbsolutePath()}),
               null));
     }
   } catch (IOException e) {
     throw new TeamException(
         new Status(
             IStatus.ERROR,
             CVSUIPlugin.ID,
             TeamException.UNABLE,
             NLS.bind(
                 CVSUIMessages.RepositoryManager_save, new String[] {stateFile.getAbsolutePath()}),
             e));
   }
 }
Example #27
0
 /**
  * Unzips the transferred file. Returns <code>true</code> if the unzip was successful, and <code>
  * false</code> otherwise. In case of failure, this method handles setting an appropriate
  * response.
  */
 private boolean completeUnzip(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException {
   IPath destPath = new Path(getPath());
   try {
     ZipFile source = new ZipFile(new File(getStorageDirectory(), FILE_DATA));
     IFileStore destinationRoot = NewFileServlet.getFileStore(destPath);
     Enumeration<? extends ZipEntry> entries = source.entries();
     while (entries.hasMoreElements()) {
       ZipEntry entry = entries.nextElement();
       IFileStore destination = destinationRoot.getChild(entry.getName());
       if (entry.isDirectory()) destination.mkdir(EFS.NONE, null);
       else {
         destination.getParent().mkdir(EFS.NONE, null);
         IOUtilities.pipe(
             source.getInputStream(entry),
             destination.openOutputStream(EFS.NONE, null),
             false,
             true);
       }
     }
     source.close();
   } catch (ZipException e) {
     // zip exception implies client sent us invalid input
     String msg = NLS.bind("Failed to complete file transfer on {0}", destPath.toString());
     statusHandler.handleRequest(
         req, resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, e));
     return false;
   } catch (Exception e) {
     // other failures should be considered server errors
     String msg = NLS.bind("Failed to complete file transfer on {0}", destPath.toString());
     statusHandler.handleRequest(
         req,
         resp,
         new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
     return false;
   }
   return true;
 }
  protected void doIncludeVersions(NameVersionDescriptor[] descriptions) throws Exception {
    String bsn = MULTI_VERSION_LOW_DESCRIPTION.getId();

    IPath extras = extractMultiVersionPlugins();
    ITargetDefinition target = getNewTarget();
    ITargetLocation container = getTargetService().newDirectoryLocation(extras.toOSString());
    target.setTargetLocations(new ITargetLocation[] {container});
    target.setIncluded(descriptions);
    try {
      getTargetService().saveTargetDefinition(target);
      setTargetPlatform(target);
      IPluginModelBase[] models = PluginRegistry.getExternalModels();
      Set enabled = new HashSet();
      for (int i = 0; i < models.length; i++) {
        IPluginModelBase pm = models[i];
        if (pm.getBundleDescription().getSymbolicName().equals(bsn)) {
          NameVersionDescriptor desc =
              new NameVersionDescriptor(
                  pm.getPluginBase().getId(), pm.getPluginBase().getVersion());
          if (pm.isEnabled()) {
            enabled.add(desc);
          }
        }
      }
      if (descriptions == null) {

      } else {
        assertEquals("Wrong number of enabled bundles", descriptions.length, enabled.size());
        for (int i = 0; i < descriptions.length; i++) {
          assertTrue("Missing bundle", enabled.contains(descriptions[i]));
        }
      }
    } finally {
      getTargetService().deleteTarget(target.getHandle());
      resetTargetPlatform();
    }
  }
Example #29
0
 public static String getRelativePath(IPath filePath, IPath pathToGitRoot) {
   StringBuilder sb = new StringBuilder();
   String file = null;
   if (!filePath.hasTrailingSeparator()) {
     file = filePath.lastSegment();
     filePath = filePath.removeLastSegments(1);
   }
   for (int i = 0; i < pathToGitRoot.segments().length; i++) {
     if (pathToGitRoot.segments()[i].equals(".."))
       sb.append(
               filePath.segment(filePath.segments().length - pathToGitRoot.segments().length + i))
           .append("/");
     // else TODO
   }
   if (file != null) sb.append(file);
   return sb.toString();
 }
Example #30
0
 /** Recursively walks down a directory tree and collects the paths of all git repositories. */
 private static void getGitDirsInChildren(File localFile, IPath path, Map<IPath, File> gitDirs)
     throws CoreException {
   if (localFile.exists() && localFile.isDirectory()) {
     if (RepositoryCache.FileKey.isGitRepository(localFile, FS.DETECTED)) {
       gitDirs.put(path.addTrailingSeparator(), localFile);
       return;
     } else if (RepositoryCache.FileKey.isGitRepository(
         new File(localFile, Constants.DOT_GIT), FS.DETECTED)) {
       gitDirs.put(path.addTrailingSeparator(), new File(localFile, Constants.DOT_GIT));
       return;
     }
     File[] folders =
         localFile.listFiles(
             new FileFilter() {
               public boolean accept(File file) {
                 return file.isDirectory() && !file.getName().equals(Constants.DOT_GIT);
               }
             });
     for (File folder : folders) {
       getGitDirsInChildren(folder, path.append(folder.getName()), gitDirs);
     }
     return;
   }
 }