コード例 #1
0
ファイル: EMFNature.java プロジェクト: nitind/webtools.common
  /**
   * Return true if the IFile with the given name exists in this project.
   *
   * @param aFileName filename can be relative to one of the input file paths for the
   *     WorkbenchURIConverter.
   * @return <code>true</code> if filename exists in this project
   * @since 1.0.0
   */
  public boolean fileExists(String aFileName) {
    if (aFileName == null) return false;

    IPath path = new Path(aFileName);
    if (path.isAbsolute()) return ResourcesPlugin.getWorkspace().getRoot().getFile(path).exists();
    else return getWorkbenchURIConverter().canGetUnderlyingResource(aFileName);
  }
コード例 #2
0
  /**
   * 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]));
    }
  }
コード例 #3
0
  private boolean handleDelete(
      HttpServletRequest request, HttpServletResponse response, String pathString)
      throws GitAPIException, CoreException, IOException, ServletException {
    IPath path = pathString == null ? Path.EMPTY : new Path(pathString);
    // expected path format is /file/{workspaceId}/{projectId}[/{directoryPath}]
    if (path.segment(0).equals("file") && path.segmentCount() > 2) { // $NON-NLS-1$

      // make sure a clone is addressed
      WebProject webProject = GitUtils.projectFromPath(path);
      if (webProject != null && isAccessAllowed(request.getRemoteUser(), webProject)) {
        File gitDir = GitUtils.getGitDirs(path, Traverse.CURRENT).values().iterator().next();
        Repository repo = new FileRepository(gitDir);
        repo.close();
        FileUtils.delete(repo.getWorkTree(), FileUtils.RECURSIVE | FileUtils.RETRY);
        if (path.segmentCount() == 3)
          return statusHandler.handleRequest(
              request, response, removeProject(request.getRemoteUser(), webProject));
        return true;
      }
      String msg = NLS.bind("Nothing found for the given ID: {0}", path);
      return statusHandler.handleRequest(
          request,
          response,
          new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null));
    }
    String msg = NLS.bind("Invalid delete request {0}", pathString);
    return statusHandler.handleRequest(
        request,
        response,
        new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
  }
コード例 #4
0
  /**
   * 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);
    }
  }
コード例 #5
0
ファイル: MoveDelegate.java プロジェクト: spiritman1990/pdt
  /**
   * Final check before the actual refactoring
   *
   * @return status
   * @throws OperationCanceledException
   */
  public RefactoringStatus checkFinalConditions() throws OperationCanceledException {
    RefactoringStatus status = new RefactoringStatus();
    IContainer destination = fProcessor.getDestination();
    IProject sourceProject = fProcessor.getSourceSelection()[0].getProject();
    IProject destinationProject = destination.getProject();
    if (sourceProject != destinationProject)
      status.merge(MoveUtils.checkMove(phpFiles, sourceProject, destination));

    // Checks if one of the resources already exists with the same name in
    // the destination
    IPath dest = fProcessor.getDestination().getFullPath();
    IResource[] sourceResources = fProcessor.getSourceSelection();

    for (IResource element : sourceResources) {
      String newFilePath = dest.toOSString() + File.separatorChar + element.getName();
      IResource resource =
          ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(newFilePath));
      if (resource != null && resource.exists()) {
        status.merge(
            RefactoringStatus.createFatalErrorStatus(
                NLS.bind(
                    PhpRefactoringCoreMessages.getString("MoveDelegate.6"),
                    element.getName(),
                    dest.toOSString()))); // $NON-NLS-1$
      }
    }
    return status;
  }
コード例 #6
0
  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;
  }
コード例 #7
0
  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);
  }
コード例 #8
0
  /**
   * 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());
  }
コード例 #9
0
 /**
  * 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;
 }
コード例 #10
0
ファイル: GitUtils.java プロジェクト: Corly/orion.server
 /**
  * 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;
   }
 }
コード例 #11
0
  private IRuntimeClasspathEntry convertClasspathEntry(IClasspathEntry entry) {
    if (entry == null) return null;

    IPath srcPath = entry.getSourceAttachmentPath();
    if (srcPath != null && srcPath.segmentCount() > 0) {
      IRuntimeClasspathEntry rte = JavaRuntime.newArchiveRuntimeClasspathEntry(entry.getPath());
      rte.setSourceAttachmentPath(srcPath);
      rte.setSourceAttachmentRootPath(entry.getSourceAttachmentRootPath());
      return rte;
    }
    return null;
  }
コード例 #12
0
  /**
   * 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());
    }
  }
コード例 #13
0
  /**
   * 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());
  }
コード例 #14
0
 private IResource createSourceResource(IResourceDelta delta) {
   IPath sourcePath = delta.getMovedFromPath();
   IResource resource = delta.getResource();
   IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot();
   switch (resource.getType()) {
     case IResource.PROJECT:
       return wsRoot.getProject(sourcePath.segment(0));
     case IResource.FOLDER:
       return wsRoot.getFolder(sourcePath);
     case IResource.FILE:
       return wsRoot.getFile(sourcePath);
   }
   return null;
 }
コード例 #15
0
  /**
   * Returns the charset explicitly set by the user for the given resource, or <code>null</code>. If
   * no setting exists for the given resource and <code>recurse</code> is <code>true</code>, every
   * parent up to the workspace root will be checked until a charset setting can be found.
   *
   * @param resourcePath the path for the resource
   * @param recurse whether the parent should be queried
   * @return the charset setting for the given resource
   */
  public String getCharsetFor(IPath resourcePath, boolean recurse) {
    Assert.isLegal(resourcePath.segmentCount() >= 1);
    IProject project = workspace.getRoot().getProject(resourcePath.segment(0));

    Preferences prefs = getPreferences(project, false, false);
    Preferences derivedPrefs = getPreferences(project, false, true);

    if (prefs == null && derivedPrefs == null)
      // no preferences found - for performance reasons, short-circuit
      // lookup by falling back to workspace's default setting
      return recurse ? ResourcesPlugin.getEncoding() : null;

    return internalGetCharsetFor(prefs, derivedPrefs, resourcePath, recurse);
  }
コード例 #16
0
ファイル: Util.java プロジェクト: mickaelistria/rt.equinox.p2
  /** Returns the name of the Eclipse application launcher. */
  private static String getLauncherName(String name, String os, File installFolder) {
    if (os == null) {
      EnvironmentInfo info =
          (EnvironmentInfo)
              ServiceHelper.getService(Activator.getContext(), EnvironmentInfo.class.getName());
      if (info == null) return null;
      os = info.getOS();
    }

    if (os.equals(org.eclipse.osgi.service.environment.Constants.OS_WIN32)) {
      IPath path = new Path(name);
      if ("exe".equals(path.getFileExtension())) // $NON-NLS-1$
      return name;
      return name + ".exe"; // $NON-NLS-1$
    }
    if (os.equals(Constants.MACOSX_BUNDLED)) {
      return "/Contents/MacOS/" + name; // $NON-NLS-1$
    }

    if (os.equals(org.eclipse.osgi.service.environment.Constants.OS_MACOSX)) {
      IPath path = new Path(name);
      if (path.segment(0).endsWith(".app")) // $NON-NLS-1$
      return name;

      String appName = null;
      if (installFolder != null) {
        File appFolder = new File(installFolder, name + ".app"); // $NON-NLS-1$
        if (appFolder.exists()) {
          try {
            appName = appFolder.getCanonicalFile().getName();
          } catch (IOException e) {
            appName = appFolder.getName();
          }
        }
      }

      StringBuffer buffer = new StringBuffer();
      if (appName != null) {
        buffer.append(appName);
      } else {
        buffer.append(name.substring(0, 1).toUpperCase());
        buffer.append(name.substring(1));
        buffer.append(".app"); // $NON-NLS-1$
      }
      buffer.append("/Contents/MacOS/"); // $NON-NLS-1$
      buffer.append(name);
      return buffer.toString();
    }
    return name;
  }
コード例 #17
0
 /**
  * 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);
 }
コード例 #18
0
ファイル: GitUtils.java プロジェクト: Corly/orion.server
 /**
  * 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;
 }
コード例 #19
0
  /**
   * 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();
    }
  }
コード例 #20
0
 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);
   }
 }
コード例 #21
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;
 }
コード例 #22
0
  /**
   * 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();
  }
コード例 #23
0
  /**
   * Returns paths constructed by rewriting pathInfo using rules from the hosted site's mappings.
   * Paths are ordered from most to least specific match.
   *
   * @param site The hosted site.
   * @param pathInfo Path to be rewritten.
   * @param queryString
   * @return The rewritten path. May be either:
   *     <ul>
   *       <li>A path to a file in the Orion workspace, eg. <code>/ProjectA/foo/bar.txt</code>
   *       <li>An absolute URL pointing to another site, eg. <code>http://foo.com/bar.txt</code>
   *     </ul>
   *
   * @return The rewritten paths.
   * @throws URISyntaxException
   */
  private URI[] getMapped(IHostedSite site, IPath pathInfo, String queryString)
      throws URISyntaxException {
    final Map<String, List<String>> map = site.getMappings();
    final IPath originalPath = pathInfo;
    IPath path = originalPath.removeTrailingSeparator();

    List<URI> uris = new ArrayList<URI>();
    String rest = null;
    final int count = path.segmentCount();
    for (int i = 0; i <= count; i++) {
      List<String> base = map.get(path.toString());
      if (base != null) {
        rest = originalPath.removeFirstSegments(count - i).toString();
        for (int j = 0; j < base.size(); j++) {
          URI uri =
              rest.equals("") ? new URI(base.get(j)) : URIUtil.append(new URI(base.get(j)), rest);
          uris.add(
              new URI(
                  uri.getScheme(),
                  uri.getUserInfo(),
                  uri.getHost(),
                  uri.getPort(),
                  uri.getPath(),
                  queryString,
                  uri.getFragment()));
        }
      }
      path = path.removeLastSegments(1);
    }
    if (uris.size() == 0)
      // No mapping for /
      return null;
    else return uris.toArray(new URI[uris.size()]);
  }
コード例 #24
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);
   }
 }
コード例 #25
0
    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_;
    }
コード例 #26
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;
 }
コード例 #27
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;
  }
コード例 #28
0
  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$
    }
  }
コード例 #29
0
ファイル: MoveDelegate.java プロジェクト: spiritman1990/pdt
  private void removeBuildPath(IResource resource, IProject project) {

    IScriptProject projrct = DLTKCore.create(project);
    IPath filePath = resource.getFullPath();

    oldBuildEntries = Arrays.asList(projrct.readRawBuildpath());

    newBuildEntries = new ArrayList<IBuildpathEntry>();

    newBuildEntries.addAll(oldBuildEntries);

    for (int i = 0; i < oldBuildEntries.size(); i++) {
      IBuildpathEntry fEntryToChange = oldBuildEntries.get(i);
      IPath entryPath = fEntryToChange.getPath();

      int mattchedPath = entryPath.matchingFirstSegments(filePath);

      if (mattchedPath == filePath.segmentCount()) {
        newBuildEntries.remove(fEntryToChange);
      } else {
        IBuildpathEntry newEntry =
            RefactoringUtility.createNewBuildpathEntry(
                fEntryToChange, fEntryToChange.getPath(), filePath, ""); // $NON-NLS-1$
        newBuildEntries.remove(fEntryToChange);
        newBuildEntries.add(newEntry);
      }
    }

    oldIncludePath = new ArrayList<IBuildpathEntry>();

    newIncludePathEntries = new ArrayList<IBuildpathEntry>();
    List<IncludePath> includePathEntries =
        Arrays.asList(IncludePathManager.getInstance().getIncludePaths(project));

    for (IncludePath entry : includePathEntries) {
      Object includePathEntry = entry.getEntry();
      IResource includeResource = null;
      if (!(includePathEntry instanceof IBuildpathEntry)) {
        includeResource = (IResource) includePathEntry;
        IPath entryPath = includeResource.getFullPath();

        IBuildpathEntry oldEntry =
            RefactoringUtility.createNewBuildpathEntry(IBuildpathEntry.BPE_SOURCE, entryPath);
        oldIncludePath.add((IBuildpathEntry) oldEntry);

        if (filePath.isPrefixOf(entryPath) || entryPath.equals(filePath)) {
        } else {
          IBuildpathEntry newEntry =
              RefactoringUtility.createNewBuildpathEntry(IBuildpathEntry.BPE_SOURCE, entryPath);
          newIncludePathEntries.add(newEntry);
        }
      } else {
        newIncludePathEntries.add((IBuildpathEntry) includePathEntry);
        oldIncludePath.add((IBuildpathEntry) includePathEntry);
      }
    }
  }
コード例 #30
0
  // temp code for grabbing files from filesystem
  protected IFileStore tempGetFileStore(IPath path) {
    // first check if we have an alias registered
    if (path.segmentCount() > 0) {
      URI alias = aliasRegistry.lookupAlias(path.segment(0));
      if (alias != null)
        try {
          return EFS.getStore(alias).getFileStore(path.removeFirstSegments(1));
        } catch (CoreException e) {
          LogHelper.log(
              new Status(
                  IStatus.WARNING,
                  HostingActivator.PI_SERVER_HOSTING,
                  1,
                  "An error occured when getting file store for path '"
                      + path
                      + "' and alias '"
                      + alias
                      + '\'',
                  e)); //$NON-NLS-1$ //$NON-NLS-2$
          // fallback is to try the same path relatively to the root
        }
    }
    // assume it is relative to the root
    try {
      return EFS.getStore(rootStoreURI).getFileStore(path);
    } catch (CoreException e) {
      LogHelper.log(
          new Status(
              IStatus.WARNING,
              HostingActivator.PI_SERVER_HOSTING,
              1,
              "An error occured when getting file store for path '"
                  + path
                  + "' and root '"
                  + rootStoreURI
                  + '\'',
              e)); //$NON-NLS-1$ //$NON-NLS-2$
      // fallback and return null
    }

    return null;
  }