protected void addDependentsOf(
      IPath path,
      boolean isStructuralChange,
      StringSet qualifiedNames,
      StringSet simpleNames,
      StringSet rootNames) {
    path = path.setDevice(null);
    if (isStructuralChange) {
      String last = path.lastSegment();
      if (last.length() == TypeConstants.PACKAGE_INFO_NAME.length)
        if (CharOperation.equals(last.toCharArray(), TypeConstants.PACKAGE_INFO_NAME)) {
          path =
              path.removeLastSegments(
                  1); // the package-info file has changed so blame the package itself
          /* https://bugs.eclipse.org/bugs/show_bug.cgi?id=323785, in the case of default package,
            there is no need to blame the package itself as there can be no annotations or documentation
            comment tags in the package-info file that can influence the rest of the package. Just bail out
            so we don't touch null objects below.
          */
          if (path.isEmpty()) return;
        }
    }

    if (isStructuralChange && !this.hasStructuralChanges) {
      this.newState.tagAsStructurallyChanged();
      this.hasStructuralChanges = true;
    }
    // the qualifiedStrings are of the form 'p1/p2' & the simpleStrings are just 'X'
    rootNames.add(path.segment(0));
    String packageName = path.removeLastSegments(1).toString();
    boolean wasNew = qualifiedNames.add(packageName);
    String typeName = path.lastSegment();
    int memberIndex = typeName.indexOf('$');
    if (memberIndex > 0) typeName = typeName.substring(0, memberIndex);
    wasNew = simpleNames.add(typeName) | wasNew;
    if (wasNew && JavaBuilder.DEBUG)
      System.out.println(
          "  will look for dependents of " //$NON-NLS-1$
              + typeName
              + " in "
              + packageName); //$NON-NLS-1$
  }
 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 #3
0
 public static String getRelativePath(IPath filePath, IPath pathToGitRoot) {
   StringBuilder sb = new StringBuilder();
   String file = null;
   if (!filePath.hasTrailingSeparator()) {
     file = filePath.lastSegment();
     filePath = filePath.removeLastSegments(1);
   }
   for (int i = 0; i < pathToGitRoot.segments().length; i++) {
     if (pathToGitRoot.segments()[i].equals(".."))
       sb.append(
               filePath.segment(filePath.segments().length - pathToGitRoot.segments().length + i))
           .append("/");
     // else TODO
   }
   if (file != null) sb.append(file);
   return sb.toString();
 }
  /**
   * 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();
  }
  /* 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;
  }
 /**
  * @see
  *     org.eclipse.jdt.internal.core.builder.AbstractImageBuilder#writeClassFileContents(org.eclipse.jdt.internal.compiler.ClassFile,
  *     org.eclipse.core.resources.IFile, java.lang.String, boolean,
  *     org.eclipse.jdt.internal.core.builder.SourceFile)
  */
 protected void writeClassFileContents(
     ClassFile classfile,
     IFile file,
     String qualifiedFileName,
     boolean isTopLevelType,
     SourceFile compilationUnit)
     throws CoreException {
   // Before writing out the class file, compare it to the previous file
   // If structural changes occurred then add dependent source files
   byte[] bytes = classfile.getBytes();
   if (file.exists()) {
     if (writeClassFileCheck(file, qualifiedFileName, bytes)
         || compilationUnit.updateClassFile) { // see 46093
       if (JavaBuilder.DEBUG)
         System.out.println("Writing changed class file " + file.getName()); // $NON-NLS-1$
       if (!file.isDerived()) file.setDerived(true, null);
       file.setContents(new ByteArrayInputStream(bytes), true, false, null);
     } else if (JavaBuilder.DEBUG) {
       System.out.println("Skipped over unchanged class file " + file.getName()); // $NON-NLS-1$
     }
   } else {
     if (isTopLevelType) addDependentsOf(new Path(qualifiedFileName), true); // new type
     if (JavaBuilder.DEBUG)
       System.out.println("Writing new class file " + file.getName()); // $NON-NLS-1$
     try {
       file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null);
     } catch (CoreException e) {
       if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) {
         IStatus status = e.getStatus();
         if (status instanceof IResourceStatus) {
           IPath oldFilePath = ((IResourceStatus) status).getPath();
           char[] oldTypeName = oldFilePath.removeFileExtension().lastSegment().toCharArray();
           char[][] previousTypeNames =
               this.newState.getDefinedTypeNamesFor(compilationUnit.typeLocator());
           boolean fromSameFile = false;
           if (previousTypeNames == null) {
             fromSameFile = CharOperation.equals(compilationUnit.getMainTypeName(), oldTypeName);
           } else {
             for (int i = 0, l = previousTypeNames.length; i < l; i++) {
               if (CharOperation.equals(previousTypeNames[i], oldTypeName)) {
                 fromSameFile = true;
                 break;
               }
             }
           }
           if (fromSameFile) {
             // file is defined by the same compilationUnit, but won't be deleted until later so do
             // it now
             IFile collision = file.getParent().getFile(new Path(oldFilePath.lastSegment()));
             collision.delete(true, false, null);
             boolean success = false;
             try {
               file.create(
                   new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null);
               success = true;
             } catch (CoreException ignored) {
               // ignore the second exception
             }
             if (success) return;
           }
         }
         // catch the case that a type has been renamed and collides on disk with an
         // as-yet-to-be-deleted type
         throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedFileName));
       }
       throw e; // rethrow
     }
   }
 }
 private void addContentTypeHeader(HttpServletResponse resp, IPath path) {
   String mimeType = getServletContext().getMimeType(path.lastSegment());
   if (mimeType != null) resp.addHeader("Content-Type", mimeType);
 }
  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);
  }