GitHub API for Java

 


This library defines an object oriented representation of the GitHub API. By "object oriented" we mean there are classes that correspond to the domain model of GitHub (such as GHUser and GHRepository), operations that act on them as defined as methods (such as GHUser.follow()), and those object references are used in favor of using string handle (such as GHUser.isMemberOf(GHOrganization) instead of GHUser.isMemberOf(String))

This is the GitHub repo: https://github.com/hub4j/github-api.

In a recent project, I used this library and I promised to make a post about it because I see that there are few examples in the documentation.

So I am sharing with you the experience I had with this library:


1. One of the ways to connect to a repository (public or private) is to use your personal token.

        @Value("${github.personaltoken}")

        String githubPersonalToken;


        @Value("${github.repo.skill.organization}")

        String githubRepoSkillOrganization;


        @Value("${github.repo.skill.target}")

        String githubRepoSkillTarget;  


        GitHub github = new GitHubBuilder().withOAuthToken(githubPersonalToken,

                        githubRepoSkillOrganization).build();


        GHRepository repo = github.getRepository(githubRepoSkillOrganization + "/" +       githubRepoSkillTarget);


        GHContentBuilder ghContentBuilder = null;

        GHContentUpdateResponse ghContentUpdateResponse = null;


2. If you are only interested in committing new files, this code will help you. It fails if the file exists on the destination.


        try {


          //Get DTO object

          Skill skill = skillConverter.entityToDto(optionalSkillEntity.get(), true);

          ObjectWriter ow = new ObjectMapper().registerModule(new JavaTimeModule()).writer().withDefaultPrettyPrinter();

          //Create file with the structure of DTO in json format

          fileName = skill.getName() + "-" + skill.getId() +".json";

          Path jsonPath = Paths.get("json/"+fileName);

          ow.writeValue(jsonPath.toFile(), skill);


          //Get contents of json file

          byte[] fileContent = Files.readAllBytes(jsonPath);

          DateTimeFormatter formatterLocalDateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");


          String message = "Public skill definitions: " + skill.getName() + " with owner: "

              + skill.getSkillOwner()

              + " was  edited by " + skill.getEditedByUsername() + " on " +

              formatterLocalDateTime.format(skill.getLastEdited());

          //Commit to Repo

          if(!testMode) {

            ghContentBuilder = repo.createContent();

            ghContentUpdateResponse = ghContentBuilder.content(fileContent).path(fileName)

                .message(message).commit();

            log.info("ghContentUpdateResponse: " +ghContentUpdateResponse);

          }else{

            log.info(message);

          }



          //...


        } catch (JsonProcessingException e) {

          throw new RuntimeException(e);

        } catch (IOException e) {

          throw new RuntimeException(e);

        }




I tested with 500 files and it created them in the destination repository without problems. But, as I mentioned, it fails if the file exists. Below I show you a code that works in both cases (create/update).


3. In this new version, creation and updating is guaranteed.


           try {


                                //This sleep guarantees more files committed

                Thread.sleep(1000); 


                Optional<SkillEntity> optionalSkillEntity = skillRepository.findById(

                        skillStatusEntity.getSkillId());


                if (optionalSkillEntity.isPresent()) {


                    try {


                        //Get DTO Object

                        Skill skill = skillConverter.entityToDto(optionalSkillEntity.get(), true);

                        ObjectWriter ow = new ObjectMapper().registerModule(new JavaTimeModule()).writer().withDefaultPrettyPrinter();

                        //Get file name and fill it with DTO in json format

                        fileName = skill.getName() + "-" + skill.getId() + ".json";

                        Path jsonPath = Paths.get("json/" + fileName);

                        ow.writeValue(jsonPath.toFile(), skill);


                        DateTimeFormatter formatterLocalDateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");


                        String message = "Public skill definitions: " + skill.getName() + " with owner: "

                                + skill.getSkillOwnerUsername()

                                + " was edited by " + skill.getEditedByUsername() + " on " +

                                formatterLocalDateTime.format(skill.getLastEdited());

                        //commit to Repo

                        if (!testMode) {

                            try {

                                String filePath = "quadim-public-skilldefinitions/" + fileName;

                                log.debug("Commiting public skill definition to Github: {0}", filePath);


                                GitHub github = new GitHubBuilder().withOAuthToken(githubPersonalToken,

                                        githubRepoSkillOrganization).build();

                                GHRepository repo = github.getRepository(githubRepoSkillOrganization + "/" + githubRepoSkillTarget);


                                // get the reference to the main branch

                                GHRef masterRef = repo.getRef("heads/main");

                                // get the SHA of the latest commit on the master branch

                                String masterTreeSha = repo

                                        .getTreeRecursive("main", 1)

                                        .getSha();


                                // create a tree with our entry and get its SHA

                                String treeSha = repo.createTree()

                                        .baseTree(masterTreeSha)

                                        .textEntry(filePath, FileUtils.readFileToString(jsonPath.toFile()), false)

                                        .create().getSha();


                                //create a commit for the new tree and get its SHA

                                String commitSha = repo.createCommit()

                                        .message(message)

                                        .tree(treeSha)

                                        .parent(masterRef.getObject().getSha())

                                        .create().getSHA1();

                                // Update the master reference to refer to the new commit

                                masterRef.updateTo(commitSha);


                                //....

                            } catch (IOException e) {

                                log.error("Error Committing public skill definition to Github ", e.getMessage());

                            }

                        } else {

                            log.debug("We only committed public skill definitions to PROD: " + message);

                            updateSkillStatusByGithubStatus(skillStatusEntity, GithubStatus.COMMITTED);

                        }


                    } catch (JsonProcessingException e) {

                        log.error("Error processing json file ", e.getMessage());

                    }

                }


             

            } catch (Exception e) {

                log.error("Trouble handling a skill-definition", e);

            }

        }



Congratulations to Kohsuke Kawaguchi for this great job and contributors around the world.


Enjoy!


Joe




Share:

0 comentarios:

Publicar un comentario