private String fetchPatchContentFromUrl(final String url) throws IOException {
   GetMethod m = new GetMethod(url);
   getHttpClient().executeMethod(m);
   if (m.getStatusCode() == HttpStatus.SC_OK) {
     return IOUtilities.toString(m.getResponseBodyAsStream());
   }
   return null;
 }
 /** Reads the chunk of data to be imported from the request's input stream. */
 private byte[] readChunk(HttpServletRequest req, int chunkSize) throws IOException {
   ServletInputStream requestStream = req.getInputStream();
   String contentType = req.getHeader(ProtocolConstants.HEADER_CONTENT_TYPE);
   if (contentType.startsWith("multipart")) // $NON-NLS-1$
   return readMultiPartChunk(requestStream, contentType);
   ByteArrayOutputStream outputStream = new ByteArrayOutputStream(chunkSize);
   IOUtilities.pipe(requestStream, outputStream, false, false);
   return outputStream.toByteArray();
 }
 private void doImportFromURL(HttpServletRequest req, HttpServletResponse resp)
     throws IOException, ServletException {
   URL source = getSourceURL();
   IOUtilities.pipe(
       source.openStream(),
       new FileOutputStream(new File(getStorageDirectory(), FILE_DATA), true),
       true,
       true);
   completeTransfer(req, resp);
 }
 static WebRequest getPutGitConfigRequest(String location, String value)
     throws JSONException, UnsupportedEncodingException {
   String requestURI = toAbsoluteURI(location);
   JSONObject body = new JSONObject();
   body.put(GitConstants.KEY_CONFIG_ENTRY_VALUE, value);
   WebRequest request =
       new PutMethodWebRequest(requestURI, IOUtilities.toInputStream(body.toString()), "UTF-8");
   request.setHeaderField(ProtocolConstants.HEADER_ORION_VERSION, "1");
   setAuthentication(request);
   return request;
 }
 private String readPatch(ServletInputStream requestStream, String contentType)
     throws IOException {
   // fast forward stream past multi-part header
   int boundaryOff = contentType.indexOf("boundary="); // $NON-NLS-1$
   String boundary =
       contentType.substring(
           boundaryOff + "boundary=".length(), contentType.length()); // $NON-NLS-1$
   Map<String, String> parts = IOUtilities.parseMultiPart(requestStream, boundary);
   if ("fileRadio".equals(parts.get("radio"))) // $NON-NLS-1$ //$NON-NLS-2$
   return parts.get("uploadedfile"); // $NON-NLS-1$
   if ("urlRadio".equals(parts.get("radio"))) // $NON-NLS-1$ //$NON-NLS-2$
   return fetchPatchContentFromUrl(parts.get("url")); // $NON-NLS-1$
   return null;
 }
 private boolean applyPatch(
     HttpServletRequest request, HttpServletResponse response, Repository db, String contentType)
     throws ServletException {
   try {
     String patch = readPatch(request.getInputStream(), contentType);
     Git git = new Git(db);
     ApplyCommand applyCommand = git.apply();
     applyCommand.setPatch(IOUtilities.toInputStream(patch));
     // TODO: ignore all errors for now, see bug 366008
     try {
       ApplyResult applyResult = applyCommand.call();
       JSONObject resp = new JSONObject();
       JSONArray modifiedFieles = new JSONArray();
       for (File file : applyResult.getUpdatedFiles()) {
         modifiedFieles.put(stripGlobalPaths(db, file.getAbsolutePath()));
       }
       resp.put("modifiedFieles", modifiedFieles);
       return statusHandler.handleRequest(
           request, response, new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, resp));
       // OrionServlet.writeJSONResponse(request, response, toJSON(applyResult));
     } catch (PatchFormatException e) {
       return statusHandler.handleRequest(
           request,
           response,
           new ServerStatus(
               IStatus.ERROR,
               HttpServletResponse.SC_BAD_REQUEST,
               stripGlobalPaths(db, e.getMessage()),
               null));
     } catch (PatchApplyException e) {
       return statusHandler.handleRequest(
           request,
           response,
           new ServerStatus(
               IStatus.ERROR,
               HttpServletResponse.SC_BAD_REQUEST,
               stripGlobalPaths(db, e.getMessage()),
               null));
     }
   } catch (Exception e) {
     return statusHandler.handleRequest(
         request,
         response,
         new ServerStatus(
             IStatus.ERROR,
             HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
             "An error occured when reading the patch.",
             e));
   }
 }
 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 WebRequest getCheckoutRequest(String location, String[] paths, boolean removeUntracked)
     throws IOException, JSONException {
   String requestURI;
   if (location.startsWith("http://")) {
     // assume the caller knows what he's doing
     // assertCloneUri(location);
     requestURI = location;
   } else {
     requestURI = SERVER_LOCATION + GIT_SERVLET_LOCATION + Clone.RESOURCE + location;
   }
   JSONObject body = new JSONObject();
   JSONArray jsonPaths = new JSONArray();
   for (String path : paths) jsonPaths.put(path);
   body.put(ProtocolConstants.KEY_PATH, jsonPaths);
   if (removeUntracked) body.put(GitConstants.KEY_REMOVE_UNTRACKED, removeUntracked);
   WebRequest request =
       new PutMethodWebRequest(requestURI, IOUtilities.toInputStream(body.toString()), "UTF-8");
   request.setHeaderField(ProtocolConstants.HEADER_ORION_VERSION, "1");
   setAuthentication(request);
   return request;
 }
 /**
  * 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;
 }
  private boolean handleMultiPartGet(
      HttpServletRequest request,
      HttpServletResponse response,
      Repository db,
      String scope,
      String pattern)
      throws Exception {
    String boundary = createBoundaryString();
    response.setHeader(
        ProtocolConstants.HEADER_CONTENT_TYPE,
        "multipart/related; boundary=\"" + boundary + '"'); // $NON-NLS-1$
    OutputStream outputStream = response.getOutputStream();
    Writer out = new OutputStreamWriter(outputStream);
    try {
      out.write("--" + boundary + EOL); // $NON-NLS-1$
      out.write(
          ProtocolConstants.HEADER_CONTENT_TYPE
              + ": "
              + ProtocolConstants.CONTENT_TYPE_JSON
              + EOL
              + EOL); //$NON-NLS-1$
      out.flush();
      JSONObject getURIs = new Diff(getURI(request), db).toJSON();
      JsonURIUnqualificationStrategy.ALL.run(request, getURIs);

      out.write(getURIs.toString());
      out.write(EOL + "--" + boundary + EOL); // $NON-NLS-1$
      out.write(ProtocolConstants.HEADER_CONTENT_TYPE + ": plain/text" + EOL + EOL); // $NON-NLS-1$
      out.flush();
      handleGetDiff(request, response, db, scope, pattern, outputStream);
      out.write(EOL);
      out.flush();
    } finally {
      IOUtilities.safeClose(out);
    }
    return true;
  }
  @Test
  public void testGetOthersClones() throws Exception {
    // my clone
    URI workspaceLocation = createWorkspace(getMethodName());
    String workspaceId = getWorkspaceId(workspaceLocation);
    JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), null);
    IPath clonePath =
        new Path("file").append(project.getString(ProtocolConstants.KEY_ID)).makeAbsolute();
    clone(clonePath);

    WebRequest request = listGitClonesRequest(workspaceId, null);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    JSONObject clones = new JSONObject(response.getText());
    JSONArray clonesArray = clones.getJSONArray(ProtocolConstants.KEY_CHILDREN);
    assertEquals(1, clonesArray.length());

    createUser("bob", "bob");
    // URI bobWorkspaceLocation = createWorkspace(getMethodName() + "bob");
    String workspaceName = getClass().getName() + "#" + getMethodName() + "bob";
    request = new PostMethodWebRequest(SERVER_LOCATION + "/workspace");
    request.setHeaderField(ProtocolConstants.HEADER_SLUG, workspaceName);
    request.setHeaderField(ProtocolConstants.HEADER_ORION_VERSION, "1");
    setAuthentication(request, "bob", "bob");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    URI bobWorkspaceLocation =
        URI.create(response.getHeaderField(ProtocolConstants.HEADER_LOCATION));

    // String bobWorkspaceId = getWorkspaceId(bobWorkspaceLocation);
    request = new GetMethodWebRequest(bobWorkspaceLocation.toString());
    request.setHeaderField(ProtocolConstants.HEADER_ORION_VERSION, "1");
    setAuthentication(request, "bob", "bob");
    response = webConversation.getResponse(request);

    // JSONObject bobProject = createProjectOrLink(bobWorkspaceLocation, getMethodName() + "bob",
    // null);
    JSONObject body = new JSONObject();
    request =
        new PostMethodWebRequest(
            bobWorkspaceLocation.toString(), IOUtilities.toInputStream(body.toString()), "UTF-8");
    request.setHeaderField(ProtocolConstants.HEADER_SLUG, getMethodName() + "bob");
    request.setHeaderField(ProtocolConstants.HEADER_ORION_VERSION, "1");
    setAuthentication(request, "bob", "bob");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
    JSONObject bobProject = new JSONObject(response.getText());
    assertEquals(getMethodName() + "bob", bobProject.getString(ProtocolConstants.KEY_NAME));
    String bobProjectId = bobProject.optString(ProtocolConstants.KEY_ID, null);
    assertNotNull(bobProjectId);

    IPath bobClonePath = new Path("file").append(bobProjectId).makeAbsolute();

    // bob's clone
    URIish uri = new URIish(gitDir.toURI().toURL());
    request = getPostGitCloneRequest(uri, null, bobClonePath, null, null, null);
    setAuthentication(request, "bob", "bob");
    response = webConversation.getResponse(request);
    response = waitForTaskCompletionObjectResponse(response, "bob", "bob");
    String cloneLocation = response.getHeaderField(ProtocolConstants.HEADER_LOCATION);
    if (cloneLocation == null) {
      JSONObject taskResp = new JSONObject(response.getText());
      assertTrue(taskResp.has(ProtocolConstants.KEY_LOCATION));
      cloneLocation = taskResp.getString(ProtocolConstants.KEY_LOCATION);
    }
    assertNotNull(cloneLocation);

    // validate the clone metadata
    request = getGetRequest(cloneLocation);
    setAuthentication(request, "bob", "bob");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // list my clones again
    request = listGitClonesRequest(workspaceId, null);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    clones = new JSONObject(response.getText());
    clonesArray = clones.getJSONArray(ProtocolConstants.KEY_CHILDREN);
    assertEquals(1, clonesArray.length()); // nothing has been added

    // try to get Bob's clone
    request = getGetRequest(cloneLocation);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getResponseCode());
  }