public boolean select(Viewer viewer, Object parentElement, Object element) {
    if (element instanceof IFolder) {
      IFolder folder = (IFolder) element;
      IProject project = folder.getProject();
      try {
        if (project.hasNature(IMavenConstants.NATURE_ID)) {
          IMavenProjectRegistry projectManager = MavenPlugin.getMavenProjectRegistry();

          IMavenProjectFacade projectFacade = projectManager.create(project, null);
          if (projectFacade != null) {
            // XXX implement corner cases
            // modules have ".." in the path
            // modules have more then one segment in the path
            // modules not imported in workspace
            MavenProject mavenProject = projectFacade.getMavenProject(null);
            IPath folderPath = folder.getFullPath();

            // workspace-relative path sans project name
            String folderName = folderPath.removeFirstSegments(1).toPortableString();

            if (mavenProject.getModules().contains(folderName)) {
              return false;
            }
          }
        }
      } catch (CoreException ex) {
        log.error(ex.getMessage(), ex);
      }
    }
    return true;
  }
  /**
   * @param filePath
   * @return
   */
  protected IFile findFilePath(String filePath) {
    IPath path = null;
    IPath fp = new Path(filePath);
    if (fp.isAbsolute()) {
      if (getBaseDirectory().isPrefixOf(fp)) {
        int segments = getBaseDirectory().matchingFirstSegments(fp);
        path = fp.removeFirstSegments(segments);
      } else {
        path = fp;
      }
    } else {
      path = getWorkingDirectory().append(filePath);
    }

    IFile file = null;
    // The workspace may throw an IllegalArgumentException
    // Catch it and the parser should fallback to scan the entire project.
    try {
      file = findFileInWorkspace(path);
    } catch (Exception e) {
    }

    // We have to do another try, on Windows for cases like "TEST.C" vs "test.c"
    // We use the java.io.File canonical path.
    if (file == null || !file.exists()) {
      File f = path.toFile();
      try {
        String canon = f.getCanonicalPath();
        path = new Path(canon);
        file = findFileInWorkspace(path);
      } catch (IOException e1) {
      }
    }
    return (file != null && file.exists()) ? file : null;
  }
  /**
   * 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()]);
  }
Beispiel #4
0
  public IVResource[] listFiles() {
    IPath p1 = new Path(this.bundleRoot);
    // p1 = p1.removeFirstSegments(new Path(virtualRoot).matchingFirstSegments(p1));
    String path = p1.append("*").toString();

    URL[] files = this.library.find(path);
    ArrayList found = new ArrayList();
    for (int i = 0; i < files.length; i++) {
      if (files[i] == null) continue;
      IPath myPath = new Path(this.resourcePointer.getPath());
      IPath itemPath = new Path(files[i].getPath());
      IPath newPath = itemPath.removeFirstSegments(myPath.matchingFirstSegments(itemPath));
      IVResource item = null;
      // String cp =
      // myPath.append(newPath).toString();//itemPath.removeFirstSegments(myPath.matchingFirstSegments(itemPath)).toString();

      item =
          new VLibraryResource(
              this.library,
              files[i],
              this,
              newPath.removeTrailingSeparator().toString(),
              new Path(this.bundleRoot).append(newPath).toString());

      if (item != null) found.add(item);
    }
    return (IVResource[]) found.toArray(new IVResource[found.size()]);
  }
Beispiel #5
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;
 }
  public void elementEncode(XMLWriter writer, IPath projectPath, boolean newLine) {
    // Keeping this as a HashMap (not a Map) for the XMLWriter
    HashMap parameters = new HashMap();

    parameters.put(TAG_ENTRY_KIND, IncludePathEntry.entryKindToString(this.entryKind));
    parameters.put(TAG_CONTENT_KIND, IncludePathEntry.contentKindToString(this.contentKind));
    parameters.put(
        TAG_CREATEDREFERENCE, createdReference ? "true" : "false"); // $NON-NLS-1$ //$NON-NLS-2$

    IPath xmlPath = this.path;
    if (this.entryKind != IIncludePathEntry.IPE_VARIABLE
        && this.entryKind != IIncludePathEntry.IPE_CONTAINER) {
      // translate to project relative from absolute (unless a device path)
      if (projectPath != null && projectPath.isPrefixOf(xmlPath)) {
        if (xmlPath.segment(0).equals(projectPath.segment(0))) {
          xmlPath = xmlPath.removeFirstSegments(1);
          xmlPath = xmlPath.makeRelative();
        } else {
          xmlPath = xmlPath.makeAbsolute();
        }
      }
    }
    parameters.put(TAG_PATH, String.valueOf(xmlPath));
    if (resource != null) {
      parameters.put(TAG_RESOURCE, resource.getName());
    }
    if (this.isExported) {
      parameters.put(TAG_EXPORTED, "true"); // $NON-NLS-1$
    }

    writer.printTag(TAG_INCLUDEPATHENTRY, parameters);
    writer.endTag(TAG_INCLUDEPATHENTRY);
  }
 /**
  * Checks if all source files are existing. If not, create them.
  *
  * @param javaProj
  */
 private void checkSourceFolders(final IJavaProject javaProj) {
   if (javaProj == null) return;
   if (javaProj.exists()) {
     try {
       if (!javaProj.isOpen()) {
         javaProj.open(new NullProgressMonitor());
       }
       IClasspathEntry[] entries = javaProj.getRawClasspath();
       for (IClasspathEntry entry : entries) {
         if (IClasspathEntry.CPE_SOURCE == entry.getEntryKind()) {
           IPath path = entry.getPath();
           final IPath folderPath = path.removeFirstSegments(1);
           if (!folderPath.isEmpty()) {
             Display.getDefault()
                 .asyncExec(
                     new Runnable() {
                       public void run() {
                         try {
                           ImportUtils.createFolders(
                               javaProj.getProject(), folderPath, IResource.FORCE);
                         } catch (CoreException e) {
                           _log.error(e.getMessage());
                         }
                       }
                     });
           }
         }
       }
     } catch (JavaModelException e) {
       _log.error("findProjectSources: Could not retrieve project sources:", e); // $NON-NLS-1$
     }
   }
 }
 private IPath resolveResourcePath(IPath fullPath) {
   for (IPath projectPath : getProjectPaths()) {
     if (projectPath.isPrefixOf(fullPath)) {
       return fullPath.removeFirstSegments(projectPath.segmentCount() - 1);
     }
   }
   return null;
 }
Beispiel #9
0
  public static IPath adjustPath(IPath path, String ownerId, String version, String projectName) {
    // Map the request lib path stored in the snapshot to the actual system lib path
    // A path like: project1/./lib/dojo/dojo.js
    IReviewManager reviewManager = ReviewManager.getReviewManager();
    IDavinciProject project = new DavinciProject();
    project.setOwnerId(ownerId);
    project.setProjectName(projectName);
    ILibInfo[] sysLibs = reviewManager.getSystemLibs(project);
    ILibInfo[] versionLibs = reviewManager.getVersionLib(project, version);

    // If the lib path is not specified in the review version,
    // just return the path
    if (versionLibs == null) return path;

    IPath cp = new Path(path.toString());
    IPath newPath = new Path(cp.segment(0));
    cp = cp.removeFirstSegments(1);

    int c = 0;
    while (cp.segment(0).equals(".") || cp.segment(0).equals("..")) {
      c++;
    }
    cp = cp.removeFirstSegments(c);

    for (ILibInfo info : versionLibs) {
      if (info.getVirtualRoot() == null) {
        continue;
      }
      IPath versionVirtualRoot = new Path(info.getVirtualRoot());
      if (cp.matchingFirstSegments(versionVirtualRoot) == versionVirtualRoot.segmentCount()) {
        String virtualRoot = null;
        for (ILibInfo lib : sysLibs) {
          if (lib.getId().equals(info.getId())) {
            virtualRoot = lib.getVirtualRoot();
            break;
          }
        }
        if (virtualRoot != null) {
          IPath vr = newPath.append(virtualRoot);
          return vr.append(cp.removeFirstSegments(versionVirtualRoot.segmentCount()));
        }
        break;
      }
    }
    return path;
  }
 private void renameSourceFile(CompositeChange change) {
   String unitPath = declaration.getUnit().getFullPath();
   IPath oldPath = project.getFullPath().append(unitPath);
   String newFileName = getNewName() + ".ceylon";
   IPath newPath = oldPath.removeFirstSegments(1).removeLastSegments(1).append(newFileName);
   if (!project.getFile(newPath).exists()) {
     change.add(new RenameResourceChange(oldPath, newFileName));
   }
 }
 /**
  * Respects images residing in any plug-in. If path is relative, then this bundle is looked up for
  * the image, otherwise, for absolute path, first segment is taken as id of plug-in with image
  *
  * @generated
  * @param path the path to image, either absolute (with plug-in id as first segment), or relative
  *     for bundled images
  * @return the image descriptor
  */
 public static ImageDescriptor findImageDescriptor(String path) {
   final IPath p = new Path(path);
   if (p.isAbsolute() && p.segmentCount() > 1) {
     return AbstractUIPlugin.imageDescriptorFromPlugin(
         p.segment(0), p.removeFirstSegments(1).makeAbsolute().toString());
   } else {
     return getBundledImageDescriptor(p.makeAbsolute().toString());
   }
 }
Beispiel #12
0
  public static IResource getSourceResource(IResource classFile) {
    try {
      if (isJavaProject(classFile) && classFile.getName().endsWith(CLASS_FILE_EXTENSION)) {
        IPath classFilePath = classFile.getFullPath();
        String classFileName = null;

        IJavaProject project = getJavaProject(classFile);
        IPath defaultOutput = project.getOutputLocation();

        if (defaultOutput.isPrefixOf(classFilePath)) {
          classFileName =
              classFilePath.removeFirstSegments(defaultOutput.segmentCount()).toString();
        } else {
          for (IClasspathEntry entry : project.getRawClasspath()) {
            if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
              IPath output = entry.getOutputLocation();
              if (output != null) {
                if (classFilePath.isPrefixOf(output)) {
                  classFileName =
                      classFilePath.removeFirstSegments(output.segmentCount()).toString();
                }
              }
            }
          }
        }

        if (classFileName != null) {
          // Replace file extension
          String sourceFileName = classFileName.replace(".class", ".java");
          for (IClasspathEntry entry : project.getRawClasspath()) {
            if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
              IPath path = entry.getPath().append(sourceFileName).removeFirstSegments(1);
              IResource resource = project.getProject().findMember(path);
              if (resource != null) {
                return resource;
              }
            }
          }
        }
      }
    } catch (JavaModelException e) {
    }
    return null;
  }
  /**
   * If the value starts with a path variable such as %ROOT%, replace it with the absolute path.
   *
   * @param value the value of a -Akey=value command option
   */
  private static String resolveVarPath(IJavaProject jproj, String value) {
    if (value == null) {
      return null;
    }
    // is there a token to substitute?
    if (!Pattern.matches(PATHVAR_TOKEN, value)) {
      return value;
    }
    IPath path = new Path(value);
    String firstToken = path.segment(0);
    // If it matches %ROOT%/project, it is a project-relative path.
    if (PATHVAR_ROOT.equals(firstToken)) {
      IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
      IResource proj = root.findMember(path.segment(1));
      if (proj == null) {
        return value;
      }
      // all is well; do the substitution
      IPath relativePath = path.removeFirstSegments(2);
      IPath absoluteProjPath = proj.getLocation();
      IPath absoluteResPath = absoluteProjPath.append(relativePath);
      return absoluteResPath.toOSString();
    }

    // If it matches %PROJECT.DIR%/project, the path is relative to the current project.
    if (jproj != null && PATHVAR_PROJECTROOT.equals(firstToken)) {
      // all is well; do the substitution
      IPath relativePath = path.removeFirstSegments(1);
      IPath absoluteProjPath = jproj.getProject().getLocation();
      IPath absoluteResPath = absoluteProjPath.append(relativePath);
      return absoluteResPath.toOSString();
    }

    // otherwise it's a classpath-var-based path.
    String cpvName = firstToken.substring(1, firstToken.length() - 1);
    IPath cpvPath = JavaCore.getClasspathVariable(cpvName);
    if (cpvPath != null) {
      IPath resolved = cpvPath.append(path.removeFirstSegments(1));
      return resolved.toOSString();
    } else {
      return value;
    }
  }
  /**
   * Determine the exposed (exported) dependencies from the project named 'otherProject' and add
   * them to the accumulatedPathEntries String Set. This will include the output location of the
   * project plus other kinds of entry that are re-exported. If dependent on another project and
   * that project is re-exported, the method will recurse.
   *
   * @param baseProject the original project for which the classpath is being computed
   * @param otherProject a project something in the dependency chain for the original project
   * @param accumulatedPathEntries a String set of classpath entries, into which new entries should
   *     be added
   */
  private static void computeDependenciesFromProject(
      IProject baseProject, String otherProject, Set accumulatedPathEntries)
      throws JavaModelException {

    // First the output location for the project:
    IProject iproject = baseProject.getWorkspace().getRoot().getProject(otherProject);
    IJavaProject ijp = JavaCore.create(iproject);
    accumulatedPathEntries.add(pathToString(ijp.getOutputLocation(), iproject));

    // Look for exported entries from otherProject
    IClasspathEntry[] cpes = ijp.getResolvedClasspath(true);
    if (cpes != null) {
      for (int j = 0; j < cpes.length; j++) {
        IClasspathEntry cpe = cpes[j];
        if (cpe.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
          continue;
        }
        if (cpe.isExported()) {
          // TODO should quickly dismiss source entries? others?
          IPath cpePath = cpes[j].getPath();
          String segmentZero = cpePath.segment(0);
          if (segmentZero != null && segmentZero.equals(otherProject)) {
            accumulatedPathEntries.add(
                iproject.getFile(cpePath.removeFirstSegments(1)).getRawLocation().toOSString());
          } else {
            if (cpe.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
              // segmentZero is a project name
              computeDependenciesFromProject(baseProject, segmentZero, accumulatedPathEntries);
            } else {
              String otherPathElement = null;
              if (segmentZero != null && segmentZero.equals(iproject.getName())) {
                otherPathElement =
                    iproject.getFile(cpePath.removeFirstSegments(1)).getRawLocation().toOSString();
              } else {
                otherPathElement = cpePath.toOSString();
              }
              accumulatedPathEntries.add(otherPathElement);
            }
          }
        }
      }
    }
  }
  private static File convertPathToFile(IProject project, IPath path) throws MalformedURLException {
    if (path != null && project != null && path.removeFirstSegments(1) != null) {
      IResource resource = project.findMember(path.removeFirstSegments(1));
      if (resource != null) {
        URI uri = resource.getRawLocationURI();

        if (uri != null) {
          String scheme = uri.getScheme();
          if (SpringCoreUtils.FILE_SCHEME.equalsIgnoreCase(scheme)) {
            return toLocalFile(uri);
          } else {
            IPathVariableManager variableManager =
                ResourcesPlugin.getWorkspace().getPathVariableManager();
            return toLocalFile(variableManager.resolveURI(uri));
          }
        }
      }
    }
    return null;
  }
Beispiel #16
0
 protected void setRelativePath(String directory) {
   IPath folderPath = new Path(directory).setDevice(null);
   IPath workdirPath = new Path(this.selectedRepository.getWorkTree().getPath()).setDevice(null);
   if (!workdirPath.isPrefixOf(folderPath)) {
     MessageDialog.openError(
         getShell(),
         UIText.ExistingOrNewPage_WrongPathErrorDialogTitle,
         UIText.ExistingOrNewPage_WrongPathErrorDialogMessage);
     return;
   }
   relPath.setText(folderPath.removeFirstSegments(workdirPath.segmentCount()).toString());
 }
 protected void pushDirectory(IPath dir) {
   if (dir != null) {
     IPath pwd = null;
     if (fBaseDirectory != null && fBaseDirectory.isPrefixOf(dir)) {
       pwd = dir.removeFirstSegments(fBaseDirectory.segmentCount());
     } else {
       // check if it is a cygpath
       pwd = convertCygpath(dir);
     }
     fDirectoryStack.addElement(pwd);
   }
 }
  public static IResource findResource(String fullPath, IProject p) {

    IPath projectPath = p.getLocation();
    IPath path = new Path(fullPath);

    if (projectPath.isPrefixOf(path)) {
      // remove project location and project name segment
      path = path.removeFirstSegments(projectPath.segmentCount());
    }
    // find resource relative to project
    IResource ret = p.findMember(path);
    return ret;
  }
Beispiel #19
0
 private boolean containsPublishedFiles(IStorage dir, IDesignerUser user, String timeStamp) {
   for (Version version : user.getVersions()) {
     if (!version.getTime().equals(timeStamp)) continue;
     for (String res : version.resources) {
       IPath resPath = new Path(res);
       while (resPath.segment(0).equals(".")) resPath = resPath.removeFirstSegments(1);
       if (dir.getName().equals(resPath.segment(0))) {
         return true;
       }
     }
   }
   return false;
 }
 @Override
 public IFile getResource(Source source) {
   if (source == null) {
     return null;
   }
   IPath path = new Path(source.getFullName());
   if (containerLocation.isPrefixOf(path)) {
     IPath relPath = path.removeFirstSegments(containerLocation.segmentCount());
     return container.getFile(relPath);
   }
   // TODO (danrubel): Handle mapped subfolders
   return null;
 }
 /**
  * This will return the set of output folders name for the given (java) project.
  *
  * <p>For example, if a project has a source folder "src" with its output folder set as "bin" and
  * a source folder "src-gen" with its output folder set as "bin-gen", this will return a
  * LinkedHashSet containing both "bin" and "bin-gen".
  *
  * @param project The project we seek the output folders of.
  * @return The set of output folders name for the given (java) project.
  */
 private static Set<String> getOutputFolders(IProject project) {
   final Set<String> classpathEntries = new CompactLinkedHashSet<String>();
   final IJavaProject javaProject = JavaCore.create(project);
   try {
     for (IClasspathEntry entry : javaProject.getResolvedClasspath(true)) {
       if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
         final IPath output = entry.getOutputLocation();
         if (output != null) {
           classpathEntries.add(output.removeFirstSegments(1).toString());
         }
       }
     }
     /*
      * Add the default output location to the classpath anyway since source folders are not required
      * to have their own
      */
     final IPath output = javaProject.getOutputLocation();
     classpathEntries.add(output.removeFirstSegments(1).toString());
   } catch (JavaModelException e) {
     AcceleoCommonPlugin.log(e, false);
   }
   return classpathEntries;
 }
  /**
   * Returns the cheatsheet collection child object corresponding to the passed path (relative to
   * this object), or <code>null</code> if such an object could not be found.
   *
   * @param searchPath org.eclipse.core.runtime.IPath
   * @return CheatSheetCollectionElement
   */
  public CheatSheetCollectionElement findChildCollection(IPath searchPath) {
    Object[] children = getChildren();
    String searchString = searchPath.segment(0);
    for (int i = 0; i < children.length; ++i) {
      CheatSheetCollectionElement currentCategory = (CheatSheetCollectionElement) children[i];
      if (currentCategory.getLabel(null).equals(searchString)) {
        if (searchPath.segmentCount() == 1) return currentCategory;

        return currentCategory.findChildCollection(searchPath.removeFirstSegments(1));
      }
    }

    return null;
  }
 @Override
 protected void service(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   traceRequest(req);
   String pathInfoString = req.getPathInfo();
   String queryString = getQueryString(req);
   IPath pathInfo =
       new Path(
           null /*don't parse host:port as device*/,
           pathInfoString == null ? "" : pathInfoString); // $NON-NLS-1$
   if (pathInfo.segmentCount() > 0) {
     String hostedHost = pathInfo.segment(0);
     IHostedSite site = HostingActivator.getDefault().getHostingService().get(hostedHost);
     if (site != null) {
       IPath path = pathInfo.removeFirstSegments(1);
       IPath contextPath = new Path(req.getContextPath());
       IPath contextlessPath = path.makeRelativeTo(contextPath).makeAbsolute();
       URI[] mappedPaths;
       try {
         mappedPaths = getMapped(site, contextlessPath, queryString);
       } catch (URISyntaxException e) {
         handleException(
             resp,
             new ServerStatus(
                 IStatus.ERROR,
                 HttpServletResponse.SC_BAD_REQUEST,
                 "Could not create target URI	",
                 e));
         return;
       }
       if (mappedPaths != null) {
         serve(req, resp, site, mappedPaths);
       } else {
         handleException(
             resp,
             new ServerStatus(
                 IStatus.ERROR,
                 HttpServletResponse.SC_NOT_FOUND,
                 NLS.bind("No mappings matched {0}", path),
                 null));
       }
     } else {
       String msg = NLS.bind("Hosted site {0} is stopped", hostedHost);
       handleException(
           resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null));
     }
   } else {
     super.doGet(req, resp);
   }
 }
 /**
  * Returns the preference node associated with this request. This method controls exactly what
  * preference nodes are exposed via this service. If there is no matching preference node for the
  * request, this method handles the appropriate response and returns <code>null</code>.
  *
  * @param req
  * @param resp
  * @param create If <code>true</code>, the node will be created if it does not already exist. If
  *     <code>false</code>, this method sets the response status to 404 and returns null.
  */
 private IEclipsePreferences getNode(
     HttpServletRequest req, HttpServletResponse resp, boolean create) throws ServletException {
   if (prefRoot == null) {
     handleException(resp, "Unable to obtain preference service", null);
     return null;
   }
   String pathString = req.getPathInfo();
   if (pathString == null) pathString = ""; // $NON-NLS-1$
   IPath path = new Path(pathString);
   int segmentCount = path.segmentCount();
   String scope = path.segment(0);
   // note that the preference service API scope names don't match those used in our persistence
   // layer.
   IPath nodePath = null;
   if ("user".equalsIgnoreCase(scope)) { // $NON-NLS-1$
     String username = req.getRemoteUser();
     if (username == null) {
       resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
       return null;
     }
     nodePath = new Path("Users").append(username); // $NON-NLS-1$
   } else if ("workspace".equalsIgnoreCase(scope) && segmentCount > 1) { // $NON-NLS-1$
     nodePath = new Path("Workspaces"); // $NON-NLS-1$
   } else if ("project".equalsIgnoreCase(scope) && segmentCount > 1) { // $NON-NLS-1$
     nodePath = new Path("Projects"); // $NON-NLS-1$
   } else {
     // invalid prefix
     handleNotFound(req, resp, HttpServletResponse.SC_METHOD_NOT_ALLOWED);
     return null;
   }
   // we allow arbitrary subtrees beneath our three supported roots
   if (nodePath != null) {
     String childPath = nodePath.append(path.removeFirstSegments(1)).toString();
     try {
       if (create || prefRoot.nodeExists(childPath))
         return (IEclipsePreferences) prefRoot.node(childPath);
     } catch (BackingStoreException e) {
       String msg = NLS.bind("Error retrieving preferences for path {0}", pathString);
       handleException(
           resp,
           new Status(IStatus.ERROR, Activator.PI_SERVER_SERVLETS, msg),
           HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
       return null;
     }
   }
   handleNotFound(req, resp, HttpServletResponse.SC_NOT_FOUND);
   return null;
 }
  public IArchive createDefaultConfiguration(String projectName, IProgressMonitor monitor) {
    // IPackageType t = this;
    IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
    Assert.isNotNull(project);

    IJavaProject javaProject = JavaCore.create(project);
    Assert.isNotNull(javaProject);

    if (monitor == null) monitor = new NullProgressMonitor();

    monitor.beginTask(
        ArchivesCore.bind(ArchivesCoreMessages.CreatingDefaultJarConfig, project.getName()), 2);

    IPath outputPath;
    try {
      outputPath = javaProject.getOutputLocation();
    } catch (JavaModelException e) {
      ArchivesCore.getInstance().getLogger().log(IStatus.WARNING, e.getMessage(), e);
      return null;
    }

    outputPath = outputPath.removeFirstSegments(1);
    IContainer outputContainer = project.getFolder(outputPath);

    IArchive jar = new ArchiveImpl();

    jar.setDestinationPath(project.getLocation());
    jar.setInWorkspace(true);
    jar.setExploded(false);
    jar.setName(project.getName() + ".jar"); // $NON-NLS-1$
    jar.setArchiveType(this);

    IArchiveStandardFileSet classes = new ArchiveFileSetImpl();
    classes.setIncludesPattern("**/*"); // $NON-NLS-1$
    classes.setRawSourcePath(outputContainer.getFullPath().toString());
    classes.setInWorkspace(true);

    try {
      jar.addChild(classes);
    } catch (ArchivesModelException ame) {
    }

    monitor.worked(1);
    monitor.done();

    return jar;
  }
Beispiel #26
0
 private void setBopOpenFileText(String fileName) {
   // from absolute path to project relative path
   if (fileName.length() > 0) {
     IPath filePath = new Path(fileName);
     if (filePath.isAbsolute()) {
       if (getContainer().getProject() != null) {
         IPath projectPath = getContainer().getProject().getLocation();
         if (projectPath.isPrefixOf(filePath)) {
           filePath = filePath.removeFirstSegments(projectPath.segmentCount());
           filePath = filePath.setDevice(null);
           fileName = filePath.toString();
         }
       }
     }
   }
   bopOpenFileText.setText(fileName);
 }
 public IResource[] getResourcesToDelete() {
   List<IResource> resources = new ArrayList<IResource>(dependencyMap.size());
   IPath projectPath = project.getLocation();
   IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
   for (ProjectDependency pd : dependencyMap.keySet()) {
     if (pd.getDependencyKind() == DependencyKind.Archive) {
       IPath p = pd.getPath();
       if (projectPath.isPrefixOf(p)) {
         p = p.removeFirstSegments(projectPath.segmentCount() - 1);
       }
       IFile f = root.getFile(p);
       if (f.exists() && project.equals(f.getProject())) {
         resources.add(f);
       }
     }
   }
   return resources.toArray(new IResource[0]);
 }
Beispiel #28
0
  /** {@inheritDoc} */
  protected void finishPage(IProgressMonitor monitor) throws InterruptedException, CoreException {
    if (fDoFlushChange) {
      IScriptProject scriptProject = getEntryToEdit().getScriptProject();

      BuildpathsBlock.flush(getExistingEntries(), scriptProject, monitor);

      IProject project = scriptProject.getProject();
      IPath projPath = project.getFullPath();
      IPath path = getEntryToEdit().getPath();

      if (!projPath.equals(path) && projPath.isPrefixOf(path)) {
        path = path.removeFirstSegments(projPath.segmentCount());
      }

      IFolder folder = project.getFolder(path);
      fProjectFragment = scriptProject.getProjectFragment(folder);
    }
  }
  public static URL computeURL(
      ISchemaDescriptor parentDesc, String schemaLocation, List<IPath> additionalSearchLocations)
      throws MalformedURLException {
    URL parentURL = parentDesc == null ? null : parentDesc.getSchemaURL();
    if (schemaLocation.startsWith("schema://")) { // $NON-NLS-1$
      // extract plug-in ID
      IPath path = new Path(schemaLocation.substring(9));
      return getPluginRelativePath(
          path.segment(0), path.removeFirstSegments(1), parentURL, additionalSearchLocations);
    }

    if (parentURL == null) return null;

    // parent-relative location
    IPath path = new Path(parentURL.getPath());
    path = path.removeLastSegments(1).append(schemaLocation);
    return new URL(parentURL.getProtocol(), parentURL.getHost(), path.toString());
  }
Beispiel #30
0
  /**
   * Constructs a link with the given model, parent and file.
   *
   * @param model The model associated with the new link.
   * @param parent The parent TocObject of the new link.
   * @param file The TOC file to link to.
   */
  public TocLink(TocModel model, IFile file) {
    super(model, ELEMENT_LINK);

    IPath path = file.getFullPath();
    if (file.getProject().equals(getSharedModel().getUnderlyingResource().getProject())) { // If
      // the
      // file
      // is
      // from
      // the
      // same
      // project,
      // remove the project name segment
      setFieldTocPath(path.removeFirstSegments(1).toString()); // $NON-NLS-1$
    } else { // If the file is from another project, add ".."
      // to traverse outside this model's project
      setFieldTocPath(".." + path.toString()); // $NON-NLS-1$
    }
  }