Example #1
0
  private boolean handleDelete(
      HttpServletRequest request, HttpServletResponse response, String pathString)
      throws GitAPIException, CoreException, IOException, ServletException {
    IPath path = pathString == null ? Path.EMPTY : new Path(pathString);
    // expected path format is /file/{workspaceId}/{projectId}[/{directoryPath}]
    if (path.segment(0).equals("file") && path.segmentCount() > 2) { // $NON-NLS-1$

      // make sure a clone is addressed
      WebProject webProject = GitUtils.projectFromPath(path);
      if (webProject != null && isAccessAllowed(request.getRemoteUser(), webProject)) {
        File gitDir = GitUtils.getGitDirs(path, Traverse.CURRENT).values().iterator().next();
        Repository repo = new FileRepository(gitDir);
        repo.close();
        FileUtils.delete(repo.getWorkTree(), FileUtils.RECURSIVE | FileUtils.RETRY);
        if (path.segmentCount() == 3)
          return statusHandler.handleRequest(
              request, response, removeProject(request.getRemoteUser(), webProject));
        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));
    }
    String msg = NLS.bind("Invalid delete request {0}", pathString);
    return statusHandler.handleRequest(
        request,
        response,
        new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
  }
  public PagedResult<Repository> readRepositories(String source) throws ReviewboardException {

    try {
      JSONObject rootObject = checkedGetJSonRootObject(source);

      int totalResults = rootObject.getInt("total_results");

      JSONArray jsonRepositories = rootObject.getJSONArray("repositories");

      List<Repository> repositories = new ArrayList<Repository>();

      for (int i = 0; i < jsonRepositories.length(); i++) {

        JSONObject jsonRepository = jsonRepositories.getJSONObject(i);

        Repository repository = new Repository();
        repository.setId(jsonRepository.getInt("id"));
        repository.setName(jsonRepository.getString("name"));
        repository.setTool(RepositoryType.fromDisplayName(jsonRepository.getString("tool")));
        repository.setPath(jsonRepository.getString("path"));

        repositories.add(repository);
      }

      return PagedResult.create(repositories, totalResults);
    } catch (JSONException e) {
      throw new ReviewboardException(e.getMessage(), e);
    }
  }
Example #3
0
  /**
   * Resolves a module id to a package resource. If module id consists of just one term and resolves
   * to a package directory, the main module of the package is returned. If the module id consists
   * of several terms and the first term resolves to a package directory, the remaining part of the
   * module id is resolved against the "lib" directory of the package.
   *
   * @link http://nodejs.org/docs/v0.4.4/api/modules.html#folders_as_Modules
   * @param moduleName the name of the package to load
   * @param localPath the path of the resource issuing this call
   * @return the location of the package's main module
   * @throws IOException an unrecoverable I/O exception occurred while reading the package
   */
  protected Resource loadPackage(String moduleName, Repository localPath) throws IOException {

    int slash = 0;
    String packageName, remainingName;

    do {
      slash = moduleName.indexOf('/', slash + 1);
      if (slash == -1) {
        packageName = moduleName;
        remainingName = null;
      } else {
        packageName = moduleName.substring(0, slash);
        if (".".equals(packageName) || "..".equals(packageName)) continue;
        remainingName = moduleName.substring(slash + 1);
      }

      Resource json = findResource(packageName + "/package.json", null, localPath);

      if (json != null && json.exists()) {

        Scriptable obj = parseJsonResource(json);
        Repository parent = json.getParentRepository();
        String moduleId;
        Resource res;

        if (remainingName == null) {
          // get the main module of this package
          moduleId = getStringProperty(obj, "main", null);
          if (moduleId != null) {
            // optimize for the common case where main module
            // property links to the exact file name
            res = parent.getResource(moduleId);
            if (res != null && res.exists()) return res;
          }
        } else {
          // map remaining name to libs directory
          String lib = "lib";
          Object dirs = ScriptableObject.getProperty(obj, "directories");
          if (dirs instanceof Scriptable) {
            lib = getStringProperty((Scriptable) dirs, "lib", "lib");
          }
          moduleId = lib + "/" + remainingName;
        }

        if (moduleId != null) {
          for (ModuleLoader loader : loaders) {
            res = parent.getResource(moduleId + loader.getExtension());
            if (res != null && res.exists()) return res;
          }
          if (remainingName != null) {
            res = parent.getResource(moduleId);
            if (res != null && res.exists()) return res;
          }
        }
      }

    } while (slash != -1);

    return findResource(moduleName + "/index", loaders, localPath);
  }
Example #4
0
 @Override
 protected IStatus performJob() {
   try {
     // list all tags
     File gitDir = GitUtils.getGitDir(path);
     Repository db = new FileRepository(gitDir);
     Git git = new Git(db);
     List<Ref> refs = git.tagList().call();
     JSONObject result = new JSONObject();
     List<Tag> tags = new ArrayList<Tag>();
     for (Ref ref : refs) {
       Tag tag = new Tag(cloneLocation, db, ref);
       tags.add(tag);
     }
     Collections.sort(tags, Tag.COMPARATOR);
     JSONArray children = new JSONArray();
     int firstTag = pageSize > 0 ? pageSize * (pageNo - 1) : 0;
     int lastTag = pageSize > 0 ? firstTag + pageSize - 1 : tags.size() - 1;
     lastTag = lastTag > tags.size() - 1 ? tags.size() - 1 : lastTag;
     if (pageNo > 1 && baseLocation != null) {
       String prev = baseLocation + "?page=" + (pageNo - 1) + "&pageSize=" + pageSize;
       if (commitsSize > 0) {
         prev += "&" + GitConstants.KEY_TAG_COMMITS + "=" + commitsSize;
       }
       result.put(ProtocolConstants.KEY_PREVIOUS_LOCATION, prev);
     }
     if (lastTag < tags.size() - 1) {
       String next = baseLocation + "?page=" + (pageNo + 1) + "&pageSize=" + pageSize;
       if (commitsSize > 0) {
         next += "&" + GitConstants.KEY_TAG_COMMITS + "=" + commitsSize;
       }
       result.put(ProtocolConstants.KEY_NEXT_LOCATION, next);
     }
     for (int i = firstTag; i <= lastTag; i++) {
       Tag tag = tags.get(i);
       if (this.commitsSize == 0) {
         children.put(tag.toJSON());
       } else {
         // add info about commits if requested
         LogCommand lc = git.log();
         String toCommitName = tag.getRevCommitName();
         ObjectId toCommitId = db.resolve(toCommitName);
         Ref toCommitRef = db.getRef(toCommitName);
         toCommitId = getCommitObjectId(db, toCommitId);
         lc.add(toCommitId);
         lc.setMaxCount(this.commitsSize);
         Iterable<RevCommit> commits = lc.call();
         Log log = new Log(cloneLocation, db, commits, null, null, toCommitRef);
         children.put(tag.toJSON(log.toJSON(1, commitsSize)));
       }
     }
     result.put(ProtocolConstants.KEY_CHILDREN, children);
     result.put(ProtocolConstants.KEY_TYPE, Tag.TYPE);
     return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result);
   } catch (Exception e) {
     String msg = NLS.bind("An error occured when listing tags for {0}", path);
     return new Status(IStatus.ERROR, GitActivator.PI_GIT, msg, e);
   }
 }
 @Override
 public void setSender(ECKey senderPrivateKey) {
   txSender = senderPrivateKey;
   if (!getBlockchain().getRepository().isExist(senderPrivateKey.getAddress())) {
     Repository repository = getBlockchain().getRepository();
     Repository track = repository.startTracking();
     track.createAccount(senderPrivateKey.getAddress());
     track.commit();
   }
 }
  private boolean cherryPick(
      HttpServletRequest request,
      HttpServletResponse response,
      Repository db,
      String commitToCherryPick)
      throws ServletException, JSONException {
    RevWalk revWalk = new RevWalk(db);
    try {

      Ref headRef = db.getRef(Constants.HEAD);
      if (headRef == null)
        return statusHandler.handleRequest(
            request,
            response,
            new ServerStatus(
                IStatus.ERROR,
                HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "An error occured when cherry-picking.",
                null));
      RevCommit head = revWalk.parseCommit(headRef.getObjectId());

      ObjectId objectId = db.resolve(commitToCherryPick);
      Git git = new Git(db);
      CherryPickResult cherryPickResult = git.cherryPick().include(objectId).call();
      RevCommit newHead = cherryPickResult.getNewHead();

      JSONObject result = new JSONObject();
      result.put(GitConstants.KEY_RESULT, cherryPickResult.getStatus().name());
      result.put(GitConstants.KEY_HEAD_UPDATED, !head.equals(newHead));
      OrionServlet.writeJSONResponse(
          request, response, result, JsonURIUnqualificationStrategy.ALL_NO_GIT);
      return true;
    } catch (IOException e) {
      return statusHandler.handleRequest(
          request,
          response,
          new ServerStatus(
              IStatus.ERROR,
              HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
              "An error occured when cherry-picking.",
              e));
    } catch (GitAPIException e) {
      return statusHandler.handleRequest(
          request,
          response,
          new ServerStatus(
              IStatus.ERROR,
              HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
              "An error occured when cherry-picking.",
              e));
    } finally {
      revWalk.release();
    }
  }
 private AbstractTreeIterator getTreeIterator(Repository db, String name) throws IOException {
   final ObjectId id = db.resolve(name);
   if (id == null) throw new IllegalArgumentException(name);
   final CanonicalTreeParser p = new CanonicalTreeParser();
   final ObjectReader or = db.newObjectReader();
   try {
     p.reset(or, new RevWalk(db).parseTree(id));
     return p;
   } finally {
     or.release();
   }
 }
 public static Set<String> loadVersionTagList(
     Repository repository, String versionTagNamePattern) {
   Set<String> versionTagList = new HashSet<String>();
   if (versionTagNamePattern != null) {
     versionTagList = new HashSet<String>();
     for (String tagName : repository.getTags().keySet()) {
       if (tagName.matches(versionTagNamePattern)) {
         versionTagList.add(tagName);
       }
     }
   } else {
     versionTagList = repository.getTags().keySet();
   }
   return versionTagList;
 }
Example #9
0
 private boolean isLocalBranch(Git git, String branch) throws GitAPIException {
   List<Ref> branches = git.branchList().call();
   for (Ref ref : branches) {
     if (Repository.shortenRefName(ref.getName()).equals(branch)) return true;
   }
   return false;
 }
Example #10
0
 /**
  * Search for a resource in a local path, or the main repository path.
  *
  * @param path the resource name
  * @param loaders optional list of module loaders
  * @param localRoot a repository to look first
  * @return the resource
  * @throws IOException if an I/O error occurred
  */
 public Resource findResource(String path, ModuleLoader[] loaders, Repository localRoot)
     throws IOException {
   // Note: as an extension to the CommonJS modules API
   // we allow absolute module paths for resources
   File file = new File(path);
   if (file.isAbsolute()) {
     Resource res;
     outer:
     if (loaders != null) {
       // loaders must contain at least one loader
       assert loaders.length > 0 && loaders[0] != null;
       for (ModuleLoader loader : loaders) {
         res = new FileResource(path + loader.getExtension());
         if (res.exists()) {
           break outer;
         }
       }
       res = new FileResource(path + loaders[0].getExtension());
     } else {
       res = new FileResource(file);
     }
     res.setAbsolute(true);
     return res;
   } else if (localRoot != null && (path.startsWith("./") || path.startsWith("../"))) {
     String newpath = localRoot.getRelativePath() + path;
     return findResource(newpath, loaders, null);
   } else {
     return config.getResource(normalizePath(path), loaders);
   }
 }
Example #11
0
 /**
  * Search for a repository in the local path, or the main repository path.
  *
  * @param path the repository name
  * @param localPath a repository to look first
  * @return the repository
  * @throws IOException if an I/O error occurred
  */
 public Repository findRepository(String path, Repository localPath) throws IOException {
   // To be consistent, always return absolute repository if path is absolute
   // if we make this dependent on whether files exist we introduce a lot of
   // vague and undetermined behaviour.
   File file = new File(path);
   if (file.isAbsolute()) {
     return new FileRepository(file);
   }
   if (localPath != null) {
     Repository repository = localPath.getChildRepository(path);
     if (repository != null && repository.exists()) {
       return repository;
     }
   }
   return config.getRepository(normalizePath(path));
 }
Example #12
0
  CFG createCFG(String className) throws ClassNotFoundException {
    CFG cfg = new CFG();
    JavaClass jc = Repository.lookupClass(className);
    ClassGen cg = new ClassGen(jc);
    ConstantPoolGen cpg = cg.getConstantPool();
    for (Method m : cg.getMethods()) {
      MethodGen mg = new MethodGen(m, cg.getClassName(), cpg);
      InstructionList il = mg.getInstructionList();
      InstructionHandle[] handles = il.getInstructionHandles();
      int prev = 0;
      for (InstructionHandle ih : handles) {
        int position = ih.getPosition();
        cfg.addNode(position, m, jc);
        Instruction inst = ih.getInstruction();

        boolean br = inst.getName().contains("if") || inst.getName().contains("goto");
        boolean ret = inst.getName().contains("return");
        boolean stat = inst.getName().contains("invokestatic");
        int len = inst.getLength();

        if (stat) {
          int index = inst.toString(true).indexOf(" ");
          String name = inst.toString(true).substring(index + 1);
          int tar = Integer.valueOf(name);
          INVOKESTATIC inv = new INVOKESTATIC(tar);
          name = inv.getMethodName(cpg);

          Method m2 = null;
          Method[] tm = cg.getMethods();
          for (int i = 0; i < tm.length; i++) {
            if (tm[i].getName().equals(name)) {
              m2 = tm[i];
            }
          }
          cfg.addEdge(position, m, jc, 0, m2, jc);
          cfg.addEdge(-1, m2, jc, position + len, m, jc);
        }

        if (!ret && !stat) {
          cfg.addEdge(position, position + len, m, jc);
        }
        if (br) {
          cfg.addEdge(position, position + len, m, jc);
          IF_ICMPGE comp = new IF_ICMPGE(ih);
          String name = comp.getTarget().toString(false);
          int index = name.indexOf(">");
          name = name.substring(index + 2);
          int tar = Integer.valueOf(name);
          cfg.addEdge(position, tar, m, jc);
        }
        if (ret) {
          cfg.addEdge(position, -1, m, jc);
        }

        prev = position;
      }
      System.out.println(cfg.toString());
    }
    return cfg;
  }
  @Override
  public Block createForkBlock(Block parent) {
    try {
      List<Transaction> txes = new ArrayList<>();
      Map<ByteArrayWrapper, Long> nonces = new HashMap<>();
      Repository repoSnapshot =
          getBlockchain().getRepository().getSnapshotTo(parent.getStateRoot());
      for (PendingTx tx : submittedTxes) {
        ByteArrayWrapper senderW = new ByteArrayWrapper(tx.sender.getAddress());
        Long nonce = nonces.get(senderW);
        if (nonce == null) {
          BigInteger bcNonce = repoSnapshot.getNonce(tx.sender.getAddress());
          nonce = bcNonce.longValue();
        }
        nonces.put(senderW, nonce + 1);

        byte[] toAddress =
            tx.targetContract != null ? tx.targetContract.getAddress() : tx.toAddress;

        Transaction transaction =
            new Transaction(
                ByteUtil.longToBytesNoLeadZeroes(nonce),
                ByteUtil.longToBytesNoLeadZeroes(gasPrice),
                ByteUtil.longToBytesNoLeadZeroes(gasLimit),
                toAddress,
                ByteUtil.bigIntegerToBytes(tx.value),
                tx.data);
        transaction.sign(tx.sender.getPrivKeyBytes());
        if (tx.createdContract != null) {
          tx.createdContract.setAddress(transaction.getContractAddress());
        }
        txes.add(transaction);
      }
      Block b = getBlockchain().createNewBlock(parent, txes, Collections.EMPTY_LIST);
      Ethash.getForBlock(b.getNumber()).mineLight(b).get();
      ImportResult importResult = getBlockchain().tryToConnect(b);
      if (importResult != ImportResult.IMPORTED_BEST
          && importResult != ImportResult.IMPORTED_NOT_BEST) {
        throw new RuntimeException(
            "Invalid block import result " + importResult + " for block " + b);
      }
      submittedTxes.clear();
      return b;
    } catch (InterruptedException | ExecutionException e) {
      throw new RuntimeException(e);
    }
  }
  private boolean tag(
      HttpServletRequest request,
      HttpServletResponse response,
      Repository db,
      String commitId,
      String tagName,
      boolean isRoot)
      throws JSONException, URISyntaxException, ServletException {
    Git git = new Git(db);
    RevWalk walk = new RevWalk(db);
    try {
      ObjectId objectId = db.resolve(commitId);
      RevCommit revCommit = walk.lookupCommit(objectId);
      walk.parseBody(revCommit);

      GitTagHandlerV1.tag(git, revCommit, tagName);

      URI cloneLocation =
          BaseToCloneConverter.getCloneLocation(
              getURI(request), BaseToCloneConverter.COMMIT_REFRANGE);
      Commit commit = new Commit(cloneLocation, db, revCommit, null);
      JSONObject result = commit.toJSON();
      OrionServlet.writeJSONResponse(
          request, response, result, JsonURIUnqualificationStrategy.ALL_NO_GIT);
      return true;
    } catch (IOException e) {
      return statusHandler.handleRequest(
          request,
          response,
          new ServerStatus(
              IStatus.ERROR,
              HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
              "An error occured when tagging.",
              e));
    } catch (GitAPIException e) {
      return statusHandler.handleRequest(
          request,
          response,
          new ServerStatus(
              IStatus.ERROR,
              HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
              "An error occured when tagging.",
              e));
    } catch (CoreException e) {
      return statusHandler.handleRequest(
          request,
          response,
          new ServerStatus(
              IStatus.ERROR,
              HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
              "An error occured when tagging.",
              e));
    } finally {
      walk.dispose();
    }
  }
  protected static RevCommit resolveCommitIdByTagName(Repository repository, String tagName)
      throws IOException, GitAPIException {
    if (tagName == null || tagName.isEmpty()) return null;
    RevCommit revCommit = null;
    Map<String, Ref> tagMap = repository.getTags();
    Ref ref = tagMap.get(tagName);
    if (ref != null) {
      RevWalk walk = new RevWalk(repository);
      // some reduce memory effors as described in jgit user guide
      walk.setRetainBody(false);
      ObjectId from;

      from = repository.resolve("refs/heads/master");
      if (from == null) {
        Git git = new Git(repository);
        String lastTagName = git.describe().call();
        from = repository.resolve("refs/tags/" + lastTagName);
      }
      ObjectId to = repository.resolve("refs/remotes/origin/master");

      if (from == null) {
        throw new IllegalStateException("cannot determinate start commit");
      }
      walk.markStart(walk.parseCommit(from));
      walk.markUninteresting(walk.parseCommit(to));
      try {

        RevObject revObject = walk.parseAny(ref.getObjectId());
        if (revObject != null) {
          revCommit = walk.parseCommit(revObject.getId());
        }

      } finally {
        walk.close();
      }
    }

    return revCommit;
  }
    @Override
    public Object[] callConstFunction(Block callBlock, String functionName, Object... args) {

      Transaction tx =
          CallTransaction.createCallTransaction(
              0,
              0,
              100000000000000L,
              Hex.toHexString(getAddress()),
              0,
              contract.getByName(functionName),
              args);
      tx.sign(new byte[32]);

      Repository repository =
          getBlockchain().getRepository().getSnapshotTo(callBlock.getStateRoot()).startTracking();

      try {
        org.ethereum.core.TransactionExecutor executor =
            new org.ethereum.core.TransactionExecutor(
                    tx,
                    callBlock.getCoinbase(),
                    repository,
                    getBlockchain().getBlockStore(),
                    getBlockchain().getProgramInvokeFactory(),
                    callBlock)
                .setLocalCall(true);

        executor.init();
        executor.execute();
        executor.go();
        executor.finalization();

        return contract.getByName(functionName).decodeResult(executor.getResult().getHReturn());
      } finally {
        repository.rollback();
      }
    }
Example #17
0
  // SAA overrides this method
  // here we remove scnenarios as we use them to make sure each policy is generated using its own
  // scenarios.
  // so we call getIdealBids which uses m_numScenarios most recent scenarios and then remove them so
  // the next call to getIdealBids gets different scenarios
  public ArrayList<Bid> getBids() {
    Misc.myassert(!(numPolicies == 1 && numEvaluations != 0));

    ArrayList<Bid>[] policies = new ArrayList[numPolicies];
    for (int i = 0; i < numPolicies; i++) {
      policies[i] = getIdealBids();
      repository.removeXMostRecent(numScenarios);
    }

    if (numPolicies == 1) return policies[0];

    Misc.println("Algorithm.getBids : evaluating more than 1 policies...");

    // evaluation scenarios
    Priceline[] evaluationScenarios = repository.removeXMostRecent(numEvaluations);

    // evaluate policies
    int bestPolicy = -1;
    float bestEvaluation = 0;
    for (int i = 0; i < numPolicies; i++) {

      float evaluation = evaluate(policies[i], evaluationScenarios);
      if (bestPolicy == -1 || evaluation > bestEvaluation) {
        bestPolicy = i;
        bestEvaluation = evaluation;
      }
    }

    // this is to make sure we do not generate extra scenarios.
    // also see the comment at the top of the method: we need to generate enough scenarios otherwise
    // we won't have enough for all policies - vn
    Misc.myassert(repository.getAvailableScenarios().length == 0);

    Misc.println("Algorithm.getBids : best policy = " + bestPolicy);

    return policies[bestPolicy];
  }
  public static Set<String> extractJiraIssues(
      Repository repository, String sinceTagName, String untilTagName, String pattern)
      throws IOException, GitAPIException {
    Git git = new Git(repository);
    RevCommit startCommitId = resolveCommitIdByTagName(repository, sinceTagName);
    if (startCommitId == null) {
      throw new IOException("cannot resolveCommitIdByTagName by  " + sinceTagName);
    }
    ObjectId endCommitId = resolveCommitIdByTagName(repository, untilTagName);
    if (endCommitId == null) {
      endCommitId = repository.resolve(Constants.HEAD);
    }
    Iterable<RevCommit> commits = git.log().addRange(startCommitId, endCommitId).call();

    return extractJiraIssues(pattern, commits);
  }
  private BlockchainImpl createBlockchain(Genesis genesis) {
    IndexedBlockStore blockStore = new IndexedBlockStore();
    blockStore.init(new HashMapDB(), new HashMapDB());

    Repository repository = new RepositoryImpl(new HashMapDB(), new HashMapDB());

    ProgramInvokeFactoryImpl programInvokeFactory = new ProgramInvokeFactoryImpl();
    EthereumListenerAdapter listener = new EthereumListenerAdapter();

    BlockchainImpl blockchain = new BlockchainImpl(blockStore, repository);
    blockchain.setParentHeaderValidator(new DependentBlockHeaderRuleAdapter());
    blockchain.setProgramInvokeFactory(programInvokeFactory);
    programInvokeFactory.setBlockchain(blockchain);

    blockchain.byTest = true;

    PendingStateImpl pendingState = new PendingStateImpl(listener, blockchain);

    pendingState.init();

    pendingState.setBlockchain(blockchain);
    blockchain.setPendingState(pendingState);

    Repository track = repository.startTracking();
    for (ByteArrayWrapper key : genesis.getPremine().keySet()) {
      track.createAccount(key.getData());
      track.addBalance(key.getData(), genesis.getPremine().get(key).getBalance());
    }
    for (Pair<byte[], BigInteger> acc : initialBallances) {
      track.createAccount(acc.getLeft());
      track.addBalance(acc.getLeft(), acc.getRight());
    }

    track.commit();

    blockStore.saveBlock(genesis, genesis.getCumulativeDifficulty(), true);

    blockchain.setBestBlock(genesis);
    blockchain.setTotalDifficulty(genesis.getCumulativeDifficulty());

    return blockchain;
  }
 private boolean merge(
     HttpServletRequest request,
     HttpServletResponse response,
     Repository db,
     String commitToMerge,
     boolean squash)
     throws ServletException, JSONException {
   try {
     ObjectId objectId = db.resolve(commitToMerge);
     Git git = new Git(db);
     MergeResult mergeResult = git.merge().setSquash(squash).include(objectId).call();
     JSONObject result = new JSONObject();
     result.put(GitConstants.KEY_RESULT, mergeResult.getMergeStatus().name());
     if (mergeResult.getFailingPaths() != null && !mergeResult.getFailingPaths().isEmpty())
       result.put(GitConstants.KEY_FAILING_PATHS, mergeResult.getFailingPaths());
     OrionServlet.writeJSONResponse(
         request, response, result, JsonURIUnqualificationStrategy.ALL_NO_GIT);
     return true;
   } catch (CheckoutConflictException e) {
     return workaroundBug356918(request, response, e);
   } catch (IOException e) {
     return statusHandler.handleRequest(
         request,
         response,
         new ServerStatus(
             IStatus.ERROR,
             HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
             "An error occured when merging.",
             e));
   } catch (GitAPIException e) {
     return statusHandler.handleRequest(
         request,
         response,
         new ServerStatus(
             IStatus.ERROR,
             HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
             "An error occured when merging.",
             e));
   }
 }
  private boolean handleGetCommitBody(
      HttpServletRequest request,
      HttpServletResponse response,
      Repository db,
      String ref,
      String pattern)
      throws IOException, ServletException, CoreException {
    ObjectId refId = db.resolve(ref);
    if (refId == null) {
      String msg = NLS.bind("Failed to get commit body for ref {0}", ref);
      return statusHandler.handleRequest(
          request,
          response,
          new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
    }
    RevWalk walk = new RevWalk(db);
    walk.setTreeFilter(
        AndTreeFilter.create(
            PathFilterGroup.createFromStrings(Collections.singleton(pattern)),
            TreeFilter.ANY_DIFF));
    RevCommit revCommit = walk.parseCommit(refId);
    walk.dispose();

    Commit commit = new Commit(null /* not needed */, db, revCommit, pattern);
    ObjectStream stream = commit.toObjectStream();
    if (stream == null) {
      String msg = NLS.bind("Commit body for ref {0} not found", ref);
      return statusHandler.handleRequest(
          request,
          response,
          new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null));
    }
    IOUtilities.pipe(stream, response.getOutputStream(), true, false);

    return true;
  }
Example #22
0
 /**
  * Return a shell scope for interactive evaluation
  *
  * @return a shell scope
  * @throws IOException an I/O related exception occurred
  */
 public Scriptable getShellScope(RingoWorker worker) throws IOException {
   Repository repository = new FileRepository("");
   repository.setAbsolute(true);
   Scriptable protoScope = mainScope != null ? mainScope : globalScope;
   return new ModuleScope("<shell>", repository, protoScope, worker);
 }
  private boolean revert(
      HttpServletRequest request,
      HttpServletResponse response,
      Repository db,
      String commitToRevert)
      throws ServletException, JSONException {
    RevWalk revWalk = new RevWalk(db);
    try {

      Ref headRef = db.getRef(Constants.HEAD);
      if (headRef == null)
        return statusHandler.handleRequest(
            request,
            response,
            new ServerStatus(
                IStatus.ERROR,
                HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "An error occured when reverting.",
                null));

      ObjectId objectId = db.resolve(commitToRevert);
      Git git = new Git(db);

      RevertCommand revertCommand = git.revert().include(objectId);
      RevCommit revertedCommit = revertCommand.call();

      if (revertedCommit == null) {
        JSONObject result = new JSONObject();
        result.put(GitConstants.KEY_RESULT, "FAILURE"); // $NON-NLS-1$
        OrionServlet.writeJSONResponse(
            request, response, result, JsonURIUnqualificationStrategy.ALL_NO_GIT);
        return true;
      }

      JSONObject result = new JSONObject();
      result.put(GitConstants.KEY_RESULT, "OK"); // $NON-NLS-1$
      OrionServlet.writeJSONResponse(
          request, response, result, JsonURIUnqualificationStrategy.ALL_NO_GIT);
      return true;
    } catch (IOException e) {
      return statusHandler.handleRequest(
          request,
          response,
          new ServerStatus(
              IStatus.ERROR,
              HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
              "An error occured when reverting.",
              e));
    } catch (GitAPIException e) {
      return statusHandler.handleRequest(
          request,
          response,
          new ServerStatus(
              IStatus.ERROR,
              HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
              "An error occured when reverting.",
              e));
    } finally {
      revWalk.release();
    }
  }
 private boolean rebase(
     HttpServletRequest request,
     HttpServletResponse response,
     Repository db,
     String commitToRebase,
     String rebaseOperation)
     throws ServletException, JSONException, AmbiguousObjectException, IOException {
   JSONObject result = new JSONObject();
   try {
     Git git = new Git(db);
     RebaseCommand rebase = git.rebase();
     Operation operation;
     if (rebaseOperation != null) {
       operation = Operation.valueOf(rebaseOperation);
     } else {
       operation = Operation.BEGIN;
     }
     if (commitToRebase != null && !commitToRebase.isEmpty()) {
       ObjectId objectId = db.resolve(commitToRebase);
       rebase.setUpstream(objectId);
     } else if (operation.equals(Operation.BEGIN)) {
       return statusHandler.handleRequest(
           request,
           response,
           new ServerStatus(
               IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Missing commit refId.", null));
     }
     rebase.setOperation(operation);
     RebaseResult rebaseResult = rebase.call();
     result.put(GitConstants.KEY_RESULT, rebaseResult.getStatus().name());
   } catch (UnmergedPathsException e) {
     // this error should be handled by client, so return a proper status
     result.put(GitConstants.KEY_RESULT, AdditionalRebaseStatus.FAILED_UNMERGED_PATHS.name());
   } catch (WrongRepositoryStateException e) {
     // this error should be handled by client, so return a proper status
     result.put(
         GitConstants.KEY_RESULT, AdditionalRebaseStatus.FAILED_WRONG_REPOSITORY_STATE.name());
   } catch (IllegalArgumentException e) {
     return statusHandler.handleRequest(
         request,
         response,
         new ServerStatus(
             IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Invalid rebase operation.", e));
   } catch (GitAPIException e) {
     // get cause and try to handle
     if (e.getCause() instanceof org.eclipse.jgit.errors.CheckoutConflictException) {
       // this error should be handled by client, so return a proper status
       result.put(GitConstants.KEY_RESULT, AdditionalRebaseStatus.FAILED_PENDING_CHANGES.name());
     } else {
       return statusHandler.handleRequest(
           request,
           response,
           new ServerStatus(
               IStatus.ERROR,
               HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
               "An error occured when rebasing.",
               e));
     }
   }
   OrionServlet.writeJSONResponse(
       request, response, result, JsonURIUnqualificationStrategy.ALL_NO_GIT);
   return true;
 }
  @Override
  protected boolean handlePost(RequestInfo requestInfo) throws ServletException {
    String gitSegment = requestInfo.gitSegment;
    HttpServletRequest request = requestInfo.request;
    HttpServletResponse response = requestInfo.response;
    Repository db = requestInfo.db;
    String pattern = requestInfo.relativePath;
    JSONObject requestObject = requestInfo.getJSONRequest();
    try {
      String commitToMerge = requestObject.optString(GitConstants.KEY_MERGE, null);
      if (commitToMerge != null) {
        boolean squash = requestObject.optBoolean(GitConstants.KEY_SQUASH, false);
        return merge(request, response, db, commitToMerge, squash);
      }

      String commitToRebase = requestObject.optString(GitConstants.KEY_REBASE, null);
      String rebaseOperation = requestObject.optString(GitConstants.KEY_OPERATION, null);
      if (commitToRebase != null) {
        return rebase(request, response, db, commitToRebase, rebaseOperation);
      }

      String commitToCherryPick = requestObject.optString(GitConstants.KEY_CHERRY_PICK, null);
      if (commitToCherryPick != null) {
        return cherryPick(request, response, db, commitToCherryPick);
      }

      String commitToRevert = requestObject.optString(GitConstants.KEY_REVERT, null);
      if (commitToRevert != null) {
        return revert(request, response, db, commitToRevert);
      }

      String newCommit = requestObject.optString(GitConstants.KEY_COMMIT_NEW, null);
      if (newCommit != null) return identifyNewCommitResource(request, response, db, newCommit);

      String reviewReqLogin = requestObject.optString(GitConstants.KEY_REVIEW_REQ_NOTIFY_LOGIN);
      if (reviewReqLogin != null && reviewReqLogin.length() != 0) {
        String reviewReqUrl = requestObject.optString(GitConstants.KEY_REVIEW_REQ_URL);
        String ReviewReqCommit = requestObject.optString(GitConstants.KEY_REVIEW_REQ_COMMIT);
        String ReviewReqAuthorName =
            requestObject.optString(GitConstants.KEY_REVIEW_REQ_AUTHOR_NAME);
        String ReviewMessage = requestObject.optString(GitConstants.KEY_REVIEW_REQ_MESSAGE);
        return sendNotification(
            request,
            response,
            db,
            reviewReqLogin,
            ReviewReqCommit,
            reviewReqUrl,
            ReviewReqAuthorName,
            ReviewMessage);
      }

      ObjectId refId = db.resolve(gitSegment);
      if (refId == null || !Constants.HEAD.equals(gitSegment)) {
        String msg = NLS.bind("Commit failed. Ref must be HEAD and is {0}", gitSegment);
        return statusHandler.handleRequest(
            request,
            response,
            new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
      }

      String message = requestObject.optString(GitConstants.KEY_COMMIT_MESSAGE, null);
      if (message == null || message.isEmpty()) {
        return statusHandler.handleRequest(
            request,
            response,
            new ServerStatus(
                IStatus.ERROR,
                HttpServletResponse.SC_BAD_REQUEST,
                "Missing commit message.",
                null));
      }

      Git git = new Git(db);
      CommitCommand cc = git.commit();
      Config config = git.getRepository().getConfig();

      boolean amend =
          Boolean.parseBoolean(requestObject.optString(GitConstants.KEY_COMMIT_AMEND, null));
      boolean insertChangeId =
          GitUtils.isGerrit(config)
              || Boolean.parseBoolean(requestObject.optString(GitConstants.KEY_CHANGE_ID, null));

      String committerName = requestObject.optString(GitConstants.KEY_COMMITTER_NAME, null);
      String committerEmail = requestObject.optString(GitConstants.KEY_COMMITTER_EMAIL, null);
      String authorName = requestObject.optString(GitConstants.KEY_AUTHOR_NAME, null);
      String authorEmail = requestObject.optString(GitConstants.KEY_AUTHOR_EMAIL, null);

      // workaround of a bug in JGit which causes invalid
      // support of null values of author/committer name/email, see bug 352984
      PersonIdent defPersonIdent = new PersonIdent(db);
      if (committerName == null) committerName = defPersonIdent.getName();
      if (committerEmail == null) committerEmail = defPersonIdent.getEmailAddress();
      if (authorName == null) authorName = committerName;
      if (authorEmail == null) authorEmail = committerEmail;
      cc.setCommitter(committerName, committerEmail);
      cc.setAuthor(authorName, authorEmail);
      if (insertChangeId) cc.setInsertChangeId(true);

      // support for committing by path: "git commit -o path"
      if (!pattern.isEmpty()) {
        cc.setOnly(pattern);
      }

      try {
        // "git commit [--amend] -m '{message}' [-a|{path}]"
        RevCommit lastCommit = cc.setAmend(amend).setMessage(message).call();

        URI cloneLocation =
            BaseToCloneConverter.getCloneLocation(
                getURI(request), BaseToCloneConverter.COMMIT_REFRANGE);
        Commit commit = new Commit(cloneLocation, db, lastCommit, pattern);
        JSONObject result = commit.toJSON();
        OrionServlet.writeJSONResponse(
            request, response, result, JsonURIUnqualificationStrategy.ALL_NO_GIT);
        return true;
      } catch (GitAPIException e) {
        return statusHandler.handleRequest(
            request,
            response,
            new ServerStatus(
                IStatus.ERROR,
                HttpServletResponse.SC_BAD_REQUEST,
                "An error occured when commiting.",
                e));
      } catch (UnmergedPathException e) {
        return statusHandler.handleRequest(
            request,
            response,
            new ServerStatus(
                IStatus.ERROR,
                HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "An internal error occured when commiting.",
                e));
      }
    } catch (Exception e) {
      return statusHandler.handleRequest(
          request,
          response,
          new ServerStatus(
              IStatus.ERROR,
              HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
              "An error occured when requesting a commit info.",
              e));
    }
  }
  private boolean handleGetCommitLog(
      HttpServletRequest request,
      HttpServletResponse response,
      IPath filePath,
      Repository db,
      String refIdsRange,
      String pattern)
      throws AmbiguousObjectException, IOException, ServletException, JSONException,
          URISyntaxException, CoreException {
    int page =
        request.getParameter("page") != null
            ? new Integer(request.getParameter("page")).intValue()
            : 0; //$NON-NLS-1$ //$NON-NLS-2$
    int pageSize =
        request.getParameter("pageSize") != null
            ? new Integer(request.getParameter("pageSize")).intValue()
            : PAGE_SIZE; //$NON-NLS-1$ //$NON-NLS-2$

    ObjectId toObjectId = null;
    ObjectId fromObjectId = null;

    Ref toRefId = null;
    Ref fromRefId = null;

    if (refIdsRange != null) {
      // git log <since>..<until>
      if (refIdsRange.contains("..")) { // $NON-NLS-1$
        String[] commits = refIdsRange.split("\\.\\."); // $NON-NLS-1$
        if (commits.length != 2) {
          String msg = NLS.bind("Failed to generate commit log for ref {0}", refIdsRange);
          return statusHandler.handleRequest(
              request,
              response,
              new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
        }

        fromObjectId = db.resolve(commits[0]);
        fromRefId = db.getRef(commits[0]);
        if (fromObjectId == null) {
          String msg = NLS.bind("Failed to generate commit log for ref {0}", commits[0]);
          return statusHandler.handleRequest(
              request,
              response,
              new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
        }

        toObjectId = db.resolve(commits[1]);
        toRefId = db.getRef(commits[1]);
        if (toObjectId == null) {
          String msg = NLS.bind("No ref or commit found: {0}", commits[1]);
          return statusHandler.handleRequest(
              request,
              response,
              new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null));
        }
      } else {
        toObjectId = db.resolve(refIdsRange);
        toRefId = db.getRef(refIdsRange);
        if (toObjectId == null) {
          String msg = NLS.bind("No ref or commit found: {0}", refIdsRange);
          return statusHandler.handleRequest(
              request,
              response,
              new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null));
        }
      }
      toObjectId = getCommitObjectId(db, toObjectId);
    }

    URI baseLocation = getURI(request);
    URI cloneLocation =
        BaseToCloneConverter.getCloneLocation(
            baseLocation,
            refIdsRange == null
                ? BaseToCloneConverter.COMMIT
                : BaseToCloneConverter.COMMIT_REFRANGE);

    LogJob job =
        new LogJob(
            TaskJobHandler.getUserId(request),
            filePath,
            cloneLocation,
            page,
            pageSize,
            toObjectId,
            fromObjectId,
            toRefId,
            fromRefId,
            refIdsRange,
            pattern);
    return TaskJobHandler.handleTaskJob(
        request, response, job, statusHandler, JsonURIUnqualificationStrategy.ALL_NO_GIT);
  }
  private boolean handleGetDiff(
      HttpServletRequest request,
      HttpServletResponse response,
      Repository db,
      String scope,
      String pattern,
      OutputStream out)
      throws Exception {
    Git git = new Git(db);
    DiffCommand diff = git.diff();
    diff.setOutputStream(new BufferedOutputStream(out));
    AbstractTreeIterator oldTree;
    AbstractTreeIterator newTree = new FileTreeIterator(db);
    if (scope.contains("..")) { // $NON-NLS-1$
      String[] commits = scope.split("\\.\\."); // $NON-NLS-1$
      if (commits.length != 2) {
        String msg = NLS.bind("Failed to generate diff for {0}", scope);
        return statusHandler.handleRequest(
            request,
            response,
            new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
      }
      oldTree = getTreeIterator(db, commits[0]);
      newTree = getTreeIterator(db, commits[1]);
    } else if (scope.equals(GitConstants.KEY_DIFF_CACHED)) {
      ObjectId head = db.resolve(Constants.HEAD + "^{tree}"); // $NON-NLS-1$
      if (head == null) {
        String msg = NLS.bind("Failed to generate diff for {0}, no HEAD", scope);
        return statusHandler.handleRequest(
            request,
            response,
            new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
      }
      CanonicalTreeParser p = new CanonicalTreeParser();
      ObjectReader reader = db.newObjectReader();
      try {
        p.reset(reader, head);
      } finally {
        reader.release();
      }
      oldTree = p;
      newTree = new DirCacheIterator(db.readDirCache());
    } else if (scope.equals(GitConstants.KEY_DIFF_DEFAULT)) {
      oldTree = new DirCacheIterator(db.readDirCache());
    } else {
      oldTree = getTreeIterator(db, scope);
    }

    String[] paths = request.getParameterValues(ProtocolConstants.KEY_PATH);
    TreeFilter filter = null;
    TreeFilter pathFilter = null;
    if (paths != null) {
      if (paths.length > 1) {
        Set<TreeFilter> pathFilters = new HashSet<TreeFilter>(paths.length);
        for (String path : paths) {
          pathFilters.add(PathFilter.create(path));
        }
        pathFilter = OrTreeFilter.create(pathFilters);
      } else if (paths.length == 1) {
        pathFilter = PathFilter.create(paths[0]);
      }
    }
    if (pattern != null) {
      PathFilter patternFilter = PathFilter.create(pattern);
      if (pathFilter != null) filter = AndTreeFilter.create(patternFilter, pathFilter);
      else filter = patternFilter;
    } else {
      filter = pathFilter;
    }
    if (filter != null) diff.setPathFilter(filter);

    diff.setOldTree(oldTree);
    diff.setNewTree(newTree);
    diff.call();
    return true;
  }
 private String stripGlobalPaths(Repository db, String message) {
   return message.replaceAll(
       "(?i)" + Pattern.quote(db.getDirectory().getParentFile().getAbsolutePath().toLowerCase()),
       "");
 }
Example #29
0
 private boolean isInIndex(Repository db, String path) throws IOException {
   DirCache dc = DirCache.read(db.getIndexFile(), db.getFS());
   return dc.getEntry(path) != null;
 }
Example #30
0
  // evaluates a policy (an ArrayList of Bids)
  public float evaluate(ArrayList<Bid> bids, Priceline[] evaluationScenarios) {
    float ret = 0;
    for (int i = 0; i < numEvaluations; i++) {
      Misc.println("Algorithm.evaluate : scenario " + i);
      // evaluationScenarios[i].priceline.printHotel();

      float bank = 0;
      float cost = 0;
      TACCollection hown = new TACCollection(repository.getOwnCollection());

      for (int j = 0; j < bids.size(); j++) {
        Bid b = bids.get(j);
        int auction = b.getAuction();

        switch (Constants.auctionType(auction)) {
          case Constants.TYPE_FLIGHT:
            for (int k = 0; k < b.getNoBidPoints(); k++) {
              // float currentPrice = m_dr.getQuote(auction).getAskPrice();
              float currentPrice =
                  evaluationScenarios[i]
                      .currBuyPrice[auction]; // expected min price - lower than current price
              if (b.getPrice(k) >= currentPrice) {
                int q = b.getQuantity(k);
                Misc.myassert(1 == q); // comment out if causes problems - vn
                hown.setOwn(auction, hown.getOwn(auction) + q);
                bank -= q * currentPrice;
                cost += q * currentPrice;
              }
            }
            break;

          case Constants.TYPE_HOTEL:
            // It can be happen if the calculation takes more than 1 minute.
            // In that case, we just ignore the bid. sjlee.
            // Because it is not a serious bug and it can happen frequently,
            // it would be innocuous to continue this algorithm.
            if (repository.isAuctionClosed(auction)) {
              Misc.error(
                  "we are bidding on a closed hotel. a "
                      + auction
                      + " we own "
                      + hown.getOwn(auction));
              break;
              // Misc.myassert(false);
            }

            for (int k = 0; k < b.getNoBidPoints(); k++) {
              float closingPrice = evaluationScenarios[i].currBuyPrice[auction];
              if (b.getPrice(k) >= closingPrice) {
                int q = b.getQuantity(k);
                Misc.myassert(1 == q); // comment out if causes problems - vn
                hown.setOwn(auction, hown.getOwn(auction) + q);
                bank -= q * closingPrice;
                cost += q * closingPrice;
              }
            }
            break;

          case Constants.TYPE_EVENT:
            // ignore!!
            break;
        }
      }

      TACCollection forsale = Constants.forSale();
      for (int j = 0; j < Constants.AUCTION_MAX; j++) {
        forsale.setOwn(j, 0);
      }

      Completion c =
          completer.computeCompletion(
              repository.getClientPrefs(), hown, forsale, evaluationScenarios[i]);

      for (int a = 0; a < Constants.AUCTION_MAX; a++) {
        Misc.myassert(0 == c.getBidPolicy().getQuantity(a));
        Misc.myassert(0 == c.getAskPolicy().getQuantity(a));
      }

      bank += c.objectiveValue;
      ret += bank;
    }

    return (ret / (float) numEvaluations);
  }