Пример #1
0
 private void encodeChildren(IFileStore dir, URI location, JSONObject result, int depth)
     throws CoreException {
   if (depth <= 0) return;
   JSONArray children = new JSONArray();
   IFileStore[] childStores = dir.childStores(EFS.NONE, null);
   for (IFileStore childStore : childStores) {
     IFileInfo childInfo = childStore.fetchInfo();
     String name = childInfo.getName();
     if (childInfo.isDirectory()) name += "/"; // $NON-NLS-1$
     URI childLocation = URIUtil.append(location, name);
     JSONObject childResult = ServletFileStoreHandler.toJSON(childStore, childInfo, childLocation);
     if (childInfo.isDirectory())
       encodeChildren(childStore, childLocation, childResult, depth - 1);
     children.put(childResult);
   }
   try {
     result.put(ProtocolConstants.KEY_CHILDREN, children);
   } catch (JSONException e) {
     // cannot happen
     throw new RuntimeException(e);
   }
 }
Пример #2
0
 /** Returns whether the user can access the given project */
 private boolean isAccessAllowed(String userName, WebProject webProject) {
   try {
     WebUser webUser = WebUser.fromUserId(userName);
     JSONArray workspacesJSON = webUser.getWorkspacesJSON();
     for (int i = 0; i < workspacesJSON.length(); i++) {
       JSONObject workspace = workspacesJSON.getJSONObject(i);
       String workspaceId = workspace.getString(ProtocolConstants.KEY_ID);
       WebWorkspace webWorkspace = WebWorkspace.fromId(workspaceId);
       JSONArray projectsJSON = webWorkspace.getProjectsJSON();
       for (int j = 0; j < projectsJSON.length(); j++) {
         JSONObject project = projectsJSON.getJSONObject(j);
         String projectId = project.getString(ProtocolConstants.KEY_ID);
         if (projectId.equals(webProject.getId())) return true;
       }
     }
   } catch (JSONException e) {
     // ignore, deny access
   }
   return false;
 }
Пример #3
0
  @Test
  public void testReadFileMetadata() throws Exception {
    String directoryPath = "sample/directory/path" + System.currentTimeMillis();
    createDirectory(directoryPath);
    String fileName = "sampleFile" + System.currentTimeMillis() + ".txt";
    String fileContent = "Sample File Cotnent " + System.currentTimeMillis();
    createFile(directoryPath + "/" + fileName, fileContent);

    WebRequest request = getGetFilesRequest(directoryPath + "/" + fileName + "?parts=meta");
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    JSONObject result = new JSONObject(response.getText());

    assertEquals(fileName, result.optString(ProtocolConstants.KEY_NAME));

    JSONArray parents = result.optJSONArray(ProtocolConstants.KEY_PARENTS);
    assertNotNull(parents);
    assertEquals(3, parents.length());
    IPath parentPath = new Path(directoryPath);
    // immediate parent
    JSONObject parent = parents.getJSONObject(0);
    assertEquals(parentPath.segment(2), parent.getString(ProtocolConstants.KEY_NAME));
    // grandparent
    parent = parents.getJSONObject(1);
    assertEquals(parentPath.segment(1), parent.getString(ProtocolConstants.KEY_NAME));

    // ensure all parent locations end with trailing slash
    for (int i = 0; i < parents.length(); i++) {
      parent = parents.getJSONObject(i);
      String location = parent.getString(ProtocolConstants.KEY_LOCATION);
      assertTrue(location.endsWith("/"));
      location = parent.getString(ProtocolConstants.KEY_CHILDREN_LOCATION);
      URI childrenLocation = new URI(location);
      assertTrue(childrenLocation.getPath().endsWith("/"));
    }
  }
Пример #4
0
  /**
   * Looks for the project in all workspaces of the user and removes it when found.
   *
   * @see WorkspaceResourceHandler#handleRemoveProject(HttpServletRequest, HttpServletResponse,
   *     WebWorkspace)
   * @param userName the user name
   * @param webProject the project to remove
   * @return ServerStatus <code>OK</code> if the project has been found and successfully removed,
   *     <code>ERROR</code> if an error occurred or the project couldn't be found
   */
  public static ServerStatus removeProject(String userName, WebProject webProject) {
    try {
      WebUser webUser = WebUser.fromUserId(userName);
      JSONArray workspacesJSON = webUser.getWorkspacesJSON();
      for (int i = 0; i < workspacesJSON.length(); i++) {
        JSONObject workspace = workspacesJSON.getJSONObject(i);
        String workspaceId = workspace.getString(ProtocolConstants.KEY_ID);
        WebWorkspace webWorkspace = WebWorkspace.fromId(workspaceId);
        JSONArray projectsJSON = webWorkspace.getProjectsJSON();
        for (int j = 0; j < projectsJSON.length(); j++) {
          JSONObject project = projectsJSON.getJSONObject(j);
          String projectId = project.getString(ProtocolConstants.KEY_ID);
          if (projectId.equals(webProject.getId())) {
            // If found, remove project from workspace
            try {
              WorkspaceResourceHandler.removeProject(userName, webWorkspace, webProject);
            } 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 new ServerStatus(
                  IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
            }

            return new ServerStatus(IStatus.OK, HttpServletResponse.SC_OK, null, null);
          }
        }
      }
    } catch (JSONException e) {
      // ignore, no project will be harmed
    }
    // FIXME: not sure about this one
    return new ServerStatus(IStatus.OK, HttpServletResponse.SC_OK, null, null);
  }
Пример #5
0
  private boolean handlePut(
      HttpServletRequest request, HttpServletResponse response, String pathString)
      throws GitAPIException, CoreException, IOException, JSONException, ServletException {
    IPath path = pathString == null ? Path.EMPTY : new Path(pathString);
    if (path.segment(0).equals("file") && path.segmentCount() > 1) { // $NON-NLS-1$

      // make sure a clone is addressed
      WebProject webProject = GitUtils.projectFromPath(path);
      if (isAccessAllowed(request.getRemoteUser(), webProject)) {
        Map<IPath, File> gitDirs = GitUtils.getGitDirs(path, Traverse.CURRENT);
        if (gitDirs.isEmpty()) {
          String msg = NLS.bind("Request path is not a git repository: {0}", path);
          return statusHandler.handleRequest(
              request,
              response,
              new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
        }
        File gitDir = gitDirs.values().iterator().next();

        // make sure required fields are set
        JSONObject toCheckout = OrionServlet.readJSONRequest(request);
        JSONArray paths = toCheckout.optJSONArray(ProtocolConstants.KEY_PATH);
        String branch = toCheckout.optString(GitConstants.KEY_BRANCH_NAME, null);
        String tag = toCheckout.optString(GitConstants.KEY_TAG_NAME, null);
        boolean removeUntracked = toCheckout.optBoolean(GitConstants.KEY_REMOVE_UNTRACKED, false);
        if ((paths == null || paths.length() == 0) && branch == null && tag == null) {
          String msg =
              NLS.bind(
                  "Either '{0}' or '{1}' or '{2}' should be provided, got: {3}",
                  new Object[] {
                    ProtocolConstants.KEY_PATH,
                    GitConstants.KEY_BRANCH_NAME,
                    GitConstants.KEY_TAG_NAME,
                    toCheckout
                  });
          return statusHandler.handleRequest(
              request,
              response,
              new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
        }

        Git git = new Git(new FileRepository(gitDir));
        if (paths != null) {
          Set<String> toRemove = new HashSet<String>();
          CheckoutCommand checkout = git.checkout();
          for (int i = 0; i < paths.length(); i++) {
            String p = paths.getString(i);
            if (removeUntracked && !isInIndex(git.getRepository(), p)) toRemove.add(p);
            checkout.addPath(p);
          }
          checkout.call();
          for (String p : toRemove) {
            File f = new File(git.getRepository().getWorkTree(), p);
            f.delete();
          }
          return true;
        } else if (tag != null && branch != null) {
          CheckoutCommand co = git.checkout();
          try {
            co.setName(branch).setStartPoint(tag).setCreateBranch(true).call();
            return true;
          } catch (RefNotFoundException e) {
            String msg = NLS.bind("Tag not found: {0}", tag);
            return statusHandler.handleRequest(
                request,
                response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, e));
          } catch (GitAPIException e) {
            if (org.eclipse.jgit.api.CheckoutResult.Status.CONFLICTS.equals(
                co.getResult().getStatus())) {
              return statusHandler.handleRequest(
                  request,
                  response,
                  new ServerStatus(
                      IStatus.ERROR, HttpServletResponse.SC_CONFLICT, "Checkout aborted.", e));
            }
            // TODO: handle other exceptions
          }
        } else if (branch != null) {

          if (!isLocalBranch(git, branch)) {
            String msg = NLS.bind("{0} is not a branch.", branch);
            return statusHandler.handleRequest(
                request,
                response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null));
          }

          CheckoutCommand co = git.checkout();
          try {
            co.setName(Constants.R_HEADS + branch).call();
            return true;
          } catch (CheckoutConflictException e) {
            return statusHandler.handleRequest(
                request,
                response,
                new ServerStatus(
                    IStatus.ERROR, HttpServletResponse.SC_CONFLICT, "Checkout aborted.", e));
          } catch (RefNotFoundException e) {
            String msg = NLS.bind("Branch name not found: {0}", branch);
            return statusHandler.handleRequest(
                request,
                response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, e));
          } // TODO: handle other exceptions
        }
      } else {
        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 checkout request {0}", pathString);
    return statusHandler.handleRequest(
        request,
        response,
        new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
  }
Пример #6
0
 private boolean handleGet(
     HttpServletRequest request, HttpServletResponse response, String pathString)
     throws IOException, JSONException, ServletException, URISyntaxException, CoreException {
   IPath path = pathString == null ? Path.EMPTY : new Path(pathString);
   URI baseLocation = getURI(request);
   String user = request.getRemoteUser();
   // expected path format is 'workspace/{workspaceId}' or
   // 'file/{workspaceId}/{projectName}/{path}]'
   if ("workspace".equals(path.segment(0)) && path.segmentCount() == 2) { // $NON-NLS-1$
     // all clones in the workspace
     if (WebWorkspace.exists(path.segment(1))) {
       WebWorkspace workspace = WebWorkspace.fromId(path.segment(1));
       JSONObject result = new JSONObject();
       JSONArray children = new JSONArray();
       for (WebProject webProject : workspace.getProjects()) {
         // this is the location of the project metadata
         if (isAccessAllowed(user, webProject)) {
           IPath projectPath = GitUtils.pathFromProject(workspace, webProject);
           Map<IPath, File> gitDirs = GitUtils.getGitDirs(projectPath, Traverse.GO_DOWN);
           for (Map.Entry<IPath, File> entry : gitDirs.entrySet()) {
             children.put(new Clone().toJSON(entry, baseLocation));
           }
         }
       }
       result.put(ProtocolConstants.KEY_TYPE, Clone.TYPE);
       result.put(ProtocolConstants.KEY_CHILDREN, children);
       OrionServlet.writeJSONResponse(request, response, result);
       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));
   } else if ("file".equals(path.segment(0)) && path.segmentCount() > 1) { // $NON-NLS-1$
     // clones under given path
     WebProject webProject = GitUtils.projectFromPath(path);
     IPath projectRelativePath = path.removeFirstSegments(3);
     if (webProject != null
         && isAccessAllowed(user, webProject)
         && webProject.getProjectStore().getFileStore(projectRelativePath).fetchInfo().exists()) {
       Map<IPath, File> gitDirs = GitUtils.getGitDirs(path, Traverse.GO_DOWN);
       JSONObject result = new JSONObject();
       JSONArray children = new JSONArray();
       for (Map.Entry<IPath, File> entry : gitDirs.entrySet()) {
         children.put(new Clone().toJSON(entry, baseLocation));
       }
       result.put(ProtocolConstants.KEY_TYPE, Clone.TYPE);
       result.put(ProtocolConstants.KEY_CHILDREN, children);
       OrionServlet.writeJSONResponse(request, response, result);
       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));
   }
   // else the request is malformed
   String msg = NLS.bind("Invalid clone request: {0}", path);
   return statusHandler.handleRequest(
       request,
       response,
       new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
 }
Пример #7
0
  private boolean handleGet(HttpServletRequest request, HttpServletResponse response, String path)
      throws IOException, JSONException, ServletException, URISyntaxException, CoreException {
    Path p = new Path(path);
    // FIXME: what if a remote or branch is named "file"?
    if (p.segment(0).equals("file")) { // $NON-NLS-1$
      // /git/remote/file/{path}
      File gitDir = GitUtils.getGitDir(p);
      Repository db = new FileRepository(gitDir);
      Set<String> configNames =
          db.getConfig().getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
      JSONObject result = new JSONObject();
      JSONArray children = new JSONArray();
      URI cloneLocation =
          BaseToCloneConverter.getCloneLocation(getURI(request), BaseToCloneConverter.REMOTE_LIST);
      for (String configName : configNames) {
        Remote remote = new Remote(cloneLocation, db, configName);
        children.put(remote.toJSON(false, null));
      }
      result.put(ProtocolConstants.KEY_CHILDREN, children);
      result.put(ProtocolConstants.KEY_TYPE, Remote.TYPE);
      OrionServlet.writeJSONResponse(request, response, result);
      return true;
    } else if (p.segment(1).equals("file")) { // $NON-NLS-1$
      // /git/remote/{remote}/file/{path}
      RemoteDetailsJob job;
      String commits = request.getParameter(GitConstants.KEY_TAG_COMMITS);
      int commitsNumber = commits == null ? 0 : Integer.parseInt(commits);
      String page = request.getParameter("page");
      if (page != null) {
        int pageNo = Integer.parseInt(page);
        int pageSize =
            request.getParameter("pageSize") == null
                ? PAGE_SIZE
                : Integer.parseInt(request.getParameter("pageSize"));
        job =
            new RemoteDetailsJob(
                TaskJobHandler.getUserId(request),
                p.segment(0),
                p.removeFirstSegments(1),
                BaseToCloneConverter.getCloneLocation(getURI(request), BaseToCloneConverter.REMOTE),
                commitsNumber,
                pageNo,
                pageSize,
                request.getRequestURI());
      } else {
        job =
            new RemoteDetailsJob(
                TaskJobHandler.getUserId(request),
                p.segment(0),
                p.removeFirstSegments(1),
                BaseToCloneConverter.getCloneLocation(getURI(request), BaseToCloneConverter.REMOTE),
                commitsNumber);
      }
      return TaskJobHandler.handleTaskJob(request, response, job, statusHandler);
    } else if (p.segment(2).equals("file")) { // $NON-NLS-1$
      // /git/remote/{remote}/{branch}/file/{path}
      File gitDir = GitUtils.getGitDir(p.removeFirstSegments(2));
      Repository db = new FileRepository(gitDir);
      URI cloneLocation =
          BaseToCloneConverter.getCloneLocation(
              getURI(request), BaseToCloneConverter.REMOTE_BRANCH);
      Remote remote = new Remote(cloneLocation, db, p.segment(0));
      RemoteBranch remoteBranch = new RemoteBranch(cloneLocation, db, remote, p.segment(1));
      JSONObject result = remoteBranch.toJSON();
      if (result != null) {
        OrionServlet.writeJSONResponse(request, response, result);
        return true;
      }
      JSONObject errorData = new JSONObject();
      errorData.put(GitConstants.KEY_CLONE, cloneLocation);

      return statusHandler.handleRequest(
          request,
          response,
          new ServerStatus(
              new Status(
                  IStatus.ERROR,
                  GitActivator.PI_GIT,
                  "No remote branch found: " + p.uptoSegment(2).removeTrailingSeparator()),
              HttpServletResponse.SC_NOT_FOUND,
              errorData));
    }
    return statusHandler.handleRequest(
        request,
        response,
        new ServerStatus(
            IStatus.ERROR,
            HttpServletResponse.SC_BAD_REQUEST,
            "Bad request, \"/git/remote/{remote}/{branch}/file/{path}\" expected",
            null));
  }