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;
  }
  /**
   * 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 #3
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;
 }
  // returns true if the request has been served, false if not (only if failEarlyOn404 is true)
  private boolean serveOrionFile(
      HttpServletRequest req,
      HttpServletResponse resp,
      IHostedSite site,
      IPath path,
      boolean failEarlyOn404)
      throws ServletException {
    String userName = site.getUserName();
    String workspaceId = site.getWorkspaceId();
    String workspaceUri = WORKSPACE_SERVLET_ALIAS + "/" + workspaceId; // $NON-NLS-1$
    boolean allow = false;
    // Check that user who launched the hosted site really has access to the workspace
    try {
      if (AuthorizationService.checkRights(userName, workspaceUri, "GET")) { // $NON-NLS-1$
        allow = true;
      }
    } catch (JSONException e) {
      throw new ServletException(e);
    }

    if (allow) {
      // FIXME: this code is copied from NewFileServlet, fix it
      // start copied
      String pathInfo = path.toString();
      IPath filePath = pathInfo == null ? Path.ROOT : new Path(pathInfo);
      IFileStore file = tempGetFileStore(filePath);
      if (file == null || !file.fetchInfo().exists()) {
        if (failEarlyOn404) {
          return false;
        }
        handleException(
            resp,
            new ServerStatus(IStatus.ERROR, 404, NLS.bind("File not found: {0}", filePath), null));
      }
      if (fileSerializer.handleRequest(req, resp, file)) {
        // return;
      }
      // end copied

      if (file != null) {
        addEditHeaders(resp, site, path);
        addContentTypeHeader(resp, path);
      }
    } else {
      String msg = NLS.bind("No rights to access {0}", workspaceUri);
      handleException(
          resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_FORBIDDEN, msg, null));
    }
    return true;
  }
 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);
   }
 }
Beispiel #6
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;
 }
 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;
 }
 private boolean identifyNewDiffResource(HttpServletRequest request, HttpServletResponse response)
     throws ServletException {
   try {
     StringWriter writer = new StringWriter();
     IOUtilities.pipe(request.getReader(), writer, false, false);
     JSONObject requestObject = new JSONObject(writer.toString());
     URI u = getURI(request);
     IPath p = new Path(u.getPath());
     IPath np = new Path("/"); // $NON-NLS-1$
     for (int i = 0; i < p.segmentCount(); i++) {
       String s = p.segment(i);
       if (i == 2) {
         s += ".."; // $NON-NLS-1$
         s += GitUtils.encode(requestObject.getString(GitConstants.KEY_COMMIT_NEW));
       }
       np = np.append(s);
     }
     if (p.hasTrailingSeparator()) np = np.addTrailingSeparator();
     URI nu =
         new URI(
             u.getScheme(),
             u.getUserInfo(),
             u.getHost(),
             u.getPort(),
             np.toString(),
             u.getQuery(),
             u.getFragment());
     JSONObject result = new JSONObject();
     result.put(ProtocolConstants.KEY_LOCATION, nu.toString());
     OrionServlet.writeJSONResponse(request, response, result);
     response.setHeader(
         ProtocolConstants.HEADER_LOCATION, resovleOrionURI(request, nu).toString());
     return true;
   } catch (Exception e) {
     return statusHandler.handleRequest(
         request,
         response,
         new ServerStatus(
             IStatus.ERROR,
             HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
             "An error occured when identifying a new Diff resource.",
             e));
   }
 }
 private boolean identifyNewCommitResource(
     HttpServletRequest request, HttpServletResponse response, Repository db, String newCommit)
     throws ServletException {
   try {
     URI u = getURI(request);
     IPath p = new Path(u.getPath());
     IPath np = new Path("/"); // $NON-NLS-1$
     for (int i = 0; i < p.segmentCount(); i++) {
       String s = p.segment(i);
       if (i == 2) {
         s += ".." + newCommit; // $NON-NLS-1$
       }
       np = np.append(s);
     }
     if (p.hasTrailingSeparator()) np = np.addTrailingSeparator();
     URI nu =
         new URI(
             u.getScheme(),
             u.getUserInfo(),
             u.getHost(),
             u.getPort(),
             np.toString(),
             u.getQuery(),
             u.getFragment());
     JSONObject result = new JSONObject();
     result.put(ProtocolConstants.KEY_LOCATION, nu);
     OrionServlet.writeJSONResponse(
         request, response, result, JsonURIUnqualificationStrategy.ALL_NO_GIT);
     response.setHeader(
         ProtocolConstants.HEADER_LOCATION, resovleOrionURI(request, nu).toString());
     return true;
   } catch (Exception e) {
     return statusHandler.handleRequest(
         request,
         response,
         new ServerStatus(
             IStatus.ERROR,
             HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
             "An error occured when identifying a new Commit resource.",
             e));
   }
 }
  protected boolean findSourceFiles(
      IResourceDelta sourceDelta, ClasspathMultiDirectory md, int segmentCount)
      throws CoreException {
    // When a package becomes a type or vice versa, expect 2 deltas,
    // one on the folder & one on the source file
    IResource resource = sourceDelta.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

        switch (sourceDelta.getKind()) {
          case IResourceDelta.ADDED:
            if (!isExcluded) {
              IPath addedPackagePath = resource.getFullPath().removeFirstSegments(segmentCount);
              createFolder(
                  addedPackagePath, md.binaryFolder); // ensure package exists in the output folder
              // see if any known source file is from the same package... classpath already includes
              // new package
              if (this.sourceLocations.length > 1
                  && this.newState.isKnownPackage(addedPackagePath.toString())) {
                if (JavaBuilder.DEBUG)
                  System.out.println(
                      "Skipped dependents of added package " + addedPackagePath); // $NON-NLS-1$
              } else {
                if (JavaBuilder.DEBUG)
                  System.out.println("Found added package " + addedPackagePath); // $NON-NLS-1$
                addDependentsOf(addedPackagePath, true);
              }
            }
            // $FALL-THROUGH$ collect all the source files
          case IResourceDelta.CHANGED:
            IResourceDelta[] children = sourceDelta.getAffectedChildren();
            for (int i = 0, l = children.length; i < l; i++)
              if (!findSourceFiles(children[i], md, segmentCount)) return false;
            return true;
          case IResourceDelta.REMOVED:
            if (isExcluded) {
              // since this folder is excluded then there is nothing to delete (from this md), but
              // must walk any included subfolders
              children = sourceDelta.getAffectedChildren();
              for (int i = 0, l = children.length; i < l; i++)
                if (!findSourceFiles(children[i], md, segmentCount)) return false;
              return true;
            }
            IPath removedPackagePath = resource.getFullPath().removeFirstSegments(segmentCount);
            if (this.sourceLocations.length > 1) {
              for (int i = 0, l = this.sourceLocations.length; i < l; i++) {
                if (this.sourceLocations[i].sourceFolder.getFolder(removedPackagePath).exists()) {
                  // only a package fragment was removed, same as removing multiple source files
                  createFolder(
                      removedPackagePath,
                      md.binaryFolder); // ensure package exists in the output folder
                  IResourceDelta[] removedChildren = sourceDelta.getAffectedChildren();
                  for (int j = 0, m = removedChildren.length; j < m; j++)
                    if (!findSourceFiles(removedChildren[j], md, segmentCount)) return false;
                  return true;
                }
              }
            }
            if ((sourceDelta.getFlags() & IResourceDelta.MOVED_TO) != 0) {
              // same idea as moving a source file
              // see bug 163200
              IResource movedFolder =
                  this.javaBuilder.workspaceRoot.getFolder(sourceDelta.getMovedToPath());
              JavaBuilder.removeProblemsAndTasksFor(movedFolder);
            }
            IFolder removedPackageFolder = md.binaryFolder.getFolder(removedPackagePath);
            if (removedPackageFolder.exists()) removedPackageFolder.delete(IResource.FORCE, null);
            // add dependents even when the package thinks it does not exist to be on the safe side
            if (JavaBuilder.DEBUG)
              System.out.println("Found removed package " + removedPackagePath); // $NON-NLS-1$
            addDependentsOf(removedPackagePath, true);
            this.newState.removePackage(sourceDelta);
        }
        return true;
      case IResource.FILE:
        if (isExcluded) return true;

        String resourceName = resource.getName();
        // GROOVY start
        // determine if this is a Groovy project
        final boolean isInterestingProject =
            LanguageSupportFactory.isInterestingProject(this.javaBuilder.getProject());
        // GROOVY end

        // GROOVY start
        /* old {
        if (org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(resourceName)) {
        } new */
        // GRECLIPSE-404 must call 'isJavaLikeFile' directly in order to make the Scala-Eclipse
        // plugin's weaving happy
        if ((!isInterestingProject
                && org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(resourceName)
                && !LanguageSupportFactory.isInterestingSourceFile(resourceName))
            || (isInterestingProject
                && LanguageSupportFactory.isSourceFile(resourceName, isInterestingProject))) {
          // GROOVY end
          IPath typePath =
              resource.getFullPath().removeFirstSegments(segmentCount).removeFileExtension();
          String typeLocator = resource.getProjectRelativePath().toString();
          switch (sourceDelta.getKind()) {
            case IResourceDelta.ADDED:
              if (JavaBuilder.DEBUG)
                System.out.println("Compile this added source file " + typeLocator); // $NON-NLS-1$
              this.sourceFiles.add(new SourceFile((IFile) resource, md, true));
              String typeName = typePath.toString();
              if (!this.newState.isDuplicateLocator(
                  typeName, typeLocator)) { // adding dependents results in 2 duplicate errors
                if (JavaBuilder.DEBUG)
                  System.out.println("Found added source file " + typeName); // $NON-NLS-1$
                addDependentsOf(typePath, true);
              }
              return true;
            case IResourceDelta.REMOVED:
              char[][] definedTypeNames = this.newState.getDefinedTypeNamesFor(typeLocator);
              if (definedTypeNames == null) { // defined a single type matching typePath
                removeClassFile(typePath, md.binaryFolder);
                if ((sourceDelta.getFlags() & IResourceDelta.MOVED_TO) != 0) {
                  // remove problems and tasks for a compilation unit that is being moved (to
                  // another package or renamed)
                  // if the target file is a compilation unit, the new cu will be recompiled
                  // if the target file is a non-java resource, then markers are removed
                  // see bug 2857
                  IResource movedFile =
                      this.javaBuilder.workspaceRoot.getFile(sourceDelta.getMovedToPath());
                  JavaBuilder.removeProblemsAndTasksFor(movedFile);
                }
              } else {
                if (JavaBuilder.DEBUG)
                  System.out.println(
                      "Found removed source file " + typePath.toString()); // $NON-NLS-1$
                addDependentsOf(
                    typePath,
                    true); // add dependents of the source file since it may be involved in a name
                // collision
                if (definedTypeNames.length
                    > 0) { // skip it if it failed to successfully define a type
                  IPath packagePath = typePath.removeLastSegments(1);
                  for (int i = 0, l = definedTypeNames.length; i < l; i++)
                    removeClassFile(
                        packagePath.append(new String(definedTypeNames[i])), md.binaryFolder);
                }
              }
              this.newState.removeLocator(typeLocator);
              return true;
            case IResourceDelta.CHANGED:
              if ((sourceDelta.getFlags() & IResourceDelta.CONTENT) == 0
                  && (sourceDelta.getFlags() & IResourceDelta.ENCODING) == 0)
                return true; // skip it since it really isn't changed
              if (JavaBuilder.DEBUG)
                System.out.println(
                    "Compile this changed source file " + typeLocator); // $NON-NLS-1$
              this.sourceFiles.add(new SourceFile((IFile) resource, md, true));
          }
          return true;
        } else if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(resourceName)) {
          // perform full build if a managed class file has been changed
          if (this.makeOutputFolderConsistent) {
            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;
        } else if (md.hasIndependentOutputFolder) {
          if (this.javaBuilder.filterExtraResource(resource)) return true;

          // copy all other resource deltas to the output folder
          IPath resourcePath = resource.getFullPath().removeFirstSegments(segmentCount);
          IResource outputFile = md.binaryFolder.getFile(resourcePath);
          switch (sourceDelta.getKind()) {
            case IResourceDelta.ADDED:
              if (outputFile.exists()) {
                if (JavaBuilder.DEBUG)
                  System.out.println("Deleting existing file " + resourcePath); // $NON-NLS-1$
                outputFile.delete(IResource.FORCE, null);
              }
              if (JavaBuilder.DEBUG)
                System.out.println("Copying added file " + resourcePath); // $NON-NLS-1$
              createFolder(
                  resourcePath.removeLastSegments(1),
                  md.binaryFolder); // ensure package exists in the output folder
              copyResource(resource, outputFile);
              return true;
            case IResourceDelta.REMOVED:
              if (outputFile.exists()) {
                if (JavaBuilder.DEBUG)
                  System.out.println("Deleting removed file " + resourcePath); // $NON-NLS-1$
                outputFile.delete(IResource.FORCE, null);
              }
              return true;
            case IResourceDelta.CHANGED:
              if ((sourceDelta.getFlags() & IResourceDelta.CONTENT) == 0
                  && (sourceDelta.getFlags() & IResourceDelta.ENCODING) == 0)
                return true; // skip it since it really isn't changed
              if (outputFile.exists()) {
                if (JavaBuilder.DEBUG)
                  System.out.println("Deleting existing file " + resourcePath); // $NON-NLS-1$
                outputFile.delete(IResource.FORCE, null);
              }
              if (JavaBuilder.DEBUG)
                System.out.println("Copying changed file " + resourcePath); // $NON-NLS-1$
              createFolder(
                  resourcePath.removeLastSegments(1),
                  md.binaryFolder); // ensure package exists in the output folder
              copyResource(resource, outputFile);
          }
          return true;
        }
    }
    return true;
  }
 protected void findAffectedSourceFiles(
     IResourceDelta binaryDelta, int segmentCount, StringSet structurallyChangedTypes) {
   // When a package becomes a type or vice versa, expect 2 deltas,
   // one on the folder & one on the class file
   IResource resource = binaryDelta.getResource();
   switch (resource.getType()) {
     case IResource.FOLDER:
       switch (binaryDelta.getKind()) {
         case IResourceDelta.ADDED:
         case IResourceDelta.REMOVED:
           IPath packagePath = resource.getFullPath().removeFirstSegments(segmentCount);
           String packageName = packagePath.toString();
           if (binaryDelta.getKind() == IResourceDelta.ADDED) {
             // see if any known source file is from the same package... classpath already includes
             // new package
             if (!this.newState.isKnownPackage(packageName)) {
               if (JavaBuilder.DEBUG)
                 System.out.println("Found added package " + packageName); // $NON-NLS-1$
               addDependentsOf(packagePath, false);
               return;
             }
             if (JavaBuilder.DEBUG)
               System.out.println(
                   "Skipped dependents of added package " + packageName); // $NON-NLS-1$
           } else {
             // see if the package still exists on the classpath
             if (!this.nameEnvironment.isPackage(packageName)) {
               if (JavaBuilder.DEBUG)
                 System.out.println("Found removed package " + packageName); // $NON-NLS-1$
               addDependentsOf(packagePath, false);
               return;
             }
             if (JavaBuilder.DEBUG)
               System.out.println(
                   "Skipped dependents of removed package " + packageName); // $NON-NLS-1$
           }
           // $FALL-THROUGH$ traverse the sub-packages and .class files
         case IResourceDelta.CHANGED:
           IResourceDelta[] children = binaryDelta.getAffectedChildren();
           for (int i = 0, l = children.length; i < l; i++)
             findAffectedSourceFiles(children[i], segmentCount, structurallyChangedTypes);
       }
       return;
     case IResource.FILE:
       if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(resource.getName())) {
         IPath typePath =
             resource.getFullPath().removeFirstSegments(segmentCount).removeFileExtension();
         switch (binaryDelta.getKind()) {
           case IResourceDelta.ADDED:
           case IResourceDelta.REMOVED:
             if (JavaBuilder.DEBUG)
               System.out.println("Found added/removed class file " + typePath); // $NON-NLS-1$
             addDependentsOf(typePath, false);
             return;
           case IResourceDelta.CHANGED:
             if ((binaryDelta.getFlags() & IResourceDelta.CONTENT) == 0)
               return; // skip it since it really isn't changed
             if (structurallyChangedTypes != null
                 && !structurallyChangedTypes.includes(typePath.toString()))
               return; // skip since it wasn't a structural change
             if (JavaBuilder.DEBUG)
               System.out.println("Found changed class file " + typePath); // $NON-NLS-1$
             addDependentsOf(typePath, false);
         }
         return;
       }
   }
 }
 private void addEditHeaders(HttpServletResponse resp, IHostedSite site, IPath path) {
   resp.addHeader(
       "X-Edit-Server", site.getEditServerUrl() + "/edit/edit.html#"); // $NON-NLS-1$ //$NON-NLS-2$
   resp.addHeader("X-Edit-Token", FILE_SERVLET_ALIAS + path.toString()); // $NON-NLS-1$
 }
Beispiel #13
0
 /** Sets the path of the file in the workspace once the import completes. */
 public void setPath(IPath path) {
   props.put(KEY_PATH, path.toString());
 }
  private boolean handlePost(
      HttpServletRequest request, HttpServletResponse response, String pathString)
      throws IOException, JSONException, ServletException, URISyntaxException, CoreException,
          NoHeadException, NoMessageException, ConcurrentRefUpdateException,
          WrongRepositoryStateException {
    // make sure required fields are set
    JSONObject toAdd = OrionServlet.readJSONRequest(request);
    if (toAdd.optBoolean(GitConstants.KEY_PULL, false)) {
      GitUtils.createGitCredentialsProvider(toAdd);
      GitCredentialsProvider cp = GitUtils.createGitCredentialsProvider(toAdd);
      boolean force = toAdd.optBoolean(GitConstants.KEY_FORCE, false);
      return pull(request, response, cp, pathString, force);
    }

    Clone clone = new Clone();
    String url = toAdd.optString(GitConstants.KEY_URL, null);
    // method handles repository clone or just repository init
    // decision is based on existence of GitUrl argument
    boolean initOnly;
    if (url == null || url.isEmpty()) initOnly = true;
    else {
      initOnly = false;
      if (!validateCloneUrl(url, request, response)) return true;
      clone.setUrl(new URIish(url));
    }
    String cloneName = toAdd.optString(ProtocolConstants.KEY_NAME, null);
    if (cloneName == null) cloneName = request.getHeader(ProtocolConstants.HEADER_SLUG);
    // expected path /workspace/{workspaceId}
    String workspacePath = toAdd.optString(ProtocolConstants.KEY_LOCATION, null);
    // expected path /file/{workspaceId}/{projectName}[/{path}]
    String filePathString = toAdd.optString(ProtocolConstants.KEY_PATH, null);
    IPath filePath = filePathString == null ? null : new Path(filePathString);
    if (filePath != null && filePath.segmentCount() < 3) filePath = null;
    if (filePath == null && workspacePath == null) {
      String msg =
          NLS.bind(
              "Either {0} or {1} should be provided: {2}",
              new Object[] {ProtocolConstants.KEY_PATH, ProtocolConstants.KEY_LOCATION, toAdd});
      return statusHandler.handleRequest(
          request,
          response,
          new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
    }
    // only during init operation filePath or cloneName must be provided
    // during clone operation, name can be obtained from URL
    if (initOnly && filePath == null && cloneName == null) {
      String msg =
          NLS.bind(
              "Either {0} or {1} should be provided: {2}",
              new Object[] {ProtocolConstants.KEY_PATH, GitConstants.KEY_NAME, toAdd});
      return statusHandler.handleRequest(
          request,
          response,
          new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
    }
    if (!validateCloneName(cloneName, request, response)) return true;

    // prepare the WebClone object, create a new project if necessary
    WebProject webProject = null;
    boolean webProjectExists = false;
    if (filePath != null) {
      // path format is /file/{workspaceId}/{projectName}/[filePath]
      clone.setId(filePath.toString());
      webProject = GitUtils.projectFromPath(filePath);
      // workspace path format needs to be used if project does not exist
      if (webProject == null) {
        String msg = NLS.bind("Specified project does not exist: {0}", filePath.segment(2));
        return statusHandler.handleRequest(
            request,
            response,
            new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
      }
      webProjectExists = true;
      clone.setContentLocation(
          webProject.getProjectStore().getFileStore(filePath.removeFirstSegments(3)).toURI());
      if (cloneName == null)
        cloneName = filePath.segmentCount() > 2 ? filePath.lastSegment() : webProject.getName();
    } else if (workspacePath != null) {
      IPath path = new Path(workspacePath);
      // TODO: move this to CloneJob
      // if so, modify init part to create a new project if necessary
      WebWorkspace workspace = WebWorkspace.fromId(path.segment(1));
      String id = WebProject.nextProjectId();
      if (cloneName == null) cloneName = new URIish(url).getHumanishName();
      cloneName = getUniqueProjectName(workspace, cloneName);
      webProjectExists = false;
      webProject = WebProject.fromId(id);
      webProject.setName(cloneName);

      try {
        WorkspaceResourceHandler.computeProjectLocation(request, webProject, null, false);
      } catch (CoreException e) {
        // we are unable to write in the platform location!
        String msg =
            NLS.bind(
                "Server content location could not be written: {0}",
                Activator.getDefault().getRootLocationURI());
        return statusHandler.handleRequest(
            request,
            response,
            new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
      } catch (URISyntaxException e) {
        // should not happen, we do not allow linking at this point
      }

      try {
        // If all went well, add project to workspace
        WorkspaceResourceHandler.addProject(request.getRemoteUser(), workspace, webProject);
      } catch (CoreException e) {
        return statusHandler.handleRequest(
            request,
            response,
            new ServerStatus(
                IStatus.ERROR,
                HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Error persisting project state",
                e));
      }

      URI baseLocation = getURI(request);
      baseLocation =
          new URI(
              baseLocation.getScheme(),
              baseLocation.getUserInfo(),
              baseLocation.getHost(),
              baseLocation.getPort(),
              workspacePath,
              baseLocation.getQuery(),
              baseLocation.getFragment());
      clone.setId(GitUtils.pathFromProject(workspace, webProject).toString());
      clone.setContentLocation(webProject.getProjectStore().toURI());
    }
    clone.setName(cloneName);
    clone.setBaseLocation(getURI(request));
    JSONObject cloneObject = clone.toJSON();
    String cloneLocation = cloneObject.getString(ProtocolConstants.KEY_LOCATION);

    if (initOnly) {
      // git init
      InitJob job =
          new InitJob(
              clone, TaskJobHandler.getUserId(request), request.getRemoteUser(), cloneLocation);
      return TaskJobHandler.handleTaskJob(request, response, job, statusHandler);
    }
    // git clone
    // prepare creds
    GitCredentialsProvider cp = GitUtils.createGitCredentialsProvider(toAdd);
    cp.setUri(new URIish(clone.getUrl()));

    // if all went well, clone
    CloneJob job =
        new CloneJob(
            clone,
            TaskJobHandler.getUserId(request),
            cp,
            request.getRemoteUser(),
            cloneLocation,
            webProjectExists
                ? null
                : webProject /* used for cleaning up, so null when not needed */);
    return TaskJobHandler.handleTaskJob(request, response, job, statusHandler);
  }
  private boolean resourceExists(String location) {
    String bundleJar = null;
    IPath path = new Path(location);
    if ("platform:".equals(path.getDevice()) && path.segmentCount() > 2) { // $NON-NLS-1$
      if ("plugin".equals(path.segment(0))) { // $NON-NLS-1$
        String id = path.segment(1);
        IMonitorModelBase model = MonitorRegistry.findModel(id);
        if (model != null && model.isEnabled()) {
          path = path.setDevice(null).removeFirstSegments(2);
          String bundleLocation = model.getInstallLocation();
          if (bundleLocation.endsWith(".jar")) { // $NON-NLS-1$
            bundleJar = bundleLocation;
          } else {
            path = new Path(model.getInstallLocation()).append(path);
          }
          location = path.toString();
        }
      }
    } else if (path.getDevice() == null
        && path.segmentCount() > 3
        && "platform:".equals(path.segment(0))) { // $NON-NLS-1$
      if ("plugin".equals(path.segment(1))) { // $NON-NLS-1$
        String id = path.segment(2);
        IMonitorModelBase model = MonitorRegistry.findModel(id);
        if (model != null && model.isEnabled()) {
          path = path.removeFirstSegments(3);
          String bundleLocation = model.getInstallLocation();
          if (bundleLocation.endsWith(".jar")) { // $NON-NLS-1$
            bundleJar = bundleLocation;
          } else {
            path = new Path(model.getInstallLocation()).append(path);
          }
          location = path.toString();
        }
      }
    }

    ArrayList paths = new ArrayList();
    if (location.indexOf("$nl$") != -1) { // $NON-NLS-1$
      StringTokenizer tokenizer = new StringTokenizer(TargetPlatform.getNL(), "_"); // $NON-NLS-1$
      String language = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null;
      String country = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null;
      if (language != null && country != null)
        paths.add(
            location.replaceAll(
                "\\$nl\\$",
                "nl"
                    + IPath.SEPARATOR
                    + language
                    + IPath.SEPARATOR
                    + country)); //$NON-NLS-1$ //$NON-NLS-2$
      if (language != null)
        paths.add(
            location.replaceAll(
                "\\$nl\\$", "nl" + IPath.SEPARATOR + language)); // $NON-NLS-1$ //$NON-NLS-2$
      paths.add(location.replaceAll("\\$nl\\$", "")); // $NON-NLS-1$ //$NON-NLS-2$
    } else {
      paths.add(location);
    }

    for (int i = 0; i < paths.size(); i++) {
      if (bundleJar == null) {
        IPath currPath = new Path(paths.get(i).toString());
        if (currPath.isAbsolute() && currPath.toFile().exists()) return true;
        if (PDEProject.getBundleRoot(fFile.getProject()).findMember(currPath) != null) return true;
        if (fBuildModel != null
            && fBuildModel.getEntry("source." + paths.get(i)) != null) // $NON-NLS-1$
        return true;
      } else {
        if (CoreUtility.jarContainsResource(new File(bundleJar), paths.get(i).toString(), false))
          return true;
      }
    }

    return false;
  }