Exemplo n.º 1
0
  public void updateBinaryRepository() throws IOException, GitException, MapServiceException {

    // 1. Check if repository exists remotely [email protected]/Binary/Repo_Binary.git
    // find the name of the "source repository"
    final String repoUrl = getSourceRemoteUrl();

    // find where ".git" folder is found
    // SourceRepository = D:\dev\devex\binrepo-devex
    // BinaryRepository = D:\dev\devex\.binrepo-devex
    final File srcRepoDir = sourceRepository.getDirectory();
    final File sourceDir = srcRepoDir.getParentFile();

    final String sourceRepoFolder = srcRepoDir.getParentFile().getCanonicalPath();

    final File parent = srcRepoDir.getParentFile().getParentFile();
    final File binaryRepoDir = new File(parent, "." + srcRepoDir.getParentFile().getName());
    System.out.println(
        "SourceRepository = "
            + sourceRepoFolder
            + "\nBinaryRepository = "
            + binaryRepoDir.getCanonicalPath());

    // 2. Get branch/commit hash for the source repo - the actual source code
    final org.eclipse.jgit.lib.Repository repository =
        new org.eclipse.jgit.storage.file.FileRepository(srcRepoDir);
    final String branch = repository.getBranch();

    final RevWalk revWalk = new RevWalk(repository);
    final ObjectId resolve = repository.resolve(Constants.HEAD);
    final RevCommit commit = revWalk.parseCommit(resolve);
    String commitHash = commit.getName();
    System.out.println("CommitHash:" + commitHash + "\tMessage:" + commit.getFullMessage());

    // 3. Call the BinRepo service and check if a corresponding BinRepo entry exists
    final String url =
        getUrlForFindByRepoBranchCommit()
            + "repourl="
            + URLEncoder.encode(repoUrl, UTF_8)
            + "&branch="
            + URLEncoder.encode(branch, UTF_8)
            + "&commitid="
            + URLEncoder.encode(commitHash, UTF_8);
    System.out.println("svc url : " + url);

    WebResource webResource = client.resource(url);

    boolean noContent = false;
    BinRepoBranchCommitDO binRepoBranchCommitDO1 = null;

    try {
      binRepoBranchCommitDO1 =
          webResource.accept(MediaType.APPLICATION_JSON).get(BinRepoBranchCommitDO.class);
    } catch (UniformInterfaceException e) {
      int statusCode = e.getResponse().getClientResponseStatus().getStatusCode();
      System.out.println("Service Status Code : " + statusCode);
      noContent =
          (statusCode == 204 || statusCode == 404); // HTTP 204 is NO CONTENT which is ok for us
    } catch (Exception e) { // Catch-all to deal with network problems etc.
      e.printStackTrace();
    }

    System.out.println(
        binRepoBranchCommitDO1 != null
            ? binRepoBranchCommitDO1.toString()
            : "Resource not found on server");

    // 4. If not copy all the target folders from the source repo to the binary repo - root to root
    // copy of artifacts
    if (noContent) {
      System.out.println(
          "Source Directory:'"
              + sourceDir.getCanonicalPath()
              + "' Destination Directory:'"
              + binaryRepoDir.getCanonicalPath()
              + "'");
      FileUtil.copyBinaries(sourceDir, binaryRepoDir);
    }

    // 5. Call git status to get the delta (Use StatusCommand and refine it)
    Git binaryRepo;
    try {
      binaryRepo = Git.open(binaryRepoDir);
    } catch (IOException e) {
      throw new GitException("Unable to open repository" + binaryRepoDir, e);
    }

    // get "status"
    final StatusCommand statusCommand = binaryRepo.status();
    // TODO: RGIROTI Ask Nambi if we should actually filter this to only add .class files and
    // nothing else
    Collection<String> filesToStage = GitUtils.getFilesToStage(statusCommand);
    /*for (String file : filesToStage) {
        System.out.println("File to be added:" + file);
    }*/

    // add files to "staging" - if there is nothing to stage none of the other operations make any
    // sense at all
    if (filesToStage.size() > 0) {
      final AddCommand addCmd = binaryRepo.add();
      for (String file : filesToStage) {
        addCmd.addFilepattern(file);
      }
      final String[] filesArr = filesToStage.toArray(new String[filesToStage.size()]);
      final String files = StringUtils.join(filesArr, ",");
      try {
        addCmd.call();
      } catch (Exception e) {
        throw new GitException("Unable to add files to repository" + files, e);
      }

      // 6. Commit the changes to local and call push after that (use JGit API for this)
      // 6a. COmmit message should use format "Saving url:branch:commit:UTC time"
      // commit
      final CommitCommand commitCommand = binaryRepo.commit();
      String msg = "Saving Repo:%s Branch:%s CommitHash:%s Time:%s";
      final String formattedMsg =
          String.format(msg, repoUrl, branch, commitHash, new Date().toString());
      commitCommand.setMessage(formattedMsg);
      String commitHashBinRepo;
      try {
        final RevCommit call = commitCommand.call();
        commitHashBinRepo = call.getName();
      } catch (Exception e) {
        throw new GitException("Unable to read commit hash from commit command", e);
      }

      // push to origin now
      final PushCommand push = binaryRepo.push();
      final String remote = push.getRemote();
      final String remoteBranch = push.getRepository().getBranch();
      System.out.println("Remote to push to:'" + remote + "'");
      try {
        push.call();
      } catch (Exception e) {
        throw new GitException("Unable to push to remote", e);
      }

      // Calculate the remote url for binary repository
      String binRepoUrl = calculateBinaryRepositoryUrl();

      // 7. Call the BinRepo service and create a new entity for this change - repoUrl, branch, and
      // commit
      System.out.println(
          "Update Bin Repo Service with the new changes - POST new object to service");
      final BinRepoBranchCommitDO binRepoBranchCommitDO =
          newInstance(repoUrl, branch, commitHash, binRepoUrl, remoteBranch, commitHashBinRepo);
      webResource = client.resource(getUrlForPost());

      BinRepoBranchCommitDO postedDO = null;
      try {
        postedDO =
            webResource
                .accept(MediaType.APPLICATION_XML)
                .post(BinRepoBranchCommitDO.class, binRepoBranchCommitDO);
      } catch (UniformInterfaceException e) {
        int statusCode = e.getResponse().getClientResponseStatus().getStatusCode();
        System.out.println("status code: " + statusCode);
        throw new MapServiceException("Unable to register the commit details in update binrepo", e);
      }
      System.out.println(postedDO != null ? postedDO.toString() : "Post failed");
    }
  }