diff --git a/.github/workflows/maven-build.yml b/.github/workflows/maven-build.yml index f009de37cb..849d046a51 100644 --- a/.github/workflows/maven-build.yml +++ b/.github/workflows/maven-build.yml @@ -19,4 +19,4 @@ jobs: - name: Maven Download all dependencies run: mvn -B org.apache.maven.plugins:maven-dependency-plugin:3.1.1:go-offline - name: Maven Build - run: mvn -B install site --file pom.xml + run: mvn -B install site -P ci --file pom.xml diff --git a/pom.xml b/pom.xml index 3fba1cf336..7ca119e17d 100644 --- a/pom.xml +++ b/pom.xml @@ -35,6 +35,7 @@ 2.2 4.2.2 2.4.1 + format .80 0.20 0.50 @@ -152,17 +153,29 @@ - - com.infradna.tool - bridge-method-injector - 1.18 - - - - process - - - + + com.infradna.tool + bridge-method-injector + 1.18 + + + + process + + + + + + net.revelc.code.formatter + formatter-maven-plugin + 2.11.0 + + + + ${formatter-maven-plugin.goal} + + + com.github.spotbugs @@ -338,6 +351,14 @@ + + ci + + validate + + + + jacoco diff --git a/src/main/java/org/kohsuke/github/AbuseLimitHandler.java b/src/main/java/org/kohsuke/github/AbuseLimitHandler.java index 2c21cdaf9c..a30969da81 100644 --- a/src/main/java/org/kohsuke/github/AbuseLimitHandler.java +++ b/src/main/java/org/kohsuke/github/AbuseLimitHandler.java @@ -17,17 +17,18 @@ public abstract class AbuseLimitHandler { * Called when the library encounters HTTP error indicating that the API abuse limit is reached. * *

- * Any exception thrown from this method will cause the request to fail, and the caller of github-api - * will receive an exception. If this method returns normally, another request will be attempted. - * For that to make sense, the implementation needs to wait for some time. + * Any exception thrown from this method will cause the request to fail, and the caller of github-api will receive + * an exception. If this method returns normally, another request will be attempted. For that to make sense, the + * implementation needs to wait for some time. * * @see API documentation from GitHub * @param e - * Exception from Java I/O layer. If you decide to fail the processing, you can throw - * this exception (or wrap this exception into another exception and throw it). + * Exception from Java I/O layer. If you decide to fail the processing, you can throw this exception (or + * wrap this exception into another exception and throw it). * @param uc - * Connection that resulted in an error. Useful for accessing other response headers. + * Connection that resulted in an error. Useful for accessing other response headers. * @throws IOException + * on failure */ public abstract void onError(IOException e, HttpURLConnection uc) throws IOException; @@ -40,15 +41,16 @@ public void onError(IOException e, HttpURLConnection uc) throws IOException { try { Thread.sleep(parseWaitTime(uc)); } catch (InterruptedException ex) { - throw (InterruptedIOException)new InterruptedIOException().initCause(e); + throw (InterruptedIOException) new InterruptedIOException().initCause(e); } } private long parseWaitTime(HttpURLConnection uc) { String v = uc.getHeaderField("Retry-After"); - if (v==null) return 60 * 1000; // can't tell, return 1 min + if (v == null) + return 60 * 1000; // can't tell, return 1 min - return Math.max(1000, Long.parseLong(v)*1000); + return Math.max(1000, Long.parseLong(v) * 1000); } }; @@ -58,7 +60,7 @@ private long parseWaitTime(HttpURLConnection uc) { public static final AbuseLimitHandler FAIL = new AbuseLimitHandler() { @Override public void onError(IOException e, HttpURLConnection uc) throws IOException { - throw (IOException)new IOException("Abuse limit reached").initCause(e); + throw (IOException) new IOException("Abuse limit reached").initCause(e); } }; } diff --git a/src/main/java/org/kohsuke/github/DeleteToken.java b/src/main/java/org/kohsuke/github/DeleteToken.java index d9d4724eb9..ebef1967f8 100644 --- a/src/main/java/org/kohsuke/github/DeleteToken.java +++ b/src/main/java/org/kohsuke/github/DeleteToken.java @@ -28,8 +28,7 @@ /** * @author Kohsuke Kawaguchi */ -@SuppressFBWarnings(value = "UUF_UNUSED_PUBLIC_OR_PROTECTED_FIELD", - justification = "Being constructed by JSON deserialization") +@SuppressFBWarnings(value = "UUF_UNUSED_PUBLIC_OR_PROTECTED_FIELD", justification = "Being constructed by JSON deserialization") class DeleteToken { public String delete_token; } diff --git a/src/main/java/org/kohsuke/github/GHApp.java b/src/main/java/org/kohsuke/github/GHApp.java index d3a73354b2..e1386e72f4 100644 --- a/src/main/java/org/kohsuke/github/GHApp.java +++ b/src/main/java/org/kohsuke/github/GHApp.java @@ -25,14 +25,13 @@ public class GHApp extends GHObject { private String description; @JsonProperty("external_url") private String externalUrl; - private Map permissions; + private Map permissions; private List events; @JsonProperty("installations_count") private long installationsCount; @JsonProperty("html_url") private String htmlUrl; - public GHUser getOwner() { return owner; } @@ -93,80 +92,105 @@ public void setPermissions(Map permissions) { this.permissions = permissions; } - /*package*/ GHApp wrapUp(GitHub root) { + GHApp wrapUp(GitHub root) { this.root = root; return this; } /** * Obtains all the installations associated with this app. - * + *

* You must use a JWT to access this endpoint. * - * @see List installations * @return a list of App installations + * @see List installations */ - @Preview @Deprecated + @Preview + @Deprecated public PagedIterable listInstallations() { - return root.retrieve().withPreview(MACHINE_MAN) - .asPagedIterable( - "/app/installations", - GHAppInstallation[].class, - item -> item.wrapUp(root) ); + return root.retrieve().withPreview(MACHINE_MAN).asPagedIterable("/app/installations", GHAppInstallation[].class, + item -> item.wrapUp(root)); } /** - * Obtain an installation associated with this app - * @param id - Installation Id - * + * Obtain an installation associated with this app. + *

* You must use a JWT to access this endpoint. * + * @param id + * Installation Id + * @return a GHAppInstallation + * @throws IOException + * on error * @see Get an installation */ - @Preview @Deprecated + @Preview + @Deprecated public GHAppInstallation getInstallationById(long id) throws IOException { - return root.retrieve().withPreview(MACHINE_MAN).to(String.format("/app/installations/%d", id), GHAppInstallation.class).wrapUp(root); + return root.retrieve().withPreview(MACHINE_MAN) + .to(String.format("/app/installations/%d", id), GHAppInstallation.class).wrapUp(root); } /** - * Obtain an organization installation associated with this app - * @param name - Organization name - * + * Obtain an organization installation associated with this app. + *

* You must use a JWT to access this endpoint. * - * @see Get an organization installation + * @param name + * Organization name + * @return a GHAppInstallation + * @throws IOException + * on error + * @see Get an organization + * installation */ - @Preview @Deprecated + @Preview + @Deprecated public GHAppInstallation getInstallationByOrganization(String name) throws IOException { - return root.retrieve().withPreview(MACHINE_MAN).to(String.format("/orgs/%s/installation", name), GHAppInstallation.class).wrapUp(root); + return root.retrieve().withPreview(MACHINE_MAN) + .to(String.format("/orgs/%s/installation", name), GHAppInstallation.class).wrapUp(root); } /** - * Obtain an repository installation associated with this app - * @param ownerName - Organization or user name - * @param repositoryName - Repository name - * + * Obtain an repository installation associated with this app. + *

* You must use a JWT to access this endpoint. * - * @see Get a repository installation + * @param ownerName + * Organization or user name + * @param repositoryName + * Repository name + * @return a GHAppInstallation + * @throws IOException + * on error + * @see Get a repository + * installation */ - @Preview @Deprecated + @Preview + @Deprecated public GHAppInstallation getInstallationByRepository(String ownerName, String repositoryName) throws IOException { - return root.retrieve().withPreview(MACHINE_MAN).to(String.format("/repos/%s/%s/installation", ownerName, repositoryName), GHAppInstallation.class).wrapUp(root); + return root.retrieve().withPreview(MACHINE_MAN) + .to(String.format("/repos/%s/%s/installation", ownerName, repositoryName), GHAppInstallation.class) + .wrapUp(root); } /** - * Obtain a user installation associated with this app - * @param name - user name - * + * Obtain a user installation associated with this app. + *

* You must use a JWT to access this endpoint. * + * @param name + * user name + * @return a GHAppInstallation + * @throws IOException + * on error * @see Get a user installation */ - @Preview @Deprecated + @Preview + @Deprecated public GHAppInstallation getInstallationByUser(String name) throws IOException { - return root.retrieve().withPreview(MACHINE_MAN).to(String.format("/users/%s/installation", name), GHAppInstallation.class).wrapUp(root); + return root.retrieve().withPreview(MACHINE_MAN) + .to(String.format("/users/%s/installation", name), GHAppInstallation.class).wrapUp(root); } } - diff --git a/src/main/java/org/kohsuke/github/GHAppCreateTokenBuilder.java b/src/main/java/org/kohsuke/github/GHAppCreateTokenBuilder.java index 807ebcf102..e677e634cb 100644 --- a/src/main/java/org/kohsuke/github/GHAppCreateTokenBuilder.java +++ b/src/main/java/org/kohsuke/github/GHAppCreateTokenBuilder.java @@ -18,12 +18,13 @@ public class GHAppCreateTokenBuilder { protected final Requester builder; private final String apiUrlTail; - @Preview @Deprecated - /*package*/ GHAppCreateTokenBuilder(GitHub root, String apiUrlTail, Map permissions) { + @Preview + @Deprecated + GHAppCreateTokenBuilder(GitHub root, String apiUrlTail, Map permissions) { this.root = root; this.apiUrlTail = apiUrlTail; this.builder = new Requester(root); - this.builder.withPermissions("permissions",permissions); + this.builder.withPermissions("permissions", permissions); } /** @@ -31,12 +32,15 @@ public class GHAppCreateTokenBuilder { * the access to specific repositories, you can provide the repository_ids when creating the token. When you omit * repository_ids, the response does not contain neither the repositories nor the permissions key. * - * @param repositoryIds - Array containing the repositories Ids + * @param repositoryIds + * Array containing the repositories Ids * + * @return a GHAppCreateTokenBuilder */ - @Preview @Deprecated + @Preview + @Deprecated public GHAppCreateTokenBuilder repositoryIds(List repositoryIds) { - this.builder.with("repository_ids",repositoryIds); + this.builder.with("repository_ids", repositoryIds); return this; } @@ -44,10 +48,16 @@ public GHAppCreateTokenBuilder repositoryIds(List repositoryIds) { * Creates an app token with all the parameters. * * You must use a JWT to access this endpoint. + * + * @return a GHAppInstallationToken + * @throws IOException + * on error */ - @Preview @Deprecated + @Preview + @Deprecated public GHAppInstallationToken create() throws IOException { - return builder.method("POST").withPreview(MACHINE_MAN).to(apiUrlTail, GHAppInstallationToken.class).wrapUp(root); + return builder.method("POST").withPreview(MACHINE_MAN).to(apiUrlTail, GHAppInstallationToken.class) + .wrapUp(root); } } diff --git a/src/main/java/org/kohsuke/github/GHAppInstallation.java b/src/main/java/org/kohsuke/github/GHAppInstallation.java index 3925742162..96e2633c08 100644 --- a/src/main/java/org/kohsuke/github/GHAppInstallation.java +++ b/src/main/java/org/kohsuke/github/GHAppInstallation.java @@ -135,7 +135,7 @@ public void setRepositorySelection(GHRepositorySelection repositorySelection) { this.repositorySelection = repositorySelection; } - /*package*/ GHAppInstallation wrapUp(GitHub root) { + GHAppInstallation wrapUp(GitHub root) { this.root = root; return this; } @@ -145,23 +145,30 @@ public void setRepositorySelection(GHRepositorySelection repositorySelection) { * * You must use a JWT to access this endpoint. * + * @throws IOException + * on error * @see Delete an installation */ - @Preview @Deprecated + @Preview + @Deprecated public void deleteInstallation() throws IOException { root.retrieve().method("DELETE").withPreview(GAMBIT).to(String.format("/app/installations/%d", id)); } - /** * Starts a builder that creates a new App Installation Token. * *

- * You use the returned builder to set various properties, then call {@link GHAppCreateTokenBuilder#create()} - * to finally create an access token. + * You use the returned builder to set various properties, then call {@link GHAppCreateTokenBuilder#create()} to + * finally create an access token. + * + * @param permissions + * map of permissions for the created token + * @return a GHAppCreateTokenBuilder on error */ - @Preview @Deprecated - public GHAppCreateTokenBuilder createToken(Map permissions){ - return new GHAppCreateTokenBuilder(root,String.format("/app/installations/%d/access_tokens", id), permissions); + @Preview + @Deprecated + public GHAppCreateTokenBuilder createToken(Map permissions) { + return new GHAppCreateTokenBuilder(root, String.format("/app/installations/%d/access_tokens", id), permissions); } } diff --git a/src/main/java/org/kohsuke/github/GHAppInstallationToken.java b/src/main/java/org/kohsuke/github/GHAppInstallationToken.java index 2b6e78fdee..992e7ee349 100644 --- a/src/main/java/org/kohsuke/github/GHAppInstallationToken.java +++ b/src/main/java/org/kohsuke/github/GHAppInstallationToken.java @@ -68,9 +68,11 @@ public void setRepositorySelection(GHRepositorySelection repositorySelection) { } /** - * When was this tokens expires? + * @return date when this token expires + * @throws IOException + * on error */ - @WithBridgeMethods(value=String.class, adapterMethod="expiresAtStr") + @WithBridgeMethods(value = String.class, adapterMethod = "expiresAtStr") public Date getExpiresAt() throws IOException { return GitHub.parseDate(expires_at); } @@ -80,7 +82,7 @@ private Object expiresAtStr(Date id, Class type) { return expires_at; } - /*package*/ GHAppInstallationToken wrapUp(GitHub root) { + GHAppInstallationToken wrapUp(GitHub root) { this.root = root; return this; } diff --git a/src/main/java/org/kohsuke/github/GHAsset.java b/src/main/java/org/kohsuke/github/GHAsset.java index 9f0be15863..877d85fbc0 100644 --- a/src/main/java/org/kohsuke/github/GHAsset.java +++ b/src/main/java/org/kohsuke/github/GHAsset.java @@ -81,7 +81,6 @@ public void delete() throws IOException { new Requester(root).method("DELETE").to(getApiRoute()); } - private String getApiRoute() { return "/repos/" + owner.getOwnerName() + "/" + owner.getName() + "/releases/assets/" + id; } diff --git a/src/main/java/org/kohsuke/github/GHAuthorization.java b/src/main/java/org/kohsuke/github/GHAuthorization.java index bf7e24c7f2..033beda0a2 100644 --- a/src/main/java/org/kohsuke/github/GHAuthorization.java +++ b/src/main/java/org/kohsuke/github/GHAuthorization.java @@ -42,8 +42,8 @@ public class GHAuthorization extends GHObject { private String note; private String note_url; private String fingerprint; - //TODO add some user class for https://developer.github.com/v3/oauth_authorizations/#check-an-authorization ? - //private GHUser user; + // TODO add some user class for https://developer.github.com/v3/oauth_authorizations/#check-an-authorization ? + // private GHUser user; public GitHub getRoot() { return root; @@ -73,8 +73,7 @@ public String getAppName() { return app.name; } - @SuppressFBWarnings(value = "NM_CONFUSING", - justification = "It's a part of the library API, cannot be changed") + @SuppressFBWarnings(value = "NM_CONFUSING", justification = "It's a part of the library API, cannot be changed") public URL getApiURL() { return GitHub.parseURL(url); } @@ -99,13 +98,13 @@ public String getFingerprint() { return fingerprint; } - /*package*/ GHAuthorization wrap(GitHub root) { + GHAuthorization wrap(GitHub root) { this.root = root; return this; } - @SuppressFBWarnings(value = {"UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD"}, - justification = "JSON API") + @SuppressFBWarnings(value = { "UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", + "UWF_UNWRITTEN_FIELD" }, justification = "JSON API") private static class App { private String url; private String name; diff --git a/src/main/java/org/kohsuke/github/GHBlob.java b/src/main/java/org/kohsuke/github/GHBlob.java index a38a18219c..d881fd8485 100644 --- a/src/main/java/org/kohsuke/github/GHBlob.java +++ b/src/main/java/org/kohsuke/github/GHBlob.java @@ -19,7 +19,7 @@ public class GHBlob { private long size; /** - * API URL of this blob. + * @return API URL of this blob. */ public URL getUrl() { return GitHub.parseURL(url); @@ -30,7 +30,7 @@ public String getSha() { } /** - * Number of bytes in this blob. + * @return Number of bytes in this blob. */ public long getSize() { return size; @@ -41,24 +41,24 @@ public String getEncoding() { } /** - * Encoded content. You probably want {@link #read()} + * @return Encoded content. You probably want {@link #read()} */ public String getContent() { return content; } /** - * Retrieves the actual bytes of the blob. + * @return the actual bytes of the blob. */ public InputStream read() { if (encoding.equals("base64")) { try { return new Base64InputStream(new ByteArrayInputStream(content.getBytes("US-ASCII")), false); } catch (UnsupportedEncodingException e) { - throw new AssertionError(e); // US-ASCII is mandatory + throw new AssertionError(e); // US-ASCII is mandatory } } - throw new UnsupportedOperationException("Unrecognized encoding: "+encoding); + throw new UnsupportedOperationException("Unrecognized encoding: " + encoding); } } diff --git a/src/main/java/org/kohsuke/github/GHBlobBuilder.java b/src/main/java/org/kohsuke/github/GHBlobBuilder.java index a6259e5b6d..9397fe89b8 100644 --- a/src/main/java/org/kohsuke/github/GHBlobBuilder.java +++ b/src/main/java/org/kohsuke/github/GHBlobBuilder.java @@ -5,8 +5,7 @@ import java.io.IOException; /** - * Builder pattern for creating a new blob. - * Based on https://developer.github.com/v3/git/blobs/#create-a-blob + * Builder pattern for creating a new blob. Based on https://developer.github.com/v3/git/blobs/#create-a-blob */ public class GHBlobBuilder { private final GHRepository repo; @@ -19,6 +18,10 @@ public class GHBlobBuilder { /** * Configures a blob with the specified text {@code content}. + * + * @param content + * string text of the blob + * @return a GHBlobBuilder */ public GHBlobBuilder textContent(String content) { req.with("content", content); @@ -28,6 +31,10 @@ public GHBlobBuilder textContent(String content) { /** * Configures a blob with the specified binary {@code content}. + * + * @param content + * byte array of the blob + * @return a GHBlobBuilder */ public GHBlobBuilder binaryContent(byte[] content) { String base64Content = Base64.encodeBase64String(content); @@ -42,6 +49,10 @@ private String getApiTail() { /** * Creates a blob based on the parameters specified thus far. + * + * @return a GHBlob + * @throws IOException + * if the blob cannot be created. */ public GHBlob create() throws IOException { return req.method("POST").to(getApiTail(), GHBlob.class); diff --git a/src/main/java/org/kohsuke/github/GHBranch.java b/src/main/java/org/kohsuke/github/GHBranch.java index e457fc243d..64c62c9d2a 100644 --- a/src/main/java/org/kohsuke/github/GHBranch.java +++ b/src/main/java/org/kohsuke/github/GHBranch.java @@ -14,8 +14,8 @@ * * @author Yusuke Kokubo */ -@SuppressFBWarnings(value = {"UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", - "NP_UNWRITTEN_FIELD", "URF_UNREAD_FIELD"}, justification = "JSON API") +@SuppressFBWarnings(value = { "UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", "NP_UNWRITTEN_FIELD", + "URF_UNREAD_FIELD" }, justification = "JSON API") public class GHBranch { private GitHub root; private GHRepository owner; @@ -26,7 +26,6 @@ public class GHBranch { private boolean protection; private String protection_url; - public static class Commit { String sha; @@ -39,7 +38,7 @@ public GitHub getRoot() { } /** - * Repository that this branch is in. + * @return the repository that this branch is in. */ public GHRepository getOwner() { return owner; @@ -50,17 +49,19 @@ public String getName() { } /** - * Returns true if the push to this branch is restricted via branch protection. + * @return true if the push to this branch is restricted via branch protection. */ - @Preview @Deprecated + @Preview + @Deprecated public boolean isProtected() { return protection; } /** - * Returns API URL that deals with the protection of this branch. + * @return API URL that deals with the protection of this branch. */ - @Preview @Deprecated + @Preview + @Deprecated public URL getProtectionUrl() { return GitHub.parseURL(protection_url); } @@ -70,7 +71,7 @@ public GHBranchProtection getProtection() throws IOException { } /** - * The commit that this branch currently points to. + * @return The SHA1 of the commit that this branch currently points to. */ public String getSHA1() { return commit.sha; @@ -78,6 +79,9 @@ public String getSHA1() { /** * Disables branch protection and allows anyone with push access to push changes. + * + * @throws IOException + * if disabling protection fails */ public void disableProtection() throws IOException { new Requester(root).method("DELETE").to(protection_url); @@ -86,9 +90,11 @@ public void disableProtection() throws IOException { /** * Enables branch protection to control what commit statuses are required to push. * + * @return GHBranchProtectionBuilder for enabling protection * @see GHCommitStatus#getContext() */ - @Preview @Deprecated + @Preview + @Deprecated public GHBranchProtectionBuilder enableProtection() { return new GHBranchProtectionBuilder(this); } @@ -102,16 +108,13 @@ public void enableProtection(EnforcementLevel level, Collection contexts break; case NON_ADMINS: case EVERYONE: - enableProtection() - .addRequiredChecks(contexts) - .includeAdmins(level==EnforcementLevel.EVERYONE) - .enable(); + enableProtection().addRequiredChecks(contexts).includeAdmins(level == EnforcementLevel.EVERYONE).enable(); break; } } String getApiRoute() { - return owner.getApiTailUrl("/branches/"+name); + return owner.getApiTailUrl("/branches/" + name); } @Override @@ -120,7 +123,7 @@ public String toString() { return "Branch:" + name + " in " + url; } - /*package*/ GHBranch wrap(GHRepository repo) { + GHBranch wrap(GHRepository repo) { this.owner = repo; this.root = repo.root; return this; diff --git a/src/main/java/org/kohsuke/github/GHBranchProtection.java b/src/main/java/org/kohsuke/github/GHBranchProtection.java index 8420a531ad..41f5dda107 100644 --- a/src/main/java/org/kohsuke/github/GHBranchProtection.java +++ b/src/main/java/org/kohsuke/github/GHBranchProtection.java @@ -8,8 +8,8 @@ import java.io.IOException; import java.util.Collection; -@SuppressFBWarnings(value = {"UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", "NP_UNWRITTEN_FIELD", - "URF_UNREAD_FIELD"}, justification = "JSON API") +@SuppressFBWarnings(value = { "UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", "NP_UNWRITTEN_FIELD", + "URF_UNREAD_FIELD" }, justification = "JSON API") public class GHBranchProtection { private static final String REQUIRE_SIGNATURES_URI = "/required_signatures"; @@ -30,16 +30,16 @@ public class GHBranchProtection { @JsonProperty private String url; - @Preview @Deprecated + @Preview + @Deprecated public void enabledSignedCommits() throws IOException { - requester().method("POST") - .to(url + REQUIRE_SIGNATURES_URI, RequiredSignatures.class); + requester().method("POST").to(url + REQUIRE_SIGNATURES_URI, RequiredSignatures.class); } - @Preview @Deprecated + @Preview + @Deprecated public void disableSignedCommits() throws IOException { - requester().method("DELETE") - .to(url + REQUIRE_SIGNATURES_URI); + requester().method("DELETE").to(url + REQUIRE_SIGNATURES_URI); } public EnforceAdmins getEnforceAdmins() { @@ -50,10 +50,10 @@ public RequiredReviews getRequiredReviews() { return requiredReviews; } - @Preview @Deprecated + @Preview + @Deprecated public boolean getRequiredSignatures() throws IOException { - return requester().method("GET") - .to(url + REQUIRE_SIGNATURES_URI, RequiredSignatures.class).enabled; + return requester().method("GET").to(url + REQUIRE_SIGNATURES_URI, RequiredSignatures.class).enabled; } public RequiredStatusChecks getRequiredStatusChecks() { diff --git a/src/main/java/org/kohsuke/github/GHBranchProtectionBuilder.java b/src/main/java/org/kohsuke/github/GHBranchProtectionBuilder.java index 822541a14d..fd819d59d1 100644 --- a/src/main/java/org/kohsuke/github/GHBranchProtectionBuilder.java +++ b/src/main/java/org/kohsuke/github/GHBranchProtectionBuilder.java @@ -37,7 +37,7 @@ public GHBranchProtectionBuilder addRequiredChecks(Collection checks) { getStatusChecks().contexts.addAll(checks); return this; } - + public GHBranchProtectionBuilder addRequiredChecks(String... checks) { addRequiredChecks(Arrays.asList(checks)); return this; @@ -53,13 +53,10 @@ public GHBranchProtectionBuilder dismissStaleReviews(boolean v) { } public GHBranchProtection enable() throws IOException { - return requester().method("PUT") - .withNullable("required_status_checks", statusChecks) - .withNullable("required_pull_request_reviews", prReviews) - .withNullable("restrictions", restrictions) + return requester().method("PUT").withNullable("required_status_checks", statusChecks) + .withNullable("required_pull_request_reviews", prReviews).withNullable("restrictions", restrictions) .withNullable("enforce_admins", enforceAdmins) - .to(branch.getProtectionUrl().toString(), GHBranchProtection.class) - .wrap(branch); + .to(branch.getProtectionUrl().toString(), GHBranchProtection.class).wrap(branch); } public GHBranchProtectionBuilder includeAdmins() { @@ -148,7 +145,7 @@ public GHBranchProtectionBuilder userPushAccess(Collection users) { } return this; } - + public GHBranchProtectionBuilder userPushAccess(GHUser... users) { for (GHUser user : users) { getRestrictions().users.add(user.getLogin()); @@ -173,7 +170,7 @@ public GHBranchProtectionBuilder userReviewDismissals(GHUser... users) { private void addReviewRestriction(String restriction, boolean isTeam) { restrictReviewDismissals(); Restrictions restrictions = (Restrictions) prReviews.get("dismissal_restrictions"); - + if (isTeam) { restrictions.teams.add(restriction); } else { diff --git a/src/main/java/org/kohsuke/github/GHCommit.java b/src/main/java/org/kohsuke/github/GHCommit.java index 4891065ad5..f8d56d66e9 100644 --- a/src/main/java/org/kohsuke/github/GHCommit.java +++ b/src/main/java/org/kohsuke/github/GHCommit.java @@ -18,24 +18,23 @@ * @see GHRepository#getCommit(String) * @see GHCommitComment#getCommit() */ -@SuppressFBWarnings(value = {"NP_UNWRITTEN_FIELD", "UWF_UNWRITTEN_FIELD"}, - justification = "JSON API") +@SuppressFBWarnings(value = { "NP_UNWRITTEN_FIELD", "UWF_UNWRITTEN_FIELD" }, justification = "JSON API") public class GHCommit { private GHRepository owner; - + private ShortInfo commit; /** * Short summary of this commit. */ - @SuppressFBWarnings(value = {"UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", - "NP_UNWRITTEN_FIELD", "UWF_UNWRITTEN_FIELD"}, justification = "JSON API") + @SuppressFBWarnings(value = { "UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", + "NP_UNWRITTEN_FIELD", "UWF_UNWRITTEN_FIELD" }, justification = "JSON API") public static class ShortInfo { private GHAuthor author; private GHAuthor committer; - + private String message; - + private int comment_count; static class Tree { @@ -63,7 +62,7 @@ public Date getCommitDate() { } /** - * Commit message. + * @return Commit message. */ public String getMessage() { return message; @@ -82,89 +81,89 @@ public static class GHAuthor extends GitUser { } public static class Stats { - int total,additions,deletions; + int total, additions, deletions; } /** * A file that was modified. */ - @SuppressFBWarnings(value = "UWF_UNWRITTEN_FIELD", - justification = "It's being initilized by JSON deserialization") + @SuppressFBWarnings(value = "UWF_UNWRITTEN_FIELD", justification = "It's being initilized by JSON deserialization") public static class File { String status; - int changes,additions,deletions; + int changes, additions, deletions; String raw_url, blob_url, sha, patch; String filename, previous_filename; /** - * Number of lines added + removed. + * @return Number of lines added + removed. */ public int getLinesChanged() { return changes; } /** - * Number of lines added. + * @return Number of lines added. */ public int getLinesAdded() { return additions; } /** - * Number of lines removed. + * @return Number of lines removed. */ public int getLinesDeleted() { return deletions; } /** - * "modified", "added", or "removed" + * @return "modified", "added", or "removed" */ public String getStatus() { return status; } /** - * Full path in the repository. + * @return Full path in the repository. */ - @SuppressFBWarnings(value = "NM_CONFUSING", - justification = "It's a part of the library's API and cannot be renamed") + @SuppressFBWarnings(value = "NM_CONFUSING", justification = "It's a part of the library's API and cannot be renamed") public String getFileName() { return filename; } /** - * Previous path, in case file has moved. + * @return Previous path, in case file has moved. */ public String getPreviousFilename() { return previous_filename; } /** - * The actual change. + * @return The actual change. */ public String getPatch() { return patch; } /** - * URL like 'https://raw.github.com/jenkinsci/jenkins/4eb17c197dfdcf8ef7ff87eb160f24f6a20b7f0e/core/pom.xml' - * that resolves to the actual content of the file. + * @return URL like + * 'https://raw.github.com/jenkinsci/jenkins/4eb17c197dfdcf8ef7ff87eb160f24f6a20b7f0e/core/pom.xml' that + * resolves to the actual content of the file. */ public URL getRawUrl() { return GitHub.parseURL(raw_url); } /** - * URL like 'https://github.com/jenkinsci/jenkins/blob/1182e2ebb1734d0653142bd422ad33c21437f7cf/core/pom.xml' - * that resolves to the HTML page that describes this file. + * @return URL like + * 'https://github.com/jenkinsci/jenkins/blob/1182e2ebb1734d0653142bd422ad33c21437f7cf/core/pom.xml' + * that resolves to the HTML page that describes this file. */ public URL getBlobUrl() { return GitHub.parseURL(blob_url); } /** - * [0-9a-f]{40} SHA1 checksum. + * @return [0-9a-f]{40} SHA1 checksum. */ public String getSha() { return sha; @@ -173,42 +172,43 @@ public String getSha() { public static class Parent { @SuppressFBWarnings(value = "UUF_UNUSED_FIELD", justification = "We don't provide it in API now") - String url; + String url; String sha; } static class User { // TODO: what if someone who doesn't have an account on GitHub makes a commit? @SuppressFBWarnings(value = "UUF_UNUSED_FIELD", justification = "We don't provide it in API now") - String url,avatar_url,gravatar_id; + String url, avatar_url, gravatar_id; @SuppressFBWarnings(value = "UUF_UNUSED_FIELD", justification = "We don't provide it in API now") int id; - + String login; } - String url,html_url,sha; + String url, html_url, sha; List files; Stats stats; List parents; - User author,committer; - + User author, committer; public ShortInfo getCommitShortInfo() throws IOException { - if (commit==null) + if (commit == null) populate(); return commit; } /** - * The repository that contains the commit. + * @return the repository that contains the commit. */ public GHRepository getOwner() { return owner; } /** - * Number of lines added + removed. + * @return the number of lines added + removed. + * @throws IOException + * if the field was not populated and refresh fails */ public int getLinesChanged() throws IOException { populate(); @@ -216,7 +216,9 @@ public int getLinesChanged() throws IOException { } /** - * Number of lines added. + * @return Number of lines added. + * @throws IOException + * if the field was not populated and refresh fails */ public int getLinesAdded() throws IOException { populate(); @@ -224,7 +226,9 @@ public int getLinesAdded() throws IOException { } /** - * Number of lines removed. + * @return Number of lines removed. + * @throws IOException + * if the field was not populated and refresh fails */ public int getLinesDeleted() throws IOException { populate(); @@ -232,21 +236,26 @@ public int getLinesDeleted() throws IOException { } /** - * Use this method to walk the tree + * Use this method to walk the tree. + * + * @return a GHTree to walk + * @throws IOException + * on error */ public GHTree getTree() throws IOException { return owner.getTree(getCommitShortInfo().tree.sha); } /** - * URL of this commit like "https://github.com/kohsuke/sandbox-ant/commit/8ae38db0ea5837313ab5f39d43a6f73de3bd9000" + * @return URL of this commit like + * "https://github.com/kohsuke/sandbox-ant/commit/8ae38db0ea5837313ab5f39d43a6f73de3bd9000" */ public URL getHtmlUrl() { return GitHub.parseURL(html_url); } /** - * [0-9a-f]{40} SHA1 checksum. + * @return [0-9a-f]{40} SHA1 checksum. */ public String getSHA1() { return sha; @@ -255,19 +264,21 @@ public String getSHA1() { /** * List of files changed/added/removed in this commit. * - * @return - * Can be empty but never null. + * @return Can be empty but never null. + * @throws IOException + * on error */ public List getFiles() throws IOException { populate(); - return files!=null ? Collections.unmodifiableList(files) : Collections.emptyList(); + return files != null ? Collections.unmodifiableList(files) : Collections. emptyList(); } /** - * Returns the SHA1 of parent commit objects. + * @return SHA1 of parent commit objects. */ public List getParentSHA1s() { - if (parents==null) return Collections.emptyList(); + if (parents == null) + return Collections.emptyList(); return new AbstractList() { @Override public String get(int index) { @@ -283,6 +294,10 @@ public int size() { /** * Resolves the parent commit objects and return them. + * + * @return parent commit objects + * @throws IOException + * on error */ public List getParents() throws IOException { List r = new ArrayList(); @@ -297,8 +312,10 @@ public GHUser getAuthor() throws IOException { /** * Gets the date the change was authored on. + * * @return the date the change was authored on. - * @throws IOException if the information was not already fetched and an attempt at fetching the information failed. + * @throws IOException + * if the information was not already fetched and an attempt at fetching the information failed. */ public Date getAuthoredDate() throws IOException { return getCommitShortInfo().getAuthoredDate(); @@ -312,40 +329,51 @@ public GHUser getCommitter() throws IOException { * Gets the date the change was committed on. * * @return the date the change was committed on. - * @throws IOException if the information was not already fetched and an attempt at fetching the information failed. + * @throws IOException + * if the information was not already fetched and an attempt at fetching the information failed. */ public Date getCommitDate() throws IOException { return getCommitShortInfo().getCommitDate(); } private GHUser resolveUser(User author) throws IOException { - if (author==null || author.login==null) return null; + if (author == null || author.login == null) + return null; return owner.root.getUser(author.login); } /** - * Lists up all the commit comments in this repository. + * @return {@link PagedIterable} with all the commit comments in this repository. */ public PagedIterable listComments() { - return owner.root.retrieve() - .asPagedIterable( + return owner.root.retrieve().asPagedIterable( String.format("/repos/%s/%s/commits/%s/comments", owner.getOwnerName(), owner.getName(), sha), - GHCommitComment[].class, - item -> item.wrap(owner) ); + GHCommitComment[].class, item -> item.wrap(owner)); } /** * Creates a commit comment. * * I'm not sure how path/line/position parameters interact with each other. + * + * @param body + * body of the comment + * @param path + * path of file being commented on + * @param line + * target line for comment + * @param position + * position on line + * + * @return created GHCommitComment + * @throws IOException + * if comment is not created */ public GHCommitComment createComment(String body, String path, Integer line, Integer position) throws IOException { - GHCommitComment r = new Requester(owner.root) - .with("body",body) - .with("path",path) - .with("line",line) - .with("position",position) - .to(String.format("/repos/%s/%s/commits/%s/comments",owner.getOwnerName(),owner.getName(),sha),GHCommitComment.class); + GHCommitComment r = new Requester(owner.root).with("body", body).with("path", path).with("line", line) + .with("position", position) + .to(String.format("/repos/%s/%s/commits/%s/comments", owner.getOwnerName(), owner.getName(), sha), + GHCommitComment.class); return r.wrap(owner); } @@ -354,14 +382,18 @@ public GHCommitComment createComment(String body) throws IOException { } /** - * Gets the status of this commit, newer ones first. + * @return status of this commit, newer ones first. + * @throws IOException + * if statuses cannot be read */ public PagedIterable listStatuses() throws IOException { return owner.listCommitStatuses(sha); } /** - * Gets the last status of this commit, which is what gets shown in the UI. + * @return the last status of this commit, which is what gets shown in the UI. + * @throws IOException + * on error */ public GHCommitStatus getLastStatus() throws IOException { return owner.getLastCommitStatus(sha); @@ -369,9 +401,12 @@ public GHCommitStatus getLastStatus() throws IOException { /** * Some of the fields are not always filled in when this object is retrieved as a part of another API call. + * + * @throws IOException + * on error */ void populate() throws IOException { - if (files==null && stats==null) + if (files == null && stats == null) owner.root.retrieve().to(owner.getApiTailUrl("commits/" + sha), this); } diff --git a/src/main/java/org/kohsuke/github/GHCommitBuilder.java b/src/main/java/org/kohsuke/github/GHCommitBuilder.java index 76e846a7d7..01a35fa16a 100644 --- a/src/main/java/org/kohsuke/github/GHCommitBuilder.java +++ b/src/main/java/org/kohsuke/github/GHCommitBuilder.java @@ -9,8 +9,7 @@ import java.util.TimeZone; /** - * Builder pattern for creating a new commit. - * Based on https://developer.github.com/v3/git/commits/#create-a-commit + * Builder pattern for creating a new commit. Based on https://developer.github.com/v3/git/commits/#create-a-commit */ public class GHCommitBuilder { private final GHRepository repo; @@ -39,7 +38,8 @@ private UserInfo(String name, String email, Date date) { } /** - * @param message the commit message + * @param message + * the commit message */ public GHCommitBuilder message(String message) { req.with("message", message); @@ -47,7 +47,8 @@ public GHCommitBuilder message(String message) { } /** - * @param tree the SHA of the tree object this commit points to + * @param tree + * the SHA of the tree object this commit points to */ public GHCommitBuilder tree(String tree) { req.with("tree", tree); @@ -55,7 +56,8 @@ public GHCommitBuilder tree(String tree) { } /** - * @param parent the SHA of a parent commit. + * @param parent + * the SHA of a parent commit. */ public GHCommitBuilder parent(String parent) { parents.add(parent); diff --git a/src/main/java/org/kohsuke/github/GHCommitComment.java b/src/main/java/org/kohsuke/github/GHCommitComment.java index a0047c3d15..56eb9a93b1 100644 --- a/src/main/java/org/kohsuke/github/GHCommitComment.java +++ b/src/main/java/org/kohsuke/github/GHCommitComment.java @@ -15,22 +15,23 @@ * @see GHCommit#listComments() * @see GHCommit#createComment(String, String, Integer, Integer) */ -@SuppressFBWarnings(value = {"UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", - "NP_UNWRITTEN_FIELD"}, justification = "JSON API") +@SuppressFBWarnings(value = { "UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", + "NP_UNWRITTEN_FIELD" }, justification = "JSON API") public class GHCommitComment extends GHObject implements Reactable { private GHRepository owner; String body, html_url, commit_id; Integer line; String path; - GHUser user; // not fully populated. beware. + GHUser user; // not fully populated. beware. public GHRepository getOwner() { return owner; } /** - * URL like 'https://github.com/kohsuke/sandbox-ant/commit/8ae38db0ea5837313ab5f39d43a6f73de3bd9000#commitcomment-1252827' to + * URL like + * 'https://github.com/kohsuke/sandbox-ant/commit/8ae38db0ea5837313ab5f39d43a6f73de3bd9000#commitcomment-1252827' to * show this commit comment in a browser. */ public URL getHtmlUrl() { @@ -49,19 +50,19 @@ public String getBody() { } /** - * A commit comment can be on a specific line of a specific file, if so, this field points to a file. - * Otherwise null. + * A commit comment can be on a specific line of a specific file, if so, this field points to a file. Otherwise + * null. */ public String getPath() { return path; } /** - * A commit comment can be on a specific line of a specific file, if so, this field points to the line number in the file. - * Otherwise -1. + * A commit comment can be on a specific line of a specific file, if so, this field points to the line number in the + * file. Otherwise -1. */ public int getLine() { - return line!=null ? line : -1; + return line != null ? line : -1; } /** @@ -82,27 +83,22 @@ public GHCommit getCommit() throws IOException { * Updates the body of the commit message. */ public void update(String body) throws IOException { - new Requester(owner.root) - .with("body", body) - .method("PATCH").to(getApiTail(), GHCommitComment.class); + new Requester(owner.root).with("body", body).method("PATCH").to(getApiTail(), GHCommitComment.class); this.body = body; } - @Preview @Deprecated + @Preview + @Deprecated public GHReaction createReaction(ReactionContent content) throws IOException { - return new Requester(owner.root) - .withPreview(SQUIRREL_GIRL) - .with("content", content.getContent()) - .to(getApiTail()+"/reactions", GHReaction.class).wrap(owner.root); + return new Requester(owner.root).withPreview(SQUIRREL_GIRL).with("content", content.getContent()) + .to(getApiTail() + "/reactions", GHReaction.class).wrap(owner.root); } - @Preview @Deprecated + @Preview + @Deprecated public PagedIterable listReactions() { - return owner.root.retrieve().withPreview(SQUIRREL_GIRL) - .asPagedIterable( - getApiTail()+"/reactions", - GHReaction[].class, - item -> item.wrap(owner.root) ); + return owner.root.retrieve().withPreview(SQUIRREL_GIRL).asPagedIterable(getApiTail() + "/reactions", + GHReaction[].class, item -> item.wrap(owner.root)); } /** @@ -113,10 +109,9 @@ public void delete() throws IOException { } private String getApiTail() { - return String.format("/repos/%s/%s/comments/%s",owner.getOwnerName(),owner.getName(),id); + return String.format("/repos/%s/%s/comments/%s", owner.getOwnerName(), owner.getName(), id); } - GHCommitComment wrap(GHRepository owner) { this.owner = owner; if (owner.root.isOffline()) { diff --git a/src/main/java/org/kohsuke/github/GHCommitPointer.java b/src/main/java/org/kohsuke/github/GHCommitPointer.java index b6c347864e..3f0fb3cc3d 100644 --- a/src/main/java/org/kohsuke/github/GHCommitPointer.java +++ b/src/main/java/org/kohsuke/github/GHCommitPointer.java @@ -36,11 +36,11 @@ public class GHCommitPointer { private GHRepository repo; /** - * This points to the user who owns - * the {@link #getRepository()}. + * This points to the user who owns the {@link #getRepository()}. */ public GHUser getUser() throws IOException { - if (user != null) return user.root.intern(user); + if (user != null) + return user.root.intern(user); return user; } @@ -80,7 +80,9 @@ public GHCommit getCommit() throws IOException { } void wrapUp(GitHub root) { - if (user!=null) user.root = root; - if (repo!=null) repo.wrap(root); + if (user != null) + user.root = root; + if (repo != null) + repo.wrap(root); } } diff --git a/src/main/java/org/kohsuke/github/GHCommitQueryBuilder.java b/src/main/java/org/kohsuke/github/GHCommitQueryBuilder.java index 64b3a0e935..32d1d964a8 100644 --- a/src/main/java/org/kohsuke/github/GHCommitQueryBuilder.java +++ b/src/main/java/org/kohsuke/github/GHCommitQueryBuilder.java @@ -17,21 +17,21 @@ * * @author Kohsuke Kawaguchi * @see GHRepository#queryCommits() -*/ + */ public class GHCommitQueryBuilder { private final Requester req; private final GHRepository repo; - /*package*/ GHCommitQueryBuilder(GHRepository repo) { + GHCommitQueryBuilder(GHRepository repo) { this.repo = repo; - this.req = repo.root.retrieve(); // requester to build up + this.req = repo.root.retrieve(); // requester to build up } /** * GItHub login or email address by which to filter by commit author. */ public GHCommitQueryBuilder author(String author) { - req.with("author",author); + req.with("author", author); return this; } @@ -39,7 +39,7 @@ public GHCommitQueryBuilder author(String author) { * Only commits containing this file path will be returned. */ public GHCommitQueryBuilder path(String path) { - req.with("path",path); + req.with("path", path); return this; } @@ -48,12 +48,12 @@ public GHCommitQueryBuilder path(String path) { * */ public GHCommitQueryBuilder from(String ref) { - req.with("sha",ref); + req.with("sha", ref); return this; } public GHCommitQueryBuilder pageSize(int pageSize) { - req.with("per_page",pageSize); + req.with("per_page", pageSize); return this; } @@ -61,7 +61,7 @@ public GHCommitQueryBuilder pageSize(int pageSize) { * Only commits after this date will be returned */ public GHCommitQueryBuilder since(Date dt) { - req.with("since",GitHub.printDate(dt)); + req.with("since", GitHub.printDate(dt)); return this; } @@ -76,7 +76,7 @@ public GHCommitQueryBuilder since(long timestamp) { * Only commits before this date will be returned */ public GHCommitQueryBuilder until(Date dt) { - req.with("until",GitHub.printDate(dt)); + req.with("until", GitHub.printDate(dt)); return this; } @@ -91,10 +91,6 @@ public GHCommitQueryBuilder until(long timestamp) { * Lists up the commits with the criteria built so far. */ public PagedIterable list() { - return req - .asPagedIterable( - repo.getApiTailUrl("commits"), - GHCommit[].class, - item -> item.wrapUp(repo) ); + return req.asPagedIterable(repo.getApiTailUrl("commits"), GHCommit[].class, item -> item.wrapUp(repo)); } } diff --git a/src/main/java/org/kohsuke/github/GHCommitSearchBuilder.java b/src/main/java/org/kohsuke/github/GHCommitSearchBuilder.java index 3d29aa80fd..5d75afbb3c 100644 --- a/src/main/java/org/kohsuke/github/GHCommitSearchBuilder.java +++ b/src/main/java/org/kohsuke/github/GHCommitSearchBuilder.java @@ -10,10 +10,11 @@ * @author Marc de Verdelhan * @see GitHub#searchCommits() */ -@Preview @Deprecated +@Preview +@Deprecated public class GHCommitSearchBuilder extends GHSearchBuilder { - /*package*/ GHCommitSearchBuilder(GitHub root) { - super(root,CommitSearchResult.class); + GHCommitSearchBuilder(GitHub root) { + super(root, CommitSearchResult.class); req.withPreview(Previews.CLOAK); } @@ -26,99 +27,103 @@ public GHCommitSearchBuilder q(String term) { } public GHCommitSearchBuilder author(String v) { - return q("author:"+v); + return q("author:" + v); } public GHCommitSearchBuilder committer(String v) { - return q("committer:"+v); + return q("committer:" + v); } public GHCommitSearchBuilder authorName(String v) { - return q("author-name:"+v); + return q("author-name:" + v); } public GHCommitSearchBuilder committerName(String v) { - return q("committer-name:"+v); + return q("committer-name:" + v); } public GHCommitSearchBuilder authorEmail(String v) { - return q("author-email:"+v); + return q("author-email:" + v); } public GHCommitSearchBuilder committerEmail(String v) { - return q("committer-email:"+v); + return q("committer-email:" + v); } public GHCommitSearchBuilder authorDate(String v) { - return q("author-date:"+v); + return q("author-date:" + v); } public GHCommitSearchBuilder committerDate(String v) { - return q("committer-date:"+v); + return q("committer-date:" + v); } public GHCommitSearchBuilder merge(boolean merge) { - return q("merge:"+Boolean.valueOf(merge).toString().toLowerCase()); + return q("merge:" + Boolean.valueOf(merge).toString().toLowerCase()); } public GHCommitSearchBuilder hash(String v) { - return q("hash:"+v); + return q("hash:" + v); } public GHCommitSearchBuilder parent(String v) { - return q("parent:"+v); + return q("parent:" + v); } public GHCommitSearchBuilder tree(String v) { - return q("tree:"+v); + return q("tree:" + v); } public GHCommitSearchBuilder is(String v) { - return q("is:"+v); + return q("is:" + v); } public GHCommitSearchBuilder user(String v) { - return q("user:"+v); + return q("user:" + v); } public GHCommitSearchBuilder org(String v) { - return q("org:"+v); + return q("org:" + v); } public GHCommitSearchBuilder repo(String v) { - return q("repo:"+v); + return q("repo:" + v); } public GHCommitSearchBuilder order(GHDirection v) { - req.with("order",v); + req.with("order", v); return this; } public GHCommitSearchBuilder sort(Sort sort) { - req.with("sort",sort); + req.with("sort", sort); return this; } - public enum Sort { AUTHOR_DATE, COMMITTER_DATE } + public enum Sort { + AUTHOR_DATE, COMMITTER_DATE + } private static class CommitSearchResult extends SearchResult { private GHCommit[] items; @Override - /*package*/ GHCommit[] getItems(GitHub root) { + GHCommit[] getItems(GitHub root) { for (GHCommit commit : items) { String repoName = getRepoName(commit.url); try { GHRepository repo = root.getRepository(repoName); commit.wrapUp(repo); - } catch (IOException ioe) {} + } catch (IOException ioe) { + } } return items; } } - + /** - * @param commitUrl a commit URL + * @param commitUrl + * a commit URL * @return the repo name ("username/reponame") */ private static String getRepoName(String commitUrl) { diff --git a/src/main/java/org/kohsuke/github/GHCommitStatus.java b/src/main/java/org/kohsuke/github/GHCommitStatus.java index 63a62ae8d0..148a2a17bc 100644 --- a/src/main/java/org/kohsuke/github/GHCommitStatus.java +++ b/src/main/java/org/kohsuke/github/GHCommitStatus.java @@ -13,14 +13,15 @@ */ public class GHCommitStatus extends GHObject { String state; - String target_url,description; + String target_url, description; String context; GHUser creator; private GitHub root; - /*package*/ GHCommitStatus wrapUp(GitHub root) { - if (creator!=null) creator.wrapUp(root); + GHCommitStatus wrapUp(GitHub root) { + if (creator != null) + creator.wrapUp(root); this.root = root; return this; } @@ -30,7 +31,7 @@ public GHCommitState getState() { if (s.name().equalsIgnoreCase(state)) return s; } - throw new IllegalStateException("Unexpected state: "+state); + throw new IllegalStateException("Unexpected state: " + state); } /** diff --git a/src/main/java/org/kohsuke/github/GHCompare.java b/src/main/java/org/kohsuke/github/GHCompare.java index 100753db01..bfcc9423e7 100644 --- a/src/main/java/org/kohsuke/github/GHCompare.java +++ b/src/main/java/org/kohsuke/github/GHCompare.java @@ -67,6 +67,7 @@ public Commit getMergeBaseCommit() { /** * Gets an array of commits. + * * @return A copy of the array being stored in the class. */ public Commit[] getCommits() { @@ -74,9 +75,10 @@ public Commit[] getCommits() { System.arraycopy(commits, 0, newValue, 0, commits.length); return newValue; } - + /** * Gets an array of commits. + * * @return A copy of the array being stored in the class. */ public GHCommit.File[] getFiles() { @@ -96,11 +98,11 @@ public GHCompare wrap(GHRepository owner) { } /** - * Compare commits had a child commit element with additional details we want to capture. - * This extenstion of GHCommit provides that. + * Compare commits had a child commit element with additional details we want to capture. This extenstion of + * GHCommit provides that. */ - @SuppressFBWarnings(value = {"UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD"}, - justification = "JSON API") + @SuppressFBWarnings(value = { "UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", + "UWF_UNWRITTEN_FIELD" }, justification = "JSON API") public static class Commit extends GHCommit { private InnerCommit commit; @@ -110,7 +112,6 @@ public InnerCommit getCommit() { } } - public static class InnerCommit { private String url, sha, message; private User author, committer; @@ -128,12 +129,12 @@ public String getMessage() { return message; } - @WithBridgeMethods(value=User.class,castRequired=true) + @WithBridgeMethods(value = User.class, castRequired = true) public GitUser getAuthor() { return author; } - @WithBridgeMethods(value=User.class,castRequired=true) + @WithBridgeMethods(value = User.class, castRequired = true) public GitUser getCommitter() { return committer; } diff --git a/src/main/java/org/kohsuke/github/GHContent.java b/src/main/java/org/kohsuke/github/GHContent.java index 9b9f787a67..2be7016fd3 100644 --- a/src/main/java/org/kohsuke/github/GHContent.java +++ b/src/main/java/org/kohsuke/github/GHContent.java @@ -15,11 +15,11 @@ * @author Alexandre COLLIGNON * @see GHRepository#getFileContent(String) */ -@SuppressWarnings({"UnusedDeclaration"}) +@SuppressWarnings({ "UnusedDeclaration" }) public class GHContent implements Refreshable { /* - In normal use of this class, repository field is set via wrap(), - but in the code search API, there's a nested 'repository' field that gets populated from JSON. + * In normal use of this class, repository field is set via wrap(), but in the code search API, there's a nested + * 'repository' field that gets populated from JSON. */ private GHRepository repository; @@ -33,8 +33,8 @@ In normal use of this class, repository field is set via wrap(), private String path; private String content; private String url; // this is the API url - private String git_url; // this is the Blob url - private String html_url; // this is the UI + private String git_url; // this is the Blob url + private String html_url; // this is the UI private String download_url; public GHRepository getOwner() { @@ -69,12 +69,10 @@ public String getPath() { * Retrieve the decoded content that is stored at this location. * *

- * Due to the nature of GitHub's API, you're not guaranteed that - * the content will already be populated, so this may trigger - * network activity, and can throw an IOException. + * Due to the nature of GitHub's API, you're not guaranteed that the content will already be populated, so this may + * trigger network activity, and can throw an IOException. * - * @deprecated - * Use {@link #read()} + * @deprecated Use {@link #read()} */ @SuppressFBWarnings("DM_DEFAULT_ENCODING") public String getContent() throws IOException { @@ -85,12 +83,10 @@ public String getContent() throws IOException { * Retrieve the base64-encoded content that is stored at this location. * *

- * Due to the nature of GitHub's API, you're not guaranteed that - * the content will already be populated, so this may trigger - * network activity, and can throw an IOException. + * Due to the nature of GitHub's API, you're not guaranteed that the content will already be populated, so this may + * trigger network activity, and can throw an IOException. * - * @deprecated - * Use {@link #read()} + * @deprecated Use {@link #read()} */ public String getEncodedContent() throws IOException { refresh(content); @@ -121,11 +117,11 @@ public InputStream read() throws IOException { try { return new Base64InputStream(new ByteArrayInputStream(content.getBytes("US-ASCII")), false); } catch (UnsupportedEncodingException e) { - throw new AssertionError(e); // US-ASCII is mandatory + throw new AssertionError(e); // US-ASCII is mandatory } } - throw new UnsupportedOperationException("Unrecognized encoding: "+encoding); + throw new UnsupportedOperationException("Unrecognized encoding: " + encoding); } /** @@ -158,13 +154,9 @@ protected synchronized void populate() throws IOException { */ public PagedIterable listDirectoryContent() throws IOException { if (!isDirectory()) - throw new IllegalStateException(path+" is not a directory"); + throw new IllegalStateException(path + " is not a directory"); - return root.retrieve() - .asPagedIterable( - url, - GHContent[].class, - item -> item.wrap(repository) ); + return root.retrieve().asPagedIterable(url, GHContent[].class, item -> item.wrap(repository)); } @SuppressFBWarnings("DM_DEFAULT_ENCODING") @@ -181,15 +173,12 @@ public GHContentUpdateResponse update(byte[] newContentBytes, String commitMessa return update(newContentBytes, commitMessage, null); } - public GHContentUpdateResponse update(byte[] newContentBytes, String commitMessage, String branch) throws IOException { + public GHContentUpdateResponse update(byte[] newContentBytes, String commitMessage, String branch) + throws IOException { String encodedContent = Base64.encodeBase64String(newContentBytes); - Requester requester = new Requester(root) - .with("path", path) - .with("message", commitMessage) - .with("sha", sha) - .with("content", encodedContent) - .method("PUT"); + Requester requester = new Requester(root).with("path", path).with("message", commitMessage).with("sha", sha) + .with("content", encodedContent).method("PUT"); if (branch != null) { requester.with("branch", branch); @@ -209,11 +198,8 @@ public GHContentUpdateResponse delete(String message) throws IOException { } public GHContentUpdateResponse delete(String commitMessage, String branch) throws IOException { - Requester requester = new Requester(root) - .with("path", path) - .with("message", commitMessage) - .with("sha", sha) - .method("DELETE"); + Requester requester = new Requester(root).with("path", path).with("message", commitMessage).with("sha", sha) + .method("DELETE"); if (branch != null) { requester.with("branch", branch); @@ -234,14 +220,14 @@ GHContent wrap(GHRepository owner) { this.root = owner.root; return this; } + GHContent wrap(GitHub root) { this.root = root; - if (repository!=null) + if (repository != null) repository.wrap(root); return this; } - public static GHContent[] wrap(GHContent[] contents, GHRepository repository) { for (GHContent unwrappedContent : contents) { unwrappedContent.wrap(repository); diff --git a/src/main/java/org/kohsuke/github/GHContentBuilder.java b/src/main/java/org/kohsuke/github/GHContentBuilder.java index cdc019f6d1..d31a73d831 100644 --- a/src/main/java/org/kohsuke/github/GHContentBuilder.java +++ b/src/main/java/org/kohsuke/github/GHContentBuilder.java @@ -26,7 +26,7 @@ public final class GHContentBuilder { public GHContentBuilder path(String path) { this.path = path; - req.with("path",path); + req.with("path", path); return this; } @@ -36,8 +36,7 @@ public GHContentBuilder branch(String branch) { } /** - * Used when updating (but not creating a new content) to specify - * Thetblob SHA of the file being replaced. + * Used when updating (but not creating a new content) to specify Thetblob SHA of the file being replaced. */ public GHContentBuilder sha(String sha) { req.with("sha", sha); @@ -66,7 +65,8 @@ public GHContentBuilder message(String commitMessage) { * Commits a new content. */ public GHContentUpdateResponse commit() throws IOException { - GHContentUpdateResponse response = req.to(repo.getApiTailUrl("contents/" + path), GHContentUpdateResponse.class); + GHContentUpdateResponse response = req.to(repo.getApiTailUrl("contents/" + path), + GHContentUpdateResponse.class); response.getContent().wrap(repo); response.getCommit().wrapUp(repo); diff --git a/src/main/java/org/kohsuke/github/GHContentSearchBuilder.java b/src/main/java/org/kohsuke/github/GHContentSearchBuilder.java index 47e5a46f52..f7438d2bbf 100644 --- a/src/main/java/org/kohsuke/github/GHContentSearchBuilder.java +++ b/src/main/java/org/kohsuke/github/GHContentSearchBuilder.java @@ -7,8 +7,8 @@ * @see GitHub#searchContent() */ public class GHContentSearchBuilder extends GHSearchBuilder { - /*package*/ GHContentSearchBuilder(GitHub root) { - super(root,ContentSearchResult.class); + GHContentSearchBuilder(GitHub root) { + super(root, ContentSearchResult.class); } /** @@ -20,47 +20,46 @@ public GHContentSearchBuilder q(String term) { } public GHContentSearchBuilder in(String v) { - return q("in:"+v); + return q("in:" + v); } public GHContentSearchBuilder language(String v) { - return q("language:"+v); + return q("language:" + v); } public GHContentSearchBuilder fork(String v) { - return q("fork:"+v); + return q("fork:" + v); } public GHContentSearchBuilder size(String v) { - return q("size:"+v); + return q("size:" + v); } public GHContentSearchBuilder path(String v) { - return q("path:"+v); + return q("path:" + v); } public GHContentSearchBuilder filename(String v) { - return q("filename:"+v); + return q("filename:" + v); } public GHContentSearchBuilder extension(String v) { - return q("extension:"+v); + return q("extension:" + v); } public GHContentSearchBuilder user(String v) { - return q("user:"+v); + return q("user:" + v); } - public GHContentSearchBuilder repo(String v) { - return q("repo:"+v); + return q("repo:" + v); } private static class ContentSearchResult extends SearchResult { private GHContent[] items; @Override - /*package*/ GHContent[] getItems(GitHub root) { + GHContent[] getItems(GitHub root) { for (GHContent item : items) item.wrap(root); return items; diff --git a/src/main/java/org/kohsuke/github/GHContentUpdateResponse.java b/src/main/java/org/kohsuke/github/GHContentUpdateResponse.java index 07f10d710c..cd66091e6b 100644 --- a/src/main/java/org/kohsuke/github/GHContentUpdateResponse.java +++ b/src/main/java/org/kohsuke/github/GHContentUpdateResponse.java @@ -1,9 +1,8 @@ package org.kohsuke.github; /** - * The response that is returned when updating - * repository content. -**/ + * The response that is returned when updating repository content. + **/ public class GHContentUpdateResponse { private GHContent content; private GHCommit commit; diff --git a/src/main/java/org/kohsuke/github/GHContentWithLicense.java b/src/main/java/org/kohsuke/github/GHContentWithLicense.java index c067d5a037..c5e6e37753 100644 --- a/src/main/java/org/kohsuke/github/GHContentWithLicense.java +++ b/src/main/java/org/kohsuke/github/GHContentWithLicense.java @@ -13,7 +13,7 @@ class GHContentWithLicense extends GHContent { @Override GHContentWithLicense wrap(GHRepository owner) { super.wrap(owner); - if (license!=null) + if (license != null) license.wrap(owner.root); return this; } diff --git a/src/main/java/org/kohsuke/github/GHCreateRepositoryBuilder.java b/src/main/java/org/kohsuke/github/GHCreateRepositoryBuilder.java index a11fc4493f..8c33e9efbe 100644 --- a/src/main/java/org/kohsuke/github/GHCreateRepositoryBuilder.java +++ b/src/main/java/org/kohsuke/github/GHCreateRepositoryBuilder.java @@ -13,123 +13,193 @@ public class GHCreateRepositoryBuilder { protected final Requester builder; private final String apiUrlTail; - /*package*/ GHCreateRepositoryBuilder(GitHub root, String apiUrlTail, String name) { + GHCreateRepositoryBuilder(GitHub root, String apiUrlTail, String name) { this.root = root; this.apiUrlTail = apiUrlTail; this.builder = new Requester(root); - this.builder.with("name",name); + this.builder.with("name", name); } + /** + * Description for repository + * + * @param description + * description of repository + * + * @return a builder to continue with building + */ public GHCreateRepositoryBuilder description(String description) { - this.builder.with("description",description); + this.builder.with("description", description); return this; } + /** + * Homepage for repository + * + * @param homepage + * homepage of repository + * + * @return a builder to continue with building + */ public GHCreateRepositoryBuilder homepage(URL homepage) { return homepage(homepage.toExternalForm()); } + /** + * Homepage for repository + * + * @param homepage + * homepage of repository + * + * @return a builder to continue with building + */ public GHCreateRepositoryBuilder homepage(String homepage) { - this.builder.with("homepage",homepage); + this.builder.with("homepage", homepage); return this; } /** * Creates a private repository + * + * @param enabled + * private if true + * @return a builder to continue with building */ - public GHCreateRepositoryBuilder private_(boolean b) { - this.builder.with("private",b); + public GHCreateRepositoryBuilder private_(boolean enabled) { + this.builder.with("private", enabled); return this; } /** * Enables issue tracker + * + * @param enabled + * true if enabled + * @return a builder to continue with building */ - public GHCreateRepositoryBuilder issues(boolean b) { - this.builder.with("has_issues",b); + public GHCreateRepositoryBuilder issues(boolean enabled) { + this.builder.with("has_issues", enabled); return this; } /** * Enables wiki + * + * @param enabled + * true if enabled + * @return a builder to continue with building */ - public GHCreateRepositoryBuilder wiki(boolean b) { - this.builder.with("has_wiki",b); + public GHCreateRepositoryBuilder wiki(boolean enabled) { + this.builder.with("has_wiki", enabled); return this; } /** * Enables downloads + * + * @param enabled + * true if enabled + * @return a builder to continue with building */ - public GHCreateRepositoryBuilder downloads(boolean b) { - this.builder.with("has_downloads",b); + public GHCreateRepositoryBuilder downloads(boolean enabled) { + this.builder.with("has_downloads", enabled); return this; } /** * If true, create an initial commit with empty README. + * + * @param enabled + * true if enabled + * @return a builder to continue with building */ - public GHCreateRepositoryBuilder autoInit(boolean b) { - this.builder.with("auto_init",b); + public GHCreateRepositoryBuilder autoInit(boolean enabled) { + this.builder.with("auto_init", enabled); return this; } /** * Allow or disallow squash-merging pull requests. + * + * @param enabled + * true if enabled + * @return a builder to continue with building */ - public GHCreateRepositoryBuilder allowSquashMerge(boolean b) { - this.builder.with("allow_squash_merge",b); + public GHCreateRepositoryBuilder allowSquashMerge(boolean enabled) { + this.builder.with("allow_squash_merge", enabled); return this; } /** * Allow or disallow merging pull requests with a merge commit. + * + * @param enabled + * true if enabled + * @return a builder to continue with building */ - public GHCreateRepositoryBuilder allowMergeCommit(boolean b) { - this.builder.with("allow_merge_commit",b); + public GHCreateRepositoryBuilder allowMergeCommit(boolean enabled) { + this.builder.with("allow_merge_commit", enabled); return this; } /** * Allow or disallow rebase-merging pull requests. + * + * @param enabled + * true if enabled + * @return a builder to continue with building */ - public GHCreateRepositoryBuilder allowRebaseMerge(boolean b) { - this.builder.with("allow_rebase_merge",b); + public GHCreateRepositoryBuilder allowRebaseMerge(boolean enabled) { + this.builder.with("allow_rebase_merge", enabled); return this; } /** * Creates a default .gitignore + * + * @param language + * template to base the ignore file on + * @return a builder to continue with building * - * See https://developer.github.com/v3/repos/#create + * See https://developer.github.com/v3/repos/#create */ public GHCreateRepositoryBuilder gitignoreTemplate(String language) { - this.builder.with("gitignore_template",language); + this.builder.with("gitignore_template", language); return this; } /** * Desired license template to apply + * + * @param license + * template to base the license file on + * @return a builder to continue with building * - * See https://developer.github.com/v3/repos/#create + * See https://developer.github.com/v3/repos/#create */ public GHCreateRepositoryBuilder licenseTemplate(String license) { - this.builder.with("license_template",license); + this.builder.with("license_template", license); return this; } /** - * The team that gets granted access to this repository. Only valid for creating a repository in - * an organization. + * The team that gets granted access to this repository. Only valid for creating a repository in an organization. + * + * @param team + * team to grant access to + * @return a builder to continue with building */ public GHCreateRepositoryBuilder team(GHTeam team) { - if (team!=null) - this.builder.with("team_id",team.getId()); + if (team != null) + this.builder.with("team_id", team.getId()); return this; } /** * Creates a repository with all the parameters. + * + * @throws IOException + * if repsitory cannot be created */ public GHRepository create() throws IOException { return builder.method("POST").to(apiUrlTail, GHRepository.class).wrap(root); diff --git a/src/main/java/org/kohsuke/github/GHDeployKey.java b/src/main/java/org/kohsuke/github/GHDeployKey.java index f5d0f9de6d..4b74875604 100644 --- a/src/main/java/org/kohsuke/github/GHDeployKey.java +++ b/src/main/java/org/kohsuke/github/GHDeployKey.java @@ -37,10 +37,11 @@ public GHDeployKey wrap(GHRepository repo) { } public String toString() { - return new ToStringBuilder(this).append("title",title).append("id",id).append("key",key).toString(); + return new ToStringBuilder(this).append("title", title).append("id", id).append("key", key).toString(); } - + public void delete() throws IOException { - new Requester(owner.root).method("DELETE").to(String.format("/repos/%s/%s/keys/%d", owner.getOwnerName(), owner.getName(), id)); + new Requester(owner.root).method("DELETE") + .to(String.format("/repos/%s/%s/keys/%d", owner.getOwnerName(), owner.getName(), id)); } } diff --git a/src/main/java/org/kohsuke/github/GHDeployment.java b/src/main/java/org/kohsuke/github/GHDeployment.java index 7a7febf6ce..ddff6158d6 100644 --- a/src/main/java/org/kohsuke/github/GHDeployment.java +++ b/src/main/java/org/kohsuke/github/GHDeployment.java @@ -23,11 +23,11 @@ public class GHDeployment extends GHObject { protected String repository_url; protected GHUser creator; - GHDeployment wrap(GHRepository owner) { this.owner = owner; this.root = owner.root; - if(creator != null) creator.wrapUp(root); + if (creator != null) + creator.wrapUp(root); return this; } @@ -42,19 +42,24 @@ public URL getRepositoryUrl() { public String getTask() { return task; } + public String getPayload() { return (String) payload; } + public String getEnvironment() { return environment; } + public GHUser getCreator() throws IOException { return root.intern(creator); } + public String getRef() { return ref; } - public String getSha(){ + + public String getSha() { return sha; } @@ -67,15 +72,11 @@ public URL getHtmlUrl() { } public GHDeploymentStatusBuilder createStatus(GHDeploymentState state) { - return new GHDeploymentStatusBuilder(owner,id,state); + return new GHDeploymentStatusBuilder(owner, id, state); } public PagedIterable listStatuses() { - return root.retrieve() - .asPagedIterable( - statuses_url, - GHDeploymentStatus[].class, - item -> item.wrap(owner) ); + return root.retrieve().asPagedIterable(statuses_url, GHDeploymentStatus[].class, item -> item.wrap(owner)); } } diff --git a/src/main/java/org/kohsuke/github/GHDeploymentBuilder.java b/src/main/java/org/kohsuke/github/GHDeploymentBuilder.java index 00d10fad1b..ed13e14241 100644 --- a/src/main/java/org/kohsuke/github/GHDeploymentBuilder.java +++ b/src/main/java/org/kohsuke/github/GHDeploymentBuilder.java @@ -19,37 +19,41 @@ public GHDeploymentBuilder(GHRepository repo, String ref) { } public GHDeploymentBuilder ref(String branch) { - builder.with("ref",branch); + builder.with("ref", branch); return this; } + public GHDeploymentBuilder task(String task) { - builder.with("task",task); + builder.with("task", task); return this; } + public GHDeploymentBuilder autoMerge(boolean autoMerge) { - builder.with("auto_merge",autoMerge); + builder.with("auto_merge", autoMerge); return this; } public GHDeploymentBuilder requiredContexts(List requiredContexts) { - builder.with("required_contexts",requiredContexts); + builder.with("required_contexts", requiredContexts); return this; } + public GHDeploymentBuilder payload(String payload) { - builder.with("payload",payload); + builder.with("payload", payload); return this; } public GHDeploymentBuilder environment(String environment) { - builder.with("environment",environment); + builder.with("environment", environment); return this; } + public GHDeploymentBuilder description(String description) { - builder.with("description",description); + builder.with("description", description); return this; } public GHDeployment create() throws IOException { - return builder.to(repo.getApiTailUrl("deployments"),GHDeployment.class).wrap(repo); + return builder.to(repo.getApiTailUrl("deployments"), GHDeployment.class).wrap(repo); } } diff --git a/src/main/java/org/kohsuke/github/GHDeploymentStatus.java b/src/main/java/org/kohsuke/github/GHDeploymentStatus.java index a058b8a447..b8c751bbc3 100644 --- a/src/main/java/org/kohsuke/github/GHDeploymentStatus.java +++ b/src/main/java/org/kohsuke/github/GHDeploymentStatus.java @@ -12,12 +12,15 @@ public class GHDeploymentStatus extends GHObject { protected String target_url; protected String deployment_url; protected String repository_url; + public GHDeploymentStatus wrap(GHRepository owner) { this.owner = owner; this.root = owner.root; - if(creator != null) creator.wrapUp(root); + if (creator != null) + creator.wrapUp(root); return this; } + public URL getTargetUrl() { return GitHub.parseURL(target_url); } @@ -29,7 +32,7 @@ public URL getDeploymentUrl() { public URL getRepositoryUrl() { return GitHub.parseURL(repository_url); } - + public GHDeploymentState getState() { return GHDeploymentState.valueOf(state.toUpperCase(Locale.ENGLISH)); } diff --git a/src/main/java/org/kohsuke/github/GHDeploymentStatusBuilder.java b/src/main/java/org/kohsuke/github/GHDeploymentStatusBuilder.java index 821a3e744e..c842c8ddd1 100644 --- a/src/main/java/org/kohsuke/github/GHDeploymentStatusBuilder.java +++ b/src/main/java/org/kohsuke/github/GHDeploymentStatusBuilder.java @@ -5,8 +5,7 @@ /** * Creates a new deployment status. * - * @see - * GHDeployment#createStatus(GHDeploymentState) + * @see GHDeployment#createStatus(GHDeploymentState) */ public class GHDeploymentStatusBuilder { private final Requester builder; @@ -14,31 +13,31 @@ public class GHDeploymentStatusBuilder { private long deploymentId; /** - * @deprecated - * Use {@link GHDeployment#createStatus(GHDeploymentState)} + * @deprecated Use {@link GHDeployment#createStatus(GHDeploymentState)} */ public GHDeploymentStatusBuilder(GHRepository repo, int deploymentId, GHDeploymentState state) { - this(repo,(long)deploymentId,state); + this(repo, (long) deploymentId, state); } - /*package*/ GHDeploymentStatusBuilder(GHRepository repo, long deploymentId, GHDeploymentState state) { + GHDeploymentStatusBuilder(GHRepository repo, long deploymentId, GHDeploymentState state) { this.repo = repo; this.deploymentId = deploymentId; this.builder = new Requester(repo.root); - this.builder.with("state",state); + this.builder.with("state", state); } public GHDeploymentStatusBuilder description(String description) { - this.builder.with("description",description); - return this; + this.builder.with("description", description); + return this; } public GHDeploymentStatusBuilder targetUrl(String targetUrl) { - this.builder.with("target_url",targetUrl); + this.builder.with("target_url", targetUrl); return this; } public GHDeploymentStatus create() throws IOException { - return builder.to(repo.getApiTailUrl("deployments/"+deploymentId+"/statuses"),GHDeploymentStatus.class).wrap(repo); + return builder.to(repo.getApiTailUrl("deployments/" + deploymentId + "/statuses"), GHDeploymentStatus.class) + .wrap(repo); } } diff --git a/src/main/java/org/kohsuke/github/GHEmail.java b/src/main/java/org/kohsuke/github/GHEmail.java index 9eeac04336..76246dab75 100644 --- a/src/main/java/org/kohsuke/github/GHEmail.java +++ b/src/main/java/org/kohsuke/github/GHEmail.java @@ -25,14 +25,13 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; - /** * Represents an email of GitHub. * * @author Kelly Campbell */ -@SuppressFBWarnings(value = {"UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", - "NP_UNWRITTEN_FIELD", "NP_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD"}, justification = "JSON API") +@SuppressFBWarnings(value = { "UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", "NP_UNWRITTEN_FIELD", + "NP_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD" }, justification = "JSON API") public class GHEmail { protected String email; @@ -51,10 +50,9 @@ public boolean isVerified() { return verified; } - @Override public String toString() { - return "Email:"+email; + return "Email:" + email; } @Override diff --git a/src/main/java/org/kohsuke/github/GHEvent.java b/src/main/java/org/kohsuke/github/GHEvent.java index 8ad6368fe5..7d92543449 100644 --- a/src/main/java/org/kohsuke/github/GHEvent.java +++ b/src/main/java/org/kohsuke/github/GHEvent.java @@ -10,57 +10,23 @@ * @see Event type reference */ public enum GHEvent { - COMMIT_COMMENT, - CREATE, - DELETE, - DEPLOYMENT, - DEPLOYMENT_STATUS, - DOWNLOAD, - FOLLOW, - FORK, - FORK_APPLY, - GIST, - GOLLUM, - INSTALLATION, - INSTALLATION_REPOSITORIES, - INTEGRATION_INSTALLATION_REPOSITORIES, - CHECK_SUITE, - ISSUE_COMMENT, - ISSUES, - LABEL, - MARKETPLACE_PURCHASE, - MEMBER, - MEMBERSHIP, - MILESTONE, - ORGANIZATION, - ORG_BLOCK, - PAGE_BUILD, - PROJECT_CARD, - PROJECT_COLUMN, - PROJECT, - PUBLIC, - PULL_REQUEST, - PULL_REQUEST_REVIEW, - PULL_REQUEST_REVIEW_COMMENT, - PUSH, - RELEASE, - REPOSITORY, // only valid for org hooks - STATUS, - TEAM, - TEAM_ADD, - WATCH, - PING, + COMMIT_COMMENT, CREATE, DELETE, DEPLOYMENT, DEPLOYMENT_STATUS, DOWNLOAD, FOLLOW, FORK, FORK_APPLY, GIST, GOLLUM, INSTALLATION, INSTALLATION_REPOSITORIES, INTEGRATION_INSTALLATION_REPOSITORIES, CHECK_SUITE, ISSUE_COMMENT, ISSUES, LABEL, MARKETPLACE_PURCHASE, MEMBER, MEMBERSHIP, MILESTONE, ORGANIZATION, ORG_BLOCK, PAGE_BUILD, PROJECT_CARD, PROJECT_COLUMN, PROJECT, PUBLIC, PULL_REQUEST, PULL_REQUEST_REVIEW, PULL_REQUEST_REVIEW_COMMENT, PUSH, RELEASE, REPOSITORY, // only + // valid + // for + // org + // hooks + STATUS, TEAM, TEAM_ADD, WATCH, PING, /** * Special event type that means "every possible event" */ ALL; - /** * Returns GitHub's internal representation of this event. */ String symbol() { - if (this==ALL) return "*"; + if (this == ALL) + return "*"; return name().toLowerCase(Locale.ENGLISH); } } diff --git a/src/main/java/org/kohsuke/github/GHEventInfo.java b/src/main/java/org/kohsuke/github/GHEventInfo.java index ca7e3d4f04..4e139c94d0 100644 --- a/src/main/java/org/kohsuke/github/GHEventInfo.java +++ b/src/main/java/org/kohsuke/github/GHEventInfo.java @@ -30,27 +30,28 @@ public class GHEventInfo { /** * Inside the event JSON model, GitHub uses a slightly different format. */ - @SuppressFBWarnings(value = {"UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", - "UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR" }, justification = "JSON API") + @SuppressFBWarnings(value = { "UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", + "UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR" }, justification = "JSON API") public static class GHEventRepository { @SuppressFBWarnings(value = "UUF_UNUSED_FIELD", justification = "We don't provide it in API now") private long id; @SuppressFBWarnings(value = "UUF_UNUSED_FIELD", justification = "We don't provide it in API now") - private String url; // repository API URL - private String name; // owner/repo + private String url; // repository API URL + private String name; // owner/repo } public GHEvent getType() { String t = type; - if (t.endsWith("Event")) t=t.substring(0,t.length()-5); + if (t.endsWith("Event")) + t = t.substring(0, t.length() - 5); for (GHEvent e : GHEvent.values()) { - if (e.name().replace("_","").equalsIgnoreCase(t)) + if (e.name().replace("_", "").equalsIgnoreCase(t)) return e; } - return null; // unknown event type + return null; // unknown event type } - /*package*/ GHEventInfo wrapUp(GitHub root) { + GHEventInfo wrapUp(GitHub root) { this.root = root; return this; } @@ -64,39 +65,52 @@ public Date getCreatedAt() { } /** - * Repository where the change was made. + * @return Repository where the change was made. + * @throws IOException + * on error */ - @SuppressFBWarnings(value = {"UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR" }, - justification = "The field comes from JSON deserialization") + @SuppressFBWarnings(value = { + "UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR" }, justification = "The field comes from JSON deserialization") public GHRepository getRepository() throws IOException { return root.getRepository(repo.name); } - - @SuppressFBWarnings(value = {"UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR" }, - justification = "The field comes from JSON deserialization") + + /** + * @return the {@link GHUser} actor for this event. + * @throws IOException + * on error + */ + @SuppressFBWarnings(value = { + "UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR" }, justification = "The field comes from JSON deserialization") public GHUser getActor() throws IOException { return root.getUser(actor.getLogin()); } /** - * Quick way to just get the actor of the login. + * @return the login of the actor. + * @throws IOException + * on error */ public String getActorLogin() throws IOException { return actor.getLogin(); } - @SuppressFBWarnings(value = {"UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR" }, - justification = "The field comes from JSON deserialization") + @SuppressFBWarnings(value = { + "UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR" }, justification = "The field comes from JSON deserialization") public GHOrganization getOrganization() throws IOException { - return (org==null || org.getLogin()==null) ? null : root.getOrganization(org.getLogin()); + return (org == null || org.getLogin() == null) ? null : root.getOrganization(org.getLogin()); } /** * Retrieves the payload. - * + * * @param type - * Specify one of the {@link GHEventPayload} subtype that defines a type-safe access to the payload. - * This must match the {@linkplain #getType() event type}. + * Specify one of the {@link GHEventPayload} subtype that defines a type-safe access to the payload. This + * must match the {@linkplain #getType() event type}. + * + * @return parsed event payload + * @throws IOException + * if payload cannot be parsed */ public T getPayload(Class type) throws IOException { T v = GitHub.MAPPER.readValue(payload.traverse(), type); diff --git a/src/main/java/org/kohsuke/github/GHEventPayload.java b/src/main/java/org/kohsuke/github/GHEventPayload.java index acdf5c74e9..01b29c88e8 100644 --- a/src/main/java/org/kohsuke/github/GHEventPayload.java +++ b/src/main/java/org/kohsuke/github/GHEventPayload.java @@ -9,7 +9,7 @@ /** * Base type for types used in databinding of the event payload. - * + * * @see GitHub#parseEventPayload(Reader, Class) * @see GHEventInfo#getPayload(Class) */ @@ -19,11 +19,12 @@ public abstract class GHEventPayload { private GHUser sender; - /*package*/ GHEventPayload() { + GHEventPayload() { } /** * Gets the sender or {@code null} if accessed via the events API. + * * @return the sender or {@code null} if accessed via the events API. */ public GHUser getSender() { @@ -34,7 +35,7 @@ public void setSender(GHUser sender) { this.sender = sender; } - /*package*/ void wrapUp(GitHub root) { + void wrapUp(GitHub root) { this.root = root; if (sender != null) { sender.wrapUp(root); @@ -46,8 +47,8 @@ public void setSender(GHUser sender) { * * @see authoritative source */ - @SuppressFBWarnings(value = {"UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", - "NP_UNWRITTEN_FIELD"}, justification = "JSON API") + @SuppressFBWarnings(value = { "UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", + "NP_UNWRITTEN_FIELD" }, justification = "JSON API") public static class PullRequest extends GHEventPayload { private String action; private int number; @@ -74,9 +75,10 @@ public GHRepository getRepository() { @Override void wrapUp(GitHub root) { super.wrapUp(root); - if (pull_request==null) - throw new IllegalStateException("Expected pull_request payload, but got something else. Maybe we've got another type of event?"); - if (repository!=null) { + if (pull_request == null) + throw new IllegalStateException( + "Expected pull_request payload, but got something else. Maybe we've got another type of event?"); + if (repository != null) { repository.wrap(root); pull_request.wrapUp(repository); } else { @@ -85,11 +87,11 @@ void wrapUp(GitHub root) { } } - /** * A review was added to a pull request * - * @see authoritative source + * @see authoritative + * source */ public static class PullRequestReview extends GHEventPayload { private String action; @@ -100,7 +102,7 @@ public static class PullRequestReview extends GHEventPayload { public String getAction() { return action; } - + public GHPullRequestReview getReview() { return review; } @@ -116,12 +118,13 @@ public GHRepository getRepository() { @Override void wrapUp(GitHub root) { super.wrapUp(root); - if (review==null) - throw new IllegalStateException("Expected pull_request_review payload, but got something else. Maybe we've got another type of event?"); - + if (review == null) + throw new IllegalStateException( + "Expected pull_request_review payload, but got something else. Maybe we've got another type of event?"); + review.wrapUp(pull_request); - - if (repository!=null) { + + if (repository != null) { repository.wrap(root); pull_request.wrapUp(repository); } else { @@ -129,11 +132,12 @@ void wrapUp(GitHub root) { } } } - + /** * A review comment was added to a pull request * - * @see authoritative source + * @see authoritative + * source */ public static class PullRequestReviewComment extends GHEventPayload { private String action; @@ -144,7 +148,7 @@ public static class PullRequestReviewComment extends GHEventPayload { public String getAction() { return action; } - + public GHPullRequestReviewComment getComment() { return comment; } @@ -160,12 +164,13 @@ public GHRepository getRepository() { @Override void wrapUp(GitHub root) { super.wrapUp(root); - if (comment==null) - throw new IllegalStateException("Expected pull_request_review_comment payload, but got something else. Maybe we've got another type of event?"); - + if (comment == null) + throw new IllegalStateException( + "Expected pull_request_review_comment payload, but got something else. Maybe we've got another type of event?"); + comment.wrapUp(pull_request); - - if (repository!=null) { + + if (repository != null) { repository.wrap(root); pull_request.wrapUp(repository); } else { @@ -175,12 +180,13 @@ void wrapUp(GitHub root) { } /** - * A Issue has been assigned, unassigned, labeled, unlabeled, opened, edited, milestoned, demilestoned, closed, or reopened. + * A Issue has been assigned, unassigned, labeled, unlabeled, opened, edited, milestoned, demilestoned, closed, or + * reopened. * * @see authoritative source */ - @SuppressFBWarnings(value = {"UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", "NP_UNWRITTEN_FIELD" }, - justification = "Constructed by JSON deserialization") + @SuppressFBWarnings(value = { "UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", + "NP_UNWRITTEN_FIELD" }, justification = "Constructed by JSON deserialization") public static class Issue extends GHEventPayload { private String action; private GHIssue issue; @@ -224,8 +230,8 @@ void wrapUp(GitHub root) { * * @see authoritative source */ - @SuppressFBWarnings(value = {"UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", "NP_UNWRITTEN_FIELD" }, - justification = "Constructed by JSON deserialization") + @SuppressFBWarnings(value = { "UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", + "NP_UNWRITTEN_FIELD" }, justification = "Constructed by JSON deserialization") public static class IssueComment extends GHEventPayload { private String action; private GHIssueComment comment; @@ -279,8 +285,8 @@ void wrapUp(GitHub root) { * * @see authoritative source */ - @SuppressFBWarnings(value = {"UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", "NP_UNWRITTEN_FIELD" }, - justification = "Constructed by JSON deserialization") + @SuppressFBWarnings(value = { "UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", + "NP_UNWRITTEN_FIELD" }, justification = "Constructed by JSON deserialization") public static class CommitComment extends GHEventPayload { private String action; private GHCommitComment comment; @@ -322,8 +328,8 @@ void wrapUp(GitHub root) { * * @see authoritative source */ - @SuppressFBWarnings(value = {"UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", "NP_UNWRITTEN_FIELD" }, - justification = "Constructed by JSON deserialization") + @SuppressFBWarnings(value = { "UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", + "NP_UNWRITTEN_FIELD" }, justification = "Constructed by JSON deserialization") public static class Create extends GHEventPayload { private String ref; @JsonProperty("ref_type") @@ -375,8 +381,8 @@ void wrapUp(GitHub root) { * * @see authoritative source */ - @SuppressFBWarnings(value = {"UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", "NP_UNWRITTEN_FIELD" }, - justification = "Constructed by JSON deserialization") + @SuppressFBWarnings(value = { "UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", + "NP_UNWRITTEN_FIELD" }, justification = "Constructed by JSON deserialization") public static class Delete extends GHEventPayload { private String ref; @JsonProperty("ref_type") @@ -415,8 +421,8 @@ void wrapUp(GitHub root) { * * @see authoritative source */ - @SuppressFBWarnings(value = {"UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", "NP_UNWRITTEN_FIELD" }, - justification = "Constructed by JSON deserialization") + @SuppressFBWarnings(value = { "UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", + "NP_UNWRITTEN_FIELD" }, justification = "Constructed by JSON deserialization") public static class Deployment extends GHEventPayload { private GHDeployment deployment; private GHRepository repository; @@ -450,10 +456,11 @@ void wrapUp(GitHub root) { /** * A deployment * - * @see authoritative source + * @see authoritative + * source */ - @SuppressFBWarnings(value = {"UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", "NP_UNWRITTEN_FIELD" }, - justification = "Constructed by JSON deserialization") + @SuppressFBWarnings(value = { "UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", + "NP_UNWRITTEN_FIELD" }, justification = "Constructed by JSON deserialization") public static class DeploymentStatus extends GHEventPayload { @JsonProperty("deployment_status") private GHDeploymentStatus deploymentStatus; @@ -500,13 +507,12 @@ void wrapUp(GitHub root) { * * @see authoritative source */ - @SuppressFBWarnings(value = {"UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", "NP_UNWRITTEN_FIELD" }, - justification = "Constructed by JSON deserialization") + @SuppressFBWarnings(value = { "UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", + "NP_UNWRITTEN_FIELD" }, justification = "Constructed by JSON deserialization") public static class Fork extends GHEventPayload { private GHRepository forkee; private GHRepository repository; - public GHRepository getForkee() { return forkee; } @@ -559,7 +565,7 @@ public void setOrganization(GHOrganization organization) { @Override void wrapUp(GitHub root) { super.wrapUp(root); - if (repository!=null) + if (repository != null) repository.wrap(root); if (organization != null) { organization.wrapUp(root); @@ -587,7 +593,7 @@ public GHRepository getRepository() { @Override void wrapUp(GitHub root) { super.wrapUp(root); - if (repository!=null) + if (repository != null) repository.wrap(root); } @@ -598,8 +604,8 @@ void wrapUp(GitHub root) { * * @see authoritative source */ - @SuppressFBWarnings(value = {"UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", "NP_UNWRITTEN_FIELD", "UUF_UNUSED_FIELD"}, - justification = "Constructed by JSON deserialization") + @SuppressFBWarnings(value = { "UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", "NP_UNWRITTEN_FIELD", + "UUF_UNUSED_FIELD" }, justification = "Constructed by JSON deserialization") public static class Push extends GHEventPayload { private String head, before; private boolean created, deleted, forced; @@ -617,8 +623,8 @@ public String getHead() { } /** - * This is undocumented, but it looks like this captures the commit that the ref was pointing to - * before the push. + * This is undocumented, but it looks like this captures the commit that the ref was pointing to before the + * push. */ public String getBefore() { return before; @@ -637,8 +643,7 @@ public String getRef() { } /** - * The number of commits in the push. - * Is this always the same as {@code getCommits().size()}? + * The number of commits in the push. Is this always the same as {@code getCommits().size()}? */ public int getSize() { return size; @@ -678,7 +683,7 @@ public void setPusher(Pusher pusher) { @Override void wrapUp(GitHub root) { super.wrapUp(root); - if (repository!=null) + if (repository != null) repository.wrap(root); } @@ -766,8 +771,8 @@ public List getModified() { * * @see authoritative source */ - @SuppressFBWarnings(value = {"UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", "NP_UNWRITTEN_FIELD" }, - justification = "Constructed by JSON deserialization") + @SuppressFBWarnings(value = { "UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", + "NP_UNWRITTEN_FIELD" }, justification = "Constructed by JSON deserialization") public static class Release extends GHEventPayload { private String action; private GHRelease release; @@ -808,8 +813,8 @@ void wrapUp(GitHub root) { * * @see authoritative source */ - @SuppressFBWarnings(value = {"UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", "NP_UNWRITTEN_FIELD", "UWF_UNWRITTEN_FIELD"}, - justification = "Constructed by JSON deserialization") + @SuppressFBWarnings(value = { "UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", "NP_UNWRITTEN_FIELD", + "UWF_UNWRITTEN_FIELD" }, justification = "Constructed by JSON deserialization") public static class Repository extends GHEventPayload { private String action; private GHRepository repository; diff --git a/src/main/java/org/kohsuke/github/GHFileNotFoundException.java b/src/main/java/org/kohsuke/github/GHFileNotFoundException.java index 9f4b37c560..b8ebadddf8 100644 --- a/src/main/java/org/kohsuke/github/GHFileNotFoundException.java +++ b/src/main/java/org/kohsuke/github/GHFileNotFoundException.java @@ -7,8 +7,7 @@ import java.util.Map; /** - * Request/responce contains useful metadata. - * Custom exception allows store info for next diagnostics. + * Request/responce contains useful metadata. Custom exception allows store info for next diagnostics. * * @author Kanstantsin Shautsou */ diff --git a/src/main/java/org/kohsuke/github/GHGist.java b/src/main/java/org/kohsuke/github/GHGist.java index 19a2b626f2..c8681f5c0f 100644 --- a/src/main/java/org/kohsuke/github/GHGist.java +++ b/src/main/java/org/kohsuke/github/GHGist.java @@ -20,8 +20,8 @@ * @see documentation */ public class GHGist extends GHObject { - /*package almost final*/ GHUser owner; - /*package almost final*/ GitHub root; + /* package almost final */ GHUser owner; + /* package almost final */ GitHub root; private String forks_url, commits_url, id, git_pull_url, git_push_url, html_url; @@ -34,10 +34,10 @@ public class GHGist extends GHObject { private String comments_url; - private Map files = new HashMap(); + private Map files = new HashMap(); /** - * User that owns this Gist. + * @return User that owns this Gist. */ public GHUser getOwner() throws IOException { return root.intern(owner); @@ -52,7 +52,7 @@ public String getCommitsUrl() { } /** - * URL like https://gist.github.com/gists/12345.git + * @return URL like https://gist.github.com/gists/12345.git */ public String getGitPullUrl() { return git_pull_url; @@ -79,7 +79,7 @@ public int getCommentCount() { } /** - * API URL of listing comments. + * @return API URL of listing comments. */ public String getCommentsUrl() { return comments_url; @@ -89,11 +89,11 @@ public GHGistFile getFile(String name) { return files.get(name); } - public Map getFiles() { + public Map getFiles() { return Collections.unmodifiableMap(files); } - /*package*/ GHGist wrapUp(GHUser owner) { + GHGist wrapUp(GHUser owner) { this.owner = owner; this.root = owner.root; wrapUp(); @@ -101,10 +101,10 @@ public Map getFiles() { } /** - * Used when caller obtains {@link GHGist} without knowing its owner. - * A partially constructed owner object is interned. + * Used when caller obtains {@link GHGist} without knowing its owner. A partially constructed owner object is + * interned. */ - /*package*/ GHGist wrapUp(GitHub root) { + GHGist wrapUp(GitHub root) { this.owner = root.getUser(owner); this.root = root; wrapUp(); @@ -134,22 +134,18 @@ public void unstar() throws IOException { } public boolean isStarred() throws IOException { - return root.retrieve().asHttpStatusCode(getApiTailUrl("star"))/100==2; + return root.retrieve().asHttpStatusCode(getApiTailUrl("star")) / 100 == 2; } /** * Forks this gist into your own. */ public GHGist fork() throws IOException { - return new Requester(root).to(getApiTailUrl("forks"),GHGist.class).wrapUp(root); + return new Requester(root).to(getApiTailUrl("forks"), GHGist.class).wrapUp(root); } public PagedIterable listForks() { - return root.retrieve() - .asPagedIterable( - getApiTailUrl("forks"), - GHGist[].class, - item -> item.wrapUp(root) ); + return root.retrieve().asPagedIterable(getApiTailUrl("forks"), GHGist[].class, item -> item.wrapUp(root)); } /** @@ -168,8 +164,10 @@ public GHGistUpdater update() throws IOException { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; GHGist ghGist = (GHGist) o; return id.equals(ghGist.id); diff --git a/src/main/java/org/kohsuke/github/GHGistBuilder.java b/src/main/java/org/kohsuke/github/GHGistBuilder.java index 57fd255031..c8742ad61d 100644 --- a/src/main/java/org/kohsuke/github/GHGistBuilder.java +++ b/src/main/java/org/kohsuke/github/GHGistBuilder.java @@ -13,7 +13,7 @@ public class GHGistBuilder { private final GitHub root; private final Requester req; - private final LinkedHashMap files = new LinkedHashMap(); + private final LinkedHashMap files = new LinkedHashMap(); public GHGistBuilder(GitHub root) { this.root = root; @@ -21,17 +21,17 @@ public GHGistBuilder(GitHub root) { } public GHGistBuilder description(String desc) { - req.with("description",desc); + req.with("description", desc); return this; } public GHGistBuilder public_(boolean v) { - req.with("public",v); + req.with("public", v); return this; } /** - * Adds a new file. + * @return Adds a new file. */ public GHGistBuilder file(String fileName, String content) { files.put(fileName, Collections.singletonMap("content", content)); @@ -40,9 +40,13 @@ public GHGistBuilder file(String fileName, String content) { /** * Creates a Gist based on the parameters specified thus far. + * + * @return created Gist + * @throws IOException + * if Gist cannot be created. */ public GHGist create() throws IOException { - req._with("files",files); - return req.to("/gists",GHGist.class).wrapUp(root); + req._with("files", files); + return req.to("/gists", GHGist.class).wrapUp(root); } } diff --git a/src/main/java/org/kohsuke/github/GHGistFile.java b/src/main/java/org/kohsuke/github/GHGistFile.java index 605afc993a..4f8084de1b 100644 --- a/src/main/java/org/kohsuke/github/GHGistFile.java +++ b/src/main/java/org/kohsuke/github/GHGistFile.java @@ -8,13 +8,12 @@ * @see GHGist#getFiles() */ public class GHGistFile { - /*package almost final*/ String fileName; + /* package almost final */ String fileName; private int size; private String raw_url, type, language, content; private boolean truncated; - public String getFileName() { return fileName; } diff --git a/src/main/java/org/kohsuke/github/GHGistUpdater.java b/src/main/java/org/kohsuke/github/GHGistUpdater.java index 71bff34e22..40c37bded6 100644 --- a/src/main/java/org/kohsuke/github/GHGistUpdater.java +++ b/src/main/java/org/kohsuke/github/GHGistUpdater.java @@ -12,7 +12,7 @@ public class GHGistUpdater { private final GHGist base; private final Requester builder; - LinkedHashMap files; + LinkedHashMap files; GHGistUpdater(GHGist base) { this.base = base; @@ -26,14 +26,13 @@ public GHGistUpdater addFile(String fileName, String content) throws IOException return this; } -// // This method does not work. -// public GHGistUpdater deleteFile(String fileName) throws IOException { -// files.put(fileName, Collections.singletonMap("filename", null)); -// return this; -// } + // // This method does not work. + // public GHGistUpdater deleteFile(String fileName) throws IOException { + // files.put(fileName, Collections.singletonMap("filename", null)); + // return this; + // } - public GHGistUpdater renameFile(String fileName, String newFileName) throws IOException - { + public GHGistUpdater renameFile(String fileName, String newFileName) throws IOException { files.put(fileName, Collections.singletonMap("filename", newFileName)); return this; } @@ -44,7 +43,7 @@ public GHGistUpdater updateFile(String fileName, String content) throws IOExcept } public GHGistUpdater description(String desc) { - builder.with("description",desc); + builder.with("description", desc); return this; } @@ -53,8 +52,6 @@ public GHGistUpdater description(String desc) { */ public GHGist update() throws IOException { builder._with("files", files); - return builder - .method("PATCH") - .to(base.getApiTailUrl(""), GHGist.class).wrap(base.owner); + return builder.method("PATCH").to(base.getApiTailUrl(""), GHGist.class).wrap(base.owner); } } diff --git a/src/main/java/org/kohsuke/github/GHHook.java b/src/main/java/org/kohsuke/github/GHHook.java index b7f450307a..4ede438bb5 100644 --- a/src/main/java/org/kohsuke/github/GHHook.java +++ b/src/main/java/org/kohsuke/github/GHHook.java @@ -13,13 +13,13 @@ /** * @author Kohsuke Kawaguchi */ -@SuppressFBWarnings(value = {"UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", - "NP_UNWRITTEN_FIELD"}, justification = "JSON API") +@SuppressFBWarnings(value = { "UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", + "NP_UNWRITTEN_FIELD" }, justification = "JSON API") public abstract class GHHook extends GHObject { String name; List events; boolean active; - Map config; + Map config; public String getName() { return name; @@ -28,8 +28,10 @@ public String getName() { public EnumSet getEvents() { EnumSet s = EnumSet.noneOf(GHEvent.class); for (String e : events) { - if (e.equals("*")) s.add(GHEvent.ALL); - else s.add(Enum.valueOf(GHEvent.class, e.toUpperCase(Locale.ENGLISH))); + if (e.equals("*")) + s.add(GHEvent.ALL); + else + s.add(Enum.valueOf(GHEvent.class, e.toUpperCase(Locale.ENGLISH))); } return s; } diff --git a/src/main/java/org/kohsuke/github/GHHooks.java b/src/main/java/org/kohsuke/github/GHHooks.java index 6ecbb04b6e..5b994b141b 100644 --- a/src/main/java/org/kohsuke/github/GHHooks.java +++ b/src/main/java/org/kohsuke/github/GHHooks.java @@ -16,15 +16,16 @@ static abstract class Context { private final GitHub root; private Context(GitHub root) { - this.root = root; + this.root = root; } public List getHooks() throws IOException { - - GHHook [] hookArray = root.retrieve().to(collection(),collectionClass()); // jdk/eclipse bug requires this to be on separate line + + GHHook[] hookArray = root.retrieve().to(collection(), collectionClass()); // jdk/eclipse bug requires this + // to be on separate line List list = new ArrayList(Arrays.asList(hookArray)); for (GHHook h : list) - wrap(h); + wrap(h); return list; } @@ -33,20 +34,17 @@ public GHHook getHook(int id) throws IOException { return wrap(hook); } - public GHHook createHook(String name, Map config, Collection events, boolean active) throws IOException { + public GHHook createHook(String name, Map config, Collection events, boolean active) + throws IOException { List ea = null; - if (events!=null) { - ea = new ArrayList(); - for (GHEvent e : events) - ea.add(e.symbol()); + if (events != null) { + ea = new ArrayList(); + for (GHEvent e : events) + ea.add(e.symbol()); } - GHHook hook = new Requester(root) - .with("name", name) - .with("active", active) - ._with("config", config) - ._with("events", ea) - .to(collection(), clazz()); + GHHook hook = new Requester(root).with("name", name).with("active", active)._with("config", config) + ._with("events", ea).to(collection(), clazz()); return wrap(hook); } @@ -87,7 +85,7 @@ Class clazz() { @Override GHHook wrap(GHHook hook) { - return ((GHRepoHook)hook).wrap(repository); + return ((GHRepoHook) hook).wrap(repository); } } @@ -116,15 +114,15 @@ Class clazz() { @Override GHHook wrap(GHHook hook) { - return ((GHOrgHook)hook).wrap(organization); + return ((GHOrgHook) hook).wrap(organization); } } - static Context repoContext(GHRepository repository, GHUser owner) { - return new RepoContext(repository, owner); - } + static Context repoContext(GHRepository repository, GHUser owner) { + return new RepoContext(repository, owner); + } - static Context orgContext(GHOrganization organization) { - return new OrgContext(organization); - } + static Context orgContext(GHOrganization organization) { + return new OrgContext(organization); + } } diff --git a/src/main/java/org/kohsuke/github/GHIOException.java b/src/main/java/org/kohsuke/github/GHIOException.java index b07144bcb7..45dc3404ed 100644 --- a/src/main/java/org/kohsuke/github/GHIOException.java +++ b/src/main/java/org/kohsuke/github/GHIOException.java @@ -7,8 +7,7 @@ import java.util.Map; /** - * Request/responce contains useful metadata. - * Custom exception allows store info for next diagnostics. + * Request/responce contains useful metadata. Custom exception allows store info for next diagnostics. * * @author Kanstantsin Shautsou */ diff --git a/src/main/java/org/kohsuke/github/GHInvitation.java b/src/main/java/org/kohsuke/github/GHInvitation.java index 74619ad6e0..5db4eb4282 100644 --- a/src/main/java/org/kohsuke/github/GHInvitation.java +++ b/src/main/java/org/kohsuke/github/GHInvitation.java @@ -9,10 +9,10 @@ * @see GitHub#getMyInvitations() * @see GHRepository#listInvitations() */ -@SuppressFBWarnings(value = {"UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", - "NP_UNWRITTEN_FIELD", "UUF_UNUSED_FIELD"}, justification = "JSON API") +@SuppressFBWarnings(value = { "UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", "NP_UNWRITTEN_FIELD", + "UUF_UNUSED_FIELD" }, justification = "JSON API") public class GHInvitation extends GHObject { - /*package almost final*/ GitHub root; + /* package almost final */ GitHub root; private int id; private GHRepository repository; @@ -20,7 +20,7 @@ public class GHInvitation extends GHObject { private String permissions; private String html_url; - /*package*/ GHInvitation wrapUp(GitHub root) { + GHInvitation wrapUp(GitHub root) { this.root = root; return this; } diff --git a/src/main/java/org/kohsuke/github/GHIssue.java b/src/main/java/org/kohsuke/github/GHIssue.java index 20343266b7..dfd8102372 100644 --- a/src/main/java/org/kohsuke/github/GHIssue.java +++ b/src/main/java/org/kohsuke/github/GHIssue.java @@ -49,14 +49,14 @@ * @see GitHub#searchIssues() * @see GHIssueSearchBuilder */ -public class GHIssue extends GHObject implements Reactable{ +public class GHIssue extends GHObject implements Reactable { private static final String ASSIGNEES = "assignees"; GitHub root; GHRepository owner; - + // API v3 - protected GHUser assignee; // not sure what this field is now that 'assignees' exist + protected GHUser assignee; // not sure what this field is now that 'assignees' exist protected GHUser[] assignees; protected String state; protected int number; @@ -78,23 +78,28 @@ public class GHIssue extends GHObject implements Reactable{ */ public static class Label extends GHLabel { } - - /*package*/ GHIssue wrap(GHRepository owner) { + + GHIssue wrap(GHRepository owner) { this.owner = owner; - if(milestone != null) milestone.wrap(owner); + if (milestone != null) + milestone.wrap(owner); return wrap(owner.root); } - /*package*/ GHIssue wrap(GitHub root) { + GHIssue wrap(GitHub root) { this.root = root; - if(assignee != null) assignee.wrapUp(root); - if(assignees!=null) GHUser.wrap(assignees,root); - if(user != null) user.wrapUp(root); - if(closed_by != null) closed_by.wrapUp(root); + if (assignee != null) + assignee.wrapUp(root); + if (assignees != null) + GHUser.wrap(assignees, root); + if (user != null) + user.wrapUp(root); + if (closed_by != null) + closed_by.wrapUp(root); return this; } - /*package*/ static GHIssue[] wrap(GHIssue[] issues, GHRepository owner) { + static GHIssue[] wrap(GHIssue[] issues, GHRepository owner) { for (GHIssue i : issues) i.wrap(owner); return issues; @@ -122,8 +127,7 @@ public int getNumber() { } /** - * The HTML page of this issue, - * like https://github.com/jenkinsci/jenkins/issues/100 + * The HTML page of this issue, like https://github.com/jenkinsci/jenkins/issues/100 */ public URL getHtmlUrl() { return GitHub.parseURL(html_url); @@ -142,37 +146,37 @@ public GHIssueState getState() { } public Collection getLabels() throws IOException { - if(labels == null){ + if (labels == null) { return Collections.emptyList(); } - return Collections.unmodifiableList(labels); + return Collections. unmodifiableList(labels); } public Date getClosedAt() { return GitHub.parseDate(closed_at); } - public URL getApiURL(){ + public URL getApiURL() { return GitHub.parseURL(url); } public void lock() throws IOException { - new Requester(root).method("PUT").to(getApiRoute()+"/lock"); + new Requester(root).method("PUT").to(getApiRoute() + "/lock"); } public void unlock() throws IOException { - new Requester(root).method("PUT").to(getApiRoute()+"/lock"); + new Requester(root).method("PUT").to(getApiRoute() + "/lock"); } /** * Updates the issue by adding a comment. * - * @return - * Newly posted comment. + * @return Newly posted comment. */ @WithBridgeMethods(void.class) public GHIssueComment comment(String message) throws IOException { - GHIssueComment r = new Requester(root).with("body",message).to(getIssuesApiRoute() + "/comments", GHIssueComment.class); + GHIssueComment r = new Requester(root).with("body", message).to(getIssuesApiRoute() + "/comments", + GHIssueComment.class); return r.wrapUp(this); } @@ -199,15 +203,15 @@ public void reopen() throws IOException { } public void setTitle(String title) throws IOException { - edit("title",title); + edit("title", title); } public void setBody(String body) throws IOException { - edit("body",body); + edit("body", body); } public void setMilestone(GHMilestone milestone) throws IOException { - edit("milestone",milestone.getNumber()); + edit("milestone", milestone.getNumber()); } public void assignTo(GHUser user) throws IOException { @@ -215,13 +219,14 @@ public void assignTo(GHUser user) throws IOException { } public void setLabels(String... labels) throws IOException { - editIssue("labels",labels); + editIssue("labels", labels); } /** * Adds labels to the issue. * - * @param names Names of the label + * @param names + * Names of the label */ public void addLabels(String... names) throws IOException { _addLabels(Arrays.asList(names)); @@ -281,39 +286,33 @@ private void _removeLabels(Collection names) throws IOException { /** * Obtains all the comments associated with this issue. - * - * @see #listComments() + * + * @see #listComments() */ public List getComments() throws IOException { return listComments().asList(); } - + /** * Obtains all the comments associated with this issue. */ public PagedIterable listComments() throws IOException { - return root.retrieve() - .asPagedIterable( - getIssuesApiRoute() + "/comments", - GHIssueComment[].class, - item -> item.wrapUp(GHIssue.this) ); + return root.retrieve().asPagedIterable(getIssuesApiRoute() + "/comments", GHIssueComment[].class, + item -> item.wrapUp(GHIssue.this)); } - @Preview @Deprecated + @Preview + @Deprecated public GHReaction createReaction(ReactionContent content) throws IOException { - return new Requester(owner.root) - .withPreview(SQUIRREL_GIRL) - .with("content", content.getContent()) - .to(getApiRoute()+"/reactions", GHReaction.class).wrap(root); + return new Requester(owner.root).withPreview(SQUIRREL_GIRL).with("content", content.getContent()) + .to(getApiRoute() + "/reactions", GHReaction.class).wrap(root); } - @Preview @Deprecated + @Preview + @Deprecated public PagedIterable listReactions() { - return owner.root.retrieve().withPreview(SQUIRREL_GIRL) - .asPagedIterable( - getApiRoute()+"/reactions", - GHReaction[].class, - item -> item.wrap(owner.root) ); + return owner.root.retrieve().withPreview(SQUIRREL_GIRL).asPagedIterable(getApiRoute() + "/reactions", + GHReaction[].class, item -> item.wrap(owner.root)); } public void addAssignees(GHUser... assignees) throws IOException { @@ -321,7 +320,7 @@ public void addAssignees(GHUser... assignees) throws IOException { } public void addAssignees(Collection assignees) throws IOException { - root.retrieve().method("POST").withLogins(ASSIGNEES,assignees).to(getIssuesApiRoute()+"/assignees",this); + root.retrieve().method("POST").withLogins(ASSIGNEES, assignees).to(getIssuesApiRoute() + "/assignees", this); } public void setAssignees(GHUser... assignees) throws IOException { @@ -337,7 +336,8 @@ public void removeAssignees(GHUser... assignees) throws IOException { } public void removeAssignees(Collection assignees) throws IOException { - root.retrieve().method("DELETE").withLogins(ASSIGNEES,assignees).inBody().to(getIssuesApiRoute()+"/assignees",this); + root.retrieve().method("DELETE").withLogins(ASSIGNEES, assignees).inBody() + .to(getIssuesApiRoute() + "/assignees", this); } protected String getApiRoute() { @@ -345,7 +345,7 @@ protected String getApiRoute() { } protected String getIssuesApiRoute() { - return "/repos/"+owner.getOwnerName()+"/"+owner.getName()+"/issues/"+number; + return "/repos/" + owner.getOwnerName() + "/" + owner.getName() + "/issues/" + number; } public GHUser getAssignee() throws IOException { @@ -367,23 +367,21 @@ public GHUser getUser() throws IOException { * Reports who has closed the issue. * *

- * Note that GitHub doesn't always seem to report this information - * even for an issue that's already closed. See + * Note that GitHub doesn't always seem to report this information even for an issue that's already closed. See * https://github.com/kohsuke/github-api/issues/60. */ public GHUser getClosedBy() throws IOException { - if(!"closed".equals(state)) return null; + if (!"closed".equals(state)) + return null; - //TODO + // TODO /* - if (closed_by==null) { - closed_by = owner.getIssue(number).getClosed_by(); - } - */ + * if (closed_by==null) { closed_by = owner.getIssue(number).getClosed_by(); } + */ return root.intern(closed_by); } - - public int getCommentsCount(){ + + public int getCommentsCount() { return comments; } @@ -395,39 +393,36 @@ public PullRequest getPullRequest() { } public boolean isPullRequest() { - return pull_request!=null; + return pull_request != null; } public GHMilestone getMilestone() { return milestone; } - @SuppressFBWarnings(value = {"UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD"}, - justification = "JSON API") - public static class PullRequest{ + @SuppressFBWarnings(value = { "UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", + "UWF_UNWRITTEN_FIELD" }, justification = "JSON API") + public static class PullRequest { private String diff_url, patch_url, html_url; - + public URL getDiffUrl() { return GitHub.parseURL(diff_url); } - + public URL getPatchUrl() { return GitHub.parseURL(patch_url); } - + public URL getUrl() { return GitHub.parseURL(html_url); } } /** - * Lists events for this issue. - * See https://developer.github.com/v3/issues/events/ + * Lists events for this issue. See https://developer.github.com/v3/issues/events/ */ public PagedIterable listEvents() throws IOException { - return root.retrieve().asPagedIterable( - owner.getApiTailUrl(String.format("/issues/%s/events", number)), - GHIssueEvent[].class, - item -> item.wrapUp(GHIssue.this) ); + return root.retrieve().asPagedIterable(owner.getApiTailUrl(String.format("/issues/%s/events", number)), + GHIssueEvent[].class, item -> item.wrapUp(GHIssue.this)); } } diff --git a/src/main/java/org/kohsuke/github/GHIssueBuilder.java b/src/main/java/org/kohsuke/github/GHIssueBuilder.java index 3a5a532308..e1dbba012e 100644 --- a/src/main/java/org/kohsuke/github/GHIssueBuilder.java +++ b/src/main/java/org/kohsuke/github/GHIssueBuilder.java @@ -16,37 +16,37 @@ public class GHIssueBuilder { GHIssueBuilder(GHRepository repo, String title) { this.repo = repo; this.builder = new Requester(repo.root); - builder.with("title",title); + builder.with("title", title); } /** * Sets the main text of an issue, which is arbitrary multi-line text. */ public GHIssueBuilder body(String str) { - builder.with("body",str); + builder.with("body", str); return this; } public GHIssueBuilder assignee(GHUser user) { - if (user!=null) + if (user != null) assignees.add(user.getLogin()); return this; } public GHIssueBuilder assignee(String user) { - if (user!=null) + if (user != null) assignees.add(user); return this; } public GHIssueBuilder milestone(GHMilestone milestone) { - if (milestone!=null) - builder.with("milestone",milestone.getNumber()); + if (milestone != null) + builder.with("milestone", milestone.getNumber()); return this; } public GHIssueBuilder label(String label) { - if (label!=null) + if (label != null) labels.add(label); return this; } @@ -55,6 +55,7 @@ public GHIssueBuilder label(String label) { * Creates a new issue. */ public GHIssue create() throws IOException { - return builder.with("labels",labels).with("assignees",assignees).to(repo.getApiTailUrl("issues"),GHIssue.class).wrap(repo); + return builder.with("labels", labels).with("assignees", assignees) + .to(repo.getApiTailUrl("issues"), GHIssue.class).wrap(repo); } } diff --git a/src/main/java/org/kohsuke/github/GHIssueComment.java b/src/main/java/org/kohsuke/github/GHIssueComment.java index 258718312c..cddc2e02f5 100644 --- a/src/main/java/org/kohsuke/github/GHIssueComment.java +++ b/src/main/java/org/kohsuke/github/GHIssueComment.java @@ -41,7 +41,7 @@ public class GHIssueComment extends GHObject implements Reactable { private String body, gravatar_id, html_url, author_association; private GHUser user; // not fully populated. beware. - /*package*/ GHIssueComment wrapUp(GHIssue owner) { + GHIssueComment wrapUp(GHIssue owner) { this.owner = owner; return this; } @@ -74,7 +74,7 @@ public String getUserName() { public GHUser getUser() throws IOException { return owner == null || owner.root.isOffline() ? user : owner.root.getUser(user.getLogin()); } - + @Override public URL getHtmlUrl() { return GitHub.parseURL(html_url); @@ -83,7 +83,7 @@ public URL getHtmlUrl() { public GHCommentAuthorAssociation getAuthorAssociation() { return GHCommentAuthorAssociation.valueOf(author_association); } - + /** * Updates the body of the issue comment. */ @@ -99,25 +99,22 @@ public void delete() throws IOException { new Requester(owner.root).method("DELETE").to(getApiRoute()); } - @Preview @Deprecated + @Preview + @Deprecated public GHReaction createReaction(ReactionContent content) throws IOException { - return new Requester(owner.root) - .withPreview(SQUIRREL_GIRL) - .with("content", content.getContent()) - .to(getApiRoute()+"/reactions", GHReaction.class).wrap(owner.root); + return new Requester(owner.root).withPreview(SQUIRREL_GIRL).with("content", content.getContent()) + .to(getApiRoute() + "/reactions", GHReaction.class).wrap(owner.root); } - @Preview @Deprecated + @Preview + @Deprecated public PagedIterable listReactions() { - return owner.root.retrieve() - .withPreview(SQUIRREL_GIRL) - .asPagedIterable( - getApiRoute()+"/reactions", - GHReaction[].class, - item -> item.wrap(owner.root) ); + return owner.root.retrieve().withPreview(SQUIRREL_GIRL).asPagedIterable(getApiRoute() + "/reactions", + GHReaction[].class, item -> item.wrap(owner.root)); } private String getApiRoute() { - return "/repos/"+owner.getRepository().getOwnerName()+"/"+owner.getRepository().getName()+"/issues/comments/" + id; + return "/repos/" + owner.getRepository().getOwnerName() + "/" + owner.getRepository().getName() + + "/issues/comments/" + id; } } diff --git a/src/main/java/org/kohsuke/github/GHIssueEvent.java b/src/main/java/org/kohsuke/github/GHIssueEvent.java index 089e87a831..3f618414ca 100644 --- a/src/main/java/org/kohsuke/github/GHIssueEvent.java +++ b/src/main/java/org/kohsuke/github/GHIssueEvent.java @@ -72,10 +72,7 @@ GHIssueEvent wrapUp(GHIssue parent) { @Override public String toString() { - return String.format("Issue %d was %s by %s on %s", - getIssue().getNumber(), - getEvent(), - getActor().getLogin(), + return String.format("Issue %d was %s by %s on %s", getIssue().getNumber(), getEvent(), getActor().getLogin(), getCreatedAt().toString()); } } diff --git a/src/main/java/org/kohsuke/github/GHIssueSearchBuilder.java b/src/main/java/org/kohsuke/github/GHIssueSearchBuilder.java index 6cefc01678..49c58aff3a 100644 --- a/src/main/java/org/kohsuke/github/GHIssueSearchBuilder.java +++ b/src/main/java/org/kohsuke/github/GHIssueSearchBuilder.java @@ -7,8 +7,8 @@ * @see GitHub#searchIssues() */ public class GHIssueSearchBuilder extends GHSearchBuilder { - /*package*/ GHIssueSearchBuilder(GitHub root) { - super(root,IssueSearchResult.class); + GHIssueSearchBuilder(GitHub root) { + super(root, IssueSearchResult.class); } /** @@ -24,7 +24,7 @@ public GHIssueSearchBuilder mentions(GHUser u) { } public GHIssueSearchBuilder mentions(String login) { - return q("mentions:"+login); + return q("mentions:" + login); } public GHIssueSearchBuilder isOpen() { @@ -40,22 +40,24 @@ public GHIssueSearchBuilder isMerged() { } public GHIssueSearchBuilder order(GHDirection v) { - req.with("order",v); + req.with("order", v); return this; } public GHIssueSearchBuilder sort(Sort sort) { - req.with("sort",sort); + req.with("sort", sort); return this; } - public enum Sort { COMMENTS, CREATED, UPDATED } + public enum Sort { + COMMENTS, CREATED, UPDATED + } private static class IssueSearchResult extends SearchResult { private GHIssue[] items; @Override - /*package*/ GHIssue[] getItems(GitHub root) { + GHIssue[] getItems(GitHub root) { for (GHIssue i : items) i.wrap(root); return items; diff --git a/src/main/java/org/kohsuke/github/GHIssueState.java b/src/main/java/org/kohsuke/github/GHIssueState.java index ec3cf10d24..4377ea596c 100644 --- a/src/main/java/org/kohsuke/github/GHIssueState.java +++ b/src/main/java/org/kohsuke/github/GHIssueState.java @@ -28,7 +28,5 @@ * @see GHPullRequestQueryBuilder#state(GHIssueState) */ public enum GHIssueState { - OPEN, - CLOSED, - ALL + OPEN, CLOSED, ALL } \ No newline at end of file diff --git a/src/main/java/org/kohsuke/github/GHKey.java b/src/main/java/org/kohsuke/github/GHKey.java index d4c8197dbf..8d46b34f68 100644 --- a/src/main/java/org/kohsuke/github/GHKey.java +++ b/src/main/java/org/kohsuke/github/GHKey.java @@ -10,7 +10,7 @@ */ @SuppressFBWarnings(value = "UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", justification = "JSON API") public class GHKey { - /*package almost final*/ GitHub root; + /* package almost final */ GitHub root; protected String url, key, title; protected boolean verified; @@ -38,17 +38,17 @@ public String getUrl() { public GitHub getRoot() { return root; } - + public boolean isVerified() { return verified; } - /*package*/ GHKey wrap(GitHub root) { + GHKey wrap(GitHub root) { this.root = root; return this; } public String toString() { - return new ToStringBuilder(this).append("title",title).append("id",id).append("key",key).toString(); + return new ToStringBuilder(this).append("title", title).append("id", id).append("key", key).toString(); } } diff --git a/src/main/java/org/kohsuke/github/GHLabel.java b/src/main/java/org/kohsuke/github/GHLabel.java index 29ab891473..fd737e3d8a 100644 --- a/src/main/java/org/kohsuke/github/GHLabel.java +++ b/src/main/java/org/kohsuke/github/GHLabel.java @@ -7,6 +7,7 @@ import java.util.Objects; import static org.kohsuke.github.Previews.SYMMETRA; + /** * @author Kohsuke Kawaguchi * @see GHIssue#getLabels() @@ -34,12 +35,13 @@ public String getColor() { /** * Purpose of Label */ - @Preview @Deprecated + @Preview + @Deprecated public String getDescription() { return description; } - /*package*/ GHLabel wrapUp(GHRepository repo) { + GHLabel wrapUp(GHRepository repo) { this.repo = repo; return this; } @@ -50,32 +52,25 @@ public void delete() throws IOException { /** * @param newColor - * 6-letter hex color code, like "f29513" + * 6-letter hex color code, like "f29513" */ public void setColor(String newColor) throws IOException { - repo.root.retrieve().method("PATCH") - .withPreview(SYMMETRA) - .with("name", name) - .with("color", newColor) - .with("description", description) - .to(url); + repo.root.retrieve().method("PATCH").withPreview(SYMMETRA).with("name", name).with("color", newColor) + .with("description", description).to(url); } /** * @param newDescription - * Description of label + * Description of label */ - @Preview @Deprecated + @Preview + @Deprecated public void setDescription(String newDescription) throws IOException { - repo.root.retrieve().method("PATCH") - .withPreview(SYMMETRA) - .with("name", name) - .with("color", color) - .with("description", newDescription) - .to(url); + repo.root.retrieve().method("PATCH").withPreview(SYMMETRA).with("name", name).with("color", color) + .with("description", newDescription).to(url); } - /*package*/ static Collection toNames(Collection labels) { + static Collection toNames(Collection labels) { List r = new ArrayList(); for (GHLabel l : labels) { r.add(l.getName()); @@ -85,13 +80,13 @@ public void setDescription(String newDescription) throws IOException { @Override public boolean equals(final Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; final GHLabel ghLabel = (GHLabel) o; - return Objects.equals(url, ghLabel.url) && - Objects.equals(name, ghLabel.name) && - Objects.equals(color, ghLabel.color) && - Objects.equals(repo, ghLabel.repo); + return Objects.equals(url, ghLabel.url) && Objects.equals(name, ghLabel.name) + && Objects.equals(color, ghLabel.color) && Objects.equals(repo, ghLabel.repo); } @Override diff --git a/src/main/java/org/kohsuke/github/GHLicense.java b/src/main/java/org/kohsuke/github/GHLicense.java index b18e7e9338..1cfba97fea 100644 --- a/src/main/java/org/kohsuke/github/GHLicense.java +++ b/src/main/java/org/kohsuke/github/GHLicense.java @@ -34,19 +34,19 @@ /** * The GitHub Preview API's license information - *

* * @author Duncan Dickinson * @see GitHub#getLicense(String) * @see GHRepository#getLicense() * @see https://developer.github.com/v3/licenses/ */ -@SuppressWarnings({"UnusedDeclaration"}) -@SuppressFBWarnings(value = {"UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", - "NP_UNWRITTEN_FIELD"}, justification = "JSON API") +@SuppressWarnings({ "UnusedDeclaration" }) +@SuppressFBWarnings(value = { "UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", + "NP_UNWRITTEN_FIELD" }, justification = "JSON API") public class GHLicense extends GHObject { - @SuppressFBWarnings("IS2_INCONSISTENT_SYNC") // root is set before the object is returned to the app - /*package almost final*/ GitHub root; + @SuppressFBWarnings("IS2_INCONSISTENT_SYNC") + // root is set before the object is returned to the app + /* package almost final */ GitHub root; // these fields are always present, even in the short form protected String key, name; @@ -138,15 +138,18 @@ public String getBody() throws IOException { * Depending on the original API call where this object is created, it may not contain everything. */ protected synchronized void populate() throws IOException { - if (description!=null) return; // already populated + if (description != null) + return; // already populated root.retrieve().to(url, this); } @Override public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof GHLicense)) return false; + if (this == o) + return true; + if (!(o instanceof GHLicense)) + return false; GHLicense that = (GHLicense) o; return this.url.equals(that.url); @@ -157,7 +160,7 @@ public int hashCode() { return url.hashCode(); } - /*package*/ GHLicense wrap(GitHub root) { + GHLicense wrap(GitHub root) { this.root = root; return this; } diff --git a/src/main/java/org/kohsuke/github/GHMembership.java b/src/main/java/org/kohsuke/github/GHMembership.java index 2847e1891c..d5e29ea016 100644 --- a/src/main/java/org/kohsuke/github/GHMembership.java +++ b/src/main/java/org/kohsuke/github/GHMembership.java @@ -45,17 +45,19 @@ public GHOrganization getOrganization() { * @see GHMyself#getMembership(GHOrganization) */ public void activate() throws IOException { - root.retrieve().method("PATCH").with("state",State.ACTIVE).to(url,this); + root.retrieve().method("PATCH").with("state", State.ACTIVE).to(url, this); } - /*package*/ GHMembership wrap(GitHub root) { + GHMembership wrap(GitHub root) { this.root = root; - if (user!=null) user = root.getUser(user.wrapUp(root)); - if (organization!=null) organization.wrapUp(root); + if (user != null) + user = root.getUser(user.wrapUp(root)); + if (organization != null) + organization.wrapUp(root); return this; } - /*package*/ static void wrap(GHMembership[] page, GitHub root) { + static void wrap(GHMembership[] page, GitHub root) { for (GHMembership m : page) m.wrap(root); } @@ -78,7 +80,6 @@ public enum Role { * Whether a role is currently active or waiting for acceptance (pending) */ public enum State { - ACTIVE, - PENDING; + ACTIVE, PENDING; } } diff --git a/src/main/java/org/kohsuke/github/GHMilestone.java b/src/main/java/org/kohsuke/github/GHMilestone.java index 3ed54636c7..40d5a1eea5 100644 --- a/src/main/java/org/kohsuke/github/GHMilestone.java +++ b/src/main/java/org/kohsuke/github/GHMilestone.java @@ -6,7 +6,7 @@ import java.util.Locale; /** - * + * * @author Yusuke Kokubo * */ @@ -22,17 +22,18 @@ public class GHMilestone extends GHObject { public GitHub getRoot() { return root; } - + public GHRepository getOwner() { return owner; } - + public GHUser getCreator() throws IOException { return root.intern(creator); } - + public Date getDueOn() { - if (due_on == null) return null; + if (due_on == null) + return null; return GitHub.parseDate(due_on); } @@ -46,19 +47,19 @@ public Date getClosedAt() throws IOException { public String getTitle() { return title; } - + public String getDescription() { return description; } - + public int getClosedIssues() { return closed_issues; } - + public int getOpenIssues() { return open_issues; } - + public int getNumber() { return number; } @@ -66,7 +67,7 @@ public int getNumber() { public URL getHtmlUrl() { return GitHub.parseURL(html_url); } - + public GHMilestoneState getState() { return Enum.valueOf(GHMilestoneState.class, state.toUpperCase(Locale.ENGLISH)); } @@ -109,7 +110,7 @@ public void setDueOn(Date dueOn) throws IOException { } protected String getApiRoute() { - return "/repos/"+owner.getOwnerName()+"/"+owner.getName()+"/milestones/"+number; + return "/repos/" + owner.getOwnerName() + "/" + owner.getName() + "/milestones/" + number; } public GHMilestone wrap(GHRepository repo) { diff --git a/src/main/java/org/kohsuke/github/GHMilestoneState.java b/src/main/java/org/kohsuke/github/GHMilestoneState.java index 92194546cb..ce45048186 100644 --- a/src/main/java/org/kohsuke/github/GHMilestoneState.java +++ b/src/main/java/org/kohsuke/github/GHMilestoneState.java @@ -1,11 +1,10 @@ package org.kohsuke.github; /** - * + * * @author Yusuke Kokubo * */ public enum GHMilestoneState { - OPEN, - CLOSED + OPEN, CLOSED } \ No newline at end of file diff --git a/src/main/java/org/kohsuke/github/GHMyself.java b/src/main/java/org/kohsuke/github/GHMyself.java index e059f58226..f370aa7c1b 100644 --- a/src/main/java/org/kohsuke/github/GHMyself.java +++ b/src/main/java/org/kohsuke/github/GHMyself.java @@ -44,8 +44,7 @@ public enum RepositoryListFilter { } /** - * @deprecated - * Use {@link #getEmails2()} + * @deprecated Use {@link #getEmails2()} */ public List getEmails() throws IOException { List src = getEmails2(); @@ -59,12 +58,10 @@ public List getEmails() throws IOException { /** * Returns the read-only list of e-mail addresses configured for you. * - * This corresponds to the stuff you configure in https://github.com/settings/emails, - * and not to be confused with {@link #getEmail()} that shows your public e-mail address - * set in https://github.com/settings/profile + * This corresponds to the stuff you configure in https://github.com/settings/emails, and not to be confused with + * {@link #getEmail()} that shows your public e-mail address set in https://github.com/settings/profile * - * @return - * Always non-null. + * @return Always non-null. */ public List getEmails2() throws IOException { GHEmail[] addresses = root.retrieve().to("/user/emails", GHEmail[].class); @@ -74,11 +71,10 @@ public List getEmails2() throws IOException { /** * Returns the read-only list of all the pulic keys of the current user. * - * NOTE: When using OAuth authenticaiton, the READ/WRITE User scope is - * required by the GitHub APIs, otherwise you will get a 404 NOT FOUND. + * NOTE: When using OAuth authenticaiton, the READ/WRITE User scope is required by the GitHub APIs, otherwise you + * will get a 404 NOT FOUND. * - * @return - * Always non-null. + * @return Always non-null. */ public List getPublicKeys() throws IOException { return Collections.unmodifiableList(Arrays.asList(root.retrieve().to("/user/keys", GHKey[].class))); @@ -87,17 +83,15 @@ public List getPublicKeys() throws IOException { /** * Returns the read-only list of all the public verified keys of the current user. * - * Differently from the getPublicKeys() method, the retrieval of the user's - * verified public keys does not require any READ/WRITE OAuth Scope to the - * user's profile. + * Differently from the getPublicKeys() method, the retrieval of the user's verified public keys does not require + * any READ/WRITE OAuth Scope to the user's profile. * - * @return - * Always non-null. + * @return Always non-null. */ - public List getPublicVerifiedKeys() throws IOException { - return Collections.unmodifiableList(Arrays.asList(root.retrieve().to( - "/users/" + getLogin() + "/keys", GHVerifiedKey[].class))); - } + public List getPublicVerifiedKeys() throws IOException { + return Collections.unmodifiableList( + Arrays.asList(root.retrieve().to("/users/" + getLogin() + "/keys", GHVerifiedKey[].class))); + } /** * Gets the organization that this user belongs to. @@ -106,7 +100,7 @@ public GHPersonSet getAllOrganizations() throws IOException { GHPersonSet orgs = new GHPersonSet(); Set names = new HashSet(); for (GHOrganization o : root.retrieve().to("/user/orgs", GHOrganization[].class)) { - if (names.add(o.getLogin())) // in case of rumoured duplicates in the data + if (names.add(o.getLogin())) // in case of rumoured duplicates in the data orgs.add(root.getOrganization(o.getLogin())); } return orgs; @@ -115,10 +109,10 @@ public GHPersonSet getAllOrganizations() throws IOException { /** * Gets the all repositories this user owns (public and private). */ - public synchronized Map getAllRepositories() throws IOException { - Map repositories = new TreeMap(); + public synchronized Map getAllRepositories() throws IOException { + Map repositories = new TreeMap(); for (GHRepository r : listAllRepositories()) { - repositories.put(r.getName(),r); + repositories.put(r.getName(), r); } return Collections.unmodifiableMap(repositories); } @@ -126,48 +120,47 @@ public synchronized Map getAllRepositories() throws IOExcep /** * Lists up all repositories this user owns (public and private). * - * Unlike {@link #getAllRepositories()}, this does not wait until all the repositories are returned. - * Repositories are returned by GitHub API with a 30 items per page. + * Unlike {@link #getAllRepositories()}, this does not wait until all the repositories are returned. Repositories + * are returned by GitHub API with a 30 items per page. */ @Override public PagedIterable listRepositories() { - return listRepositories(30); + return listRepositories(30); } /** - * List repositories that are accessible to the authenticated user (public and private) using the specified page size. + * List repositories that are accessible to the authenticated user (public and private) using the specified page + * size. * - * This includes repositories owned by the authenticated user, repositories that belong to other users - * where the authenticated user is a collaborator, and other organizations' repositories that the authenticated - * user has access to through an organization membership. + * This includes repositories owned by the authenticated user, repositories that belong to other users where the + * authenticated user is a collaborator, and other organizations' repositories that the authenticated user has + * access to through an organization membership. * - * @param pageSize size for each page of items returned by GitHub. Maximum page size is 100. + * @param pageSize + * size for each page of items returned by GitHub. Maximum page size is 100. * - * Unlike {@link #getRepositories()}, this does not wait until all the repositories are returned. + * Unlike {@link #getRepositories()}, this does not wait until all the repositories are returned. */ public PagedIterable listRepositories(final int pageSize) { return listRepositories(pageSize, RepositoryListFilter.ALL); } /** - * List repositories of a certain type that are accessible by current authenticated user using the specified page size. + * List repositories of a certain type that are accessible by current authenticated user using the specified page + * size. * - * @param pageSize size for each page of items returned by GitHub. Maximum page size is 100. - * @param repoType type of repository returned in the listing + * @param pageSize + * size for each page of items returned by GitHub. Maximum page size is 100. + * @param repoType + * type of repository returned in the listing */ public PagedIterable listRepositories(final int pageSize, final RepositoryListFilter repoType) { - return root.retrieve() - .with("type",repoType) - .asPagedIterable( - "/user/repos", - GHRepository[].class, - item -> item.wrap(root) - ).withPageSize(pageSize); + return root.retrieve().with("type", repoType) + .asPagedIterable("/user/repos", GHRepository[].class, item -> item.wrap(root)).withPageSize(pageSize); } /** - * @deprecated - * Use {@link #listRepositories()} + * @deprecated Use {@link #listRepositories()} */ public PagedIterable listAllRepositories() { return listRepositories(); @@ -184,26 +177,22 @@ public PagedIterable listOrgMemberships() { * List your organization memberships * * @param state - * Filter by a specific state + * Filter by a specific state */ public PagedIterable listOrgMemberships(final GHMembership.State state) { - return root.retrieve() - .with("state",state) - .asPagedIterable( - "/user/memberships/orgs", - GHMembership[].class, - item -> item.wrap(root) ); + return root.retrieve().with("state", state).asPagedIterable("/user/memberships/orgs", GHMembership[].class, + item -> item.wrap(root)); } /** * Gets your membership in a specific organization. */ public GHMembership getMembership(GHOrganization o) throws IOException { - return root.retrieve().to("/user/memberships/orgs/"+o.getLogin(),GHMembership.class).wrap(root); + return root.retrieve().to("/user/memberships/orgs/" + o.getLogin(), GHMembership.class).wrap(root); } -// public void addEmails(Collection emails) throws IOException { -//// new Requester(root,ApiVersion.V3).withCredential().to("/user/emails"); -// root.retrieveWithAuth3() -// } + // public void addEmails(Collection emails) throws IOException { + //// new Requester(root,ApiVersion.V3).withCredential().to("/user/emails"); + // root.retrieveWithAuth3() + // } } diff --git a/src/main/java/org/kohsuke/github/GHNotificationStream.java b/src/main/java/org/kohsuke/github/GHNotificationStream.java index b8f8d7c296..4a8e733193 100644 --- a/src/main/java/org/kohsuke/github/GHNotificationStream.java +++ b/src/main/java/org/kohsuke/github/GHNotificationStream.java @@ -9,19 +9,15 @@ * Listens to GitHub notification stream. * *

- * This class supports two modes of retrieving notifications that can - * be controlled via {@link #nonBlocking(boolean)}. + * This class supports two modes of retrieving notifications that can be controlled via {@link #nonBlocking(boolean)}. * *

- * In the blocking mode, which is the default, iterator will be infinite. - * The call to {@link Iterator#next()} will block until a new notification - * arrives. This is useful for application that runs perpetually and reacts - * to notifications. + * In the blocking mode, which is the default, iterator will be infinite. The call to {@link Iterator#next()} will block + * until a new notification arrives. This is useful for application that runs perpetually and reacts to notifications. * *

- * In the non-blocking mode, the iterator will only report the set of - * notifications initially retrieved from GitHub, then quit. This is useful - * for a batch application to process the current set of notifications. + * In the non-blocking mode, the iterator will only report the set of notifications initially retrieved from GitHub, + * then quit. This is useful for a batch application to process the current set of notifications. * * @author Kohsuke Kawaguchi * @see GitHub#listNotifications() @@ -35,7 +31,7 @@ public class GHNotificationStream implements Iterable { private String apiUrl; private boolean nonBlocking = false; - /*package*/ GHNotificationStream(GitHub root, String apiUrl) { + GHNotificationStream(GitHub root, String apiUrl) { this.root = root; this.apiUrl = apiUrl; } @@ -49,8 +45,7 @@ public GHNotificationStream read(boolean v) { } /** - * Should the stream be restricted to notifications in which the user - * is directly participating or mentioned? + * Should the stream be restricted to notifications in which the user is directly participating or mentioned? */ public GHNotificationStream participating(boolean v) { participating = v; @@ -67,8 +62,8 @@ public GHNotificationStream since(Date dt) { } /** - * If set to true, {@link #iterator()} will stop iterating instead of blocking and - * waiting for the updates to arrive. + * If set to true, {@link #iterator()} will stop iterating instead of blocking and waiting for the updates to + * arrive. */ public GHNotificationStream nonBlocking(boolean v) { this.nonBlocking = v; @@ -76,25 +71,23 @@ public GHNotificationStream nonBlocking(boolean v) { } /** - * Returns an infinite blocking {@link Iterator} that returns - * {@link GHThread} as notifications arrive. + * Returns an infinite blocking {@link Iterator} that returns {@link GHThread} as notifications arrive. */ public Iterator iterator() { // capture the configuration setting here - final Requester req = new Requester(root).method("GET") - .with("all", all).with("participating", participating).with("since", since); + final Requester req = new Requester(root).method("GET").with("all", all).with("participating", participating) + .with("since", since); return new Iterator() { /** - * Stuff we've fetched but haven't returned to the caller. - * Newer ones first. + * Stuff we've fetched but haven't returned to the caller. Newer ones first. */ private GHThread[] threads = EMPTY_ARRAY; /** * Next element in {@link #threads} to return. This counts down. */ - private int idx=-1; + private int idx = -1; /** * threads whose updated_at is older than this should be ignored. @@ -114,9 +107,9 @@ public Iterator iterator() { private GHThread next; public GHThread next() { - if (next==null) { + if (next == null) { next = fetch(); - if (next==null) + if (next == null) throw new NoSuchElementException(); } @@ -126,9 +119,9 @@ public GHThread next() { } public boolean hasNext() { - if (next==null) + if (next == null) next = fetch(); - return next!=null; + return next != null; } GHThread fetch() { @@ -136,7 +129,7 @@ GHThread fetch() { while (true) {// loop until we get new threads to return // if we have fetched un-returned threads, use them first - while (idx>=0) { + while (idx >= 0) { GHThread n = threads[idx--]; long nt = n.getUpdatedAt().getTime(); if (nt >= lastUpdated) { @@ -145,13 +138,14 @@ GHThread fetch() { } } - if (nonBlocking && nextCheckTime>=0) - return null; // nothing more to report, and we aren't blocking + if (nonBlocking && nextCheckTime >= 0) + return null; // nothing more to report, and we aren't blocking // observe the polling interval before making the call while (true) { long now = System.currentTimeMillis(); - if (nextCheckTime < now) break; + if (nextCheckTime < now) + break; long waitTime = Math.min(Math.max(nextCheckTime - now, 1000), 60 * 1000); Thread.sleep(waitTime); } @@ -159,13 +153,13 @@ GHThread fetch() { req.setHeader("If-Modified-Since", lastModified); threads = req.to(apiUrl, GHThread[].class); - if (threads==null) { - threads = EMPTY_ARRAY; // if unmodified, we get empty array + if (threads == null) { + threads = EMPTY_ARRAY; // if unmodified, we get empty array } else { // we get a new batch, but we want to ignore the ones that we've seen lastUpdated++; } - idx = threads.length-1; + idx = threads.length - 1; nextCheckTime = calcNextCheckTime(); lastModified = req.getResponseHeader("Last-Modified"); @@ -179,9 +173,10 @@ GHThread fetch() { private long calcNextCheckTime() { String v = req.getResponseHeader("X-Poll-Interval"); - if (v==null) v="60"; + if (v == null) + v = "60"; long seconds = Integer.parseInt(v); - return System.currentTimeMillis() + seconds*1000; + return System.currentTimeMillis() + seconds * 1000; } public void remove() { @@ -199,7 +194,7 @@ public void markAsRead() throws IOException { */ public void markAsRead(long timestamp) throws IOException { final Requester req = new Requester(root).method("PUT"); - if (timestamp>=0) + if (timestamp >= 0) req.with("last_read_at", GitHub.printDate(new Date(timestamp))); req.asHttpStatusCode(apiUrl); } diff --git a/src/main/java/org/kohsuke/github/GHOTPRequiredException.java b/src/main/java/org/kohsuke/github/GHOTPRequiredException.java index f7d935bd54..3bfd2e1150 100644 --- a/src/main/java/org/kohsuke/github/GHOTPRequiredException.java +++ b/src/main/java/org/kohsuke/github/GHOTPRequiredException.java @@ -1,10 +1,11 @@ -package org.kohsuke.github; -/** - * This exception is thrown when GitHub is requesting an OTP from the user - * - * @author Kevin Harrington mad.hephaestus@gmail.com - * - */ -public class GHOTPRequiredException extends GHIOException { -//... -} +package org.kohsuke.github; + +/** + * This exception is thrown when GitHub is requesting an OTP from the user + * + * @author Kevin Harrington mad.hephaestus@gmail.com + * + */ +public class GHOTPRequiredException extends GHIOException { + // ... +} diff --git a/src/main/java/org/kohsuke/github/GHObject.java b/src/main/java/org/kohsuke/github/GHObject.java index 2bad0891bc..4251162253 100644 --- a/src/main/java/org/kohsuke/github/GHObject.java +++ b/src/main/java/org/kohsuke/github/GHObject.java @@ -16,8 +16,8 @@ /** * Most (all?) domain objects in GitHub seems to have these 4 properties. */ -@SuppressFBWarnings(value = {"UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", - "NP_UNWRITTEN_FIELD"}, justification = "JSON API") +@SuppressFBWarnings(value = { "UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", + "NP_UNWRITTEN_FIELD" }, justification = "JSON API") public abstract class GHObject { /** * Capture response HTTP headers on the state object. @@ -29,28 +29,35 @@ public abstract class GHObject { protected String created_at; protected String updated_at; - /*package*/ GHObject() { + GHObject() { } /** * Returns the HTTP response headers given along with the state of this object. * *

- * Some of the HTTP headers have nothing to do with the object, for example "Cache-Control" - * and others are different depending on how this object was retrieved. + * Some of the HTTP headers have nothing to do with the object, for example "Cache-Control" and others are different + * depending on how this object was retrieved. * - * This method was added as a kind of hack to allow the caller to retrieve OAuth scopes and such. - * Use with caution. The method might be removed in the future. + * This method was added as a kind of hack to allow the caller to retrieve OAuth scopes and such. Use with caution. + * The method might be removed in the future. + * + * @return a map of header names to value lists */ - @CheckForNull @Deprecated + @CheckForNull + @Deprecated public Map> getResponseHeaderFields() { return responseHeaderFields; } /** * When was this resource created? + * + * @return date created + * @throws IOException + * on error */ - @WithBridgeMethods(value=String.class, adapterMethod="createdAtStr") + @WithBridgeMethods(value = String.class, adapterMethod = "createdAtStr") public Date getCreatedAt() throws IOException { return GitHub.parseDate(created_at); } @@ -61,51 +68,57 @@ private Object createdAtStr(Date id, Class type) { } /** - * API URL of this object. + * @return API URL of this object. */ - @WithBridgeMethods(value=String.class, adapterMethod="urlToString") + @WithBridgeMethods(value = String.class, adapterMethod = "urlToString") public URL getUrl() { return GitHub.parseURL(url); } /** - * URL of this object for humans, which renders some HTML. + * @return URL of this object for humans, which renders some HTML. + * @throws IOException + * on error */ - @WithBridgeMethods(value=String.class, adapterMethod="urlToString") + @WithBridgeMethods(value = String.class, adapterMethod = "urlToString") public abstract URL getHtmlUrl() throws IOException; /** * When was this resource last updated? + * + * @return updated date + * @throws IOException + * on error */ public Date getUpdatedAt() throws IOException { return GitHub.parseDate(updated_at); } /** - * Unique ID number of this resource. + * @return Unique ID number of this resource. */ - @WithBridgeMethods(value={String.class,int.class}, adapterMethod="longToStringOrInt") + @WithBridgeMethods(value = { String.class, int.class }, adapterMethod = "longToStringOrInt") public long getId() { return id; } @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD", justification = "Bridge method of getId") private Object longToStringOrInt(long id, Class type) { - if (type==String.class) + if (type == String.class) return String.valueOf(id); - if (type==int.class) - return (int)id; - throw new AssertionError("Unexpected type: "+type); + if (type == int.class) + return (int) id; + throw new AssertionError("Unexpected type: " + type); } @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD", justification = "Bridge method of getHtmlUrl") private Object urlToString(URL url, Class type) { - return url==null ? null : url.toString(); + return url == null ? null : url.toString(); } /** - * String representation to assist debugging and inspection. The output format of this string - * is not a committed part of the API and is subject to change. + * String representation to assist debugging and inspection. The output format of this string is not a committed + * part of the API and is subject to change. */ @Override public String toString() { @@ -134,7 +147,7 @@ public void append(StringBuffer buffer, String fieldName, Object value, Boolean if (value instanceof GitHub) return; - super.append(buffer,fieldName,value,fullDetail); + super.append(buffer, fieldName, value, fullDetail); } }; } diff --git a/src/main/java/org/kohsuke/github/GHOrgHook.java b/src/main/java/org/kohsuke/github/GHOrgHook.java index 58404019bf..d13f766401 100644 --- a/src/main/java/org/kohsuke/github/GHOrgHook.java +++ b/src/main/java/org/kohsuke/github/GHOrgHook.java @@ -8,9 +8,9 @@ class GHOrgHook extends GHHook { /** * Organization that the hook belongs to. */ - /*package*/ transient GHOrganization organization; + transient GHOrganization organization; - /*package*/ GHOrgHook wrap(GHOrganization owner) { + GHOrgHook wrap(GHOrganization owner) { this.organization = owner; return this; } diff --git a/src/main/java/org/kohsuke/github/GHOrganization.java b/src/main/java/org/kohsuke/github/GHOrganization.java index 2b56d02f07..a2366136d2 100644 --- a/src/main/java/org/kohsuke/github/GHOrganization.java +++ b/src/main/java/org/kohsuke/github/GHOrganization.java @@ -15,53 +15,53 @@ * @author Kohsuke Kawaguchi */ public class GHOrganization extends GHPerson { - /*package*/ GHOrganization wrapUp(GitHub root) { - return (GHOrganization)super.wrapUp(root); + GHOrganization wrapUp(GitHub root) { + return (GHOrganization) super.wrapUp(root); } /** * Creates a new repository. * - * @return - * Newly created repository. - * @deprecated - * Use {@link #createRepository(String)} that uses a builder pattern to let you control every aspect. + * @return Newly created repository. + * @deprecated Use {@link #createRepository(String)} that uses a builder pattern to let you control every aspect. */ - public GHRepository createRepository(String name, String description, String homepage, String team, boolean isPublic) throws IOException { + public GHRepository createRepository(String name, String description, String homepage, String team, + boolean isPublic) throws IOException { GHTeam t = getTeams().get(team); - if (t==null) - throw new IllegalArgumentException("No such team: "+team); + if (t == null) + throw new IllegalArgumentException("No such team: " + team); return createRepository(name, description, homepage, t, isPublic); } /** - * @deprecated - * Use {@link #createRepository(String)} that uses a builder pattern to let you control every aspect. + * @deprecated Use {@link #createRepository(String)} that uses a builder pattern to let you control every aspect. */ - public GHRepository createRepository(String name, String description, String homepage, GHTeam team, boolean isPublic) throws IOException { - if (team==null) + public GHRepository createRepository(String name, String description, String homepage, GHTeam team, + boolean isPublic) throws IOException { + if (team == null) throw new IllegalArgumentException("Invalid team"); - return createRepository(name).description(description).homepage(homepage).private_(!isPublic).team(team).create(); + return createRepository(name).description(description).homepage(homepage).private_(!isPublic).team(team) + .create(); } /** * Starts a builder that creates a new repository. * *

- * You use the returned builder to set various properties, then call {@link GHCreateRepositoryBuilder#create()} - * to finally createa repository. + * You use the returned builder to set various properties, then call {@link GHCreateRepositoryBuilder#create()} to + * finally createa repository. */ public GHCreateRepositoryBuilder createRepository(String name) { - return new GHCreateRepositoryBuilder(root,"/orgs/"+login+"/repos",name); + return new GHCreateRepositoryBuilder(root, "/orgs/" + login + "/repos", name); } /** * Teams by their names. */ - public Map getTeams() throws IOException { - Map r = new TreeMap(); + public Map getTeams() throws IOException { + Map r = new TreeMap(); for (GHTeam t : listTeams()) { - r.put(t.getName(),t); + r.put(t.getName(), t); } return r; } @@ -70,11 +70,8 @@ public Map getTeams() throws IOException { * List up all the teams. */ public PagedIterable listTeams() throws IOException { - return root.retrieve() - .asPagedIterable( - String.format("/orgs/%s/teams", login), - GHTeam[].class, - item -> item.wrapUp(GHOrganization.this) ); + return root.retrieve().asPagedIterable(String.format("/orgs/%s/teams", login), GHTeam[].class, + item -> item.wrapUp(GHOrganization.this)); } /** @@ -82,7 +79,7 @@ public PagedIterable listTeams() throws IOException { */ public GHTeam getTeamByName(String name) throws IOException { for (GHTeam t : listTeams()) { - if(t.getName().equals(name)) + if (t.getName().equals(name)) return t; } return null; @@ -93,7 +90,7 @@ public GHTeam getTeamByName(String name) throws IOException { */ public GHTeam getTeamBySlug(String slug) throws IOException { for (GHTeam t : listTeams()) { - if(t.getSlug().equals(slug)) + if (t.getSlug().equals(slug)) return t; } return null; @@ -101,17 +98,19 @@ public GHTeam getTeamBySlug(String slug) throws IOException { /** Member's role in an organization */ public enum Role { - ADMIN, /** The user is an owner of the organization. */ + ADMIN, + /** The user is an owner of the organization. */ MEMBER /** The user is a non-owner member of the organization. */ } /** * Adds (invites) a user to the organization. - * @see documentation + * + * @see documentation */ public void add(GHUser user, Role role) throws IOException { - root.retrieve().method("PUT") - .with("role", role.name().toLowerCase()) + root.retrieve().method("PUT").with("role", role.name().toLowerCase()) .to("/orgs/" + login + "/memberships/" + user.getLogin()); } @@ -120,7 +119,7 @@ public void add(GHUser user, Role role) throws IOException { */ public boolean hasMember(GHUser user) { try { - root.retrieve().to("/orgs/" + login + "/members/" + user.getLogin()); + root.retrieve().to("/orgs/" + login + "/members/" + user.getLogin()); return true; } catch (IOException ignore) { return false; @@ -128,11 +127,11 @@ public boolean hasMember(GHUser user) { } /** - * Remove a member of the organisation - which will remove them from - * all teams, and remove their access to the organization’s repositories. + * Remove a member of the organisation - which will remove them from all teams, and remove their access to the + * organization’s repositories. */ public void remove(GHUser user) throws IOException { - root.retrieve().method("DELETE").to("/orgs/" + login + "/members/" + user.getLogin()); + root.retrieve().method("DELETE").to("/orgs/" + login + "/members/" + user.getLogin()); } /** @@ -185,11 +184,8 @@ public PagedIterable listMembersWithFilter(String filter) throws IOExcep private PagedIterable listMembers(final String suffix, final String filter) throws IOException { String filterParams = (filter == null) ? "" : ("?filter=" + filter); - return root.retrieve() - .asPagedIterable( - String.format("/orgs/%s/%s%s", login, suffix, filterParams), - GHUser[].class, - item -> item.wrapUp(root) ); + return root.retrieve().asPagedIterable(String.format("/orgs/%s/%s%s", login, suffix, filterParams), + GHUser[].class, item -> item.wrapUp(root)); } /** @@ -201,15 +197,13 @@ public void conceal(GHUser u) throws IOException { /** * Returns the projects for this organization. - * @param status The status filter (all, open or closed). + * + * @param status + * The status filter (all, open or closed). */ public PagedIterable listProjects(final GHProject.ProjectStateFilter status) throws IOException { - return root.retrieve().withPreview(INERTIA) - .with("state", status) - .asPagedIterable( - String.format("/orgs/%s/projects", login), - GHProject[].class, - item -> item.wrap(root) ); + return root.retrieve().withPreview(INERTIA).with("state", status) + .asPagedIterable(String.format("/orgs/%s/projects", login), GHProject[].class, item -> item.wrap(root)); } /** @@ -223,14 +217,13 @@ public PagedIterable listProjects() throws IOException { * Creates a project for the organization. */ public GHProject createProject(String name, String body) throws IOException { - return root.retrieve().method("POST") - .withPreview(INERTIA) - .with("name", name) - .with("body", body) + return root.retrieve().method("POST").withPreview(INERTIA).with("name", name).with("body", body) .to(String.format("/orgs/%s/projects", login), GHProject.class).wrap(root); } - public enum Permission { ADMIN, PUSH, PULL } + public enum Permission { + ADMIN, PUSH, PULL + } /** * Creates a new team and assigns the repositories. @@ -241,7 +234,7 @@ public GHTeam createTeam(String name, Permission p, Collection rep for (GHRepository r : repositories) { repo_names.add(login + "/" + r.getName()); } - post.with("repo_names",repo_names); + post.with("repo_names", repo_names); return post.method("POST").to("/orgs/" + login + "/teams", GHTeam.class).wrapUp(this); } @@ -252,8 +245,8 @@ public GHTeam createTeam(String name, Permission p, GHRepository... repositories /** * List up repositories that has some open pull requests. * - * This used to be an efficient method that didn't involve traversing every repository, but now - * it doesn't do any optimization. + * This used to be an efficient method that didn't involve traversing every repository, but now it doesn't do any + * optimization. */ public List getRepositoriesWithOpenPullRequests() throws IOException { List r = new ArrayList(); @@ -282,28 +275,23 @@ public List getPullRequests() throws IOException { * Lists events performed by a user (this includes private events if the caller is authenticated. */ public PagedIterable listEvents() throws IOException { - return root.retrieve() - .asPagedIterable( - String.format("/orgs/%s/events", login), - GHEventInfo[].class, - item -> item.wrapUp(root) ); + return root.retrieve().asPagedIterable(String.format("/orgs/%s/events", login), GHEventInfo[].class, + item -> item.wrapUp(root)); } /** * Lists up all the repositories using the specified page size. * - * @param pageSize size for each page of items returned by GitHub. Maximum page size is 100. + * @param pageSize + * size for each page of items returned by GitHub. Maximum page size is 100. * - * Unlike {@link #getRepositories()}, this does not wait until all the repositories are returned. + * Unlike {@link #getRepositories()}, this does not wait until all the repositories are returned. */ @Override public PagedIterable listRepositories(final int pageSize) { return root.retrieve() - .asPagedIterable( - "/orgs/" + login + "/repos", - GHRepository[].class, - item -> item.wrap(root) - ).withPageSize(pageSize); + .asPagedIterable("/orgs/" + login + "/repos", GHRepository[].class, item -> item.wrap(root)) + .withPageSize(pageSize); } /** @@ -319,22 +307,23 @@ public GHHook getHook(int id) throws IOException { /** * - * See https://api.github.com/hooks for possible names and their configuration scheme. - * TODO: produce type-safe binding + * See https://api.github.com/hooks for possible names and their configuration scheme. TODO: produce type-safe + * binding * * @param name - * Type of the hook to be created. See https://api.github.com/hooks for possible names. + * Type of the hook to be created. See https://api.github.com/hooks for possible names. * @param config - * The configuration hash. + * The configuration hash. * @param events - * Can be null. Types of events to hook into. + * Can be null. Types of events to hook into. */ - public GHHook createHook(String name, Map config, Collection events, boolean active) throws IOException { + public GHHook createHook(String name, Map config, Collection events, boolean active) + throws IOException { return GHHooks.orgContext(this).createHook(name, config, events, active); } public GHHook createWebHook(URL url, Collection events) throws IOException { - return createHook("web", Collections.singletonMap("url", url.toExternalForm()),events,true); + return createHook("web", Collections.singletonMap("url", url.toExternalForm()), events, true); } public GHHook createWebHook(URL url) throws IOException { diff --git a/src/main/java/org/kohsuke/github/GHPermission.java b/src/main/java/org/kohsuke/github/GHPermission.java index 51a808dfc0..2f97576e6e 100644 --- a/src/main/java/org/kohsuke/github/GHPermission.java +++ b/src/main/java/org/kohsuke/github/GHPermission.java @@ -28,9 +28,10 @@ /** * Permission for a user in a repository. + * * @see API */ -/*package*/ class GHPermission { +class GHPermission { private String permission; private GHUser user; diff --git a/src/main/java/org/kohsuke/github/GHPermissionType.java b/src/main/java/org/kohsuke/github/GHPermissionType.java index d3e2bd0909..b3f4664f33 100644 --- a/src/main/java/org/kohsuke/github/GHPermissionType.java +++ b/src/main/java/org/kohsuke/github/GHPermissionType.java @@ -4,8 +4,5 @@ * @author Kohsuke Kawaguchi */ public enum GHPermissionType { - ADMIN, - WRITE, - READ, - NONE + ADMIN, WRITE, READ, NONE } diff --git a/src/main/java/org/kohsuke/github/GHPerson.java b/src/main/java/org/kohsuke/github/GHPerson.java index 137dd5b368..d93d6f9f49 100644 --- a/src/main/java/org/kohsuke/github/GHPerson.java +++ b/src/main/java/org/kohsuke/github/GHPerson.java @@ -13,21 +13,21 @@ /** * Common part of {@link GHUser} and {@link GHOrganization}. - * + * * @author Kohsuke Kawaguchi */ public abstract class GHPerson extends GHObject { - /*package almost final*/ GitHub root; + /* package almost final */ GitHub root; // core data fields that exist even for "small" user data (such as the user info in pull request) protected String login, avatar_url, gravatar_id; // other fields (that only show up in full data) - protected String location,blog,email,name,company; + protected String location, blog, email, name, company; protected String html_url; - protected int followers,following,public_repos,public_gists; + protected int followers, following, public_repos, public_gists; - /*package*/ GHPerson wrapUp(GitHub root) { + GHPerson wrapUp(GitHub root) { this.root = root; return this; } @@ -38,7 +38,7 @@ public abstract class GHPerson extends GHObject { * Depending on the original API call where this object is created, it may not contain everything. */ protected synchronized void populate() throws IOException { - if (created_at!=null) { + if (created_at != null) { return; // already populated } if (root == null || root.isOffline()) { @@ -51,13 +51,12 @@ protected synchronized void populate() throws IOException { * Gets the public repositories this user owns. * *

- * To list your own repositories, including private repositories, - * use {@link GHMyself#listRepositories()} + * To list your own repositories, including private repositories, use {@link GHMyself#listRepositories()} */ - public synchronized Map getRepositories() throws IOException { - Map repositories = new TreeMap(); + public synchronized Map getRepositories() throws IOException { + Map repositories = new TreeMap(); for (GHRepository r : listRepositories(100)) { - repositories.put(r.getName(),r); + repositories.put(r.getName(), r); } return Collections.unmodifiableMap(repositories); } @@ -68,43 +67,41 @@ public synchronized Map getRepositories() throws IOExceptio * Unlike {@link #getRepositories()}, this does not wait until all the repositories are returned. */ public PagedIterable listRepositories() { - return listRepositories(30); + return listRepositories(30); } /** * Lists up all the repositories using the specified page size. * - * @param pageSize size for each page of items returned by GitHub. Maximum page size is 100. + * @param pageSize + * size for each page of items returned by GitHub. Maximum page size is 100. * - * Unlike {@link #getRepositories()}, this does not wait until all the repositories are returned. + * Unlike {@link #getRepositories()}, this does not wait until all the repositories are returned. */ public PagedIterable listRepositories(final int pageSize) { return root.retrieve() - .asPagedIterable( - "/users/" + login + "/repos", - GHRepository[].class, - item -> item.wrap(root) - ).withPageSize(pageSize); + .asPagedIterable("/users/" + login + "/repos", GHRepository[].class, item -> item.wrap(root)) + .withPageSize(pageSize); } /** * Loads repository list in a paginated fashion. * *

- * For a person with a lot of repositories, GitHub returns the list of repositories in a paginated fashion. - * Unlike {@link #getRepositories()}, this method allows the caller to start processing data as it arrives. + * For a person with a lot of repositories, GitHub returns the list of repositories in a paginated fashion. Unlike + * {@link #getRepositories()}, this method allows the caller to start processing data as it arrives. * - * Every {@link Iterator#next()} call results in I/O. Exceptions that occur during the processing is wrapped - * into {@link Error}. + * Every {@link Iterator#next()} call results in I/O. Exceptions that occur during the processing is wrapped into + * {@link Error}. * - * @deprecated - * Use {@link #listRepositories()} + * @deprecated Use {@link #listRepositories()} */ @Deprecated public synchronized Iterable> iterateRepositories(final int pageSize) { return new Iterable>() { public Iterator> iterator() { - final Iterator pager = root.retrieve().asIterator("/users/" + login + "/repos",GHRepository[].class, pageSize); + final Iterator pager = root.retrieve().asIterator("/users/" + login + "/repos", + GHRepository[].class, pageSize); return new Iterator>() { public boolean hasNext() { @@ -128,8 +125,7 @@ public void remove() { /** * - * @return - * null if the repository was not found + * @return null if the repository was not found */ public GHRepository getRepository(String name) throws IOException { try { @@ -147,22 +143,21 @@ public GHRepository getRepository(String name) throws IOException { /** * Gravatar ID of this user, like 0cb9832a01c22c083390f3c5dcb64105 * - * @deprecated - * No longer available in the v3 API. + * @deprecated No longer available in the v3 API. */ public String getGravatarId() { return gravatar_id; } /** - * Returns a string like 'https://secure.gravatar.com/avatar/0cb9832a01c22c083390f3c5dcb64105' - * that indicates the avatar image URL. + * Returns a string like 'https://secure.gravatar.com/avatar/0cb9832a01c22c083390f3c5dcb64105' that indicates the + * avatar image URL. */ public String getAvatarUrl() { - if (avatar_url!=null) + if (avatar_url != null) return avatar_url; - if (gravatar_id!=null) - return "https://secure.gravatar.com/avatar/"+gravatar_id; + if (gravatar_id != null) + return "https://secure.gravatar.com/avatar/" + gravatar_id; return null; } diff --git a/src/main/java/org/kohsuke/github/GHPersonSet.java b/src/main/java/org/kohsuke/github/GHPersonSet.java index eb35b1bf7a..2a68a3ff57 100644 --- a/src/main/java/org/kohsuke/github/GHPersonSet.java +++ b/src/main/java/org/kohsuke/github/GHPersonSet.java @@ -6,12 +6,12 @@ /** * Set of {@link GHPerson} with helper lookup methods. - * + * * @author Kohsuke Kawaguchi */ public class GHPersonSet extends HashSet { private static final long serialVersionUID = 1L; - + public GHPersonSet() { } @@ -39,5 +39,5 @@ public T byLogin(String login) { if (t.getLogin().equals(login)) return t; return null; - } + } } diff --git a/src/main/java/org/kohsuke/github/GHProject.java b/src/main/java/org/kohsuke/github/GHProject.java index 66e347cbc3..35198666e4 100644 --- a/src/main/java/org/kohsuke/github/GHProject.java +++ b/src/main/java/org/kohsuke/github/GHProject.java @@ -32,6 +32,7 @@ /** * A GitHub project. + * * @see Projects * @author Martin van Zijl */ @@ -58,13 +59,13 @@ public GitHub getRoot() { } public GHObject getOwner() throws IOException { - if(owner == null) { + if (owner == null) { try { - if(owner_url.contains("/orgs/")) { + if (owner_url.contains("/orgs/")) { owner = root.retrieve().to(getOwnerUrl().getPath(), GHOrganization.class).wrapUp(root); - } else if(owner_url.contains("/users/")) { + } else if (owner_url.contains("/users/")) { owner = root.retrieve().to(getOwnerUrl().getPath(), GHUser.class).wrapUp(root); - } else if(owner_url.contains("/repos/")) { + } else if (owner_url.contains("/repos/")) { owner = root.retrieve().to(getOwnerUrl().getPath(), GHRepository.class).wrap(root); } } catch (FileNotFoundException e) { @@ -130,8 +131,7 @@ public void setBody(String body) throws IOException { } public enum ProjectState { - OPEN, - CLOSED + OPEN, CLOSED } public void setState(ProjectState state) throws IOException { @@ -139,22 +139,19 @@ public void setState(ProjectState state) throws IOException { } public static enum ProjectStateFilter { - ALL, - OPEN, - CLOSED + ALL, OPEN, CLOSED } /** - * Set the permission level that all members of the project's organization will have on this project. - * Only applicable for organization-owned projects. + * Set the permission level that all members of the project's organization will have on this project. Only + * applicable for organization-owned projects. */ public void setOrganizationPermission(GHPermissionType permission) throws IOException { edit("organization_permission", permission.toString().toLowerCase()); } /** - * Sets visibility of the project within the organization. - * Only applicable for organization-owned projects. + * Sets visibility of the project within the organization. Only applicable for organization-owned projects. */ public void setPublic(boolean isPublic) throws IOException { edit("public", isPublic); @@ -166,18 +163,12 @@ public void delete() throws IOException { public PagedIterable listColumns() throws IOException { final GHProject project = this; - return root.retrieve() - .withPreview(INERTIA) - .asPagedIterable( - String.format("/projects/%d/columns", id), - GHProjectColumn[].class, - item -> item.wrap(project) ); + return root.retrieve().withPreview(INERTIA).asPagedIterable(String.format("/projects/%d/columns", id), + GHProjectColumn[].class, item -> item.wrap(project)); } public GHProjectColumn createColumn(String name) throws IOException { - return root.retrieve().method("POST") - .withPreview(INERTIA) - .with("name", name) + return root.retrieve().method("POST").withPreview(INERTIA).with("name", name) .to(String.format("/projects/%d/columns", id), GHProjectColumn.class).wrap(this); } } \ No newline at end of file diff --git a/src/main/java/org/kohsuke/github/GHProjectCard.java b/src/main/java/org/kohsuke/github/GHProjectCard.java index d6fb97cd87..574c016420 100644 --- a/src/main/java/org/kohsuke/github/GHProjectCard.java +++ b/src/main/java/org/kohsuke/github/GHProjectCard.java @@ -12,112 +12,112 @@ * @author Gunnar Skjold */ public class GHProjectCard extends GHObject { - private GitHub root; - private GHProject project; - private GHProjectColumn column; - - private String note; - private GHUser creator; - private String content_url, project_url, column_url; - private boolean archived; - - public URL getHtmlUrl() throws IOException { - return null; - } - - public GHProjectCard wrap(GitHub root) { - this.root = root; - return this; - } - - public GHProjectCard wrap(GHProjectColumn column) { - this.column = column; - this.project = column.project; - this.root = column.root; - return this; - } - - public GitHub getRoot() { - return root; - } - - public GHProject getProject() throws IOException { - if(project == null) { - try { - project = root.retrieve().to(getProjectUrl().getPath(), GHProject.class).wrap(root); - } catch (FileNotFoundException e) { - return null; - } - } - return project; - } - - public GHProjectColumn getColumn() throws IOException { - if(column == null) { - try { - column = root.retrieve().to(getColumnUrl().getPath(), GHProjectColumn.class).wrap(root); - } catch (FileNotFoundException e) { - return null; - } - } - return column; - } - - public GHIssue getContent() throws IOException { - if(StringUtils.isEmpty(content_url)) - return null; - try { - if(content_url.contains("/pulls")) { - return root.retrieve().to(getContentUrl().getPath(), GHPullRequest.class).wrap(root); - } else { - return root.retrieve().to(getContentUrl().getPath(), GHIssue.class).wrap(root); - } - } catch (FileNotFoundException e) { - return null; - } - } - - public String getNote() { - return note; - } - - public GHUser getCreator() { - return creator; - } - - public URL getContentUrl() { - return GitHub.parseURL(content_url); - } - - public URL getProjectUrl() { - return GitHub.parseURL(project_url); - } - - public URL getColumnUrl() { - return GitHub.parseURL(column_url); - } - - public boolean isArchived() { - return archived; - } - - public void setNote(String note) throws IOException { - edit("note", note); - } - - public void setArchived(boolean archived) throws IOException { - edit("archived", archived); - } - - private void edit(String key, Object value) throws IOException { - new Requester(root).withPreview(INERTIA)._with(key, value).method("PATCH").to(getApiRoute()); - } - - protected String getApiRoute() { - return String.format("/projects/columns/cards/%d", id); - } - - public void delete() throws IOException { - new Requester(root).withPreview(INERTIA).method("DELETE").to(getApiRoute()); - } + private GitHub root; + private GHProject project; + private GHProjectColumn column; + + private String note; + private GHUser creator; + private String content_url, project_url, column_url; + private boolean archived; + + public URL getHtmlUrl() throws IOException { + return null; + } + + public GHProjectCard wrap(GitHub root) { + this.root = root; + return this; + } + + public GHProjectCard wrap(GHProjectColumn column) { + this.column = column; + this.project = column.project; + this.root = column.root; + return this; + } + + public GitHub getRoot() { + return root; + } + + public GHProject getProject() throws IOException { + if (project == null) { + try { + project = root.retrieve().to(getProjectUrl().getPath(), GHProject.class).wrap(root); + } catch (FileNotFoundException e) { + return null; + } + } + return project; + } + + public GHProjectColumn getColumn() throws IOException { + if (column == null) { + try { + column = root.retrieve().to(getColumnUrl().getPath(), GHProjectColumn.class).wrap(root); + } catch (FileNotFoundException e) { + return null; + } + } + return column; + } + + public GHIssue getContent() throws IOException { + if (StringUtils.isEmpty(content_url)) + return null; + try { + if (content_url.contains("/pulls")) { + return root.retrieve().to(getContentUrl().getPath(), GHPullRequest.class).wrap(root); + } else { + return root.retrieve().to(getContentUrl().getPath(), GHIssue.class).wrap(root); + } + } catch (FileNotFoundException e) { + return null; + } + } + + public String getNote() { + return note; + } + + public GHUser getCreator() { + return creator; + } + + public URL getContentUrl() { + return GitHub.parseURL(content_url); + } + + public URL getProjectUrl() { + return GitHub.parseURL(project_url); + } + + public URL getColumnUrl() { + return GitHub.parseURL(column_url); + } + + public boolean isArchived() { + return archived; + } + + public void setNote(String note) throws IOException { + edit("note", note); + } + + public void setArchived(boolean archived) throws IOException { + edit("archived", archived); + } + + private void edit(String key, Object value) throws IOException { + new Requester(root).withPreview(INERTIA)._with(key, value).method("PATCH").to(getApiRoute()); + } + + protected String getApiRoute() { + return String.format("/projects/columns/cards/%d", id); + } + + public void delete() throws IOException { + new Requester(root).withPreview(INERTIA).method("DELETE").to(getApiRoute()); + } } diff --git a/src/main/java/org/kohsuke/github/GHProjectColumn.java b/src/main/java/org/kohsuke/github/GHProjectColumn.java index 3b853962ff..3846e402d0 100644 --- a/src/main/java/org/kohsuke/github/GHProjectColumn.java +++ b/src/main/java/org/kohsuke/github/GHProjectColumn.java @@ -10,89 +10,82 @@ * @author Gunnar Skjold */ public class GHProjectColumn extends GHObject { - protected GitHub root; - protected GHProject project; - - private String name; - private String project_url; - - @Override - public URL getHtmlUrl() throws IOException { - return null; - } - - public GHProjectColumn wrap(GitHub root) { - this.root = root; - return this; - } - - public GHProjectColumn wrap(GHProject project) { - this.project = project; - this.root = project.root; - return this; - } - - public GitHub getRoot() { - return root; - } - - public GHProject getProject() throws IOException { - if(project == null) { - try { - project = root.retrieve().to(getProjectUrl().getPath(), GHProject.class).wrap(root); - } catch (FileNotFoundException e) { - return null; - } - } - return project; - } - - public String getName() { - return name; - } - - public URL getProjectUrl() { - return GitHub.parseURL(project_url); - } - - public void setName(String name) throws IOException { - edit("name", name); - } - - private void edit(String key, Object value) throws IOException { - new Requester(root).withPreview(INERTIA)._with(key, value).method("PATCH").to(getApiRoute()); - } - - protected String getApiRoute() { - return String.format("/projects/columns/%d", id); - } - - public void delete() throws IOException { - new Requester(root).withPreview(INERTIA).method("DELETE").to(getApiRoute()); - } - - public PagedIterable listCards() throws IOException { - final GHProjectColumn column = this; - return root.retrieve() - .withPreview(INERTIA) - .asPagedIterable( - String.format("/projects/columns/%d/cards", id), - GHProjectCard[].class, - item -> item.wrap(column) ); - } - - public GHProjectCard createCard(String note) throws IOException { - return root.retrieve().method("POST") - .withPreview(INERTIA) - .with("note", note) - .to(String.format("/projects/columns/%d/cards", id), GHProjectCard.class).wrap(this); - } - - public GHProjectCard createCard(GHIssue issue) throws IOException { - return root.retrieve().method("POST") - .withPreview(INERTIA) - .with("content_type", issue instanceof GHPullRequest ? "PullRequest" : "Issue") - .with("content_id", issue.getId()) - .to(String.format("/projects/columns/%d/cards", id), GHProjectCard.class).wrap(this); - } + protected GitHub root; + protected GHProject project; + + private String name; + private String project_url; + + @Override + public URL getHtmlUrl() throws IOException { + return null; + } + + public GHProjectColumn wrap(GitHub root) { + this.root = root; + return this; + } + + public GHProjectColumn wrap(GHProject project) { + this.project = project; + this.root = project.root; + return this; + } + + public GitHub getRoot() { + return root; + } + + public GHProject getProject() throws IOException { + if (project == null) { + try { + project = root.retrieve().to(getProjectUrl().getPath(), GHProject.class).wrap(root); + } catch (FileNotFoundException e) { + return null; + } + } + return project; + } + + public String getName() { + return name; + } + + public URL getProjectUrl() { + return GitHub.parseURL(project_url); + } + + public void setName(String name) throws IOException { + edit("name", name); + } + + private void edit(String key, Object value) throws IOException { + new Requester(root).withPreview(INERTIA)._with(key, value).method("PATCH").to(getApiRoute()); + } + + protected String getApiRoute() { + return String.format("/projects/columns/%d", id); + } + + public void delete() throws IOException { + new Requester(root).withPreview(INERTIA).method("DELETE").to(getApiRoute()); + } + + public PagedIterable listCards() throws IOException { + final GHProjectColumn column = this; + return root.retrieve().withPreview(INERTIA).asPagedIterable(String.format("/projects/columns/%d/cards", id), + GHProjectCard[].class, item -> item.wrap(column)); + } + + public GHProjectCard createCard(String note) throws IOException { + return root.retrieve().method("POST").withPreview(INERTIA).with("note", note) + .to(String.format("/projects/columns/%d/cards", id), GHProjectCard.class).wrap(this); + } + + public GHProjectCard createCard(GHIssue issue) throws IOException { + return root.retrieve().method("POST").withPreview(INERTIA) + .with("content_type", issue instanceof GHPullRequest ? "PullRequest" : "Issue") + .with("content_id", issue.getId()) + .to(String.format("/projects/columns/%d/cards", id), GHProjectCard.class).wrap(this); + } } diff --git a/src/main/java/org/kohsuke/github/GHPullRequest.java b/src/main/java/org/kohsuke/github/GHPullRequest.java index b4c3ee1645..3b7e3e120d 100644 --- a/src/main/java/org/kohsuke/github/GHPullRequest.java +++ b/src/main/java/org/kohsuke/github/GHPullRequest.java @@ -41,7 +41,7 @@ * @author Kohsuke Kawaguchi * @see GHRepository#getPullRequest(int) */ -@SuppressWarnings({"UnusedDeclaration"}) +@SuppressWarnings({ "UnusedDeclaration" }) public class GHPullRequest extends GHIssue implements Refreshable { private static final String COMMENTS_ACTION = "/comments"; @@ -69,52 +69,54 @@ public class GHPullRequest extends GHIssue implements Refreshable { private GHTeam[] requested_teams; /** - * GitHub doesn't return some properties of {@link GHIssue} when requesting the GET on the 'pulls' API - * route as opposed to 'issues' API route. This flag remembers whether we made the GET call on the 'issues' route - * on this object to fill in those missing details + * GitHub doesn't return some properties of {@link GHIssue} when requesting the GET on the 'pulls' API route as + * opposed to 'issues' API route. This flag remembers whether we made the GET call on the 'issues' route on this + * object to fill in those missing details */ private transient boolean fetchedIssueDetails; - GHPullRequest wrapUp(GHRepository owner) { this.wrap(owner); return wrapUp(owner.root); } GHPullRequest wrapUp(GitHub root) { - if (owner != null) owner.wrap(root); - if (base != null) base.wrapUp(root); - if (head != null) head.wrapUp(root); - if (merged_by != null) merged_by.wrapUp(root); - if (requested_reviewers != null) GHUser.wrap(requested_reviewers, root); - if (requested_teams != null) GHTeam.wrapUp(requested_teams, this); + if (owner != null) + owner.wrap(root); + if (base != null) + base.wrapUp(root); + if (head != null) + head.wrapUp(root); + if (merged_by != null) + merged_by.wrapUp(root); + if (requested_reviewers != null) + GHUser.wrap(requested_reviewers, root); + if (requested_teams != null) + GHTeam.wrapUp(requested_teams, this); return this; } @Override protected String getApiRoute() { - return "/repos/"+owner.getOwnerName()+"/"+owner.getName()+"/pulls/"+number; + return "/repos/" + owner.getOwnerName() + "/" + owner.getName() + "/pulls/" + number; } /** - * The URL of the patch file. - * like https://github.com/jenkinsci/jenkins/pull/100.patch + * The URL of the patch file. like https://github.com/jenkinsci/jenkins/pull/100.patch */ public URL getPatchUrl() { return GitHub.parseURL(patch_url); } /** - * The URL of the patch file. - * like https://github.com/jenkinsci/jenkins/pull/100.patch + * The URL of the patch file. like https://github.com/jenkinsci/jenkins/pull/100.patch */ public URL getIssueUrl() { return GitHub.parseURL(issue_url); } /** - * This points to where the change should be pulled into, - * but I'm not really sure what exactly it means. + * This points to where the change should be pulled into, but I'm not really sure what exactly it means. */ public GHCommitPointer getBase() { return base; @@ -133,8 +135,7 @@ public Date getIssueUpdatedAt() throws IOException { } /** - * The diff file, - * like https://github.com/jenkinsci/jenkins/pull/100.diff + * The diff file, like https://github.com/jenkinsci/jenkins/pull/100.diff */ public URL getDiffUrl() { return GitHub.parseURL(diff_url); @@ -202,10 +203,9 @@ public boolean isDraft() throws IOException { /** * Is this PR mergeable? * - * @return - * null if the state has not been determined yet, for example when a PR is newly created. - * If this method is called on an instance whose mergeable state is not yet known, - * API call is made to retrieve the latest state. + * @return null if the state has not been determined yet, for example when a PR is newly created. If this method is + * called on an instance whose mergeable state is not yet known, API call is made to retrieve the latest + * state. */ public Boolean getMergeable() throws IOException { refresh(mergeable); @@ -220,7 +220,6 @@ Boolean getMergeableNoRefresh() throws IOException { return mergeable; } - public int getDeletions() throws IOException { populate(); return deletions; @@ -260,7 +259,8 @@ public List getRequestedTeams() throws IOException { * Depending on the original API call where this object is created, it may not contain everything. */ private void populate() throws IOException { - if (mergeable_state!=null) return; // already populated + if (mergeable_state != null) + return; // already populated refresh(); } @@ -271,30 +271,22 @@ public void refresh() throws IOException { if (root.isOffline()) { return; // cannot populate, will have to live with what we have } - root.retrieve() - .withPreview(SHADOW_CAT) - .to(url, this).wrapUp(owner); + root.retrieve().withPreview(SHADOW_CAT).to(url, this).wrapUp(owner); } /** * Retrieves all the files associated to this pull request. */ public PagedIterable listFiles() { - return root.retrieve() - .asPagedIterable( - String.format("%s/files", getApiRoute()), - GHPullRequestFileDetail[].class, - null); + return root.retrieve().asPagedIterable(String.format("%s/files", getApiRoute()), + GHPullRequestFileDetail[].class, null); } /** * Retrieves all the reviews associated to this pull request. */ public PagedIterable listReviews() { - return root.retrieve() - .asPagedIterable( - String.format("%s/reviews", getApiRoute()), - GHPullRequestReview[].class, + return root.retrieve().asPagedIterable(String.format("%s/reviews", getApiRoute()), GHPullRequestReview[].class, item -> item.wrapUp(GHPullRequest.this)); } @@ -302,39 +294,31 @@ public PagedIterable listReviews() { * Obtains all the review comments associated with this pull request. */ public PagedIterable listReviewComments() throws IOException { - return root.retrieve() - .asPagedIterable( - getApiRoute() + COMMENTS_ACTION, - GHPullRequestReviewComment[].class, - item -> item.wrapUp(GHPullRequest.this) ); + return root.retrieve().asPagedIterable(getApiRoute() + COMMENTS_ACTION, GHPullRequestReviewComment[].class, + item -> item.wrapUp(GHPullRequest.this)); } /** * Retrieves all the commits associated to this pull request. */ public PagedIterable listCommits() { - return root.retrieve() - .asPagedIterable( - String.format("%s/commits", getApiRoute()), - GHPullRequestCommitDetail[].class, - item -> item.wrapUp(GHPullRequest.this) ); + return root.retrieve().asPagedIterable(String.format("%s/commits", getApiRoute()), + GHPullRequestCommitDetail[].class, item -> item.wrapUp(GHPullRequest.this)); } /** - * @deprecated - * Use {@link #createReview()} + * @deprecated Use {@link #createReview()} */ public GHPullRequestReview createReview(String body, @CheckForNull GHPullRequestReviewState event, - GHPullRequestReviewComment... comments) throws IOException { + GHPullRequestReviewComment... comments) throws IOException { return createReview(body, event, Arrays.asList(comments)); } /** - * @deprecated - * Use {@link #createReview()} + * @deprecated Use {@link #createReview()} */ public GHPullRequestReview createReview(String body, @CheckForNull GHPullRequestReviewState event, - List comments) throws IOException { + List comments) throws IOException { GHPullRequestReviewBuilder b = createReview().body(body); for (GHPullRequestReviewComment c : comments) { b.comment(c.getBody(), c.getPath(), c.getPosition()); @@ -346,29 +330,23 @@ public GHPullRequestReviewBuilder createReview() { return new GHPullRequestReviewBuilder(this); } - public GHPullRequestReviewComment createReviewComment(String body, String sha, String path, int position) throws IOException { - return new Requester(root).method("POST") - .with("body", body) - .with("commit_id", sha) - .with("path", path) - .with("position", position) - .to(getApiRoute() + COMMENTS_ACTION, GHPullRequestReviewComment.class).wrapUp(this); + public GHPullRequestReviewComment createReviewComment(String body, String sha, String path, int position) + throws IOException { + return new Requester(root).method("POST").with("body", body).with("commit_id", sha).with("path", path) + .with("position", position).to(getApiRoute() + COMMENTS_ACTION, GHPullRequestReviewComment.class) + .wrapUp(this); } public void requestReviewers(List reviewers) throws IOException { - new Requester(root).method("POST") - .withLogins("reviewers", reviewers) - .to(getApiRoute() + REQUEST_REVIEWERS); + new Requester(root).method("POST").withLogins("reviewers", reviewers).to(getApiRoute() + REQUEST_REVIEWERS); } public void requestTeamReviewers(List teams) throws IOException { List teamReviewers = new ArrayList(teams.size()); for (GHTeam team : teams) { - teamReviewers.add(team.getSlug()); + teamReviewers.add(team.getSlug()); } - new Requester(root).method("POST") - .with("team_reviewers", teamReviewers) - .to(getApiRoute() + REQUEST_REVIEWERS); + new Requester(root).method("POST").with("team_reviewers", teamReviewers).to(getApiRoute() + REQUEST_REVIEWERS); } /** @@ -377,10 +355,10 @@ public void requestTeamReviewers(List teams) throws IOException { * The equivalent of the big green "Merge pull request" button. * * @param msg - * Commit message. If null, the default one will be used. + * Commit message. If null, the default one will be used. */ public void merge(String msg) throws IOException { - merge(msg,null); + merge(msg, null); } /** @@ -389,9 +367,9 @@ public void merge(String msg) throws IOException { * The equivalent of the big green "Merge pull request" button. * * @param msg - * Commit message. If null, the default one will be used. + * Commit message. If null, the default one will be used. * @param sha - * SHA that pull request head must match to allow merge. + * SHA that pull request head must match to allow merge. */ public void merge(String msg, String sha) throws IOException { merge(msg, sha, null); @@ -403,19 +381,18 @@ public void merge(String msg, String sha) throws IOException { * The equivalent of the big green "Merge pull request" button. * * @param msg - * Commit message. If null, the default one will be used. + * Commit message. If null, the default one will be used. * @param method - * SHA that pull request head must match to allow merge. + * SHA that pull request head must match to allow merge. */ public void merge(String msg, String sha, MergeMethod method) throws IOException { - new Requester(root).method("PUT") - .with("commit_message", msg) - .with("sha", sha) - .with("merge_method", method) + new Requester(root).method("PUT").with("commit_message", msg).with("sha", sha).with("merge_method", method) .to(getApiRoute() + "/merge"); } - public enum MergeMethod{ MERGE, SQUASH, REBASE } + public enum MergeMethod { + MERGE, SQUASH, REBASE + } private void fetchIssue() throws IOException { if (!fetchedIssueDetails) { diff --git a/src/main/java/org/kohsuke/github/GHPullRequestCommitDetail.java b/src/main/java/org/kohsuke/github/GHPullRequestCommitDetail.java index e6c558b9e1..cc2311e1d1 100644 --- a/src/main/java/org/kohsuke/github/GHPullRequestCommitDetail.java +++ b/src/main/java/org/kohsuke/github/GHPullRequestCommitDetail.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2013, Luca Milanesio - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -30,16 +30,16 @@ /** * Commit detail inside a {@link GHPullRequest}. - * + * * @author Luca Milanesio * @see GHPullRequest#listCommits() */ -@SuppressFBWarnings(value = {"UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", - "NP_UNWRITTEN_FIELD", "URF_UNREAD_FIELD"}, justification = "JSON API") +@SuppressFBWarnings(value = { "UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", "NP_UNWRITTEN_FIELD", + "URF_UNREAD_FIELD" }, justification = "JSON API") public class GHPullRequestCommitDetail { private GHPullRequest owner; - /*package*/ void wrapUp(GHPullRequest owner) { + void wrapUp(GHPullRequest owner) { this.owner = owner; } diff --git a/src/main/java/org/kohsuke/github/GHPullRequestFileDetail.java b/src/main/java/org/kohsuke/github/GHPullRequestFileDetail.java index 35bb86c444..d0129e282c 100644 --- a/src/main/java/org/kohsuke/github/GHPullRequestFileDetail.java +++ b/src/main/java/org/kohsuke/github/GHPullRequestFileDetail.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2015, Julien Henry - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,7 +27,7 @@ /** * File detail inside a {@link GHPullRequest}. - * + * * @author Julien Henry * @see GHPullRequest#listFiles() */ @@ -85,8 +85,7 @@ public String getPatch() { return patch; } - public String getPreviousFilename() - { + public String getPreviousFilename() { return previous_filename; } } diff --git a/src/main/java/org/kohsuke/github/GHPullRequestQueryBuilder.java b/src/main/java/org/kohsuke/github/GHPullRequestQueryBuilder.java index 50b5cbb3ae..10d1bc2761 100644 --- a/src/main/java/org/kohsuke/github/GHPullRequestQueryBuilder.java +++ b/src/main/java/org/kohsuke/github/GHPullRequestQueryBuilder.java @@ -11,13 +11,13 @@ public class GHPullRequestQueryBuilder extends GHQueryBuilder { private final GHRepository repo; - /*package*/ GHPullRequestQueryBuilder(GHRepository repo) { + GHPullRequestQueryBuilder(GHRepository repo) { super(repo.root); this.repo = repo; } public GHPullRequestQueryBuilder state(GHIssueState state) { - req.with("state",state); + req.with("state", state); return this; } @@ -25,34 +25,32 @@ public GHPullRequestQueryBuilder head(String head) { if (head != null && !head.contains(":")) { head = repo.getOwnerName() + ":" + head; } - req.with("head",head); + req.with("head", head); return this; } public GHPullRequestQueryBuilder base(String base) { - req.with("base",base); + req.with("base", base); return this; } public GHPullRequestQueryBuilder sort(Sort sort) { - req.with("sort",sort); + req.with("sort", sort); return this; } - public enum Sort { CREATED, UPDATED, POPULARITY, LONG_RUNNING } + public enum Sort { + CREATED, UPDATED, POPULARITY, LONG_RUNNING + } public GHPullRequestQueryBuilder direction(GHDirection d) { - req.with("direction",d); + req.with("direction", d); return this; } @Override public PagedIterable list() { - return req - .withPreview(SHADOW_CAT) - .asPagedIterable( - repo.getApiTailUrl("pulls"), - GHPullRequest[].class, - item -> item.wrapUp(repo) ); + return req.withPreview(SHADOW_CAT).asPagedIterable(repo.getApiTailUrl("pulls"), GHPullRequest[].class, + item -> item.wrapUp(repo)); } } diff --git a/src/main/java/org/kohsuke/github/GHPullRequestReview.java b/src/main/java/org/kohsuke/github/GHPullRequestReview.java index b61a65ca05..9ea06dd2bb 100644 --- a/src/main/java/org/kohsuke/github/GHPullRequestReview.java +++ b/src/main/java/org/kohsuke/github/GHPullRequestReview.java @@ -36,7 +36,7 @@ * @see GHPullRequest#listReviews() * @see GHPullRequestReviewBuilder */ -@SuppressFBWarnings(value = {"UWF_UNWRITTEN_FIELD"}, justification = "JSON API") +@SuppressFBWarnings(value = { "UWF_UNWRITTEN_FIELD" }, justification = "JSON API") public class GHPullRequestReview extends GHObject { GHPullRequest owner; @@ -46,7 +46,7 @@ public class GHPullRequestReview extends GHObject { private GHPullRequestReviewState state; private String submitted_at; - /*package*/ GHPullRequestReview wrapUp(GHPullRequest owner) { + GHPullRequestReview wrapUp(GHPullRequest owner) { this.owner = owner; return this; } @@ -87,7 +87,7 @@ public URL getHtmlUrl() { } protected String getApiRoute() { - return owner.getApiRoute()+"/reviews/"+id; + return owner.getApiRoute() + "/reviews/" + id; } /** @@ -106,22 +106,19 @@ public Date getCreatedAt() throws IOException { } /** - * @deprecated - * Former preview method that changed when it got public. Left here for backward compatibility. - * Use {@link #submit(String, GHPullRequestReviewEvent)} + * @deprecated Former preview method that changed when it got public. Left here for backward compatibility. Use + * {@link #submit(String, GHPullRequestReviewEvent)} */ public void submit(String body, GHPullRequestReviewState state) throws IOException { - submit(body,state.toEvent()); + submit(body, state.toEvent()); } /** * Updates the comment. */ public void submit(String body, GHPullRequestReviewEvent event) throws IOException { - new Requester(owner.root).method("POST") - .with("body", body) - .with("event", event.action()) - .to(getApiRoute()+"/events",this); + new Requester(owner.root).method("POST").with("body", body).with("event", event.action()) + .to(getApiRoute() + "/events", this); this.body = body; this.state = event.toState(); } @@ -130,17 +127,14 @@ public void submit(String body, GHPullRequestReviewEvent event) throws IOExcepti * Deletes this review. */ public void delete() throws IOException { - new Requester(owner.root).method("DELETE") - .to(getApiRoute()); + new Requester(owner.root).method("DELETE").to(getApiRoute()); } /** * Dismisses this review. */ public void dismiss(String message) throws IOException { - new Requester(owner.root).method("PUT") - .with("message", message) - .to(getApiRoute()+"/dismissals"); + new Requester(owner.root).method("PUT").with("message", message).to(getApiRoute() + "/dismissals"); state = GHPullRequestReviewState.DISMISSED; } @@ -148,10 +142,7 @@ public void dismiss(String message) throws IOException { * Obtains all the review comments associated with this pull request review. */ public PagedIterable listReviewComments() throws IOException { - return owner.root.retrieve() - .asPagedIterable( - getApiRoute() + "/comments", - GHPullRequestReviewComment[].class, - item -> item.wrapUp(owner) ); + return owner.root.retrieve().asPagedIterable(getApiRoute() + "/comments", GHPullRequestReviewComment[].class, + item -> item.wrapUp(owner)); } } diff --git a/src/main/java/org/kohsuke/github/GHPullRequestReviewBuilder.java b/src/main/java/org/kohsuke/github/GHPullRequestReviewBuilder.java index 318daf721f..4649d1f1f3 100644 --- a/src/main/java/org/kohsuke/github/GHPullRequestReviewBuilder.java +++ b/src/main/java/org/kohsuke/github/GHPullRequestReviewBuilder.java @@ -15,19 +15,21 @@ public class GHPullRequestReviewBuilder { private final Requester builder; private final List comments = new ArrayList(); - /*package*/ GHPullRequestReviewBuilder(GHPullRequest pr) { + GHPullRequestReviewBuilder(GHPullRequest pr) { this.pr = pr; this.builder = new Requester(pr.root); } - // public GHPullRequestReview createReview(@Nullable String commitId, String body, GHPullRequestReviewEvent event, - // List comments) throws IOException + // public GHPullRequestReview createReview(@Nullable String commitId, String body, GHPullRequestReviewEvent event, + // List comments) throws IOException /** - * The SHA of the commit that needs a review. Not using the latest commit SHA may render your review comment outdated if a subsequent commit modifies the line you specify as the position. Defaults to the most recent commit in the pull request when you do not specify a value. + * The SHA of the commit that needs a review. Not using the latest commit SHA may render your review comment + * outdated if a subsequent commit modifies the line you specify as the position. Defaults to the most recent commit + * in the pull request when you do not specify a value. */ public GHPullRequestReviewBuilder commitId(String commitId) { - builder.with("commit_id",commitId); + builder.with("commit_id", commitId); return this; } @@ -35,34 +37,38 @@ public GHPullRequestReviewBuilder commitId(String commitId) { * Required when using REQUEST_CHANGES or COMMENT for the event parameter. The body text of the pull request review. */ public GHPullRequestReviewBuilder body(String body) { - builder.with("body",body); + builder.with("body", body); return this; } /** - * The review action you want to perform. The review actions include: APPROVE, REQUEST_CHANGES, or COMMENT. - * By leaving this blank, you set the review action state to PENDING, - * which means you will need to {@linkplain GHPullRequestReview#submit(String, GHPullRequestReviewEvent) submit the pull request review} when you are ready. + * The review action you want to perform. The review actions include: APPROVE, REQUEST_CHANGES, or COMMENT. By + * leaving this blank, you set the review action state to PENDING, which means you will need to + * {@linkplain GHPullRequestReview#submit(String, GHPullRequestReviewEvent) submit the pull request review} when you + * are ready. */ public GHPullRequestReviewBuilder event(GHPullRequestReviewEvent event) { - builder.with("event",event.action()); + builder.with("event", event.action()); return this; } /** - * @param body The relative path to the file that necessitates a review comment. - * @param path The position in the diff where you want to add a review comment. Note this value is not the same as the line number in the file. For help finding the position value, read the note below. - * @param position Text of the review comment. + * @param body + * The relative path to the file that necessitates a review comment. + * @param path + * The position in the diff where you want to add a review comment. Note this value is not the same as + * the line number in the file. For help finding the position value, read the note below. + * @param position + * Text of the review comment. */ public GHPullRequestReviewBuilder comment(String body, String path, int position) { - comments.add(new DraftReviewComment(body,path,position)); + comments.add(new DraftReviewComment(body, path, position)); return this; } public GHPullRequestReview create() throws IOException { - return builder.method("POST")._with("comments",comments) - .to(pr.getApiRoute() + "/reviews", GHPullRequestReview.class) - .wrapUp(pr); + return builder.method("POST")._with("comments", comments) + .to(pr.getApiRoute() + "/reviews", GHPullRequestReview.class).wrapUp(pr); } private static class DraftReviewComment { diff --git a/src/main/java/org/kohsuke/github/GHPullRequestReviewComment.java b/src/main/java/org/kohsuke/github/GHPullRequestReviewComment.java index 8848c28282..1804d47e93 100644 --- a/src/main/java/org/kohsuke/github/GHPullRequestReviewComment.java +++ b/src/main/java/org/kohsuke/github/GHPullRequestReviewComment.java @@ -46,10 +46,8 @@ public class GHPullRequestReviewComment extends GHObject implements Reactable { private int original_position = -1; private long in_reply_to_id = -1L; - /** - * @deprecated - * You should be using {@link GHPullRequestReviewBuilder#comment(String, String, int)} + * @deprecated You should be using {@link GHPullRequestReviewBuilder#comment(String, String, int)} */ public static GHPullRequestReviewComment draft(String body, String path, int position) { GHPullRequestReviewComment result = new GHPullRequestReviewComment(); @@ -59,7 +57,7 @@ public static GHPullRequestReviewComment draft(String body, String path, int pos return result; } - /*package*/ GHPullRequestReviewComment wrapUp(GHPullRequest owner) { + GHPullRequestReviewComment wrapUp(GHPullRequest owner) { this.owner = owner; return this; } @@ -109,14 +107,14 @@ public URL getHtmlUrl() { } protected String getApiRoute() { - return "/repos/"+owner.getRepository().getFullName()+"/pulls/comments/"+id; + return "/repos/" + owner.getRepository().getFullName() + "/pulls/comments/" + id; } /** * Updates the comment. */ public void update(String body) throws IOException { - new Requester(owner.root).method("PATCH").with("body", body).to(getApiRoute(),this); + new Requester(owner.root).method("PATCH").with("body", body).to(getApiRoute(), this); this.body = body; } @@ -131,28 +129,21 @@ public void delete() throws IOException { * Create a new comment that replies to this comment. */ public GHPullRequestReviewComment reply(String body) throws IOException { - return new Requester(owner.root).method("POST") - .with("body", body) - .with("in_reply_to", getId()) - .to(getApiRoute() + "/comments", GHPullRequestReviewComment.class) - .wrapUp(owner); + return new Requester(owner.root).method("POST").with("body", body).with("in_reply_to", getId()) + .to(getApiRoute() + "/comments", GHPullRequestReviewComment.class).wrapUp(owner); } - @Preview @Deprecated + @Preview + @Deprecated public GHReaction createReaction(ReactionContent content) throws IOException { - return new Requester(owner.root) - .withPreview(SQUIRREL_GIRL) - .with("content", content.getContent()) - .to(getApiRoute()+"/reactions", GHReaction.class).wrap(owner.root); + return new Requester(owner.root).withPreview(SQUIRREL_GIRL).with("content", content.getContent()) + .to(getApiRoute() + "/reactions", GHReaction.class).wrap(owner.root); } - @Preview @Deprecated + @Preview + @Deprecated public PagedIterable listReactions() { - return owner.root.retrieve() - .withPreview(SQUIRREL_GIRL) - .asPagedIterable( - getApiRoute() + "/reactions", - GHReaction[].class, - item -> item.wrap(owner.root) ); + return owner.root.retrieve().withPreview(SQUIRREL_GIRL).asPagedIterable(getApiRoute() + "/reactions", + GHReaction[].class, item -> item.wrap(owner.root)); } } diff --git a/src/main/java/org/kohsuke/github/GHPullRequestReviewEvent.java b/src/main/java/org/kohsuke/github/GHPullRequestReviewEvent.java index e6537e0f09..3bcea3311f 100644 --- a/src/main/java/org/kohsuke/github/GHPullRequestReviewEvent.java +++ b/src/main/java/org/kohsuke/github/GHPullRequestReviewEvent.java @@ -27,24 +27,25 @@ * Action to perform on {@link GHPullRequestReview}. */ public enum GHPullRequestReviewEvent { - PENDING, - APPROVE, - REQUEST_CHANGES, - COMMENT; + PENDING, APPROVE, REQUEST_CHANGES, COMMENT; - /*package*/ String action() { - return this==PENDING ? null : name(); + String action() { + return this == PENDING ? null : name(); } /** * When a {@link GHPullRequestReview} is submitted with this event, it should transition to this state. */ - /*package*/ GHPullRequestReviewState toState() { + GHPullRequestReviewState toState() { switch (this) { - case PENDING: return GHPullRequestReviewState.PENDING; - case APPROVE: return GHPullRequestReviewState.APPROVED; - case REQUEST_CHANGES: return GHPullRequestReviewState.CHANGES_REQUESTED; - case COMMENT: return GHPullRequestReviewState.COMMENTED; + case PENDING: + return GHPullRequestReviewState.PENDING; + case APPROVE: + return GHPullRequestReviewState.APPROVED; + case REQUEST_CHANGES: + return GHPullRequestReviewState.CHANGES_REQUESTED; + case COMMENT: + return GHPullRequestReviewState.COMMENTED; } throw new IllegalStateException(); } diff --git a/src/main/java/org/kohsuke/github/GHPullRequestReviewState.java b/src/main/java/org/kohsuke/github/GHPullRequestReviewState.java index a64a105994..5f1c0c06e3 100644 --- a/src/main/java/org/kohsuke/github/GHPullRequestReviewState.java +++ b/src/main/java/org/kohsuke/github/GHPullRequestReviewState.java @@ -4,35 +4,33 @@ * Current state of {@link GHPullRequestReview} */ public enum GHPullRequestReviewState { - PENDING, - APPROVED, - CHANGES_REQUESTED, + PENDING, APPROVED, CHANGES_REQUESTED, /** - * @deprecated - * This was the thing when this API was in preview, but it changed when it became public. - * Use {@link #CHANGES_REQUESTED}. Left here for compatibility. + * @deprecated This was the thing when this API was in preview, but it changed when it became public. Use + * {@link #CHANGES_REQUESTED}. Left here for compatibility. */ - REQUEST_CHANGES, - COMMENTED, - DISMISSED; + REQUEST_CHANGES, COMMENTED, DISMISSED; /** - * @deprecated - * This was an internal method accidentally exposed. - * Left here for compatibility. + * @deprecated This was an internal method accidentally exposed. Left here for compatibility. */ public String action() { GHPullRequestReviewEvent e = toEvent(); - return e==null ? null : e.action(); + return e == null ? null : e.action(); } - /*package*/ GHPullRequestReviewEvent toEvent() { + GHPullRequestReviewEvent toEvent() { switch (this) { - case PENDING: return GHPullRequestReviewEvent.PENDING; - case APPROVED: return GHPullRequestReviewEvent.APPROVE; - case CHANGES_REQUESTED: return GHPullRequestReviewEvent.REQUEST_CHANGES; - case REQUEST_CHANGES: return GHPullRequestReviewEvent.REQUEST_CHANGES; - case COMMENTED: return GHPullRequestReviewEvent.COMMENT; + case PENDING: + return GHPullRequestReviewEvent.PENDING; + case APPROVED: + return GHPullRequestReviewEvent.APPROVE; + case CHANGES_REQUESTED: + return GHPullRequestReviewEvent.REQUEST_CHANGES; + case REQUEST_CHANGES: + return GHPullRequestReviewEvent.REQUEST_CHANGES; + case COMMENTED: + return GHPullRequestReviewEvent.COMMENT; } return null; } diff --git a/src/main/java/org/kohsuke/github/GHQueryBuilder.java b/src/main/java/org/kohsuke/github/GHQueryBuilder.java index bb85fbbe95..bf26fa567e 100644 --- a/src/main/java/org/kohsuke/github/GHQueryBuilder.java +++ b/src/main/java/org/kohsuke/github/GHQueryBuilder.java @@ -9,7 +9,7 @@ public abstract class GHQueryBuilder { protected final GitHub root; protected final Requester req; - /*package*/ GHQueryBuilder(GitHub root) { + GHQueryBuilder(GitHub root) { this.root = root; this.req = root.retrieve(); } diff --git a/src/main/java/org/kohsuke/github/GHRateLimit.java b/src/main/java/org/kohsuke/github/GHRateLimit.java index c0b21da817..f99c848fab 100644 --- a/src/main/java/org/kohsuke/github/GHRateLimit.java +++ b/src/main/java/org/kohsuke/github/GHRateLimit.java @@ -34,21 +34,19 @@ public class GHRateLimit { /** * Allotted API call per hour. * - * @deprecated This value should never have been made public. Use {@link #getLimit()} + * @deprecated This value should never have been made public. Use {@link #getLimit()} */ @Deprecated public int limit; /** - * The time at which the current rate limit window resets in UTC epoch seconds. - * NOTE: that means to + * The time at which the current rate limit window resets in UTC epoch seconds. NOTE: that means to * * @deprecated This value should never have been made public. Use {@link #getResetDate()} */ @Deprecated public Date reset; - @Nonnull private final Record core; @@ -62,7 +60,8 @@ public class GHRateLimit { private final Record integrationManifest; static GHRateLimit Unknown() { - return new GHRateLimit(new UnknownLimitRecord(), new UnknownLimitRecord(), new UnknownLimitRecord(), new UnknownLimitRecord()); + return new GHRateLimit(new UnknownLimitRecord(), new UnknownLimitRecord(), new UnknownLimitRecord(), + new UnknownLimitRecord()); } static GHRateLimit fromHeaderRecord(Record header) { @@ -70,10 +69,9 @@ static GHRateLimit fromHeaderRecord(Record header) { } @JsonCreator - GHRateLimit(@Nonnull @JsonProperty("core") Record core, - @Nonnull @JsonProperty("search") Record search, - @Nonnull @JsonProperty("graphql") Record graphql, - @Nonnull @JsonProperty("integration_manifest") Record integrationManifest) { + GHRateLimit(@Nonnull @JsonProperty("core") Record core, @Nonnull @JsonProperty("search") Record search, + @Nonnull @JsonProperty("graphql") Record graphql, + @Nonnull @JsonProperty("integration_manifest") Record integrationManifest) { this.core = core; this.search = search; this.graphql = graphql; @@ -85,7 +83,6 @@ static GHRateLimit fromHeaderRecord(Record header) { this.reset = new Date(core.getResetEpochSeconds()); } - /** * Returns the date at which the Core API rate limit will reset. * @@ -116,7 +113,6 @@ public int getLimit() { return getCore().getLimit(); } - /** * Gets the time in epoch seconds when the Core API rate limit will reset. * @@ -149,8 +145,8 @@ public Record getCore() { } /** - * The search object provides your rate limit status for the Search API. - * TODO: integrate with header limit updating. Issue #605. + * The search object provides your rate limit status for the Search API. TODO: integrate with header limit updating. + * Issue #605. * * @return a rate limit record */ @@ -160,8 +156,8 @@ Record getSearch() { } /** - * The graphql object provides your rate limit status for the GraphQL API. - * TODO: integrate with header limit updating. Issue #605. + * The graphql object provides your rate limit status for the GraphQL API. TODO: integrate with header limit + * updating. Issue #605. * * @return a rate limit record */ @@ -171,8 +167,8 @@ Record getGraphQL() { } /** - * The integration_manifest object provides your rate limit status for the GitHub App Manifest code conversion endpoint. - * TODO: integrate with header limit updating. Issue #605. + * The integration_manifest object provides your rate limit status for the GitHub App Manifest code conversion + * endpoint. TODO: integrate with header limit updating. Issue #605. * * @return a rate limit record */ @@ -183,12 +179,8 @@ Record getIntegrationManifest() { @Override public String toString() { - return "GHRateLimit {" + - "core " + getCore().toString() + - "search " + getSearch().toString() + - "graphql " + getGraphQL().toString() + - "integrationManifest " + getIntegrationManifest().toString() + - '}'; + return "GHRateLimit {" + "core " + getCore().toString() + "search " + getSearch().toString() + "graphql " + + getGraphQL().toString() + "integrationManifest " + getIntegrationManifest().toString() + '}'; } @Override @@ -200,10 +192,9 @@ public boolean equals(Object o) { return false; } GHRateLimit rateLimit = (GHRateLimit) o; - return getCore().equals(rateLimit.getCore()) && - getSearch().equals(rateLimit.getSearch()) && - getGraphQL().equals(rateLimit.getGraphQL()) && - getIntegrationManifest().equals(rateLimit.getIntegrationManifest()); + return getCore().equals(rateLimit.getCore()) && getSearch().equals(rateLimit.getSearch()) + && getGraphQL().equals(rateLimit.getGraphQL()) + && getIntegrationManifest().equals(rateLimit.getIntegrationManifest()); } @Override @@ -233,6 +224,7 @@ private UnknownLimitRecord() { /** * A rate limit record. + * * @since 1.100 */ public static class Record { @@ -257,21 +249,19 @@ public static class Record { private final long createdAtEpochSeconds = System.currentTimeMillis() / 1000; /** - * The calculated time at which the rate limit will reset. - * Recalculated if {@link #recalculateResetDate} is called. + * The calculated time at which the rate limit will reset. Recalculated if {@link #recalculateResetDate} is + * called. */ @Nonnull private Date resetDate; @JsonCreator - public Record(@JsonProperty("limit") int limit, - @JsonProperty("remaining") int remaining, - @JsonProperty("reset")long resetEpochSeconds) { + public Record(@JsonProperty("limit") int limit, @JsonProperty("remaining") int remaining, + @JsonProperty("reset") long resetEpochSeconds) { this(limit, remaining, resetEpochSeconds, null); } - @SuppressFBWarnings(value = "URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD", - justification = "Deprecated") + @SuppressFBWarnings(value = "URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD", justification = "Deprecated") public Record(int limit, int remaining, long resetEpochSeconds, String updatedAt) { this.limit = limit; this.remaining = remaining; @@ -280,10 +270,11 @@ public Record(int limit, int remaining, long resetEpochSeconds, String updatedAt } /** - * Recalculates the reset date using the server response date to calculate a time duration - * and then add that to the local created time for this record. + * Recalculates the reset date using the server response date to calculate a time duration and then add that to + * the local created time for this record. * - * @param updatedAt a string date in RFC 1123 + * @param updatedAt + * a string date in RFC 1123 * @return reset date based on the passed date */ Date recalculateResetDate(String updatedAt) { @@ -291,7 +282,8 @@ Date recalculateResetDate(String updatedAt) { if (!StringUtils.isBlank(updatedAt)) { try { // Get the server date and reset data, will always return a time in GMT - updatedAtEpochSeconds = ZonedDateTime.parse(updatedAt, DateTimeFormatter.RFC_1123_DATE_TIME).toEpochSecond(); + updatedAtEpochSeconds = ZonedDateTime.parse(updatedAt, DateTimeFormatter.RFC_1123_DATE_TIME) + .toEpochSecond(); } catch (DateTimeParseException e) { if (LOGGER.isLoggable(FINEST)) { LOGGER.log(FINEST, "Malformed Date header value " + updatedAt, e); @@ -353,11 +345,8 @@ public Date getResetDate() { @Override public String toString() { - return "{" + - "remaining=" + getRemaining() + - ", limit=" + getLimit() + - ", resetDate=" + getResetDate() + - '}'; + return "{" + "remaining=" + getRemaining() + ", limit=" + getLimit() + ", resetDate=" + getResetDate() + + '}'; } @Override @@ -369,10 +358,9 @@ public boolean equals(Object o) { return false; } Record record = (Record) o; - return getRemaining() == record.getRemaining() && - getLimit() == record.getLimit() && - getResetEpochSeconds() == record.getResetEpochSeconds() && - getResetDate().equals(record.getResetDate()); + return getRemaining() == record.getRemaining() && getLimit() == record.getLimit() + && getResetEpochSeconds() == record.getResetEpochSeconds() + && getResetDate().equals(record.getResetDate()); } @Override diff --git a/src/main/java/org/kohsuke/github/GHReaction.java b/src/main/java/org/kohsuke/github/GHReaction.java index 6a00eb305c..e809516cac 100644 --- a/src/main/java/org/kohsuke/github/GHReaction.java +++ b/src/main/java/org/kohsuke/github/GHReaction.java @@ -11,14 +11,15 @@ * @author Kohsuke Kawaguchi * @see Reactable */ -@Preview @Deprecated +@Preview +@Deprecated public class GHReaction extends GHObject { private GitHub root; private GHUser user; private ReactionContent content; - /*package*/ GHReaction wrap(GitHub root) { + GHReaction wrap(GitHub root) { this.root = root; user.wrapUp(root); return this; @@ -50,6 +51,6 @@ public URL getHtmlUrl() { * Removes this reaction. */ public void delete() throws IOException { - new Requester(root).method("DELETE").withPreview(SQUIRREL_GIRL).to("/reactions/"+id); + new Requester(root).method("DELETE").withPreview(SQUIRREL_GIRL).to("/reactions/" + id); } } diff --git a/src/main/java/org/kohsuke/github/GHRef.java b/src/main/java/org/kohsuke/github/GHRef.java index c8462d3fe6..f8ff997512 100644 --- a/src/main/java/org/kohsuke/github/GHRef.java +++ b/src/main/java/org/kohsuke/github/GHRef.java @@ -11,7 +11,7 @@ * @author Michael Clarke */ public class GHRef { - /*package almost final*/ GitHub root; + /* package almost final */ GitHub root; private String ref, url; private GHObject object; @@ -41,48 +41,47 @@ public GHObject getObject() { * Updates this ref to the specified commit. * * @param sha - * The SHA1 value to set this reference to + * The SHA1 value to set this reference to */ public void updateTo(String sha) throws IOException { - updateTo(sha, false); + updateTo(sha, false); } /** * Updates this ref to the specified commit. * * @param sha - * The SHA1 value to set this reference to + * The SHA1 value to set this reference to * @param force - * Whether or not to force this ref update. + * Whether or not to force this ref update. */ public void updateTo(String sha, Boolean force) throws IOException { - new Requester(root) - .with("sha", sha).with("force", force).method("PATCH").to(url, GHRef.class).wrap(root); + new Requester(root).with("sha", sha).with("force", force).method("PATCH").to(url, GHRef.class).wrap(root); } /** * Deletes this ref from the repository using the GitHub API. */ public void delete() throws IOException { - new Requester(root).method("DELETE").to(url); + new Requester(root).method("DELETE").to(url); } - /*package*/ GHRef wrap(GitHub root) { + GHRef wrap(GitHub root) { this.root = root; return this; } - /*package*/ static GHRef[] wrap(GHRef[] in, GitHub root) { + static GHRef[] wrap(GHRef[] in, GitHub root) { for (GHRef r : in) { r.wrap(root); } return in; } - @SuppressFBWarnings(value = {"UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", - "NP_UNWRITTEN_FIELD"}, justification = "JSON API") + @SuppressFBWarnings(value = { "UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", + "NP_UNWRITTEN_FIELD" }, justification = "JSON API") public static class GHObject { - private String type, sha, url; + private String type, sha, url; /** * Type of the object, such as "commit" @@ -99,7 +98,8 @@ public String getSha() { } /** - * API URL to this Git data, such as https://api.github.com/repos/jenkinsci/jenkins/git/commits/b72322675eb0114363a9a86e9ad5a170d1d07ac0 + * API URL to this Git data, such as + * https://api.github.com/repos/jenkinsci/jenkins/git/commits/b72322675eb0114363a9a86e9ad5a170d1d07ac0 */ public URL getUrl() { return GitHub.parseURL(url); diff --git a/src/main/java/org/kohsuke/github/GHRelease.java b/src/main/java/org/kohsuke/github/GHRelease.java index 0df6b415b0..f7e81e2180 100644 --- a/src/main/java/org/kohsuke/github/GHRelease.java +++ b/src/main/java/org/kohsuke/github/GHRelease.java @@ -47,8 +47,7 @@ public boolean isDraft() { } /** - * @deprecated - * Use {@link #update()} + * @deprecated Use {@link #update()} */ public GHRelease setDraft(boolean draft) throws IOException { return update().draft(draft).update(); @@ -121,10 +120,10 @@ static GHRelease[] wrap(GHRelease[] releases, GHRepository owner) { /** * Because github relies on SNI (http://en.wikipedia.org/wiki/Server_Name_Indication) this method will only work on - * Java 7 or greater. Options for fixing this for earlier JVMs can be found here + * Java 7 or greater. Options for fixing this for earlier JVMs can be found here * http://stackoverflow.com/questions/12361090/server-name-indication-sni-on-java but involve more complicated * handling of the HTTP requests to github's API. - */ + */ public GHAsset uploadAsset(File file, String contentType) throws IOException { FileInputStream s = new FileInputStream(file); try { @@ -133,23 +132,19 @@ public GHAsset uploadAsset(File file, String contentType) throws IOException { s.close(); } } - + public GHAsset uploadAsset(String filename, InputStream stream, String contentType) throws IOException { Requester builder = new Requester(owner.root); - String url = format("https://uploads.github.com%s/releases/%d/assets?name=%s", - owner.getApiTailUrl(""), getId(), filename); - return builder.contentType(contentType) - .with(stream) - .to(url, GHAsset.class).wrap(this); + String url = format("https://uploads.github.com%s/releases/%d/assets?name=%s", owner.getApiTailUrl(""), getId(), + filename); + return builder.contentType(contentType).with(stream).to(url, GHAsset.class).wrap(this); } public List getAssets() throws IOException { Requester builder = new Requester(owner.root); - GHAsset[] assets = builder - .method("GET") - .to(getApiTailUrl("assets"), GHAsset[].class); + GHAsset[] assets = builder.method("GET").to(getApiTailUrl("assets"), GHAsset[].class); return Arrays.asList(GHAsset.wrap(assets, this)); } @@ -157,7 +152,7 @@ public List getAssets() throws IOException { * Deletes this release. */ public void delete() throws IOException { - new Requester(root).method("DELETE").to(owner.getApiTailUrl("releases/"+id)); + new Requester(root).method("DELETE").to(owner.getApiTailUrl("releases/" + id)); } /** @@ -168,6 +163,6 @@ public GHReleaseUpdater update() { } private String getApiTailUrl(String end) { - return owner.getApiTailUrl(format("releases/%s/%s",id,end)); + return owner.getApiTailUrl(format("releases/%s/%s", id, end)); } } diff --git a/src/main/java/org/kohsuke/github/GHReleaseBuilder.java b/src/main/java/org/kohsuke/github/GHReleaseBuilder.java index e427bdf8a5..d35943b570 100644 --- a/src/main/java/org/kohsuke/github/GHReleaseBuilder.java +++ b/src/main/java/org/kohsuke/github/GHReleaseBuilder.java @@ -18,7 +18,8 @@ public GHReleaseBuilder(GHRepository ghRepository, String tag) { } /** - * @param body The release notes body. + * @param body + * The release notes body. */ public GHReleaseBuilder body(String body) { builder.with("body", body); @@ -26,11 +27,10 @@ public GHReleaseBuilder body(String body) { } /** - * Specifies the commitish value that determines where the Git tag is created from. Can be any branch or - * commit SHA. + * Specifies the commitish value that determines where the Git tag is created from. Can be any branch or commit SHA. * - * @param commitish Defaults to the repository’s default branch (usually "master"). Unused if the Git tag - * already exists. + * @param commitish + * Defaults to the repository’s default branch (usually "master"). Unused if the Git tag already exists. */ public GHReleaseBuilder commitish(String commitish) { builder.with("target_commitish", commitish); @@ -40,8 +40,9 @@ public GHReleaseBuilder commitish(String commitish) { /** * Optional. * - * @param draft {@code true} to create a draft (unpublished) release, {@code false} to create a published one. - * Default is {@code false}. + * @param draft + * {@code true} to create a draft (unpublished) release, {@code false} to create a published one. Default + * is {@code false}. */ public GHReleaseBuilder draft(boolean draft) { builder.with("draft", draft); @@ -49,7 +50,8 @@ public GHReleaseBuilder draft(boolean draft) { } /** - * @param name the name of the release + * @param name + * the name of the release */ public GHReleaseBuilder name(String name) { builder.with("name", name); @@ -59,8 +61,9 @@ public GHReleaseBuilder name(String name) { /** * Optional * - * @param prerelease {@code true} to identify the release as a prerelease. {@code false} to identify the release - * as a full release. Default is {@code false}. + * @param prerelease + * {@code true} to identify the release as a prerelease. {@code false} to identify the release as a full + * release. Default is {@code false}. */ public GHReleaseBuilder prerelease(boolean prerelease) { builder.with("prerelease", prerelease); diff --git a/src/main/java/org/kohsuke/github/GHReleaseUpdater.java b/src/main/java/org/kohsuke/github/GHReleaseUpdater.java index a34a5b0bc2..e3905f03e3 100644 --- a/src/main/java/org/kohsuke/github/GHReleaseUpdater.java +++ b/src/main/java/org/kohsuke/github/GHReleaseUpdater.java @@ -18,12 +18,13 @@ public class GHReleaseUpdater { } public GHReleaseUpdater tag(String tag) { - builder.with("tag_name",tag); + builder.with("tag_name", tag); return this; } /** - * @param body The release notes body. + * @param body + * The release notes body. */ public GHReleaseUpdater body(String body) { builder.with("body", body); @@ -31,11 +32,10 @@ public GHReleaseUpdater body(String body) { } /** - * Specifies the commitish value that determines where the Git tag is created from. Can be any branch or - * commit SHA. + * Specifies the commitish value that determines where the Git tag is created from. Can be any branch or commit SHA. * - * @param commitish Defaults to the repository’s default branch (usually "master"). Unused if the Git tag - * already exists. + * @param commitish + * Defaults to the repository’s default branch (usually "master"). Unused if the Git tag already exists. */ public GHReleaseUpdater commitish(String commitish) { builder.with("target_commitish", commitish); @@ -45,8 +45,9 @@ public GHReleaseUpdater commitish(String commitish) { /** * Optional. * - * @param draft {@code true} to create a draft (unpublished) release, {@code false} to create a published one. - * Default is {@code false}. + * @param draft + * {@code true} to create a draft (unpublished) release, {@code false} to create a published one. Default + * is {@code false}. */ public GHReleaseUpdater draft(boolean draft) { builder.with("draft", draft); @@ -54,7 +55,8 @@ public GHReleaseUpdater draft(boolean draft) { } /** - * @param name the name of the release + * @param name + * the name of the release */ public GHReleaseUpdater name(String name) { builder.with("name", name); @@ -64,8 +66,9 @@ public GHReleaseUpdater name(String name) { /** * Optional * - * @param prerelease {@code true} to identify the release as a prerelease. {@code false} to identify the release - * as a full release. Default is {@code false}. + * @param prerelease + * {@code true} to identify the release as a prerelease. {@code false} to identify the release as a full + * release. Default is {@code false}. */ public GHReleaseUpdater prerelease(boolean prerelease) { builder.with("prerelease", prerelease); @@ -73,9 +76,8 @@ public GHReleaseUpdater prerelease(boolean prerelease) { } public GHRelease update() throws IOException { - return builder - .method("PATCH") - .to(base.owner.getApiTailUrl("releases/"+base.id), GHRelease.class).wrap(base.owner); + return builder.method("PATCH").to(base.owner.getApiTailUrl("releases/" + base.id), GHRelease.class) + .wrap(base.owner); } } diff --git a/src/main/java/org/kohsuke/github/GHRepoHook.java b/src/main/java/org/kohsuke/github/GHRepoHook.java index 948438eb96..d273168f42 100644 --- a/src/main/java/org/kohsuke/github/GHRepoHook.java +++ b/src/main/java/org/kohsuke/github/GHRepoHook.java @@ -4,9 +4,9 @@ class GHRepoHook extends GHHook { /** * Repository that the hook belongs to. */ - /*package*/ transient GHRepository repository; + transient GHRepository repository; - /*package*/ GHRepoHook wrap(GHRepository owner) { + GHRepoHook wrap(GHRepository owner) { this.repository = owner; return this; } diff --git a/src/main/java/org/kohsuke/github/GHRepository.java b/src/main/java/org/kohsuke/github/GHRepository.java index 88a13b3be5..2565c30f85 100644 --- a/src/main/java/org/kohsuke/github/GHRepository.java +++ b/src/main/java/org/kohsuke/github/GHRepository.java @@ -66,14 +66,14 @@ * * @author Kohsuke Kawaguchi */ -@SuppressWarnings({"UnusedDeclaration"}) -@SuppressFBWarnings(value = {"UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", - "NP_UNWRITTEN_FIELD"}, justification = "JSON API") +@SuppressWarnings({ "UnusedDeclaration" }) +@SuppressFBWarnings(value = { "UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", + "NP_UNWRITTEN_FIELD" }, justification = "JSON API") public class GHRepository extends GHObject { - /*package almost final*/ GitHub root; + /* package almost final */ GitHub root; private String description, homepage, name, full_name; - private String html_url; // this is the UI + private String html_url; // this is the UI /* * The license information makes use of the preview API. * @@ -82,21 +82,21 @@ public class GHRepository extends GHObject { private GHLicense license; private String git_url, ssh_url, clone_url, svn_url, mirror_url; - private GHUser owner; // not fully populated. beware. + private GHUser owner; // not fully populated. beware. private boolean has_issues, has_wiki, fork, has_downloads, has_pages, archived; - + private boolean allow_squash_merge; private boolean allow_merge_commit; private boolean allow_rebase_merge; - + @JsonProperty("private") private boolean _private; private int forks_count, stargazers_count, watchers_count, size, open_issues_count, subscribers_count; private String pushed_at; - private Map milestones = new WeakHashMap(); + private Map milestones = new WeakHashMap(); - private String default_branch,language; - private Map commits = new WeakHashMap(); + private String default_branch, language; + private Map commits = new WeakHashMap(); @SkipFromToString private GHRepoPermission permissions; @@ -104,25 +104,22 @@ public class GHRepository extends GHObject { private GHRepository source, parent; public GHDeploymentBuilder createDeployment(String ref) { - return new GHDeploymentBuilder(this,ref); + return new GHDeploymentBuilder(this, ref); } /** - * @deprecated - * Use {@code getDeployment(id).listStatuses()} + * @deprecated Use {@code getDeployment(id).listStatuses()} */ public PagedIterable getDeploymentStatuses(final int id) throws IOException { return getDeployment(id).listStatuses(); } - public PagedIterable listDeployments(String sha,String ref,String task,String environment){ - List params = Arrays.asList(getParam("sha", sha), getParam("ref", ref), getParam("task", task), getParam("environment", environment)); - final String deploymentsUrl = getApiTailUrl("deployments") + "?"+ join(params,"&"); - return root.retrieve() - .asPagedIterable( - deploymentsUrl, - GHDeployment[].class, - item -> item.wrap(GHRepository.this) ); + public PagedIterable listDeployments(String sha, String ref, String task, String environment) { + List params = Arrays.asList(getParam("sha", sha), getParam("ref", ref), getParam("task", task), + getParam("environment", environment)); + final String deploymentsUrl = getApiTailUrl("deployments") + "?" + join(params, "&"); + return root.retrieve().asPagedIterable(deploymentsUrl, GHDeployment[].class, + item -> item.wrap(GHRepository.this)); } /** @@ -134,31 +131,30 @@ public GHDeployment getDeployment(long id) throws IOException { private String join(List params, String joinStr) { StringBuilder output = new StringBuilder(); - for(String param: params){ - if(param != null){ - output.append(param+joinStr); + for (String param : params) { + if (param != null) { + output.append(param + joinStr); } } return output.toString(); } private String getParam(String name, String value) { - return StringUtils.trimToNull(value)== null? null: name+"="+value; + return StringUtils.trimToNull(value) == null ? null : name + "=" + value; } /** - * @deprecated - * Use {@code getDeployment(deploymentId).createStatus(ghDeploymentState)} + * @deprecated Use {@code getDeployment(deploymentId).createStatus(ghDeploymentState)} */ - public GHDeploymentStatusBuilder createDeployStatus(int deploymentId, GHDeploymentState ghDeploymentState) throws IOException { + public GHDeploymentStatusBuilder createDeployStatus(int deploymentId, GHDeploymentState ghDeploymentState) + throws IOException { return getDeployment(deploymentId).createStatus(ghDeploymentState); } private static class GHRepoPermission { - boolean pull,push,admin; + boolean pull, push, admin; } - public String getDescription() { return description; } @@ -168,24 +164,21 @@ public String getHomepage() { } /** - * Gets the git:// URL to this repository, such as "git://github.com/kohsuke/jenkins.git" - * This URL is read-only. + * Gets the git:// URL to this repository, such as "git://github.com/kohsuke/jenkins.git" This URL is read-only. */ public String getGitTransportUrl() { return git_url; } /** - * Gets the HTTPS URL to this repository, such as "https://github.com/kohsuke/jenkins.git" - * This URL is read-only. + * Gets the HTTPS URL to this repository, such as "https://github.com/kohsuke/jenkins.git" This URL is read-only. */ public String getHttpTransportUrl() { return clone_url; } /** - * @deprecated - * Typo of {@link #getHttpTransportUrl()} + * @deprecated Typo of {@link #getHttpTransportUrl()} */ public String gitHttpTransportUrl() { return clone_url; @@ -199,8 +192,8 @@ public String getSvnUrl() { } /** - * Gets the Mirror URL to access this repository: https://github.com/apache/tomee - * mirrored from git://git.apache.org/tomee.git + * Gets the Mirror URL to access this repository: https://github.com/apache/tomee mirrored from + * git://git.apache.org/tomee.git */ public String getMirrorUrl() { return mirror_url; @@ -225,22 +218,23 @@ public String getName() { } /** - * Full repository name including the owner or organization. For example 'jenkinsci/jenkins' in case of http://github.com/jenkinsci/jenkins + * Full repository name including the owner or organization. For example 'jenkinsci/jenkins' in case of + * http://github.com/jenkinsci/jenkins */ public String getFullName() { return full_name; } public boolean hasPullAccess() { - return permissions!=null && permissions.pull; + return permissions != null && permissions.pull; } public boolean hasPushAccess() { - return permissions!=null && permissions.push; + return permissions != null && permissions.push; } public boolean hasAdminAccess() { - return permissions!=null && permissions.admin; + return permissions != null && permissions.admin; } /** @@ -251,7 +245,7 @@ public String getLanguage() { } public GHUser getOwner() throws IOException { - return root.isOffline() ? owner : root.getUser(getOwnerName()); // because 'owner' isn't fully populated + return root.isOffline() ? owner : root.getUser(getOwnerName()); // because 'owner' isn't fully populated } public GHIssue getIssue(int id) throws IOException { @@ -259,7 +253,7 @@ public GHIssue getIssue(int id) throws IOException { } public GHIssueBuilder createIssue(String title) { - return new GHIssueBuilder(this,title); + return new GHIssueBuilder(this, title); } public List getIssues(GHIssueState state) throws IOException { @@ -267,45 +261,39 @@ public List getIssues(GHIssueState state) throws IOException { } public List getIssues(GHIssueState state, GHMilestone milestone) throws IOException { - return Arrays.asList(GHIssue.wrap(root.retrieve() - .with("state", state) + return Arrays.asList(GHIssue.wrap(root.retrieve().with("state", state) .with("milestone", milestone == null ? "none" : "" + milestone.getNumber()) - .to(getApiTailUrl("issues"), - GHIssue[].class), this)); + .to(getApiTailUrl("issues"), GHIssue[].class), this)); } /** * Lists up all the issues in this repository. */ public PagedIterable listIssues(final GHIssueState state) { - return root.retrieve().with("state",state) - .asPagedIterable( - getApiTailUrl("issues"), - GHIssue[].class, - item -> item.wrap(GHRepository.this) ); + return root.retrieve().with("state", state).asPagedIterable(getApiTailUrl("issues"), GHIssue[].class, + item -> item.wrap(GHRepository.this)); } public GHReleaseBuilder createRelease(String tag) { - return new GHReleaseBuilder(this,tag); + return new GHReleaseBuilder(this, tag); } /** * Creates a named ref, such as tag, branch, etc. * * @param name - * The name of the fully qualified reference (ie: refs/heads/master). - * If it doesn't start with 'refs' and have at least two slashes, it will be rejected. + * The name of the fully qualified reference (ie: refs/heads/master). If it doesn't start with 'refs' and + * have at least two slashes, it will be rejected. * @param sha - * The SHA1 value to set this reference to + * The SHA1 value to set this reference to */ public GHRef createRef(String name, String sha) throws IOException { - return new Requester(root) - .with("ref", name).with("sha", sha).method("POST").to(getApiTailUrl("git/refs"), GHRef.class).wrap(root); + return new Requester(root).with("ref", name).with("sha", sha).method("POST") + .to(getApiTailUrl("git/refs"), GHRef.class).wrap(root); } /** - * @deprecated - * use {@link #listReleases()} + * @deprecated use {@link #listReleases()} */ public List getReleases() throws IOException { return listReleases().asList(); @@ -326,7 +314,7 @@ public GHRelease getReleaseByTagName(String tag) throws IOException { return null; // no release for this tag } } - + public GHRelease getLatestRelease() throws IOException { try { return root.retrieve().to(getApiTailUrl("releases/latest"), GHRelease.class).wrap(this); @@ -336,30 +324,20 @@ public GHRelease getLatestRelease() throws IOException { } public PagedIterable listReleases() throws IOException { - return root.retrieve() - .asPagedIterable( - getApiTailUrl("releases"), - GHRelease[].class, - item -> item.wrap(GHRepository.this) ); + return root.retrieve().asPagedIterable(getApiTailUrl("releases"), GHRelease[].class, + item -> item.wrap(GHRepository.this)); } public PagedIterable listTags() throws IOException { - return root.retrieve() - .asPagedIterable( - getApiTailUrl("tags"), - GHTag[].class, - item -> item.wrap(GHRepository.this) ); + return root.retrieve().asPagedIterable(getApiTailUrl("tags"), GHTag[].class, + item -> item.wrap(GHRepository.this)); } /** - * List languages for the specified repository. - * The value on the right of a language is the number of bytes of code written in that language. - * { - "C": 78769, - "Python": 7769 - } + * List languages for the specified repository. The value on the right of a language is the number of bytes of code + * written in that language. { "C": 78769, "Python": 7769 } */ - public Map listLanguages() throws IOException { + public Map listLanguages() throws IOException { return root.retrieve().to(getApiTailUrl("languages"), HashMap.class); } @@ -386,22 +364,22 @@ public boolean isFork() { public boolean isArchived() { return archived; } - + public boolean isAllowSquashMerge() { - return allow_squash_merge; + return allow_squash_merge; } - + public boolean isAllowMergeCommit() { - return allow_merge_commit; + return allow_merge_commit; } - + public boolean isAllowRebaseMerge() { - return allow_rebase_merge; + return allow_rebase_merge; } /** - * Returns the number of all forks of this repository. - * This not only counts direct forks, but also forks of forks, and so on. + * Returns the number of all forks of this repository. This not only counts direct forks, but also forks of forks, + * and so on. */ public int getForks() { return forks_count; @@ -432,9 +410,7 @@ public int getOpenIssueCount() { } /** - * @deprecated - * This no longer exists in the official API documentation. - * Use {@link #getForks()} + * @deprecated This no longer exists in the official API documentation. Use {@link #getForks()} */ public int getNetworkCount() { return forks_count; @@ -446,8 +422,7 @@ public int getSubscribersCount() { /** * - * @return - * null if the repository was never pushed at. + * @return null if the repository was never pushed at. */ public Date getPushedAt() { return GitHub.parseDate(pushed_at); @@ -456,16 +431,14 @@ public Date getPushedAt() { /** * Returns the primary branch you'll configure in the "Admin > Options" config page. * - * @return - * This field is null until the user explicitly configures the master branch. + * @return This field is null until the user explicitly configures the master branch. */ public String getDefaultBranch() { return default_branch; } /** - * @deprecated - * Renamed to {@link #getDefaultBranch()} + * @deprecated Renamed to {@link #getDefaultBranch()} */ public String getMasterBranch() { return default_branch; @@ -475,10 +448,8 @@ public int getSize() { return size; } - /** - * Gets the collaborators on this repository. - * This set always appear to include the owner. + * Gets the collaborators on this repository. This set always appear to include the owner. */ @WithBridgeMethods(Set.class) public GHPersonSet getCollaborators() throws IOException { @@ -495,8 +466,9 @@ public PagedIterable listCollaborators() throws IOException { } /** - * Lists all the available assignees - * to which issues may be assigned. + * Lists all + * the + * available assignees to which issues may be assigned. */ public PagedIterable listAssignees() throws IOException { return listUsers("assignees"); @@ -506,36 +478,44 @@ public PagedIterable listAssignees() throws IOException { * Checks if the given user is an assignee for this repository. */ public boolean hasAssignee(GHUser u) throws IOException { - return root.retrieve().asHttpStatusCode(getApiTailUrl("assignees/" + u.getLogin()))/100==2; + return root.retrieve().asHttpStatusCode(getApiTailUrl("assignees/" + u.getLogin())) / 100 == 2; } /** - * Gets the names of the collaborators on this repository. - * This method deviates from the principle of this library but it works a lot faster than {@link #getCollaborators()}. + * Gets the names of the collaborators on this repository. This method deviates from the principle of this library + * but it works a lot faster than {@link #getCollaborators()}. */ public Set getCollaboratorNames() throws IOException { Set r = new HashSet(); - for (GHUser u : GHUser.wrap(root.retrieve().to(getApiTailUrl("collaborators"), GHUser[].class),root)) + for (GHUser u : GHUser.wrap(root.retrieve().to(getApiTailUrl("collaborators"), GHUser[].class), root)) r.add(u.login); return r; } /** * Obtain permission for a given user in this repository. - * @param user a {@link GHUser#getLogin} - * @throws FileNotFoundException under some conditions (e.g., private repo you can see but are not an admin of); treat as unknown - * @throws HttpException with a 403 under other conditions (e.g., public repo you have no special rights to); treat as unknown + * + * @param user + * a {@link GHUser#getLogin} + * @throws FileNotFoundException + * under some conditions (e.g., private repo you can see but are not an admin of); treat as unknown + * @throws HttpException + * with a 403 under other conditions (e.g., public repo you have no special rights to); treat as unknown */ public GHPermissionType getPermission(String user) throws IOException { - GHPermission perm = root.retrieve().to(getApiTailUrl("collaborators/" + user + "/permission"), GHPermission.class); + GHPermission perm = root.retrieve().to(getApiTailUrl("collaborators/" + user + "/permission"), + GHPermission.class); perm.wrapUp(root); return perm.getPermissionType(); } /** * Obtain permission for a given user in this repository. - * @throws FileNotFoundException under some conditions (e.g., private repo you can see but are not an admin of); treat as unknown - * @throws HttpException with a 403 under other conditions (e.g., public repo you have no special rights to); treat as unknown + * + * @throws FileNotFoundException + * under some conditions (e.g., private repo you can see but are not an admin of); treat as unknown + * @throws HttpException + * with a 403 under other conditions (e.g., public repo you have no special rights to); treat as unknown */ public GHPermissionType getPermission(GHUser u) throws IOException { return getPermission(u.getLogin()); @@ -545,7 +525,8 @@ public GHPermissionType getPermission(GHUser u) throws IOException { * If this repository belongs to an organization, return a set of teams. */ public Set getTeams() throws IOException { - return Collections.unmodifiableSet(new HashSet(Arrays.asList(GHTeam.wrapUp(root.retrieve().to(getApiTailUrl("teams"), GHTeam[].class), root.getOrganization(getOwnerName()))))); + return Collections.unmodifiableSet(new HashSet(Arrays.asList(GHTeam.wrapUp( + root.retrieve().to(getApiTailUrl("teams"), GHTeam[].class), root.getOrganization(getOwnerName()))))); } public void addCollaborators(GHUser... users) throws IOException { @@ -580,7 +561,7 @@ public void setEmailServiceHook(String address) throws IOException { private void edit(String key, String value) throws IOException { Requester requester = new Requester(root); if (!key.equals("name")) - requester.with("name", name); // even when we don't change the name, we need to send it in + requester.with("name", name); // even when we don't change the name, we need to send it in requester.with(key, value).method("PATCH").to(getApiTailUrl("")); } @@ -599,22 +580,22 @@ public void enableWiki(boolean v) throws IOException { } public void enableDownloads(boolean v) throws IOException { - edit("has_downloads",String.valueOf(v)); + edit("has_downloads", String.valueOf(v)); } /** * Rename this repository. */ public void renameTo(String name) throws IOException { - edit("name",name); + edit("name", name); } public void setDescription(String value) throws IOException { - edit("description",value); + edit("description", value); } public void setHomepage(String value) throws IOException { - edit("homepage",value); + edit("homepage", value); } public void setDefaultBranch(String value) throws IOException { @@ -624,19 +605,19 @@ public void setDefaultBranch(String value) throws IOException { public void setPrivate(boolean value) throws IOException { edit("private", Boolean.toString(value)); } - + public void allowSquashMerge(boolean value) throws IOException { edit("allow_squash_merge", Boolean.toString(value)); } - + public void allowMergeCommit(boolean value) throws IOException { edit("allow_merge_commit", Boolean.toString(value)); } - + public void allowRebaseMerge(boolean value) throws IOException { edit("allow_rebase_merge", Boolean.toString(value)); } - + /** * Deletes this repository. */ @@ -644,16 +625,18 @@ public void delete() throws IOException { try { new Requester(root).method("DELETE").to(getApiTailUrl("")); } catch (FileNotFoundException x) { - throw (FileNotFoundException) new FileNotFoundException("Failed to delete " + getOwnerName() + "/" + name + "; might not exist, or you might need the delete_repo scope in your token: http://stackoverflow.com/a/19327004/12916").initCause(x); + throw (FileNotFoundException) new FileNotFoundException("Failed to delete " + getOwnerName() + "/" + name + + "; might not exist, or you might need the delete_repo scope in your token: http://stackoverflow.com/a/19327004/12916") + .initCause(x); } } /** - * Will archive and this repository as read-only. When a repository is archived, any operation - * that can change its state is forbidden. This applies symmetrically if trying to unarchive it. + * Will archive and this repository as read-only. When a repository is archived, any operation that can change its + * state is forbidden. This applies symmetrically if trying to unarchive it. * - *

When you try to do any operation that modifies a read-only repository, it returns the - * response: + *

+ * When you try to do any operation that modifies a read-only repository, it returns the response: * *

      * org.kohsuke.github.HttpException: {
@@ -662,7 +645,8 @@ public void delete() throws IOException {
      * }
      * 
* - * @throws IOException In case of any networking error or error from the server. + * @throws IOException + * In case of any networking error or error from the server. */ public void archive() throws IOException { edit("archived", "true"); @@ -674,80 +658,80 @@ public void archive() throws IOException { /** * Sort orders for listing forks */ - public enum ForkSort { NEWEST, OLDEST, STARGAZERS } + public enum ForkSort { + NEWEST, OLDEST, STARGAZERS + } /** - * Lists all the direct forks of this repository, sorted by - * github api default, currently {@link ForkSort#NEWEST ForkSort.NEWEST}. + * Lists all the direct forks of this repository, sorted by github api default, currently {@link ForkSort#NEWEST + * ForkSort.NEWEST}. */ public PagedIterable listForks() { - return listForks(null); + return listForks(null); } /** * Lists all the direct forks of this repository, sorted by the given sort order. - * @param sort the sort order. If null, defaults to github api default, - * currently {@link ForkSort#NEWEST ForkSort.NEWEST}. + * + * @param sort + * the sort order. If null, defaults to github api default, currently {@link ForkSort#NEWEST + * ForkSort.NEWEST}. */ public PagedIterable listForks(final ForkSort sort) { - return root.retrieve().with("sort",sort) - .asPagedIterable( - getApiTailUrl("forks"), - GHRepository[].class, - item -> item.wrap(root) ); + return root.retrieve().with("sort", sort).asPagedIterable(getApiTailUrl("forks"), GHRepository[].class, + item -> item.wrap(root)); } /** * Forks this repository as your repository. * - * @return - * Newly forked repository that belong to you. + * @return Newly forked repository that belong to you. */ public GHRepository fork() throws IOException { new Requester(root).method("POST").to(getApiTailUrl("forks"), null); // this API is asynchronous. we need to wait for a bit - for (int i=0; i<10; i++) { + for (int i = 0; i < 10; i++) { GHRepository r = root.getMyself().getRepository(name); - if (r!=null) return r; + if (r != null) + return r; try { Thread.sleep(3000); } catch (InterruptedException e) { - throw (IOException)new InterruptedIOException().initCause(e); + throw (IOException) new InterruptedIOException().initCause(e); } } - throw new IOException(this+" was forked but can't find the new repository"); + throw new IOException(this + " was forked but can't find the new repository"); } /** * Forks this repository into an organization. * - * @return - * Newly forked repository that belong to you. + * @return Newly forked repository that belong to you. */ public GHRepository forkTo(GHOrganization org) throws IOException { - new Requester(root).to(getApiTailUrl("forks?org="+org.getLogin())); + new Requester(root).to(getApiTailUrl("forks?org=" + org.getLogin())); // this API is asynchronous. we need to wait for a bit - for (int i=0; i<10; i++) { + for (int i = 0; i < 10; i++) { GHRepository r = org.getRepository(name); - if (r!=null) return r; + if (r != null) + return r; try { Thread.sleep(3000); } catch (InterruptedException e) { - throw (IOException)new InterruptedIOException().initCause(e); + throw (IOException) new InterruptedIOException().initCause(e); } } - throw new IOException(this+" was forked into "+org.getLogin()+" but can't find the new repository"); + throw new IOException(this + " was forked into " + org.getLogin() + " but can't find the new repository"); } /** * Retrieves a specified pull request. */ public GHPullRequest getPullRequest(int i) throws IOException { - return root.retrieve() - .withPreview(SHADOW_CAT) - .to(getApiTailUrl("pulls/" + i), GHPullRequest.class).wrapUp(this); + return root.retrieve().withPreview(SHADOW_CAT).to(getApiTailUrl("pulls/" + i), GHPullRequest.class) + .wrapUp(this); } /** @@ -762,8 +746,7 @@ public List getPullRequests(GHIssueState state) throws IOExceptio /** * Retrieves all the pull requests of a particular state. * - * @deprecated - * Use {@link #queryPullRequests()} + * @deprecated Use {@link #queryPullRequests()} */ public PagedIterable listPullRequests(GHIssueState state) { return queryPullRequests().state(state).list(); @@ -780,17 +763,15 @@ public GHPullRequestQueryBuilder queryPullRequests() { * Creates a new pull request. * * @param title - * Required. The title of the pull request. + * Required. The title of the pull request. * @param head - * Required. The name of the branch where your changes are implemented. - * For cross-repository pull requests in the same network, - * namespace head with a user like this: username:branch. + * Required. The name of the branch where your changes are implemented. For cross-repository pull + * requests in the same network, namespace head with a user like this: username:branch. * @param base - * Required. The name of the branch you want your changes pulled into. - * This should be an existing branch on the current repository. + * Required. The name of the branch you want your changes pulled into. This should be an existing branch + * on the current repository. * @param body - * The contents of the pull request. This is the markdown description - * of a pull request. + * The contents of the pull request. This is the markdown description of a pull request. */ public GHPullRequest createPullRequest(String title, String head, String base, String body) throws IOException { return createPullRequest(title, head, base, body, true); @@ -800,19 +781,17 @@ public GHPullRequest createPullRequest(String title, String head, String base, S * Creates a new pull request. Maintainer's permissions aware. * * @param title - * Required. The title of the pull request. + * Required. The title of the pull request. * @param head - * Required. The name of the branch where your changes are implemented. - * For cross-repository pull requests in the same network, - * namespace head with a user like this: username:branch. + * Required. The name of the branch where your changes are implemented. For cross-repository pull + * requests in the same network, namespace head with a user like this: username:branch. * @param base - * Required. The name of the branch you want your changes pulled into. - * This should be an existing branch on the current repository. + * Required. The name of the branch you want your changes pulled into. This should be an existing branch + * on the current repository. * @param body - * The contents of the pull request. This is the markdown description - * of a pull request. + * The contents of the pull request. This is the markdown description of a pull request. * @param maintainerCanModify - * Indicates whether maintainers can modify the pull request. + * Indicates whether maintainers can modify the pull request. */ public GHPullRequest createPullRequest(String title, String head, String base, String body, boolean maintainerCanModify) throws IOException { @@ -823,34 +802,25 @@ public GHPullRequest createPullRequest(String title, String head, String base, S * Creates a new pull request. Maintainer's permissions and draft aware. * * @param title - * Required. The title of the pull request. + * Required. The title of the pull request. * @param head - * Required. The name of the branch where your changes are implemented. - * For cross-repository pull requests in the same network, - * namespace head with a user like this: username:branch. + * Required. The name of the branch where your changes are implemented. For cross-repository pull + * requests in the same network, namespace head with a user like this: username:branch. * @param base - * Required. The name of the branch you want your changes pulled into. - * This should be an existing branch on the current repository. + * Required. The name of the branch you want your changes pulled into. This should be an existing branch + * on the current repository. * @param body - * The contents of the pull request. This is the markdown description - * of a pull request. + * The contents of the pull request. This is the markdown description of a pull request. * @param maintainerCanModify - * Indicates whether maintainers can modify the pull request. + * Indicates whether maintainers can modify the pull request. * @param draft - * Indicates whether to create a draft pull request or not. + * Indicates whether to create a draft pull request or not. */ public GHPullRequest createPullRequest(String title, String head, String base, String body, - boolean maintainerCanModify, boolean draft) throws IOException { - return new Requester(root) - .withPreview(SHADOW_CAT) - .with("title",title) - .with("head",head) - .with("base",base) - .with("body",body) - .with("maintainer_can_modify", maintainerCanModify) - .with("draft", draft) - .to(getApiTailUrl("pulls"),GHPullRequest.class) - .wrapUp(this); + boolean maintainerCanModify, boolean draft) throws IOException { + return new Requester(root).withPreview(SHADOW_CAT).with("title", title).with("head", head).with("base", base) + .with("body", body).with("maintainer_can_modify", maintainerCanModify).with("draft", draft) + .to(getApiTailUrl("pulls"), GHPullRequest.class).wrapUp(this); } /** @@ -865,15 +835,21 @@ public GHHook getHook(int id) throws IOException { } /** - * Gets a comparison between 2 points in the repository. This would be similar - * to calling git log id1...id2 against a local repository. - * @param id1 an identifier for the first point to compare from, this can be a sha1 ID (for a commit, tag etc) or a direct tag name - * @param id2 an identifier for the second point to compare to. Can be the same as the first point. + * Gets a comparison between 2 points in the repository. This would be similar to calling + * git log id1...id2 against a local repository. + * + * @param id1 + * an identifier for the first point to compare from, this can be a sha1 ID (for a commit, tag etc) or a + * direct tag name + * @param id2 + * an identifier for the second point to compare to. Can be the same as the first point. * @return the comparison output - * @throws IOException on failure communicating with GitHub + * @throws IOException + * on failure communicating with GitHub */ public GHCompare getCompare(String id1, String id2) throws IOException { - GHCompare compare = root.retrieve().to(getApiTailUrl(String.format("compare/%s...%s", id1, id2)), GHCompare.class); + GHCompare compare = root.retrieve().to(getApiTailUrl(String.format("compare/%s...%s", id1, id2)), + GHCompare.class); return compare.wrap(this); } @@ -887,7 +863,7 @@ public GHCompare getCompare(GHBranch id1, GHBranch id2) throws IOException { GHRepository owner2 = id2.getOwner(); // If the owner of the branches is different, we have a cross-fork compare. - if (owner1!=null && owner2!=null) { + if (owner1 != null && owner2 != null) { String ownerName1 = owner1.getOwnerName(); String ownerName2 = owner2.getOwnerName(); if (!StringUtils.equals(ownerName1, ownerName2)) { @@ -903,53 +879,54 @@ public GHCompare getCompare(GHBranch id1, GHBranch id2) throws IOException { /** * Retrieves all refs for the github repository. + * * @return an array of GHRef elements coresponding with the refs in the remote repository. - * @throws IOException on failure communicating with GitHub + * @throws IOException + * on failure communicating with GitHub */ public GHRef[] getRefs() throws IOException { - return GHRef.wrap(root.retrieve().to(String.format("/repos/%s/%s/git/refs", getOwnerName(), name), GHRef[].class), root); + return GHRef.wrap( + root.retrieve().to(String.format("/repos/%s/%s/git/refs", getOwnerName(), name), GHRef[].class), root); } - /** * Retrieves all refs for the github repository. * * @return paged iterable of all refs - * @throws IOException on failure communicating with GitHub, potentially due to an invalid ref type being requested + * @throws IOException + * on failure communicating with GitHub, potentially due to an invalid ref type being requested */ public PagedIterable listRefs() throws IOException { final String url = String.format("/repos/%s/%s/git/refs", getOwnerName(), name); - return root.retrieve() - .asPagedIterable( - url, - GHRef[].class, - item -> item.wrap(root) ); + return root.retrieve().asPagedIterable(url, GHRef[].class, item -> item.wrap(root)); } /** * Retrieves all refs of the given type for the current GitHub repository. - * @param refType the type of reg to search for e.g. tags or commits + * + * @param refType + * the type of reg to search for e.g. tags or commits * @return an array of all refs matching the request type - * @throws IOException on failure communicating with GitHub, potentially due to an invalid ref type being requested + * @throws IOException + * on failure communicating with GitHub, potentially due to an invalid ref type being requested */ public GHRef[] getRefs(String refType) throws IOException { - return GHRef.wrap(root.retrieve().to(String.format("/repos/%s/%s/git/refs/%s", getOwnerName(), name, refType), GHRef[].class),root); + return GHRef.wrap(root.retrieve().to(String.format("/repos/%s/%s/git/refs/%s", getOwnerName(), name, refType), + GHRef[].class), root); } /** * Retrieves all refs of the given type for the current GitHub repository. * - * @param refType the type of reg to search for e.g. tags or commits + * @param refType + * the type of reg to search for e.g. tags or commits * @return paged iterable of all refs of the specified type - * @throws IOException on failure communicating with GitHub, potentially due to an invalid ref type being requested + * @throws IOException + * on failure communicating with GitHub, potentially due to an invalid ref type being requested */ public PagedIterable listRefs(String refType) throws IOException { final String url = String.format("/repos/%s/%s/git/refs/%s", getOwnerName(), name, refType); - return root.retrieve() - .asPagedIterable( - url, - GHRef[].class, - item -> item.wrap(root)); + return root.retrieve().asPagedIterable(url, GHRef[].class, item -> item.wrap(root)); } /** @@ -959,22 +936,24 @@ public PagedIterable listRefs(String refType) throws IOException { * eg: heads/branch * @return refs matching the request type * @throws IOException - * on failure communicating with GitHub, potentially due to an - * invalid ref type being requested + * on failure communicating with GitHub, potentially due to an invalid ref type being requested */ public GHRef getRef(String refName) throws IOException { // hashes in branch names must be replaced with the url encoded equivalent or this call will fail - // FIXME: how about other URL unsafe characters, like space, @, : etc? do we need to be using URLEncoder.encode()? + // FIXME: how about other URL unsafe characters, like space, @, : etc? do we need to be using + // URLEncoder.encode()? // OTOH, '/' need no escaping refName = refName.replaceAll("#", "%23"); - return root.retrieve().to(String.format("/repos/%s/%s/git/refs/%s", getOwnerName(), name, refName), GHRef.class).wrap(root); + return root.retrieve().to(String.format("/repos/%s/%s/git/refs/%s", getOwnerName(), name, refName), GHRef.class) + .wrap(root); } /** * Returns the annotated tag object. Only valid if the {@link GHRef#getObject()} has a * {@link GHRef.GHObject#getType()} of {@code tag}. * - * @param sha the sha of the tag object + * @param sha + * the sha of the tag object * @return the annotated tag object */ public GHTagObject getTagObject(String sha) throws IOException { @@ -984,11 +963,11 @@ public GHTagObject getTagObject(String sha) throws IOException { /** * Retrive a tree of the given type for the current GitHub repository. * - * @param sha - sha number or branch name ex: "master" + * @param sha + * sha number or branch name ex: "master" * @return refs matching the request type * @throws IOException - * on failure communicating with GitHub, potentially due to an - * invalid tree type being requested + * on failure communicating with GitHub, potentially due to an invalid tree type being requested */ public GHTree getTree(String sha) throws IOException { String url = String.format("/repos/%s/%s/git/trees/%s", getOwnerName(), name, sha); @@ -1003,11 +982,12 @@ public GHTreeBuilder createTree() { * Retrieves the tree for the current GitHub repository, recursively as described in here: * https://developer.github.com/v3/git/trees/#get-a-tree-recursively * - * @param sha - sha number or branch name ex: "master" - * @param recursive use 1 + * @param sha + * sha number or branch name ex: "master" + * @param recursive + * use 1 * @throws IOException - * on failure communicating with GitHub, potentially due to an - * invalid tree type being requested + * on failure communicating with GitHub, potentially due to an invalid tree type being requested */ public GHTree getTreeRecursive(String sha, int recursive) throws IOException { String url = String.format("/repos/%s/%s/git/trees/%s?recursive=%d", getOwnerName(), name, sha, recursive); @@ -1040,7 +1020,7 @@ public GHBlobBuilder createBlob() { */ public InputStream readBlob(String blobSha) throws IOException { String target = getApiTailUrl("git/blobs/" + blobSha); - return root.retrieve().withHeader("Accept","application/vnd.github.VERSION.raw").asStream(target); + return root.retrieve().withHeader("Accept", "application/vnd.github.VERSION.raw").asStream(target); } /** @@ -1048,9 +1028,10 @@ public InputStream readBlob(String blobSha) throws IOException { */ public GHCommit getCommit(String sha1) throws IOException { GHCommit c = commits.get(sha1); - if (c==null) { - c = root.retrieve().to(String.format("/repos/%s/%s/commits/%s", getOwnerName(), name, sha1), GHCommit.class).wrapUp(this); - commits.put(sha1,c); + if (c == null) { + c = root.retrieve().to(String.format("/repos/%s/%s/commits/%s", getOwnerName(), name, sha1), GHCommit.class) + .wrapUp(this); + commits.put(sha1, c); } return c; } @@ -1063,11 +1044,8 @@ public GHCommitBuilder createCommit() { * Lists all the commits. */ public PagedIterable listCommits() { - return root.retrieve() - .asPagedIterable( - String.format("/repos/%s/%s/commits", getOwnerName(), name), - GHCommit[].class, - item -> item.wrapUp(GHRepository.this) ); + return root.retrieve().asPagedIterable(String.format("/repos/%s/%s/commits", getOwnerName(), name), + GHCommit[].class, item -> item.wrapUp(GHRepository.this)); } /** @@ -1081,23 +1059,21 @@ public GHCommitQueryBuilder queryCommits() { * Lists up all the commit comments in this repository. */ public PagedIterable listCommitComments() { - return root.retrieve() - .asPagedIterable( - String.format("/repos/%s/%s/comments", getOwnerName(), name), - GHCommitComment[].class, - item -> item.wrap(GHRepository.this) ); + return root.retrieve().asPagedIterable(String.format("/repos/%s/%s/comments", getOwnerName(), name), + GHCommitComment[].class, item -> item.wrap(GHRepository.this)); } /** * Gets the basic license details for the repository. *

* - * @throws IOException as usual but also if you don't use the preview connector + * @throws IOException + * as usual but also if you don't use the preview connector * @return null if there's no license. */ - public GHLicense getLicense() throws IOException{ + public GHLicense getLicense() throws IOException { GHContentWithLicense lic = getLicenseContent_(); - return lic!=null ? lic.license : null; + return lic != null ? lic.license : null; } /** @@ -1105,7 +1081,8 @@ public GHLicense getLicense() throws IOException{ *

* * @return details regarding the license contents, or null if there's no license. - * @throws IOException as usual but also if you don't use the preview connector + * @throws IOException + * as usual but also if you don't use the preview connector */ public GHContent getLicenseContent() throws IOException { return getLicenseContent_(); @@ -1113,24 +1090,19 @@ public GHContent getLicenseContent() throws IOException { private GHContentWithLicense getLicenseContent_() throws IOException { try { - return root.retrieve() - .to(getApiTailUrl("license"), GHContentWithLicense.class).wrap(this); + return root.retrieve().to(getApiTailUrl("license"), GHContentWithLicense.class).wrap(this); } catch (FileNotFoundException e) { return null; } } /** - - /** - * Lists all the commit statues attached to the given commit, newer ones first. + * + * /** Lists all the commit statues attached to the given commit, newer ones first. */ public PagedIterable listCommitStatuses(final String sha1) throws IOException { - return root.retrieve() - .asPagedIterable( - String.format("/repos/%s/%s/statuses/%s", getOwnerName(), name, sha1), - GHCommitStatus[].class, - item -> item.wrapUp(root) ); + return root.retrieve().asPagedIterable(String.format("/repos/%s/%s/statuses/%s", getOwnerName(), name, sha1), + GHCommitStatus[].class, item -> item.wrapUp(root)); } /** @@ -1145,25 +1117,25 @@ public GHCommitStatus getLastCommitStatus(String sha1) throws IOException { * Creates a commit status * * @param targetUrl - * Optional parameter that points to the URL that has more details. + * Optional parameter that points to the URL that has more details. * @param description - * Optional short description. - * @param context - * Optinal commit status context. - */ - public GHCommitStatus createCommitStatus(String sha1, GHCommitState state, String targetUrl, String description, String context) throws IOException { - return new Requester(root) - .with("state", state) - .with("target_url", targetUrl) - .with("description", description) + * Optional short description. + * @param context + * Optinal commit status context. + */ + public GHCommitStatus createCommitStatus(String sha1, GHCommitState state, String targetUrl, String description, + String context) throws IOException { + return new Requester(root).with("state", state).with("target_url", targetUrl).with("description", description) .with("context", context) - .to(String.format("/repos/%s/%s/statuses/%s",getOwnerName(),this.name,sha1),GHCommitStatus.class).wrapUp(root); + .to(String.format("/repos/%s/%s/statuses/%s", getOwnerName(), this.name, sha1), GHCommitStatus.class) + .wrapUp(root); } /** - * @see #createCommitStatus(String, GHCommitState,String,String,String) + * @see #createCommitStatus(String, GHCommitState,String,String,String) */ - public GHCommitStatus createCommitStatus(String sha1, GHCommitState state, String targetUrl, String description) throws IOException { + public GHCommitStatus createCommitStatus(String sha1, GHCommitState state, String targetUrl, String description) + throws IOException { return createCommitStatus(sha1, state, targetUrl, description, null); } @@ -1171,11 +1143,8 @@ public GHCommitStatus createCommitStatus(String sha1, GHCommitState state, Strin * Lists repository events. */ public PagedIterable listEvents() throws IOException { - return root.retrieve() - .asPagedIterable( - String.format("/repos/%s/%s/events", getOwnerName(), name), - GHEventInfo[].class, - item -> item.wrapUp(root) ); + return root.retrieve().asPagedIterable(String.format("/repos/%s/%s/events", getOwnerName(), name), + GHEventInfo[].class, item -> item.wrapUp(root)); } /** @@ -1184,19 +1153,12 @@ public PagedIterable listEvents() throws IOException { * https://developer.github.com/v3/issues/labels/#list-all-labels-for-this-repository */ public PagedIterable listLabels() throws IOException { - return root.retrieve() - .withPreview(SYMMETRA) - .asPagedIterable( - getApiTailUrl("labels"), - GHLabel[].class, - item -> item.wrapUp(GHRepository.this) ); + return root.retrieve().withPreview(SYMMETRA).asPagedIterable(getApiTailUrl("labels"), GHLabel[].class, + item -> item.wrapUp(GHRepository.this)); } public GHLabel getLabel(String name) throws IOException { - return root.retrieve() - .withPreview(SYMMETRA) - .to(getApiTailUrl("labels/"+name), GHLabel.class) - .wrapUp(this); + return root.retrieve().withPreview(SYMMETRA).to(getApiTailUrl("labels/" + name), GHLabel.class).wrapUp(this); } public GHLabel createLabel(String name, String color) throws IOException { @@ -1205,31 +1167,26 @@ public GHLabel createLabel(String name, String color) throws IOException { /** * Description is still in preview. + * * @param name * @param color * @param description * @return * @throws IOException */ - @Preview @Deprecated + @Preview + @Deprecated public GHLabel createLabel(String name, String color, String description) throws IOException { - return root.retrieve().method("POST") - .withPreview(SYMMETRA) - .with("name",name) - .with("color", color) - .with("description", description) - .to(getApiTailUrl("labels"), GHLabel.class).wrapUp(this); + return root.retrieve().method("POST").withPreview(SYMMETRA).with("name", name).with("color", color) + .with("description", description).to(getApiTailUrl("labels"), GHLabel.class).wrapUp(this); } /** * Lists all the invitations. */ public PagedIterable listInvitations() { - return root.retrieve() - .asPagedIterable( - String.format("/repos/%s/%s/invitations", getOwnerName(), name), - GHInvitation[].class, - item -> item.wrapUp(root) ); + return root.retrieve().asPagedIterable(String.format("/repos/%s/%s/invitations", getOwnerName(), name), + GHInvitation[].class, item -> item.wrapUp(root)); } /** @@ -1242,76 +1199,66 @@ public PagedIterable listSubscribers() { } /** - * Lists all the users who have starred this repo based on the old version of the API. For - * additional information, like date when the repository was starred, see {@link #listStargazers2()} + * Lists all the users who have starred this repo based on the old version of the API. For additional information, + * like date when the repository was starred, see {@link #listStargazers2()} */ public PagedIterable listStargazers() { return listUsers("stargazers"); } /** - * Lists all the users who have starred this repo based on new version of the API, having extended - * information like the time when the repository was starred. For compatibility with the old API - * see {@link #listStargazers()} + * Lists all the users who have starred this repo based on new version of the API, having extended information like + * the time when the repository was starred. For compatibility with the old API see {@link #listStargazers()} */ public PagedIterable listStargazers2() { - return root.retrieve() - .withPreview("application/vnd.github.v3.star+json") - .asPagedIterable( - getApiTailUrl("stargazers"), - GHStargazer[].class, - item -> item.wrapUp(GHRepository.this) ); + return root.retrieve().withPreview("application/vnd.github.v3.star+json").asPagedIterable( + getApiTailUrl("stargazers"), GHStargazer[].class, item -> item.wrapUp(GHRepository.this)); } private PagedIterable listUsers(final String suffix) { - return root.retrieve() - .asPagedIterable( - getApiTailUrl(suffix), - GHUser[].class, - item -> item.wrapUp(root) ); + return root.retrieve().asPagedIterable(getApiTailUrl(suffix), GHUser[].class, item -> item.wrapUp(root)); } /** * - * See https://api.github.com/hooks for possible names and their configuration scheme. - * TODO: produce type-safe binding + * See https://api.github.com/hooks for possible names and their configuration scheme. TODO: produce type-safe + * binding * * @param name - * Type of the hook to be created. See https://api.github.com/hooks for possible names. + * Type of the hook to be created. See https://api.github.com/hooks for possible names. * @param config - * The configuration hash. + * The configuration hash. * @param events - * Can be null. Types of events to hook into. + * Can be null. Types of events to hook into. */ - public GHHook createHook(String name, Map config, Collection events, boolean active) throws IOException { + public GHHook createHook(String name, Map config, Collection events, boolean active) + throws IOException { return GHHooks.repoContext(this, owner).createHook(name, config, events, active); } public GHHook createWebHook(URL url, Collection events) throws IOException { - return createHook("web",Collections.singletonMap("url",url.toExternalForm()),events,true); + return createHook("web", Collections.singletonMap("url", url.toExternalForm()), events, true); } public GHHook createWebHook(URL url) throws IOException { - return createWebHook(url,null); + return createWebHook(url, null); } -// this is no different from getPullRequests(OPEN) -// /** -// * Retrieves all the pull requests. -// */ -// public List getPullRequests() throws IOException { -// return root.retrieveWithAuth("/pulls/"+owner+'/'+name,JsonPullRequests.class).wrap(root); -// } + // this is no different from getPullRequests(OPEN) + // /** + // * Retrieves all the pull requests. + // */ + // public List getPullRequests() throws IOException { + // return root.retrieveWithAuth("/pulls/"+owner+'/'+name,JsonPullRequests.class).wrap(root); + // } /** - * Returns a set that represents the post-commit hook URLs. - * The returned set is live, and changes made to them are reflected to GitHub. + * Returns a set that represents the post-commit hook URLs. The returned set is live, and changes made to them are + * reflected to GitHub. * - * @deprecated - * Use {@link #getHooks()} and {@link #createHook(String, Map, Collection, boolean)} + * @deprecated Use {@link #getHooks()} and {@link #createHook(String, Map, Collection, boolean)} */ - @SuppressFBWarnings(value = "DMI_COLLECTION_OF_URLS", - justification = "It causes a performance degradation, but we have already exposed it to the API") + @SuppressFBWarnings(value = "DMI_COLLECTION_OF_URLS", justification = "It causes a performance degradation, but we have already exposed it to the API") public Set getPostCommitHooks() { return postCommitHooks; } @@ -1319,8 +1266,7 @@ public Set getPostCommitHooks() { /** * Live set view of the post-commit hook. */ - @SuppressFBWarnings(value = "DMI_COLLECTION_OF_URLS", - justification = "It causes a performance degradation, but we have already exposed it to the API") + @SuppressFBWarnings(value = "DMI_COLLECTION_OF_URLS", justification = "It causes a performance degradation, but we have already exposed it to the API") @SkipFromToString private final Set postCommitHooks = new AbstractSet() { private List getPostCommitHooks() { @@ -1333,7 +1279,7 @@ private List getPostCommitHooks() { } return r; } catch (IOException e) { - throw new GHException("Failed to retrieve post-commit hooks",e); + throw new GHException("Failed to retrieve post-commit hooks", e); } } @@ -1353,14 +1299,14 @@ public boolean add(URL url) { createWebHook(url); return true; } catch (IOException e) { - throw new GHException("Failed to update post-commit hooks",e); + throw new GHException("Failed to update post-commit hooks", e); } } @Override public boolean remove(Object url) { try { - String _url = ((URL)url).toExternalForm(); + String _url = ((URL) url).toExternalForm(); for (GHHook h : getHooks()) { if (h.getName().equals("web") && h.getConfig().get("url").equals(_url)) { h.delete(); @@ -1369,12 +1315,12 @@ public boolean remove(Object url) { } return false; } catch (IOException e) { - throw new GHException("Failed to update post-commit hooks",e); + throw new GHException("Failed to update post-commit hooks", e); } } }; - /*package*/ GHRepository wrap(GitHub root) { + GHRepository wrap(GitHub root) { this.root = root; if (root.isOffline()) { owner.wrapUp(root); @@ -1385,19 +1331,21 @@ public boolean remove(Object url) { /** * Gets branches by {@linkplain GHBranch#getName() their names}. */ - public Map getBranches() throws IOException { - Map r = new TreeMap(); + public Map getBranches() throws IOException { + Map r = new TreeMap(); for (GHBranch p : root.retrieve().to(getApiTailUrl("branches"), GHBranch[].class)) { p.wrap(this); - r.put(p.getName(),p); + r.put(p.getName(), p); } return r; } /** - * Replace special characters (e.g. #) with standard values (e.g. %23) so - * GitHub understands what is being requested. - * @param value string to be encoded. + * Replace special characters (e.g. #) with standard values (e.g. %23) so GitHub understands what is being + * requested. + * + * @param value + * string to be encoded. * @return The encoded string. */ private String UrlEncode(String value) { @@ -1412,15 +1360,14 @@ private String UrlEncode(String value) { } public GHBranch getBranch(String name) throws IOException { - return root.retrieve().to(getApiTailUrl("branches/"+UrlEncode(name)),GHBranch.class).wrap(this); + return root.retrieve().to(getApiTailUrl("branches/" + UrlEncode(name)), GHBranch.class).wrap(this); } /** - * @deprecated - * Use {@link #listMilestones(GHIssueState)} + * @deprecated Use {@link #listMilestones(GHIssueState)} */ public Map getMilestones() throws IOException { - Map milestones = new TreeMap(); + Map milestones = new TreeMap(); for (GHMilestone m : listMilestones(GHIssueState.OPEN)) { milestones.put(m.getNumber(), m); } @@ -1431,11 +1378,8 @@ public Map getMilestones() throws IOException { * Lists up all the milestones in this repository. */ public PagedIterable listMilestones(final GHIssueState state) { - return root.retrieve().with("state",state) - .asPagedIterable( - getApiTailUrl("milestones"), - GHMilestone[].class, - item -> item.wrap(GHRepository.this) ); + return root.retrieve().with("state", state).asPagedIterable(getApiTailUrl("milestones"), GHMilestone[].class, + item -> item.wrap(GHRepository.this)); } public GHMilestone getMilestone(int number) throws IOException { @@ -1457,7 +1401,7 @@ public GHContent getFileContent(String path, String ref) throws IOException { Requester requester = root.retrieve(); String target = getApiTailUrl("contents/" + path); - return requester.with("ref",ref).to(target, GHContent.class).wrap(this); + return requester.with("ref", ref).to(target, GHContent.class).wrap(this); } public List getDirectoryContent(String path) throws IOException { @@ -1471,7 +1415,7 @@ public List getDirectoryContent(String path, String ref) throws IOExc } String target = getApiTailUrl("contents/" + path); - GHContent[] files = requester.with("ref",ref).to(target, GHContent[].class); + GHContent[] files = requester.with("ref", ref).to(target, GHContent[].class); GHContent.wrap(files, this); @@ -1505,7 +1449,8 @@ public GHContentUpdateResponse createContent(String content, String commitMessag * Use {@link #createContent()}. */ @Deprecated - public GHContentUpdateResponse createContent(String content, String commitMessage, String path, String branch) throws IOException { + public GHContentUpdateResponse createContent(String content, String commitMessage, String path, String branch) + throws IOException { return createContent().content(content).message(commitMessage).path(path).branch(branch).commit(); } @@ -1513,7 +1458,8 @@ public GHContentUpdateResponse createContent(String content, String commitMessag * Use {@link #createContent()}. */ @Deprecated - public GHContentUpdateResponse createContent(byte[] contentBytes, String commitMessage, String path) throws IOException { + public GHContentUpdateResponse createContent(byte[] contentBytes, String commitMessage, String path) + throws IOException { return createContent().content(contentBytes).message(commitMessage).path(path).commit(); } @@ -1521,56 +1467,56 @@ public GHContentUpdateResponse createContent(byte[] contentBytes, String commitM * Use {@link #createContent()}. */ @Deprecated - public GHContentUpdateResponse createContent(byte[] contentBytes, String commitMessage, String path, String branch) throws IOException { + public GHContentUpdateResponse createContent(byte[] contentBytes, String commitMessage, String path, String branch) + throws IOException { return createContent().content(contentBytes).message(commitMessage).path(path).branch(branch).commit(); } public GHMilestone createMilestone(String title, String description) throws IOException { - return new Requester(root) - .with("title", title).with("description", description).method("POST").to(getApiTailUrl("milestones"), GHMilestone.class).wrap(this); + return new Requester(root).with("title", title).with("description", description).method("POST") + .to(getApiTailUrl("milestones"), GHMilestone.class).wrap(this); } - public GHDeployKey addDeployKey(String title,String key) throws IOException { - return new Requester(root) - .with("title", title).with("key", key).method("POST").to(getApiTailUrl("keys"), GHDeployKey.class).wrap(this); + public GHDeployKey addDeployKey(String title, String key) throws IOException { + return new Requester(root).with("title", title).with("key", key).method("POST") + .to(getApiTailUrl("keys"), GHDeployKey.class).wrap(this); } - public List getDeployKeys() throws IOException{ - List list = new ArrayList(Arrays.asList( - root.retrieve().to(getApiTailUrl("keys"), GHDeployKey[].class))); - for (GHDeployKey h : list) - h.wrap(this); - return list; + public List getDeployKeys() throws IOException { + List list = new ArrayList( + Arrays.asList(root.retrieve().to(getApiTailUrl("keys"), GHDeployKey[].class))); + for (GHDeployKey h : list) + h.wrap(this); + return list; } /** * Forked repositories have a 'source' attribute that specifies the ultimate source of the forking chain. * - * @return - * {@link GHRepository} that points to the root repository where this repository is forked - * (indirectly or directly) from. Otherwise null. + * @return {@link GHRepository} that points to the root repository where this repository is forked (indirectly or + * directly) from. Otherwise null. * @see #getParent() */ public GHRepository getSource() throws IOException { - if (source == null) return null; + if (source == null) + return null; if (source.root == null) source = root.getRepository(source.getFullName()); return source; } /** - * Forked repositories have a 'parent' attribute that specifies the repository this repository - * is directly forked from. If we keep traversing {@link #getParent()} until it returns null, that - * is {@link #getSource()}. + * Forked repositories have a 'parent' attribute that specifies the repository this repository is directly forked + * from. If we keep traversing {@link #getParent()} until it returns null, that is {@link #getSource()}. * - * @return - * {@link GHRepository} that points to the repository where this repository is forked - * directly from. Otherwise null. + * @return {@link GHRepository} that points to the repository where this repository is forked directly from. + * Otherwise null. * @see #getSource() */ public GHRepository getParent() throws IOException { - if (parent == null) return null; + if (parent == null) + return null; if (parent.root == null) parent = root.getRepository(parent.getFullName()); return parent; @@ -1580,10 +1526,8 @@ public GHRepository getParent() throws IOException { * Subscribes to this repository to get notifications. */ public GHSubscription subscribe(boolean subscribed, boolean ignored) throws IOException { - return new Requester(root) - .with("subscribed", subscribed) - .with("ignored", ignored) - .method("PUT").to(getApiTailUrl("subscription"), GHSubscription.class).wrapUp(this); + return new Requester(root).with("subscribed", subscribed).with("ignored", ignored).method("PUT") + .to(getApiTailUrl("subscription"), GHSubscription.class).wrapUp(this); } /** @@ -1600,11 +1544,8 @@ public GHSubscription getSubscription() throws IOException { } public PagedIterable listContributors() throws IOException { - return root.retrieve() - .asPagedIterable( - getApiTailUrl("contributors"), - Contributor[].class, - item -> item.wrapUp(root) ); + return root.retrieve().asPagedIterable(getApiTailUrl("contributors"), Contributor[].class, + item -> item.wrapUp(root)); } public static class Contributor extends GHUser { @@ -1640,24 +1581,19 @@ public GHRepositoryStatistics getStatistics() { * Create a project for this repository. */ public GHProject createProject(String name, String body) throws IOException { - return root.retrieve().method("POST") - .withPreview(INERTIA) - .with("name", name) - .with("body", body) + return root.retrieve().method("POST").withPreview(INERTIA).with("name", name).with("body", body) .to(getApiTailUrl("projects"), GHProject.class).wrap(this); } /** * Returns the projects for this repository. - * @param status The status filter (all, open or closed). + * + * @param status + * The status filter (all, open or closed). */ public PagedIterable listProjects(final GHProject.ProjectStateFilter status) throws IOException { - return root.retrieve().withPreview(INERTIA) - .with("state", status) - .asPagedIterable( - getApiTailUrl("projects"), - GHProject[].class, - item -> item.wrap(GHRepository.this) ); + return root.retrieve().withPreview(INERTIA).with("state", status).asPagedIterable(getApiTailUrl("projects"), + GHProject[].class, item -> item.wrap(GHRepository.this)); } /** @@ -1670,76 +1606,71 @@ public PagedIterable listProjects() throws IOException { /** * Render a Markdown document. * - * In {@linkplain MarkdownMode#GFM GFM mode}, issue numbers and user mentions - * are linked accordingly. + * In {@linkplain MarkdownMode#GFM GFM mode}, issue numbers and user mentions are linked accordingly. * * @see GitHub#renderMarkdown(String) */ public Reader renderMarkdown(String text, MarkdownMode mode) throws IOException { return new InputStreamReader( - new Requester(root) - .with("text", text) - .with("mode",mode==null?null:mode.toString()) - .with("context", getFullName()) - .asStream("/markdown"), - "UTF-8"); + new Requester(root).with("text", text).with("mode", mode == null ? null : mode.toString()) + .with("context", getFullName()).asStream("/markdown"), + "UTF-8"); } /** * List all the notifications in a repository for the current user. */ public GHNotificationStream listNotifications() { - return new GHNotificationStream(root,getApiTailUrl("/notifications")); + return new GHNotificationStream(root, getApiTailUrl("/notifications")); } /** - * https://developer.github.com/v3/repos/traffic/#views + * https://developer.github.com/v3/repos/traffic/#views */ - public GHRepositoryViewTraffic getViewTraffic() throws IOException{ + public GHRepositoryViewTraffic getViewTraffic() throws IOException { return root.retrieve().to(getApiTailUrl("/traffic/views"), GHRepositoryViewTraffic.class); } /** - * https://developer.github.com/v3/repos/traffic/#clones + * https://developer.github.com/v3/repos/traffic/#clones */ - public GHRepositoryCloneTraffic getCloneTraffic() throws IOException{ + public GHRepositoryCloneTraffic getCloneTraffic() throws IOException { return root.retrieve().to(getApiTailUrl("/traffic/clones"), GHRepositoryCloneTraffic.class); } @Override public int hashCode() { - return ("Repository:"+getOwnerName()+":"+name).hashCode(); + return ("Repository:" + getOwnerName() + ":" + name).hashCode(); } @Override public boolean equals(Object obj) { if (obj instanceof GHRepository) { GHRepository that = (GHRepository) obj; - return this.getOwnerName().equals(that.getOwnerName()) - && this.name.equals(that.name); + return this.getOwnerName().equals(that.getOwnerName()) && this.name.equals(that.name); } return false; } String getApiTailUrl(String tail) { - if (tail.length()>0 && !tail.startsWith("/")) tail='/'+tail; - return "/repos/" + getOwnerName() + "/" + name +tail; + if (tail.length() > 0 && !tail.startsWith("/")) + tail = '/' + tail; + return "/repos/" + getOwnerName() + "/" + name + tail; } /** - * Get all issue events for this repository. - * See https://developer.github.com/v3/issues/events/#list-events-for-a-repository + * Get all issue events for this repository. See + * https://developer.github.com/v3/issues/events/#list-events-for-a-repository */ public PagedIterable listIssueEvents() throws IOException { - return root.retrieve().asPagedIterable( - getApiTailUrl("issues/events"), - GHIssueEvent[].class, - item -> item.wrapUp(root) ); + return root.retrieve().asPagedIterable(getApiTailUrl("issues/events"), GHIssueEvent[].class, + item -> item.wrapUp(root)); } /** - * Get a single issue event. - * See https://developer.github.com/v3/issues/events/#get-a-single-event + * Get a single issue event. See https://developer.github.com/v3/issues/events/#get-a-single-event */ public GHIssueEvent getIssueEvent(long id) throws IOException { return root.retrieve().to(getApiTailUrl("issues/events/" + id), GHIssueEvent.class).wrapUp(root); @@ -1751,8 +1682,8 @@ private static class Topics { } /** - * Return the topics for this repository. - * See https://developer.github.com/v3/repos/#list-all-topics-for-a-repository + * Return the topics for this repository. See + * https://developer.github.com/v3/repos/#list-all-topics-for-a-repository */ public List listTopics() throws IOException { Topics topics = root.retrieve().withPreview(MERCY).to(getApiTailUrl("topics"), Topics.class); @@ -1760,8 +1691,8 @@ public List listTopics() throws IOException { } /** - * Set the topics for this repository. - * See https://developer.github.com/v3/repos/#replace-all-topics-for-a-repository + * Set the topics for this repository. See + * https://developer.github.com/v3/repos/#replace-all-topics-for-a-repository */ public void setTopics(List topics) throws IOException { Requester requester = new Requester(root); diff --git a/src/main/java/org/kohsuke/github/GHRepositoryCloneTraffic.java b/src/main/java/org/kohsuke/github/GHRepositoryCloneTraffic.java index c75198e4a8..f7f4f1f7f8 100644 --- a/src/main/java/org/kohsuke/github/GHRepositoryCloneTraffic.java +++ b/src/main/java/org/kohsuke/github/GHRepositoryCloneTraffic.java @@ -10,10 +10,10 @@ public class GHRepositoryCloneTraffic extends GHRepositoryTraffic { private List clones; - /*package*/ GHRepositoryCloneTraffic() { + GHRepositoryCloneTraffic() { } - /*package*/ GHRepositoryCloneTraffic(Integer count, Integer uniques, List clones) { + GHRepositoryCloneTraffic(Integer count, Integer uniques, List clones) { super(count, uniques); this.clones = clones; } @@ -27,10 +27,10 @@ public List getDailyInfo() { } public static class DailyInfo extends GHRepositoryTraffic.DailyInfo { - /*package*/ DailyInfo() { + DailyInfo() { } - /*package*/ DailyInfo(String timestamp, int count, int uniques) { + DailyInfo(String timestamp, int count, int uniques) { super(timestamp, count, uniques); } } diff --git a/src/main/java/org/kohsuke/github/GHRepositorySearchBuilder.java b/src/main/java/org/kohsuke/github/GHRepositorySearchBuilder.java index 0ecd77e600..c60a610fdf 100644 --- a/src/main/java/org/kohsuke/github/GHRepositorySearchBuilder.java +++ b/src/main/java/org/kohsuke/github/GHRepositorySearchBuilder.java @@ -7,8 +7,8 @@ * @see GitHub#searchRepositories() */ public class GHRepositorySearchBuilder extends GHSearchBuilder { - /*package*/ GHRepositorySearchBuilder(GitHub root) { - super(root,RepositorySearchResult.class); + GHRepositorySearchBuilder(GitHub root) { + super(root, RepositorySearchResult.class); } /** @@ -20,62 +20,64 @@ public GHRepositorySearchBuilder q(String term) { } public GHRepositorySearchBuilder in(String v) { - return q("in:"+v); + return q("in:" + v); } public GHRepositorySearchBuilder size(String v) { - return q("size:"+v); + return q("size:" + v); } public GHRepositorySearchBuilder forks(String v) { - return q("forks:"+v); + return q("forks:" + v); } public GHRepositorySearchBuilder created(String v) { - return q("created:"+v); + return q("created:" + v); } public GHRepositorySearchBuilder pushed(String v) { - return q("pushed:"+v); + return q("pushed:" + v); } public GHRepositorySearchBuilder user(String v) { - return q("user:"+v); + return q("user:" + v); } public GHRepositorySearchBuilder repo(String v) { - return q("repo:"+v); + return q("repo:" + v); } public GHRepositorySearchBuilder language(String v) { - return q("language:"+v); + return q("language:" + v); } public GHRepositorySearchBuilder stars(String v) { - return q("stars:"+v); + return q("stars:" + v); } public GHRepositorySearchBuilder topic(String v) { - return q("topic:"+v); + return q("topic:" + v); } public GHRepositorySearchBuilder order(GHDirection v) { - req.with("order",v); + req.with("order", v); return this; } public GHRepositorySearchBuilder sort(Sort sort) { - req.with("sort",sort); + req.with("sort", sort); return this; } - public enum Sort { STARS, FORKS, UPDATED } + public enum Sort { + STARS, FORKS, UPDATED + } private static class RepositorySearchResult extends SearchResult { private GHRepository[] items; @Override - /*package*/ GHRepository[] getItems(GitHub root) { + GHRepository[] getItems(GitHub root) { for (GHRepository item : items) item.wrap(root); return items; diff --git a/src/main/java/org/kohsuke/github/GHRepositorySelection.java b/src/main/java/org/kohsuke/github/GHRepositorySelection.java index afba38aaa2..95ca72b850 100644 --- a/src/main/java/org/kohsuke/github/GHRepositorySelection.java +++ b/src/main/java/org/kohsuke/github/GHRepositorySelection.java @@ -10,8 +10,7 @@ * @see GHAppInstallation */ public enum GHRepositorySelection { - SELECTED, - ALL; + SELECTED, ALL; /** * Returns GitHub's internal representation of this event. diff --git a/src/main/java/org/kohsuke/github/GHRepositoryStatistics.java b/src/main/java/org/kohsuke/github/GHRepositoryStatistics.java index 3d8187da20..2371dacf8f 100644 --- a/src/main/java/org/kohsuke/github/GHRepositoryStatistics.java +++ b/src/main/java/org/kohsuke/github/GHRepositoryStatistics.java @@ -38,18 +38,18 @@ public PagedIterable getContributorStats() throws IOException, } /** - * @param waitTillReady Whether to sleep the thread if necessary until the - * statistics are ready. This is true by default. + * @param waitTillReady + * Whether to sleep the thread if necessary until the statistics are ready. This is true by default. */ @Preview @Deprecated @SuppressWarnings("SleepWhileInLoop") - @SuppressFBWarnings(value = {"RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE"}, justification = "JSON API") - public PagedIterable getContributorStats(boolean waitTillReady) throws IOException, InterruptedException { - PagedIterable stats = - getContributorStatsImpl(); + @SuppressFBWarnings(value = { "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE" }, justification = "JSON API") + public PagedIterable getContributorStats(boolean waitTillReady) + throws IOException, InterruptedException { + PagedIterable stats = getContributorStatsImpl(); - if (stats == null && waitTillReady) { + if (stats == null && waitTillReady) { for (int i = 0; i < MAX_WAIT_ITERATIONS; i += 1) { // Wait a few seconds and try again. Thread.sleep(WAIT_SLEEP_INTERVAL); @@ -64,21 +64,17 @@ public PagedIterable getContributorStats(boolean waitTillReady } /** - * This gets the actual statistics from the server. Returns null if they - * are still being cached. + * This gets the actual statistics from the server. Returns null if they are still being cached. */ private PagedIterable getContributorStatsImpl() throws IOException { - return root.retrieve() - .asPagedIterable( - getApiTailUrl("contributors"), - ContributorStats[].class, - item -> item.wrapUp(root) ); + return root.retrieve().asPagedIterable(getApiTailUrl("contributors"), ContributorStats[].class, + item -> item.wrapUp(root)); } - @SuppressFBWarnings(value = {"UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", - "NP_UNWRITTEN_FIELD", "URF_UNREAD_FIELD"}, justification = "JSON API") + @SuppressFBWarnings(value = { "UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", + "NP_UNWRITTEN_FIELD", "URF_UNREAD_FIELD" }, justification = "JSON API") public static class ContributorStats extends GHObject { - /*package almost final*/ private GitHub root; + /* package almost final */ private GitHub root; private GHUser author; private int total; private List weeks; @@ -109,9 +105,9 @@ public int getTotal() { /** * Convenience method to look up week with particular timestamp. * - * @param timestamp The timestamp to look for. - * @return The week starting with the given timestamp. Throws an - * exception if it is not found. + * @param timestamp + * The timestamp to look for. + * @return The week starting with the given timestamp. Throws an exception if it is not found. * @throws NoSuchElementException */ public Week getWeek(long timestamp) throws NoSuchElementException { @@ -135,13 +131,12 @@ public List getWeeks() { @Override public String toString() { - return author.getLogin() + " made " + String.valueOf(total) - + " contributions over " + String.valueOf(weeks.size()) - + " weeks"; + return author.getLogin() + " made " + String.valueOf(total) + " contributions over " + + String.valueOf(weeks.size()) + " weeks"; } - @SuppressFBWarnings(value = {"UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", - "NP_UNWRITTEN_FIELD", "URF_UNREAD_FIELD"}, justification = "JSON API") + @SuppressFBWarnings(value = { "UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", + "NP_UNWRITTEN_FIELD", "URF_UNREAD_FIELD" }, justification = "JSON API") public static class Week { private long w; @@ -183,7 +178,7 @@ public String toString() { } } - /*package*/ ContributorStats wrapUp(GitHub root) { + ContributorStats wrapUp(GitHub root) { this.root = root; return this; } @@ -194,24 +189,20 @@ public String toString() { * https://developer.github.com/v3/repos/statistics/#get-the-last-year-of-commit-activity-data */ public PagedIterable getCommitActivity() throws IOException { - return root.retrieve() - .asPagedIterable( - getApiTailUrl("commit_activity"), - CommitActivity[].class, - item -> item.wrapUp(root) ); + return root.retrieve().asPagedIterable(getApiTailUrl("commit_activity"), CommitActivity[].class, + item -> item.wrapUp(root)); } - @SuppressFBWarnings(value = {"UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", - "NP_UNWRITTEN_FIELD"}, justification = "JSON API") + @SuppressFBWarnings(value = { "UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", + "NP_UNWRITTEN_FIELD" }, justification = "JSON API") public static class CommitActivity extends GHObject { - /*package almost final*/ private GitHub root; + /* package almost final */ private GitHub root; private List days; private int total; private long week; /** - * @return The number of commits for each day of the week. 0 = Sunday, 1 - * = Monday, etc. + * @return The number of commits for each day of the week. 0 = Sunday, 1 = Monday, etc. */ public List getDays() { return days; @@ -231,7 +222,7 @@ public long getWeek() { return week; } - /*package*/ CommitActivity wrapUp(GitHub root) { + CommitActivity wrapUp(GitHub root) { this.root = root; return this; } @@ -246,9 +237,9 @@ public URL getHtmlUrl() throws IOException { } } - /** - * Get the number of additions and deletions per week. - * See https://developer.github.com/v3/repos/statistics/#get-the-number-of-additions-and-deletions-per-week + /** + * Get the number of additions and deletions per week. See + * https://developer.github.com/v3/repos/statistics/#get-the-number-of-additions-and-deletions-per-week */ public List getCodeFrequency() throws IOException { // Map to ArrayLists first, since there are no field names in the @@ -257,14 +248,13 @@ public List getCodeFrequency() throws IOException { InputStream stream = root.retrieve().asStream(getApiTailUrl("code_frequency")); ObjectMapper mapper = new ObjectMapper(); - TypeReference > > typeRef = - new TypeReference > >() {}; - ArrayList > list = mapper.readValue(stream, typeRef); + TypeReference>> typeRef = new TypeReference>>() { + }; + ArrayList> list = mapper.readValue(stream, typeRef); // Convert to proper objects. ArrayList returnList = new ArrayList(); - for(ArrayList item: list) - { + for (ArrayList item : list) { CodeFrequency cf = new CodeFrequency(item); returnList.add(cf); } @@ -304,8 +294,7 @@ public long getAdditions() { } /** - * @return The number of deletions for the week. - * NOTE: This will be a NEGATIVE number. + * @return The number of deletions for the week. NOTE: This will be a NEGATIVE number. */ public long getDeletions() { // TODO: Perhaps return Math.abs(deletions), @@ -315,21 +304,21 @@ public long getDeletions() { @Override public String toString() { - return "Week starting " + getWeekTimestamp() + " has " + getAdditions() + - " additions and " + Math.abs(getDeletions()) + " deletions"; + return "Week starting " + getWeekTimestamp() + " has " + getAdditions() + " additions and " + + Math.abs(getDeletions()) + " deletions"; } } /** - * Get the weekly commit count for the repository owner and everyone else. - * See https://developer.github.com/v3/repos/statistics/#get-the-weekly-commit-count-for-the-repository-owner-and-everyone-else + * Get the weekly commit count for the repository owner and everyone else. See + * https://developer.github.com/v3/repos/statistics/#get-the-weekly-commit-count-for-the-repository-owner-and-everyone-else */ public Participation getParticipation() throws IOException { return root.retrieve().to(getApiTailUrl("participation"), Participation.class); } public static class Participation extends GHObject { - /*package almost final*/ private GitHub root; + /* package almost final */ private GitHub root; private List all; private List owner; @@ -343,30 +332,28 @@ public GitHub getRoot() { } /** - * @return The list of commit counts for everyone combined, for the - * last 52 weeks. + * @return The list of commit counts for everyone combined, for the last 52 weeks. */ public List getAllCommits() { return all; } /** - * @return The list of commit counts for the owner, for the - * last 52 weeks. + * @return The list of commit counts for the owner, for the last 52 weeks. */ public List getOwnerCommits() { return owner; } - /*package*/ Participation wrapUp(GitHub root) { - this.root = root; - return this; + Participation wrapUp(GitHub root) { + this.root = root; + return this; } } /** - * Get the number of commits per hour in each day. - * See https://developer.github.com/v3/repos/statistics/#get-the-number-of-commits-per-hour-in-each-day + * Get the number of commits per hour in each day. See + * https://developer.github.com/v3/repos/statistics/#get-the-number-of-commits-per-hour-in-each-day */ public List getPunchCard() throws IOException { // Map to ArrayLists first, since there are no field names in the @@ -374,13 +361,13 @@ public List getPunchCard() throws IOException { InputStream stream = root.retrieve().asStream(getApiTailUrl("punch_card")); ObjectMapper mapper = new ObjectMapper(); - TypeReference > > typeRef = - new TypeReference > >() {}; - ArrayList > list = mapper.readValue(stream, typeRef); + TypeReference>> typeRef = new TypeReference>>() { + }; + ArrayList> list = mapper.readValue(stream, typeRef); // Convert to proper objects. ArrayList returnList = new ArrayList(); - for(ArrayList item: list) { + for (ArrayList item : list) { PunchCardItem pci = new PunchCardItem(item); returnList.add(pci); } @@ -400,8 +387,7 @@ private PunchCardItem(ArrayList item) { } /** - * @return The day of the week. - * 0 = Sunday, 1 = Monday, etc. + * @return The day of the week. 0 = Sunday, 1 = Monday, etc. */ public int getDayOfWeek() { return dayOfWeek; @@ -422,8 +408,7 @@ public long getNumberOfCommits() { } public String toString() { - return "Day " + getDayOfWeek() + " Hour " + getHourOfDay() + ": " + - getNumberOfCommits() + " commits"; + return "Day " + getDayOfWeek() + " Hour " + getHourOfDay() + ": " + getNumberOfCommits() + " commits"; } } diff --git a/src/main/java/org/kohsuke/github/GHRepositoryTraffic.java b/src/main/java/org/kohsuke/github/GHRepositoryTraffic.java index 42d07e848d..8efb74083c 100644 --- a/src/main/java/org/kohsuke/github/GHRepositoryTraffic.java +++ b/src/main/java/org/kohsuke/github/GHRepositoryTraffic.java @@ -7,10 +7,10 @@ public abstract class GHRepositoryTraffic implements TrafficInfo { private int count; private int uniques; - /*package*/ GHRepositoryTraffic() { + GHRepositoryTraffic() { } - /*package*/ GHRepositoryTraffic(int count, int uniques) { + GHRepositoryTraffic(int count, int uniques) { this.count = count; this.uniques = uniques; } @@ -42,10 +42,10 @@ public int getUniques() { return uniques; } - /*package*/ DailyInfo() { + DailyInfo() { } - /*package*/ DailyInfo(String timestamp, Integer count, Integer uniques) { + DailyInfo(String timestamp, Integer count, Integer uniques) { this.timestamp = timestamp; this.count = count; this.uniques = uniques; diff --git a/src/main/java/org/kohsuke/github/GHRepositoryViewTraffic.java b/src/main/java/org/kohsuke/github/GHRepositoryViewTraffic.java index f2f1e5b440..1f897baf49 100644 --- a/src/main/java/org/kohsuke/github/GHRepositoryViewTraffic.java +++ b/src/main/java/org/kohsuke/github/GHRepositoryViewTraffic.java @@ -10,10 +10,10 @@ public class GHRepositoryViewTraffic extends GHRepositoryTraffic { private List views; - /*package*/ GHRepositoryViewTraffic() { + GHRepositoryViewTraffic() { } - /*package*/ GHRepositoryViewTraffic(int count, int uniques, List views) { + GHRepositoryViewTraffic(int count, int uniques, List views) { super(count, uniques); this.views = views; } @@ -27,10 +27,10 @@ public List getDailyInfo() { } public static class DailyInfo extends GHRepositoryTraffic.DailyInfo { - /*package*/ DailyInfo() { + DailyInfo() { } - /*package*/ DailyInfo(String timestamp, int count, int uniques) { + DailyInfo(String timestamp, int count, int uniques) { super(timestamp, count, uniques); } } diff --git a/src/main/java/org/kohsuke/github/GHSearchBuilder.java b/src/main/java/org/kohsuke/github/GHSearchBuilder.java index 44521687f4..17a035b2aa 100644 --- a/src/main/java/org/kohsuke/github/GHSearchBuilder.java +++ b/src/main/java/org/kohsuke/github/GHSearchBuilder.java @@ -18,7 +18,7 @@ public abstract class GHSearchBuilder extends GHQueryBuilder { */ private final Class> receiverType; - /*package*/ GHSearchBuilder(GitHub root, Class> receiverType) { + GHSearchBuilder(GitHub root, Class> receiverType) { super(root); this.receiverType = receiverType; } diff --git a/src/main/java/org/kohsuke/github/GHStargazer.java b/src/main/java/org/kohsuke/github/GHStargazer.java index 2384d01939..d599a74f93 100644 --- a/src/main/java/org/kohsuke/github/GHStargazer.java +++ b/src/main/java/org/kohsuke/github/GHStargazer.java @@ -9,7 +9,7 @@ * * @author noctarius */ -@SuppressFBWarnings(value = {"UWF_UNWRITTEN_FIELD", "NP_UNWRITTEN_FIELD"}, justification = "JSON API") +@SuppressFBWarnings(value = { "UWF_UNWRITTEN_FIELD", "NP_UNWRITTEN_FIELD" }, justification = "JSON API") public class GHStargazer { private GHRepository repository; @@ -26,8 +26,8 @@ public GHRepository getRepository() { } /** - * Gets the date when the repository was starred, however old stars before - * August 2012, will all show the date the API was changed to support starred_at. + * Gets the date when the repository was starred, however old stars before August 2012, will all show the date the + * API was changed to support starred_at. * * @return the date the stargazer was added */ diff --git a/src/main/java/org/kohsuke/github/GHTag.java b/src/main/java/org/kohsuke/github/GHTag.java index 802f51f8f3..2f57031077 100644 --- a/src/main/java/org/kohsuke/github/GHTag.java +++ b/src/main/java/org/kohsuke/github/GHTag.java @@ -7,8 +7,8 @@ * * @see GHRepository#listTags() */ -@SuppressFBWarnings(value = {"UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", - "NP_UNWRITTEN_FIELD"}, justification = "JSON API") +@SuppressFBWarnings(value = { "UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", + "NP_UNWRITTEN_FIELD" }, justification = "JSON API") public class GHTag { private GHRepository owner; private GitHub root; @@ -16,10 +16,10 @@ public class GHTag { private String name; private GHCommit commit; - /*package*/ GHTag wrap(GHRepository owner) { + GHTag wrap(GHRepository owner) { this.owner = owner; this.root = owner.root; - if (commit!=null) + if (commit != null) commit.wrapUp(owner); return this; } diff --git a/src/main/java/org/kohsuke/github/GHTagObject.java b/src/main/java/org/kohsuke/github/GHTagObject.java index 0e3acdeaa7..cafe4ceacf 100644 --- a/src/main/java/org/kohsuke/github/GHTagObject.java +++ b/src/main/java/org/kohsuke/github/GHTagObject.java @@ -7,8 +7,8 @@ * * @see GHRepository#getTagObject(String) */ -@SuppressFBWarnings(value = {"UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", - "NP_UNWRITTEN_FIELD"}, justification = "JSON API") +@SuppressFBWarnings(value = { "UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", + "NP_UNWRITTEN_FIELD" }, justification = "JSON API") public class GHTagObject { private GHRepository owner; private GitHub root; @@ -20,7 +20,7 @@ public class GHTagObject { private GitUser tagger; private GHRef.GHObject object; - /*package*/ GHTagObject wrap(GHRepository owner) { + GHTagObject wrap(GHRepository owner) { this.owner = owner; this.root = owner.root; return this; diff --git a/src/main/java/org/kohsuke/github/GHTargetType.java b/src/main/java/org/kohsuke/github/GHTargetType.java index 42a23d8726..23f7800c46 100644 --- a/src/main/java/org/kohsuke/github/GHTargetType.java +++ b/src/main/java/org/kohsuke/github/GHTargetType.java @@ -12,8 +12,7 @@ * @see GHAppInstallation */ public enum GHTargetType { - ORGANIZATION, - USER; + ORGANIZATION, USER; /** * Returns GitHub's internal representation of this event. diff --git a/src/main/java/org/kohsuke/github/GHTeam.java b/src/main/java/org/kohsuke/github/GHTeam.java index 00f43e194b..49e66a6d57 100644 --- a/src/main/java/org/kohsuke/github/GHTeam.java +++ b/src/main/java/org/kohsuke/github/GHTeam.java @@ -8,15 +8,15 @@ /** * A team in GitHub organization. - * + * * @author Kohsuke Kawaguchi */ public class GHTeam implements Refreshable { - private String name,permission,slug,description; + private String name, permission, slug, description; private int id; private GHOrganization organization; // populated by GET /user/teams where Teams+Orgs are returned together - protected /*final*/ GitHub root; + protected /* final */ GitHub root; /** Member's role in a team */ public enum Role { @@ -25,30 +25,31 @@ public enum Role { */ MEMBER, /** - * Able to add/remove other team members, promote other team members to team maintainer, and edit the team's name and description. + * Able to add/remove other team members, promote other team members to team maintainer, and edit the team's + * name and description. */ MAINTAINER } - /*package*/ GHTeam wrapUp(GHOrganization owner) { + GHTeam wrapUp(GHOrganization owner) { this.organization = owner; this.root = owner.root; return this; } - /*package*/ GHTeam wrapUp(GitHub root) { // auto-wrapUp when organization is known from GET /user/teams - this.organization.wrapUp(root); - return wrapUp(organization); + GHTeam wrapUp(GitHub root) { // auto-wrapUp when organization is known from GET /user/teams + this.organization.wrapUp(root); + return wrapUp(organization); } - /*package*/ static GHTeam[] wrapUp(GHTeam[] teams, GHOrganization owner) { + static GHTeam[] wrapUp(GHTeam[] teams, GHOrganization owner) { for (GHTeam t : teams) { t.wrapUp(owner); } return teams; } - /*package*/ static GHTeam[] wrapUp(GHTeam[] teams, GHPullRequest owner) { + static GHTeam[] wrapUp(GHTeam[] teams, GHPullRequest owner) { for (GHTeam t : teams) { t.root = owner.root; } @@ -72,9 +73,7 @@ public String getDescription() { } public void setDescription(String description) throws IOException { - root.retrieve().method("PATCH") - .with("description", description) - .to(api("")); + root.retrieve().method("PATCH").with("description", description).to(api("")); } public int getId() { @@ -85,11 +84,7 @@ public int getId() { * Retrieves the current members. */ public PagedIterable listMembers() throws IOException { - return root.retrieve() - .asPagedIterable( - api("/members"), - GHUser[].class, - item -> item.wrapUp(root) ); + return root.retrieve().asPagedIterable(api("/members"), GHUser[].class, item -> item.wrapUp(root)); } public Set getMembers() throws IOException { @@ -101,15 +96,15 @@ public Set getMembers() throws IOException { */ public boolean hasMember(GHUser user) { try { - root.retrieve().to("/teams/" + id + "/members/" + user.getLogin()); + root.retrieve().to("/teams/" + id + "/members/" + user.getLogin()); return true; } catch (IOException ignore) { return false; } } - public Map getRepositories() throws IOException { - Map m = new TreeMap(); + public Map getRepositories() throws IOException { + Map m = new TreeMap(); for (GHRepository r : listRepositories()) { m.put(r.getName(), r); } @@ -117,11 +112,7 @@ public Map getRepositories() throws IOException { } public PagedIterable listRepositories() { - return root.retrieve() - .asPagedIterable( - api("/repos"), - GHRepository[].class, - item -> item.wrap(root) ); + return root.retrieve().asPagedIterable(api("/repos"), GHRepository[].class, item -> item.wrap(root)); } /** @@ -140,15 +131,15 @@ public void add(GHUser u) throws IOException { * * The user will be invited to the organization if required. * - * @param user github user - * @param role role for the new member + * @param user + * github user + * @param role + * role for the new member * * @throws IOException */ public void add(GHUser user, Role role) throws IOException { - root.retrieve().method("PUT") - .with("role", role) - .to(api("/memberships/" + user.getLogin()), null); + root.retrieve().method("PUT").with("role", role).to(api("/memberships/" + user.getLogin()), null); } /** @@ -159,19 +150,18 @@ public void remove(GHUser u) throws IOException { } public void add(GHRepository r) throws IOException { - add(r,null); + add(r, null); } public void add(GHRepository r, GHOrganization.Permission permission) throws IOException { - root.retrieve().method("PUT") - .with("permission", permission) + root.retrieve().method("PUT").with("permission", permission) .to(api("/repos/" + r.getOwnerName() + '/' + r.getName()), null); } public void remove(GHRepository r) throws IOException { root.retrieve().method("DELETE").to(api("/repos/" + r.getOwnerName() + '/' + r.getName()), null); } - + /** * Deletes this team. */ diff --git a/src/main/java/org/kohsuke/github/GHThread.java b/src/main/java/org/kohsuke/github/GHThread.java index faf4c87b7b..1375d6680e 100644 --- a/src/main/java/org/kohsuke/github/GHThread.java +++ b/src/main/java/org/kohsuke/github/GHThread.java @@ -14,8 +14,8 @@ * @see GHNotificationStream * @author Kohsuke Kawaguchi */ -@SuppressFBWarnings(value = {"UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", - "NP_UNWRITTEN_FIELD"}, justification = "JSON API") +@SuppressFBWarnings(value = { "UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", + "NP_UNWRITTEN_FIELD" }, justification = "JSON API") public class GHThread extends GHObject { private GitHub root; private GHRepository repository; @@ -23,7 +23,7 @@ public class GHThread extends GHObject { private String reason; private boolean unread; private String last_read_at; - private String url,subscription_url; + private String url, subscription_url; static class Subject { String title; @@ -71,21 +71,20 @@ public String getTitle() { public String getType() { return subject.type; } - + public String getLastCommentUrl() { return subject.latest_comment_url; } /** * If this thread is about an issue, return that issue. - * + * * @return null if this thread is not about an issue. */ public GHIssue getBoundIssue() throws IOException { if (!"Issue".equals(subject.type) && "PullRequest".equals(subject.type)) return null; - return repository.getIssue( - Integer.parseInt(subject.url.substring(subject.url.lastIndexOf('/') + 1))); + return repository.getIssue(Integer.parseInt(subject.url.substring(subject.url.lastIndexOf('/') + 1))); } /** @@ -96,8 +95,7 @@ public GHIssue getBoundIssue() throws IOException { public GHPullRequest getBoundPullRequest() throws IOException { if (!"PullRequest".equals(subject.type)) return null; - return repository.getPullRequest( - Integer.parseInt(subject.url.substring(subject.url.lastIndexOf('/') + 1))); + return repository.getPullRequest(Integer.parseInt(subject.url.substring(subject.url.lastIndexOf('/') + 1))); } /** @@ -111,9 +109,9 @@ public GHCommit getBoundCommit() throws IOException { return repository.getCommit(subject.url.substring(subject.url.lastIndexOf('/') + 1)); } - /*package*/ GHThread wrap(GitHub root) { + GHThread wrap(GitHub root) { this.root = root; - if (this.repository!=null) + if (this.repository != null) this.repository.wrap(root); return this; } @@ -129,10 +127,8 @@ public void markAsRead() throws IOException { * Subscribes to this conversation to get notifications. */ public GHSubscription subscribe(boolean subscribed, boolean ignored) throws IOException { - return new Requester(root) - .with("subscribed", subscribed) - .with("ignored", ignored) - .method("PUT").to(subscription_url, GHSubscription.class).wrapUp(root); + return new Requester(root).with("subscribed", subscribed).with("ignored", ignored).method("PUT") + .to(subscription_url, GHSubscription.class).wrapUp(root); } /** diff --git a/src/main/java/org/kohsuke/github/GHTree.java b/src/main/java/org/kohsuke/github/GHTree.java index d52e02a793..7981d55f73 100644 --- a/src/main/java/org/kohsuke/github/GHTree.java +++ b/src/main/java/org/kohsuke/github/GHTree.java @@ -6,8 +6,7 @@ import java.util.List; /** - * Provides information for Git Trees - * https://developer.github.com/v3/git/trees/ + * Provides information for Git Trees https://developer.github.com/v3/git/trees/ * * @author Daniel Teixeira - https://github.com/ddtxra * @see GHCommit#getTree() @@ -49,7 +48,8 @@ public GHTreeEntry getEntry(String path) { } /** - * Returns true if the number of items in the tree array exceeded the GitHub maximum limit. + * Returns true if the number of items in the tree array exceeded the GitHub maximum limit. + * * @return true true if the number of items in the tree array exceeded the GitHub maximum limit otherwise false. */ public boolean isTruncated() { @@ -57,14 +57,14 @@ public boolean isTruncated() { } /** - * The API URL of this tag, such as - * "url": "https://api.github.com/repos/octocat/Hello-World/trees/fc6274d15fa3ae2ab983129fb037999f264ba9a7", + * The API URL of this tag, such as "url": + * "https://api.github.com/repos/octocat/Hello-World/trees/fc6274d15fa3ae2ab983129fb037999f264ba9a7", */ public URL getUrl() { return GitHub.parseURL(url); } - /* package */GHTree wrap(GHRepository repo) { + GHTree wrap(GHRepository repo) { this.repo = repo; for (GHTreeEntry e : tree) { e.tree = this; diff --git a/src/main/java/org/kohsuke/github/GHTreeBuilder.java b/src/main/java/org/kohsuke/github/GHTreeBuilder.java index 122c5775b5..e308ed134e 100644 --- a/src/main/java/org/kohsuke/github/GHTreeBuilder.java +++ b/src/main/java/org/kohsuke/github/GHTreeBuilder.java @@ -7,8 +7,7 @@ import java.util.List; /** - * Builder pattern for creating a new tree. - * Based on https://developer.github.com/v3/git/trees/#create-a-tree + * Builder pattern for creating a new tree. Based on https://developer.github.com/v3/git/trees/#create-a-tree */ public class GHTreeBuilder { private final GHRepository repo; @@ -37,7 +36,8 @@ private TreeEntry(String path, String mode, String type) { } /** - * @param baseTree the SHA of tree you want to update with new data + * @param baseTree + * the SHA of tree you want to update with new data */ public GHTreeBuilder baseTree(String baseTree) { req.with("base_tree", baseTree); @@ -45,8 +45,7 @@ public GHTreeBuilder baseTree(String baseTree) { } /** - * Adds a new entry to the tree. - * Exactly one of the parameters {@code sha} and {@code content} must be non-null. + * Adds a new entry to the tree. Exactly one of the parameters {@code sha} and {@code content} must be non-null. */ public GHTreeBuilder entry(String path, String mode, String type, String sha, String content) { TreeEntry entry = new TreeEntry(path, mode, type); @@ -57,7 +56,8 @@ public GHTreeBuilder entry(String path, String mode, String type, String sha, St } /** - * Specialized version of {@link #entry(String, String, String, String, String)} for adding an existing blob referred by its SHA. + * Specialized version of {@link #entry(String, String, String, String, String)} for adding an existing blob + * referred by its SHA. */ public GHTreeBuilder shaEntry(String path, String sha, boolean executable) { TreeEntry entry = new TreeEntry(path, executable ? "100755" : "100644", "blob"); @@ -67,7 +67,8 @@ public GHTreeBuilder shaEntry(String path, String sha, boolean executable) { } /** - * Specialized version of {@link #entry(String, String, String, String, String)} for adding a text file with the specified {@code content}. + * Specialized version of {@link #entry(String, String, String, String, String)} for adding a text file with the + * specified {@code content}. */ public GHTreeBuilder textEntry(String path, String content, boolean executable) { TreeEntry entry = new TreeEntry(path, executable ? "100755" : "100644", "blob"); diff --git a/src/main/java/org/kohsuke/github/GHTreeEntry.java b/src/main/java/org/kohsuke/github/GHTreeEntry.java index ba6d45e15e..b4d9b576cf 100644 --- a/src/main/java/org/kohsuke/github/GHTreeEntry.java +++ b/src/main/java/org/kohsuke/github/GHTreeEntry.java @@ -5,8 +5,7 @@ import java.net.URL; /** - * Provides information for Git Trees - * https://developer.github.com/v3/git/trees/ + * Provides information for Git Trees https://developer.github.com/v3/git/trees/ * * @author Daniel Teixeira - https://github.com/ddtxra * @see GHTree @@ -18,8 +17,7 @@ public class GHTreeEntry { private long size; /** - * Get the path such as - * "subdir/file.txt" + * Get the path such as "subdir/file.txt" * * @return the path */ @@ -28,8 +26,7 @@ public String getPath() { } /** - * Get mode such as - * 100644 + * Get mode such as 100644 * * @return the mode */ @@ -38,8 +35,8 @@ public String getMode() { } /** - * Gets the size of the file, such as - * 132 + * Gets the size of the file, such as 132 + * * @return The size of the path or 0 if it is a directory */ public long getSize() { @@ -47,8 +44,7 @@ public long getSize() { } /** - * Gets the type such as: - * "blob", "tree", etc. + * Gets the type such as: "blob", "tree", etc. * * @return The type */ @@ -56,7 +52,6 @@ public String getType() { return type; } - /** * SHA1 of this object. */ @@ -65,8 +60,7 @@ public String getSha() { } /** - * API URL to this Git data, such as - * https://api.github.com/repos/jenkinsci + * API URL to this Git data, such as https://api.github.com/repos/jenkinsci * /jenkins/git/commits/b72322675eb0114363a9a86e9ad5a170d1d07ac0 */ public URL getUrl() { @@ -74,8 +68,7 @@ public URL getUrl() { } /** - * If this tree entry represents a file, then return its information. - * Otherwise null. + * If this tree entry represents a file, then return its information. Otherwise null. */ public GHBlob asBlob() throws IOException { if (type.equals("blob")) @@ -85,8 +78,7 @@ public GHBlob asBlob() throws IOException { } /** - * If this tree entry represents a file, then return its content. - * Otherwise null. + * If this tree entry represents a file, then return its content. Otherwise null. */ public InputStream readAsBlob() throws IOException { if (type.equals("blob")) @@ -96,8 +88,7 @@ public InputStream readAsBlob() throws IOException { } /** - * If this tree entry represents a directory, then return it. - * Otherwise null. + * If this tree entry represents a directory, then return it. Otherwise null. */ public GHTree asTree() throws IOException { if (type.equals("tree")) diff --git a/src/main/java/org/kohsuke/github/GHUser.java b/src/main/java/org/kohsuke/github/GHUser.java index d794a8c74f..7e46c096f4 100644 --- a/src/main/java/org/kohsuke/github/GHUser.java +++ b/src/main/java/org/kohsuke/github/GHUser.java @@ -84,11 +84,7 @@ public PagedIterable listFollowers() { } private PagedIterable listUser(final String suffix) { - return root.retrieve() - .asPagedIterable( - getApiTailUrl(suffix), - GHUser[].class, - item -> item.wrapUp(root) ); + return root.retrieve().asPagedIterable(getApiTailUrl(suffix), GHUser[].class, item -> item.wrapUp(root)); } /** @@ -108,11 +104,7 @@ public PagedIterable listStarredRepositories() { } private PagedIterable listRepositories(final String suffix) { - return root.retrieve() - .asPagedIterable( - getApiTailUrl(suffix), - GHRepository[].class, - item -> item.wrap(root) ); + return root.retrieve().asPagedIterable(getApiTailUrl(suffix), GHRepository[].class, item -> item.wrap(root)); } /** @@ -136,7 +128,7 @@ public boolean isPublicMemberOf(GHOrganization org) { return org.hasPublicMember(this); } - /*package*/ static GHUser[] wrap(GHUser[] users, GitHub root) { + static GHUser[] wrap(GHUser[] users, GitHub root) { for (GHUser f : users) f.root = root; return users; @@ -150,7 +142,7 @@ public GHPersonSet getOrganizations() throws IOException { GHPersonSet orgs = new GHPersonSet(); Set names = new HashSet(); for (GHOrganization o : root.retrieve().to("/users/" + login + "/orgs", GHOrganization[].class)) { - if (names.add(o.getLogin())) // I've seen some duplicates in the data + if (names.add(o.getLogin())) // I've seen some duplicates in the data orgs.add(root.getOrganization(o.getLogin())); } return orgs; @@ -160,22 +152,16 @@ public GHPersonSet getOrganizations() throws IOException { * Lists events performed by a user (this includes private events if the caller is authenticated. */ public PagedIterable listEvents() throws IOException { - return root.retrieve() - .asPagedIterable( - String.format("/users/%s/events", login), - GHEventInfo[].class, - item -> item.wrapUp(root) ); + return root.retrieve().asPagedIterable(String.format("/users/%s/events", login), GHEventInfo[].class, + item -> item.wrapUp(root)); } /** * Lists Gists created by this user. */ public PagedIterable listGists() throws IOException { - return root.retrieve() - .asPagedIterable( - String.format("/users/%s/gists", login), - GHGist[].class, - item -> item.wrapUp(GHUser.this) ); + return root.retrieve().asPagedIterable(String.format("/users/%s/gists", login), GHGist[].class, + item -> item.wrapUp(GHUser.this)); } @Override @@ -193,11 +179,12 @@ public boolean equals(Object obj) { } String getApiTailUrl(String tail) { - if (tail.length()>0 && !tail.startsWith("/")) tail='/'+tail; + if (tail.length() > 0 && !tail.startsWith("/")) + tail = '/' + tail; return "/users/" + login + tail; } - /*package*/ GHUser wrapUp(GitHub root) { + GHUser wrapUp(GitHub root) { super.wrapUp(root); return this; } diff --git a/src/main/java/org/kohsuke/github/GHUserSearchBuilder.java b/src/main/java/org/kohsuke/github/GHUserSearchBuilder.java index 3edcd15065..c2c2d61eeb 100644 --- a/src/main/java/org/kohsuke/github/GHUserSearchBuilder.java +++ b/src/main/java/org/kohsuke/github/GHUserSearchBuilder.java @@ -7,8 +7,8 @@ * @see GitHub#searchUsers() */ public class GHUserSearchBuilder extends GHSearchBuilder { - /*package*/ GHUserSearchBuilder(GitHub root) { - super(root,UserSearchResult.class); + GHUserSearchBuilder(GitHub root) { + super(root, UserSearchResult.class); } /** @@ -20,51 +20,53 @@ public GHUserSearchBuilder q(String term) { } public GHUserSearchBuilder type(String v) { - return q("type:"+v); + return q("type:" + v); } public GHUserSearchBuilder in(String v) { - return q("in:"+v); + return q("in:" + v); } public GHUserSearchBuilder repos(String v) { - return q("repos:"+v); + return q("repos:" + v); } public GHUserSearchBuilder location(String v) { - return q("location:"+v); + return q("location:" + v); } public GHUserSearchBuilder language(String v) { - return q("language:"+v); + return q("language:" + v); } public GHUserSearchBuilder created(String v) { - return q("created:"+v); + return q("created:" + v); } public GHUserSearchBuilder followers(String v) { - return q("followers:"+v); + return q("followers:" + v); } public GHUserSearchBuilder order(GHDirection v) { - req.with("order",v); + req.with("order", v); return this; } public GHUserSearchBuilder sort(Sort sort) { - req.with("sort",sort); + req.with("sort", sort); return this; } - public enum Sort { FOLLOWERS, REPOSITORIES, JOINED } + public enum Sort { + FOLLOWERS, REPOSITORIES, JOINED + } private static class UserSearchResult extends SearchResult { private GHUser[] items; @Override - /*package*/ GHUser[] getItems(GitHub root) { - return GHUser.wrap(items,root); + GHUser[] getItems(GitHub root) { + return GHUser.wrap(items, root); } } diff --git a/src/main/java/org/kohsuke/github/GHVerifiedKey.java b/src/main/java/org/kohsuke/github/GHVerifiedKey.java index d81597d748..65e2ec86ed 100644 --- a/src/main/java/org/kohsuke/github/GHVerifiedKey.java +++ b/src/main/java/org/kohsuke/github/GHVerifiedKey.java @@ -2,12 +2,12 @@ public class GHVerifiedKey extends GHKey { - public GHVerifiedKey() { - this.verified = true; - } + public GHVerifiedKey() { + this.verified = true; + } - @Override - public String getTitle() { - return (title == null ? "key-" + id : title); - } + @Override + public String getTitle() { + return (title == null ? "key-" + id : title); + } } diff --git a/src/main/java/org/kohsuke/github/GitHub.java b/src/main/java/org/kohsuke/github/GitHub.java index 94ffd6f0b6..e1bd982d42 100644 --- a/src/main/java/org/kohsuke/github/GitHub.java +++ b/src/main/java/org/kohsuke/github/GitHub.java @@ -26,6 +26,7 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.databind.introspect.VisibilityChecker.Std; import com.infradna.tool.bridge_method_injector.WithBridgeMethods; import org.apache.commons.codec.Charsets; @@ -59,28 +60,28 @@ * *

Thread safety

*

- * This library aims to be safe for use by multiple threads concurrently, although - * the library itself makes no attempt to control/serialize potentially conflicting - * operations to GitHub, such as updating & deleting a repository at the same time. + * This library aims to be safe for use by multiple threads concurrently, although the library itself makes no attempt + * to control/serialize potentially conflicting operations to GitHub, such as updating & deleting a repository at + * the same time. * * @author Kohsuke Kawaguchi */ public class GitHub { - /*package*/ final String login; + final String login; /** * Value of the authorization header to be sent with the request. */ - /*package*/ final String encodedAuthorization; + final String encodedAuthorization; - private final ConcurrentMap users; - private final ConcurrentMap orgs; + private final ConcurrentMap users; + private final ConcurrentMap orgs; // Cache of myself object. private GHMyself myself; private final String apiUrl; - /*package*/ final RateLimitHandler rateLimitHandler; - /*package*/ final AbuseLimitHandler abuseLimitHandler; + final RateLimitHandler rateLimitHandler; + final AbuseLimitHandler abuseLimitHandler; private HttpConnector connector = HttpConnector.DEFAULT; @@ -92,58 +93,62 @@ public class GitHub { * Creates a client API root object. * *

- * Several different combinations of the login/oauthAccessToken/password parameters are allowed - * to represent different ways of authentication. + * Several different combinations of the login/oauthAccessToken/password parameters are allowed to represent + * different ways of authentication. * *

- *
Log in anonymously - *
Leave all three parameters null and you will be making HTTP requests without any authentication. + *
Log in anonymously + *
Leave all three parameters null and you will be making HTTP requests without any authentication. * - *
Log in with password - *
Specify the login and password, then leave oauthAccessToken null. - * This will use the HTTP BASIC auth with the GitHub API. + *
Log in with password + *
Specify the login and password, then leave oauthAccessToken null. This will use the HTTP BASIC auth with the + * GitHub API. * - *
Log in with OAuth token - *
Specify oauthAccessToken, and optionally specify the login. Leave password null. - * This will send OAuth token to the GitHub API. If the login parameter is null, - * The constructor makes an API call to figure out the user name that owns the token. + *
Log in with OAuth token + *
Specify oauthAccessToken, and optionally specify the login. Leave password null. This will send OAuth token + * to the GitHub API. If the login parameter is null, The constructor makes an API call to figure out the user name + * that owns the token. * - *
Log in with JWT token - *
Specify jwtToken. Leave password null. - * This will send JWT token to the GitHub API via the Authorization HTTP header. - * Please note that only operations in which permissions have been previously configured and accepted during - * the GitHub App will be executed successfully. + *
Log in with JWT token + *
Specify jwtToken. Leave password null. This will send JWT token to the GitHub API via the Authorization HTTP + * header. Please note that only operations in which permissions have been previously configured and accepted during + * the GitHub App will be executed successfully. *
* * @param apiUrl - * The URL of GitHub (or GitHub enterprise) API endpoint, such as "https://api.github.com" or - * "http://ghe.acme.com/api/v3". Note that GitHub Enterprise has /api/v3 in the URL. - * For historical reasons, this parameter still accepts the bare domain name, but that's considered deprecated. - * Password is also considered deprecated as it is no longer required for api usage. + * The URL of GitHub (or GitHub enterprise) API endpoint, such as "https://api.github.com" or + * "http://ghe.acme.com/api/v3". Note that GitHub Enterprise has /api/v3 in the URL. For + * historical reasons, this parameter still accepts the bare domain name, but that's considered + * deprecated. Password is also considered deprecated as it is no longer required for api usage. * @param login - * The user ID on GitHub that you are logging in as. Can be omitted if the OAuth token is - * provided or if logging in anonymously. Specifying this would save one API call. + * The user ID on GitHub that you are logging in as. Can be omitted if the OAuth token is provided or if + * logging in anonymously. Specifying this would save one API call. * @param oauthAccessToken - * Secret OAuth token. + * Secret OAuth token. * @param password - * User's password. Always used in conjunction with the {@code login} parameter + * User's password. Always used in conjunction with the {@code login} parameter * @param connector - * HttpConnector to use. Pass null to use default connector. + * HttpConnector to use. Pass null to use default connector. */ - /* package */ GitHub(String apiUrl, String login, String oauthAccessToken, String jwtToken, String password, HttpConnector connector, RateLimitHandler rateLimitHandler, AbuseLimitHandler abuseLimitHandler) throws IOException { - if (apiUrl.endsWith("/")) apiUrl = apiUrl.substring(0, apiUrl.length()-1); // normalize + GitHub(String apiUrl, String login, String oauthAccessToken, String jwtToken, String password, + HttpConnector connector, RateLimitHandler rateLimitHandler, AbuseLimitHandler abuseLimitHandler) + throws IOException { + if (apiUrl.endsWith("/")) + apiUrl = apiUrl.substring(0, apiUrl.length() - 1); // normalize this.apiUrl = apiUrl; - if (null != connector) this.connector = connector; + if (null != connector) + this.connector = connector; - if (oauthAccessToken!=null) { - encodedAuthorization = "token "+oauthAccessToken; + if (oauthAccessToken != null) { + encodedAuthorization = "token " + oauthAccessToken; } else { - if(jwtToken!=null){ - encodedAuthorization = "Bearer "+jwtToken; - }else if (password!=null) { + if (jwtToken != null) { + encodedAuthorization = "Bearer " + jwtToken; + } else if (password != null) { String authorization = (login + ':' + password); String charsetName = Charsets.UTF_8.name(); - encodedAuthorization = "Basic "+new String(Base64.encodeBase64(authorization.getBytes(charsetName)), charsetName); + encodedAuthorization = "Basic " + + new String(Base64.encodeBase64(authorization.getBytes(charsetName)), charsetName); } else {// anonymous access encodedAuthorization = null; } @@ -154,7 +159,7 @@ public class GitHub { this.rateLimitHandler = rateLimitHandler; this.abuseLimitHandler = abuseLimitHandler; - if (login==null && encodedAuthorization!=null && jwtToken == null) + if (login == null && encodedAuthorization != null && jwtToken == null) login = getMyself().getLogin(); this.login = login; } @@ -169,31 +174,31 @@ public static GitHub connect() throws IOException { /** * Version that connects to GitHub Enterprise. * - * @deprecated - * Use {@link #connectToEnterpriseWithOAuth(String, String, String)} + * @deprecated Use {@link #connectToEnterpriseWithOAuth(String, String, String)} */ @Deprecated public static GitHub connectToEnterprise(String apiUrl, String oauthAccessToken) throws IOException { - return connectToEnterpriseWithOAuth(apiUrl,null,oauthAccessToken); + return connectToEnterpriseWithOAuth(apiUrl, null, oauthAccessToken); } /** * Version that connects to GitHub Enterprise. * * @param apiUrl - * The URL of GitHub (or GitHub Enterprise) API endpoint, such as "https://api.github.com" or - * "http://ghe.acme.com/api/v3". Note that GitHub Enterprise has /api/v3 in the URL. - * For historical reasons, this parameter still accepts the bare domain name, but that's considered deprecated. + * The URL of GitHub (or GitHub Enterprise) API endpoint, such as "https://api.github.com" or + * "http://ghe.acme.com/api/v3". Note that GitHub Enterprise has /api/v3 in the URL. For + * historical reasons, this parameter still accepts the bare domain name, but that's considered + * deprecated. */ - public static GitHub connectToEnterpriseWithOAuth(String apiUrl, String login, String oauthAccessToken) throws IOException { + public static GitHub connectToEnterpriseWithOAuth(String apiUrl, String login, String oauthAccessToken) + throws IOException { return new GitHubBuilder().withEndpoint(apiUrl).withOAuthToken(oauthAccessToken, login).build(); } /** * Version that connects to GitHub Enterprise. * - * @deprecated - * Use with caution. Login with password is not a preferred method. + * @deprecated Use with caution. Login with password is not a preferred method. */ @Deprecated public static GitHub connectToEnterprise(String apiUrl, String login, String password) throws IOException { @@ -205,9 +210,8 @@ public static GitHub connect(String login, String oauthAccessToken) throws IOExc } /** - * @deprecated - * Either OAuth token or password is sufficient, so there's no point in passing both. - * Use {@link #connectUsingPassword(String, String)} or {@link #connectUsingOAuth(String)}. + * @deprecated Either OAuth token or password is sufficient, so there's no point in passing both. Use + * {@link #connectUsingPassword(String, String)} or {@link #connectUsingOAuth(String)}. */ @Deprecated public static GitHub connect(String login, String oauthAccessToken, String password) throws IOException { @@ -225,6 +229,7 @@ public static GitHub connectUsingOAuth(String oauthAccessToken) throws IOExcepti public static GitHub connectUsingOAuth(String githubServer, String oauthAccessToken) throws IOException { return new GitHubBuilder().withEndpoint(githubServer).withOAuthToken(oauthAccessToken).build(); } + /** * Connects to GitHub anonymously. * @@ -252,9 +257,7 @@ public static GitHub connectToEnterpriseAnonymously(String apiUrl) throws IOExce */ public static GitHub offline() { try { - return new GitHubBuilder() - .withEndpoint("https://api.github.invalid") - .withConnector(HttpConnector.OFFLINE) + return new GitHubBuilder().withEndpoint("https://api.github.invalid").withConnector(HttpConnector.OFFLINE) .build(); } catch (IOException e) { throw new IllegalStateException("The offline implementation constructor should not connect", e); @@ -263,14 +266,16 @@ public static GitHub offline() { /** * Is this an anonymous connection + * * @return {@code true} if operations that require authentication will fail. */ public boolean isAnonymous() { - return login==null && encodedAuthorization==null; + return login == null && encodedAuthorization == null; } /** * Is this an always offline "connection". + * * @return {@code true} if this is an always offline "connection". */ public boolean isOffline() { @@ -292,12 +297,13 @@ public void setConnector(HttpConnector connector) { this.connector = connector; } - /*package*/ void requireCredential() { + void requireCredential() { if (isAnonymous()) - throw new IllegalStateException("This operation requires a credential but none is given to the GitHub constructor"); + throw new IllegalStateException( + "This operation requires a credential but none is given to the GitHub constructor"); } - /*package*/ URL getApiURL(String tailApiUrl) throws IOException { + URL getApiURL(String tailApiUrl) throws IOException { if (tailApiUrl.startsWith("/")) { if ("github.com".equals(apiUrl)) {// backward compatibility return new URL(GITHUB_URL + tailApiUrl); @@ -309,7 +315,7 @@ public void setConnector(HttpConnector connector) { } } - /*package*/ Requester retrieve() { + Requester retrieve() { return new Requester(this).method("GET"); } @@ -330,10 +336,11 @@ public GHRateLimit getRateLimit() throws IOException { } /** - * Update the Rate Limit with the latest info from response header. - * Due to multi-threading requests might complete out of order, we want to pick the one with the most recent info from the server. + * Update the Rate Limit with the latest info from response header. Due to multi-threading requests might complete + * out of order, we want to pick the one with the most recent info from the server. * - * @param observed {@link GHRateLimit.Record} constructed from the response header information + * @param observed + * {@link GHRateLimit.Record} constructed from the response header information */ void updateCoreRateLimit(@Nonnull GHRateLimit.Record observed) { synchronized (headerRateLimitLock) { @@ -345,36 +352,40 @@ void updateCoreRateLimit(@Nonnull GHRateLimit.Record observed) { } /** - * Update the Rate Limit with the latest info from response header. - * Due to multi-threading requests might complete out of order, we want to pick the one with the most recent info from the server. - * Header date is only accurate to the second, so we look at the information in the record itself. + * Update the Rate Limit with the latest info from response header. Due to multi-threading requests might complete + * out of order, we want to pick the one with the most recent info from the server. Header date is only accurate to + * the second, so we look at the information in the record itself. * - * {@link GHRateLimit.UnknownLimitRecord}s are always replaced by regular {@link GHRateLimit.Record}s. - * Regular {@link GHRateLimit.Record}s are never replaced by {@link GHRateLimit.UnknownLimitRecord}s. - * Candidates with resetEpochSeconds later than current record are more recent. - * Candidates with the same reset and a lower remaining count are more recent. - * Candidates with an earlier reset are older. + * {@link GHRateLimit.UnknownLimitRecord}s are always replaced by regular {@link GHRateLimit.Record}s. Regular + * {@link GHRateLimit.Record}s are never replaced by {@link GHRateLimit.UnknownLimitRecord}s. Candidates with + * resetEpochSeconds later than current record are more recent. Candidates with the same reset and a lower remaining + * count are more recent. Candidates with an earlier reset are older. * - * @param candidate {@link GHRateLimit.Record} constructed from the response header information - * @param current the current {@link GHRateLimit.Record} record + * @param candidate + * {@link GHRateLimit.Record} constructed from the response header information + * @param current + * the current {@link GHRateLimit.Record} record */ static boolean shouldReplace(@Nonnull GHRateLimit.Record candidate, @Nonnull GHRateLimit.Record current) { - if (candidate instanceof GHRateLimit.UnknownLimitRecord && !(current instanceof GHRateLimit.UnknownLimitRecord)) { + if (candidate instanceof GHRateLimit.UnknownLimitRecord + && !(current instanceof GHRateLimit.UnknownLimitRecord)) { // Unknown candidate never replaces a regular record return false; - } else if (current instanceof GHRateLimit.UnknownLimitRecord && !(candidate instanceof GHRateLimit.UnknownLimitRecord)) { + } else if (current instanceof GHRateLimit.UnknownLimitRecord + && !(candidate instanceof GHRateLimit.UnknownLimitRecord)) { // Any real record should replace an unknown Record. return true; } else { // records of the same type compare to each other as normal. return current.getResetEpochSeconds() < candidate.getResetEpochSeconds() - || (current.getResetEpochSeconds() == candidate.getResetEpochSeconds() && current.getRemaining() > candidate.getRemaining()); + || (current.getResetEpochSeconds() == candidate.getResetEpochSeconds() + && current.getRemaining() > candidate.getRemaining()); } } /** - * Returns the most recently observed rate limit data or {@code null} if either there is no rate limit - * (for example GitHub Enterprise) or if no requests have been made. + * Returns the most recently observed rate limit data or {@code null} if either there is no rate limit (for example + * GitHub Enterprise) or if no requests have been made. * * @return the most recently observed rate limit data or {@code null}. */ @@ -389,7 +400,8 @@ public GHRateLimit lastRateLimit() { * Gets the current rate limit while trying not to actually make any remote requests unless absolutely necessary. * * @return the current rate limit data. - * @throws IOException if we couldn't get the current rate limit data. + * @throws IOException + * if we couldn't get the current rate limit data. */ @Nonnull public GHRateLimit rateLimit() throws IOException { @@ -412,7 +424,8 @@ public GHRateLimit rateLimit() throws IOException { public GHMyself getMyself() throws IOException { requireCredential(); synchronized (this) { - if (this.myself != null) return myself; + if (this.myself != null) + return myself; GHMyself u = retrieve().to("/user", GHMyself.class); @@ -435,7 +448,6 @@ public GHUser getUser(String login) throws IOException { return u; } - /** * clears all cached data in order for external changes (modifications and del) to be reflected */ @@ -449,9 +461,9 @@ public void refreshCache() { */ protected GHUser getUser(GHUser orig) { GHUser u = users.get(orig.getLogin()); - if (u==null) { + if (u == null) { orig.root = this; - users.put(orig.getLogin(),orig); + users.put(orig.getLogin(), orig); return orig; } return u; @@ -462,9 +474,9 @@ protected GHUser getUser(GHUser orig) { */ public GHOrganization getOrganization(String name) throws IOException { GHOrganization o = orgs.get(name); - if (o==null) { + if (o == null) { o = retrieve().to("/orgs/" + name, GHOrganization.class).wrapUp(this); - orgs.put(name,o); + orgs.put(name, o); } return o; } @@ -482,12 +494,8 @@ public PagedIterable listOrganizations() { * @see List All Orgs - Parameters */ public PagedIterable listOrganizations(final String since) { - return retrieve() - .with("since",since) - .asPagedIterable( - "/organizations", - GHOrganization[].class, - item -> item.wrapUp(GitHub.this) ); + return retrieve().with("since", since).asPagedIterable("/organizations", GHOrganization[].class, + item -> item.wrapUp(GitHub.this)); } /** @@ -515,28 +523,21 @@ public GHRepository getRepositoryById(String id) throws IOException { * @return a list of popular open source licenses */ public PagedIterable listLicenses() throws IOException { - return retrieve() - .asPagedIterable( - "/licenses", - GHLicense[].class, - item -> item.wrap(GitHub.this) ); + return retrieve().asPagedIterable("/licenses", GHLicense[].class, item -> item.wrap(GitHub.this)); } /** * Returns a list of all users. */ public PagedIterable listUsers() throws IOException { - return retrieve() - .asPagedIterable( - "/users", - GHUser[].class, - item -> item.wrapUp(GitHub.this) ); + return retrieve().asPagedIterable("/users", GHUser[].class, item -> item.wrapUp(GitHub.this)); } /** * Returns the full details for a license * - * @param key The license key provided from the API + * @param key + * The license key provided from the API * @return The license details * @see GHLicense#getKey() */ @@ -558,24 +559,24 @@ public List getMyInvitations() throws IOException { /** * This method returns shallowly populated organizations. * - * To retrieve full organization details, you need to call {@link #getOrganization(String)} - * TODO: make this automatic. + * To retrieve full organization details, you need to call {@link #getOrganization(String)} TODO: make this + * automatic. */ public Map getMyOrganizations() throws IOException { GHOrganization[] orgs = retrieve().to("/user/orgs", GHOrganization[].class); Map r = new HashMap(); for (GHOrganization o : orgs) { // don't put 'o' into orgs because they are shallow - r.put(o.getLogin(),o.wrapUp(this)); + r.put(o.getLogin(), o.wrapUp(this)); } return r; } - + /** * Alias for {@link #getUserPublicOrganizations(String)}. */ public Map getUserPublicOrganizations(GHUser user) throws IOException { - return getUserPublicOrganizations( user.getLogin() ); + return getUserPublicOrganizations(user.getLogin()); } /** @@ -583,7 +584,8 @@ public Map getUserPublicOrganizations(GHUser user) throw * * To retrieve full organization details, you need to call {@link #getOrganization(String)} * - * @param login the user to retrieve public Organization membership information for + * @param login + * the user to retrieve public Organization membership information for * * @return the public Organization memberships for the user */ @@ -592,7 +594,7 @@ public Map getUserPublicOrganizations(String login) thro Map r = new HashMap(); for (GHOrganization o : orgs) { // don't put 'o' into orgs because they are shallow - r.put(o.getLogin(),o.wrapUp(this)); + r.put(o.getLogin(), o.wrapUp(this)); } return r; } @@ -600,9 +602,8 @@ public Map getUserPublicOrganizations(String login) thro /** * Gets complete map of organizations/teams that current user belongs to. * - * Leverages the new GitHub API /user/teams made available recently to - * get in a single call the complete set of organizations, teams and permissions - * in a single call. + * Leverages the new GitHub API /user/teams made available recently to get in a single call the complete set of + * organizations, teams and permissions in a single call. */ public Map> getMyTeams() throws IOException { Map> allMyTeams = new HashMap>(); @@ -625,7 +626,7 @@ public Map> getMyTeams() throws IOException { public GHTeam getTeam(int id) throws IOException { return retrieve().to("/teams/" + id, GHTeam.class).wrapUp(this); } - + /** * Public events visible to you. Equivalent of what's displayed on https://github.com/ */ @@ -640,7 +641,7 @@ public List getEvents() throws IOException { * Gets a single gist by ID. */ public GHGist getGist(String id) throws IOException { - return retrieve().to("/gists/"+id,GHGist.class).wrapUp(this); + return retrieve().to("/gists/" + id, GHGist.class).wrapUp(this); } public GHGistBuilder createGist() { @@ -650,9 +651,8 @@ public GHGistBuilder createGist() { /** * Parses the GitHub event object. * - * This is primarily intended for receiving a POST HTTP call from a hook. - * Unfortunately, hook script payloads aren't self-descriptive, so you need - * to know the type of the payload you are expecting. + * This is primarily intended for receiving a POST HTTP call from a hook. Unfortunately, hook script payloads aren't + * self-descriptive, so you need to know the type of the payload you are expecting. */ public T parseEventPayload(Reader r, Class type) throws IOException { T t = MAPPER.readValue(r, type); @@ -663,13 +663,12 @@ public T parseEventPayload(Reader r, Class type) t /** * Creates a new repository. * - * @return - * Newly created repository. - * @deprecated - * Use {@link #createRepository(String)} that uses a builder pattern to let you control every aspect. + * @return Newly created repository. + * @deprecated Use {@link #createRepository(String)} that uses a builder pattern to let you control every aspect. */ @Deprecated - public GHRepository createRepository(String name, String description, String homepage, boolean isPublic) throws IOException { + public GHRepository createRepository(String name, String description, String homepage, boolean isPublic) + throws IOException { return createRepository(name).description(description).homepage(homepage).private_(!isPublic).create(); } @@ -677,15 +676,15 @@ public GHRepository createRepository(String name, String description, String hom * Starts a builder that creates a new repository. * *

- * You use the returned builder to set various properties, then call {@link GHCreateRepositoryBuilder#create()} - * to finally create a repository. + * You use the returned builder to set various properties, then call {@link GHCreateRepositoryBuilder#create()} to + * finally create a repository. * *

* To create a repository in an organization, see * {@link GHOrganization#createRepository(String, String, String, GHTeam, boolean)} */ public GHCreateRepositoryBuilder createRepository(String name) { - return new GHCreateRepositoryBuilder(this,"/user/repos",name); + return new GHCreateRepositoryBuilder(this, "/user/repos", name); } /** @@ -695,85 +694,82 @@ public GHCreateRepositoryBuilder createRepository(String name) { * * @see Documentation */ - public GHAuthorization createToken(Collection scope, String note, String noteUrl) throws IOException{ - Requester requester = new Requester(this) - .with("scopes", scope) - .with("note", note) - .with("note_url", noteUrl); + public GHAuthorization createToken(Collection scope, String note, String noteUrl) throws IOException { + Requester requester = new Requester(this).with("scopes", scope).with("note", note).with("note_url", noteUrl); return requester.method("POST").to("/authorizations", GHAuthorization.class).wrap(this); } + /** * Creates a new authorization using an OTP. - * + * * Start by running createToken, if exception is thrown, prompt for OTP from user - * + * * Once OTP is received, call this token request * * The token created can be then used for {@link GitHub#connectUsingOAuth(String)} in the future. * * @see Documentation */ - public GHAuthorization createToken(Collection scope, String note, String noteUrl, Supplier OTP) throws IOException{ - try { - return createToken(scope, note, noteUrl); - }catch (GHOTPRequiredException ex){ - String OTPstring=OTP.get(); - Requester requester = new Requester(this) - .with("scopes", scope) - .with("note", note) - .with("note_url", noteUrl); + public GHAuthorization createToken(Collection scope, String note, String noteUrl, Supplier OTP) + throws IOException { + try { + return createToken(scope, note, noteUrl); + } catch (GHOTPRequiredException ex) { + String OTPstring = OTP.get(); + Requester requester = new Requester(this).with("scopes", scope).with("note", note).with("note_url", + noteUrl); // Add the OTP from the user requester.setHeader("x-github-otp", OTPstring); return requester.method("POST").to("/authorizations", GHAuthorization.class).wrap(this); - } + } } + /** - * @see docs + * @see docs */ public GHAuthorization createOrGetAuth(String clientId, String clientSecret, List scopes, String note, - String note_url) - throws IOException { - Requester requester = new Requester(this) - .with("client_secret", clientSecret) - .with("scopes", scopes) - .with("note", note) - .with("note_url", note_url); + String note_url) throws IOException { + Requester requester = new Requester(this).with("client_secret", clientSecret).with("scopes", scopes) + .with("note", note).with("note_url", note_url); return requester.method("PUT").to("/authorizations/clients/" + clientId, GHAuthorization.class); } /** - * @see Delete an authorization + * @see Delete an + * authorization */ public void deleteAuth(long id) throws IOException { retrieve().method("DELETE").to("/authorizations/" + id); } /** - * @see Check an authorization + * @see Check an + * authorization */ public GHAuthorization checkAuth(@Nonnull String clientId, @Nonnull String accessToken) throws IOException { return retrieve().to("/applications/" + clientId + "/tokens/" + accessToken, GHAuthorization.class); } /** - * @see Reset an authorization + * @see Reset an + * authorization */ public GHAuthorization resetAuth(@Nonnull String clientId, @Nonnull String accessToken) throws IOException { - return retrieve().method("POST").to("/applications/" + clientId + "/tokens/" + accessToken, GHAuthorization.class); + return retrieve().method("POST").to("/applications/" + clientId + "/tokens/" + accessToken, + GHAuthorization.class); } /** * Returns a list of all authorizations. - * @see List your authorizations + * + * @see List your + * authorizations */ public PagedIterable listMyAuthorizations() throws IOException { - return retrieve() - .asPagedIterable( - "/authorizations", - GHAuthorization[].class, - item -> item.wrap(GitHub.this) ); + return retrieve().asPagedIterable("/authorizations", GHAuthorization[].class, item -> item.wrap(GitHub.this)); } /** @@ -781,9 +777,11 @@ public PagedIterable listMyAuthorizations() throws IOException * * You must use a JWT to access this endpoint. * - * @see Get the authenticated GitHub App + * @see Get the authenticated + * GitHub App */ - @Preview @Deprecated + @Preview + @Deprecated public GHApp getApp() throws IOException { return retrieve().withPreview(MACHINE_MAN).to("/app", GHApp.class).wrapUp(this); } @@ -797,41 +795,45 @@ public boolean isCredentialValid() { return true; } catch (IOException e) { if (LOGGER.isLoggable(FINE)) - LOGGER.log(FINE, "Exception validating credentials on " + this.apiUrl + " with login '" + this.login + "' " + e, e); + LOGGER.log(FINE, + "Exception validating credentials on " + this.apiUrl + " with login '" + this.login + "' " + e, + e); return false; } } - /*package*/ GHUser intern(GHUser user) throws IOException { - if (user==null) return user; + GHUser intern(GHUser user) throws IOException { + if (user == null) + return user; // if we already have this user in our map, use it GHUser u = users.get(user.getLogin()); - if (u!=null) return u; + if (u != null) + return u; // if not, remember this new user - users.putIfAbsent(user.getLogin(),user); + users.putIfAbsent(user.getLogin(), user); return user; } public GHProject getProject(long id) throws IOException { - return retrieve().withPreview(INERTIA).to("/projects/"+id, GHProject.class).wrap(this); + return retrieve().withPreview(INERTIA).to("/projects/" + id, GHProject.class).wrap(this); } public GHProjectColumn getProjectColumn(long id) throws IOException { - return retrieve().withPreview(INERTIA).to("/projects/columns/"+id, GHProjectColumn.class).wrap(this); + return retrieve().withPreview(INERTIA).to("/projects/columns/" + id, GHProjectColumn.class).wrap(this); } public GHProjectCard getProjectCard(long id) throws IOException { - return retrieve().withPreview(INERTIA).to("/projects/columns/cards/"+id, GHProjectCard.class).wrap(this); + return retrieve().withPreview(INERTIA).to("/projects/columns/cards/" + id, GHProjectCard.class).wrap(this); } private static class GHApiInfo { private String rate_limit_url; void check(String apiUrl) throws IOException { - if (rate_limit_url==null) - throw new IOException(apiUrl+" doesn't look like GitHub API URL"); + if (rate_limit_url == null) + throw new IOException(apiUrl + " doesn't look like GitHub API URL"); // make sure that the URL is legitimate new URL(rate_limit_url); @@ -845,22 +847,45 @@ void check(String apiUrl) throws IOException { * Verify that the API URL and credentials are valid to access this GitHub. * *

- * This method returns normally if the endpoint is reachable and verified to be GitHub API URL. - * Otherwise this method throws {@link IOException} to indicate the problem. + * This method returns normally if the endpoint is reachable and verified to be GitHub API URL. Otherwise this + * method throws {@link IOException} to indicate the problem. */ public void checkApiUrlValidity() throws IOException { try { retrieve().to("/", GHApiInfo.class).check(apiUrl); } catch (IOException e) { if (isPrivateModeEnabled()) { - throw (IOException)new IOException("GitHub Enterprise server (" + apiUrl + ") with private mode enabled").initCause(e); + throw (IOException) new IOException( + "GitHub Enterprise server (" + apiUrl + ") with private mode enabled").initCause(e); } throw e; } } /** - * Ensures if a GitHub Enterprise server is configured in private mode. + * Checks if a GitHub Enterprise server is configured in private mode. + * + * In private mode response looks like: + * + *

+     *  $ curl -i https://github.mycompany.com/api/v3/
+     *     HTTP/1.1 401 Unauthorized
+     *     Server: GitHub.com
+     *     Date: Sat, 05 Mar 2016 19:45:01 GMT
+     *     Content-Type: application/json; charset=utf-8
+     *     Content-Length: 130
+     *     Status: 401 Unauthorized
+     *     X-GitHub-Media-Type: github.v3
+     *     X-XSS-Protection: 1; mode=block
+     *     X-Frame-Options: deny
+     *     Content-Security-Policy: default-src 'none'
+     *     Access-Control-Allow-Credentials: true
+     *     Access-Control-Expose-Headers: ETag, Link, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval
+     *     Access-Control-Allow-Origin: *
+     *     X-GitHub-Request-Id: dbc70361-b11d-4131-9a7f-674b8edd0411
+     *     Strict-Transport-Security: max-age=31536000; includeSubdomains; preload
+     *     X-Content-Type-Options: nosniff
+     * 
* * @return {@code true} if private mode is enabled. If it tries to use this method with GitHub, returns {@code * false}. @@ -868,28 +893,8 @@ public void checkApiUrlValidity() throws IOException { private boolean isPrivateModeEnabled() { try { HttpURLConnection uc = getConnector().connect(getApiURL("/")); - /* - $ curl -i https://github.mycompany.com/api/v3/ - HTTP/1.1 401 Unauthorized - Server: GitHub.com - Date: Sat, 05 Mar 2016 19:45:01 GMT - Content-Type: application/json; charset=utf-8 - Content-Length: 130 - Status: 401 Unauthorized - X-GitHub-Media-Type: github.v3 - X-XSS-Protection: 1; mode=block - X-Frame-Options: deny - Content-Security-Policy: default-src 'none' - Access-Control-Allow-Credentials: true - Access-Control-Expose-Headers: ETag, Link, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval - Access-Control-Allow-Origin: * - X-GitHub-Request-Id: dbc70361-b11d-4131-9a7f-674b8edd0411 - Strict-Transport-Security: max-age=31536000; includeSubdomains; preload - X-Content-Type-Options: nosniff - */ try { - return uc.getResponseCode() == HTTP_UNAUTHORIZED - && uc.getHeaderField("X-GitHub-Media-Type") != null; + return uc.getResponseCode() == HTTP_UNAUTHORIZED && uc.getHeaderField("X-GitHub-Media-Type") != null; } finally { // ensure that the connection opened by getResponseCode gets closed try { @@ -907,7 +912,8 @@ private boolean isPrivateModeEnabled() { /** * Search commits. */ - @Preview @Deprecated + @Preview + @Deprecated public GHCommitSearchBuilder searchCommits() { return new GHCommitSearchBuilder(this); } @@ -944,11 +950,12 @@ public GHContentSearchBuilder searchContent() { * List all the notifications. */ public GHNotificationStream listNotifications() { - return new GHNotificationStream(this,"/notifications"); + return new GHNotificationStream(this, "/notifications"); } /** * This provides a dump of every public repository, in the order that they were created. + * * @see documentation */ public PagedIterable listAllPublicRepositories() { @@ -959,46 +966,39 @@ public PagedIterable listAllPublicRepositories() { * This provides a dump of every public repository, in the order that they were created. * * @param since - * The numeric ID of the last Repository that you’ve seen. See {@link GHRepository#getId()} + * The numeric ID of the last Repository that you’ve seen. See {@link GHRepository#getId()} * @see documentation */ public PagedIterable listAllPublicRepositories(final String since) { - return retrieve().with("since",since) - .asPagedIterable( - "/repositories", - GHRepository[].class, - item -> item.wrap(GitHub.this) ); + return retrieve().with("since", since).asPagedIterable("/repositories", GHRepository[].class, + item -> item.wrap(GitHub.this)); } /** * Render a Markdown document in raw mode. * *

- * It takes a Markdown document as plaintext and renders it as plain Markdown - * without a repository context (just like a README.md file is rendered – this - * is the simplest way to preview a readme online). + * It takes a Markdown document as plaintext and renders it as plain Markdown without a repository context (just + * like a README.md file is rendered – this is the simplest way to preview a readme online). * * @see GHRepository#renderMarkdown(String, MarkdownMode) */ public Reader renderMarkdown(String text) throws IOException { - return new InputStreamReader( - new Requester(this) - .with(new ByteArrayInputStream(text.getBytes("UTF-8"))) - .contentType("text/plain;charset=UTF-8") - .asStream("/markdown/raw"), - "UTF-8"); + return new InputStreamReader(new Requester(this).with(new ByteArrayInputStream(text.getBytes("UTF-8"))) + .contentType("text/plain;charset=UTF-8").asStream("/markdown/raw"), "UTF-8"); } - /*package*/ static URL parseURL(String s) { + static URL parseURL(String s) { try { - return s==null ? null : new URL(s); + return s == null ? null : new URL(s); } catch (MalformedURLException e) { - throw new IllegalStateException("Invalid URL: "+s); + throw new IllegalStateException("Invalid URL: " + s); } } - /*package*/ static Date parseDate(String timestamp) { - if (timestamp==null) return null; + static Date parseDate(String timestamp) { + if (timestamp == null) + return null; for (String f : TIME_FORMATS) { try { SimpleDateFormat df = new SimpleDateFormat(f); @@ -1008,20 +1008,18 @@ public Reader renderMarkdown(String text) throws IOException { // try next } } - throw new IllegalStateException("Unable to parse the timestamp: "+timestamp); + throw new IllegalStateException("Unable to parse the timestamp: " + timestamp); } - /*package*/ static String printDate(Date dt) { + static String printDate(Date dt) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); df.setTimeZone(TimeZone.getTimeZone("GMT")); return df.format(dt); } - /*package*/ static final ObjectMapper MAPPER = new ObjectMapper(); + static final ObjectMapper MAPPER = new ObjectMapper(); - private static final String[] TIME_FORMATS = { - "yyyy/MM/dd HH:mm:ss ZZZZ", - "yyyy-MM-dd'T'HH:mm:ss'Z'", + private static final String[] TIME_FORMATS = { "yyyy/MM/dd HH:mm:ss ZZZZ", "yyyy-MM-dd'T'HH:mm:ss'Z'", "yyyy-MM-dd'T'HH:mm:ss.S'Z'" // GitHub App endpoints return a different date format }; @@ -1031,7 +1029,7 @@ public Reader renderMarkdown(String text) throws IOException { MAPPER.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS, true); } - /* package */ static final String GITHUB_URL = "https://api.github.com"; + static final String GITHUB_URL = "https://api.github.com"; private static final Logger LOGGER = Logger.getLogger(GitHub.class.getName()); } diff --git a/src/main/java/org/kohsuke/github/GitHubBuilder.java b/src/main/java/org/kohsuke/github/GitHubBuilder.java index f0db8e609b..3a498ebe29 100644 --- a/src/main/java/org/kohsuke/github/GitHubBuilder.java +++ b/src/main/java/org/kohsuke/github/GitHubBuilder.java @@ -37,16 +37,18 @@ public GitHubBuilder() { } /** - * First check if the credentials are configured in the environment. - * We use environment first because users are not likely to give required (full) permissions to their default key. + * First check if the credentials are configured in the environment. We use environment first because users are not + * likely to give required (full) permissions to their default key. * * If no user is specified it means there is no configuration present, so try using the ~/.github properties file. ** * If there is still no user it means there are no credentials defined and throw an IOException. * - * @return the configured Builder from credentials defined on the system or in the environment. Otherwise returns null. + * @return the configured Builder from credentials defined on the system or in the environment. Otherwise returns + * null. * - * @throws IOException If there are no credentials defined in the ~/.github properties file or the process environment. + * @throws IOException + * If there are no credentials defined in the ~/.github properties file or the process environment. */ static GitHubBuilder fromCredentials() throws IOException { Exception cause = null; @@ -54,7 +56,7 @@ static GitHubBuilder fromCredentials() throws IOException { builder = fromEnvironment(); - if (builder.oauthToken != null || builder.user != null || builder.jwtToken != null) + if (builder.oauthToken != null || builder.user != null || builder.jwtToken != null) return builder; try { @@ -66,35 +68,36 @@ static GitHubBuilder fromCredentials() throws IOException { // fall through cause = e; } - throw (IOException)new IOException("Failed to resolve credentials from ~/.github or the environment.").initCause(cause); + throw (IOException) new IOException("Failed to resolve credentials from ~/.github or the environment.") + .initCause(cause); } /** - * @deprecated - * Use {@link #fromEnvironment()} to pick up standard set of environment variables, so that - * different clients of this library will all recognize one consistent set of coordinates. + * @deprecated Use {@link #fromEnvironment()} to pick up standard set of environment variables, so that different + * clients of this library will all recognize one consistent set of coordinates. */ - public static GitHubBuilder fromEnvironment(String loginVariableName, String passwordVariableName, String oauthVariableName) throws IOException { + public static GitHubBuilder fromEnvironment(String loginVariableName, String passwordVariableName, + String oauthVariableName) throws IOException { return fromEnvironment(loginVariableName, passwordVariableName, oauthVariableName, ""); } private static void loadIfSet(String envName, Properties p, String propName) { String v = System.getenv(envName); - if (v != null) - p.put(propName, v); + if (v != null) + p.put(propName, v); } /** - * @deprecated - * Use {@link #fromEnvironment()} to pick up standard set of environment variables, so that - * different clients of this library will all recognize one consistent set of coordinates. + * @deprecated Use {@link #fromEnvironment()} to pick up standard set of environment variables, so that different + * clients of this library will all recognize one consistent set of coordinates. */ - public static GitHubBuilder fromEnvironment(String loginVariableName, String passwordVariableName, String oauthVariableName, String endpointVariableName) throws IOException { + public static GitHubBuilder fromEnvironment(String loginVariableName, String passwordVariableName, + String oauthVariableName, String endpointVariableName) throws IOException { Properties env = new Properties(); - loadIfSet(loginVariableName,env,"login"); - loadIfSet(passwordVariableName,env,"password"); - loadIfSet(oauthVariableName,env,"oauth"); - loadIfSet(endpointVariableName,env,"endpoint"); + loadIfSet(loginVariableName, env, "login"); + loadIfSet(passwordVariableName, env, "password"); + loadIfSet(oauthVariableName, env, "oauth"); + loadIfSet(endpointVariableName, env, "endpoint"); return fromProperties(env); } @@ -105,26 +108,27 @@ public static GitHubBuilder fromEnvironment(String loginVariableName, String pas * The following environment variables are recognized: * *

    - *
  • GITHUB_LOGIN: username like 'kohsuke' - *
  • GITHUB_PASSWORD: raw password - *
  • GITHUB_OAUTH: OAuth token to login - *
  • GITHUB_ENDPOINT: URL of the API endpoint - *
  • GITHUB_JWT: JWT token to login + *
  • GITHUB_LOGIN: username like 'kohsuke' + *
  • GITHUB_PASSWORD: raw password + *
  • GITHUB_OAUTH: OAuth token to login + *
  • GITHUB_ENDPOINT: URL of the API endpoint + *
  • GITHUB_JWT: JWT token to login *
* *

* See class javadoc for the relationship between these coordinates. * *

- * For backward compatibility, the following environment variables are recognized but discouraged: - * login, password, oauth + * For backward compatibility, the following environment variables are recognized but discouraged: login, password, + * oauth */ public static GitHubBuilder fromEnvironment() throws IOException { Properties props = new Properties(); for (Entry e : System.getenv().entrySet()) { String name = e.getKey().toLowerCase(Locale.ENGLISH); - if (name.startsWith("github_")) name=name.substring(7); - props.put(name,e.getValue()); + if (name.startsWith("github_")) + name = name.substring(7); + props.put(name, e.getValue()); } return fromProperties(props); } @@ -144,10 +148,10 @@ public static GitHubBuilder fromPropertyFile(String propertyFileName) throws IOE } finally { IOUtils.closeQuietly(in); } - + return fromProperties(props); } - + public static GitHubBuilder fromProperties(Properties props) { GitHubBuilder self = new GitHubBuilder(); self.withOAuthToken(props.getProperty("oauth"), props.getProperty("login")); @@ -159,22 +163,26 @@ public static GitHubBuilder fromProperties(Properties props) { /** * @param endpoint - * The URL of GitHub (or GitHub enterprise) API endpoint, such as "https://api.github.com" or - * "http://ghe.acme.com/api/v3". Note that GitHub Enterprise has /api/v3 in the URL. - * For historical reasons, this parameter still accepts the bare domain name, but that's considered deprecated. + * The URL of GitHub (or GitHub enterprise) API endpoint, such as "https://api.github.com" or + * "http://ghe.acme.com/api/v3". Note that GitHub Enterprise has /api/v3 in the URL. For + * historical reasons, this parameter still accepts the bare domain name, but that's considered + * deprecated. */ public GitHubBuilder withEndpoint(String endpoint) { this.endpoint = endpoint; return this; } + public GitHubBuilder withPassword(String user, String password) { this.user = user; this.password = password; return this; } + public GitHubBuilder withOAuthToken(String oauthToken) { return withOAuthToken(oauthToken, null); } + public GitHubBuilder withOAuthToken(String oauthToken, String user) { this.oauthToken = oauthToken; this.user = user; @@ -184,35 +192,38 @@ public GitHubBuilder withOAuthToken(String oauthToken, String user) { /** * Configures {@link GitHubBuilder} with Installation Token generated by the GitHub Application * - * @param appInstallationToken A string containing the GitHub App installation token + * @param appInstallationToken + * A string containing the GitHub App installation token * @return the configured Builder from given GitHub App installation token. * @see GHAppInstallation#createToken(java.util.Map) */ - public GitHubBuilder withAppInstallationToken(String appInstallationToken){ + public GitHubBuilder withAppInstallationToken(String appInstallationToken) { return withOAuthToken(appInstallationToken, ""); } - public GitHubBuilder withJwtToken(String jwtToken){ + public GitHubBuilder withJwtToken(String jwtToken) { this.jwtToken = jwtToken; return this; } + public GitHubBuilder withConnector(HttpConnector connector) { this.connector = connector; return this; } + public GitHubBuilder withRateLimitHandler(RateLimitHandler handler) { this.rateLimitHandler = handler; return this; } + public GitHubBuilder withAbuseLimitHandler(AbuseLimitHandler handler) { this.abuseLimitHandler = handler; return this; } /** - * Configures {@linkplain #withConnector(HttpConnector) connector} - * that uses HTTP library in JRE but use a specific proxy, instead of - * the system default one. + * Configures {@linkplain #withConnector(HttpConnector) connector} that uses HTTP library in JRE but use a specific + * proxy, instead of the system default one. */ public GitHubBuilder withProxy(final Proxy p) { return withConnector(new ImpatientHttpConnector(new HttpConnector() { @@ -223,7 +234,8 @@ public HttpURLConnection connect(URL url) throws IOException { } public GitHub build() throws IOException { - return new GitHub(endpoint, user, oauthToken, jwtToken, password, connector, rateLimitHandler, abuseLimitHandler); + return new GitHub(endpoint, user, oauthToken, jwtToken, password, connector, rateLimitHandler, + abuseLimitHandler); } @Override diff --git a/src/main/java/org/kohsuke/github/GitUser.java b/src/main/java/org/kohsuke/github/GitUser.java index 9cd50bb22a..1311916ad0 100644 --- a/src/main/java/org/kohsuke/github/GitUser.java +++ b/src/main/java/org/kohsuke/github/GitUser.java @@ -7,34 +7,32 @@ /** * Represents a user in Git who authors/commits a commit. * - * In contrast, {@link GHUser} is an user of GitHub. Because Git allows a person to - * use multiple e-mail addresses and names when creating a commit, there's generally - * no meaningful mapping between {@link GHUser} and {@link GitUser}. + * In contrast, {@link GHUser} is an user of GitHub. Because Git allows a person to use multiple e-mail addresses and + * names when creating a commit, there's generally no meaningful mapping between {@link GHUser} and {@link GitUser}. * * @author Kohsuke Kawaguchi */ -@SuppressFBWarnings(value = {"UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", - "NP_UNWRITTEN_FIELD"}, justification = "JSON API") +@SuppressFBWarnings(value = { "UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", + "NP_UNWRITTEN_FIELD" }, justification = "JSON API") public class GitUser { private String name, email, date; /** - * Human readable name of the user, such as "Kohsuke Kawaguchi" + * @return Human readable name of the user, such as "Kohsuke Kawaguchi" */ public String getName() { return name; } /** - * E-mail address, such as "foo@example.com" + * @return E-mail address, such as "foo@example.com" */ public String getEmail() { return email; } /** - * This field doesn't appear to be consistently available in all the situations where this class - * is used. + * @return This field doesn't appear to be consistently available in all the situations where this class is used. */ public Date getDate() { return GitHub.parseDate(date); diff --git a/src/main/java/org/kohsuke/github/HttpException.java b/src/main/java/org/kohsuke/github/HttpException.java index 79def83c2a..a11df26c09 100644 --- a/src/main/java/org/kohsuke/github/HttpException.java +++ b/src/main/java/org/kohsuke/github/HttpException.java @@ -6,9 +6,8 @@ import java.net.URL; /** - * {@link IOException} for http exceptions because {@link HttpURLConnection} throws un-discerned - * {@link IOException} and it can help to know the http response code to decide how to handle an - * http exceptions. + * {@link IOException} for http exceptions because {@link HttpURLConnection} throws un-discerned {@link IOException} and + * it can help to know the http response code to decide how to handle an http exceptions. * * @author Cyrille Le Clerc */ @@ -20,11 +19,14 @@ public class HttpException extends IOException { private final String url; /** - * @param message The detail message (which is saved for later retrieval - * by the {@link #getMessage()} method) - * @param responseCode Http response code. {@code -1} if no code can be discerned. - * @param responseMessage Http response message - * @param url The url that was invoked + * @param message + * The detail message (which is saved for later retrieval by the {@link #getMessage()} method) + * @param responseCode + * Http response code. {@code -1} if no code can be discerned. + * @param responseMessage + * Http response message + * @param url + * The url that was invoked * @see HttpURLConnection#getResponseCode() * @see HttpURLConnection#getResponseMessage() */ @@ -36,14 +38,17 @@ public HttpException(String message, int responseCode, String responseMessage, S } /** - * @param message The detail message (which is saved for later retrieval - * by the {@link #getMessage()} method) - * @param responseCode Http response code. {@code -1} if no code can be discerned. - * @param responseMessage Http response message - * @param url The url that was invoked - * @param cause The cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is permitted, - * and indicates that the cause is nonexistent or unknown.) + * @param message + * The detail message (which is saved for later retrieval by the {@link #getMessage()} method) + * @param responseCode + * Http response code. {@code -1} if no code can be discerned. + * @param responseMessage + * Http response message + * @param url + * The url that was invoked + * @param cause + * The cause (which is saved for later retrieval by the {@link #getCause()} method). (A null value is + * permitted, and indicates that the cause is nonexistent or unknown.) * @see HttpURLConnection#getResponseCode() * @see HttpURLConnection#getResponseMessage() */ @@ -56,18 +61,21 @@ public HttpException(String message, int responseCode, String responseMessage, S } /** - * @param responseCode Http response code. {@code -1} if no code can be discerned. - * @param responseMessage Http response message - * @param url The url that was invoked - * @param cause The cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is permitted, - * and indicates that the cause is nonexistent or unknown.) + * @param responseCode + * Http response code. {@code -1} if no code can be discerned. + * @param responseMessage + * Http response message + * @param url + * The url that was invoked + * @param cause + * The cause (which is saved for later retrieval by the {@link #getCause()} method). (A null value is + * permitted, and indicates that the cause is nonexistent or unknown.) * @see HttpURLConnection#getResponseCode() * @see HttpURLConnection#getResponseMessage() */ public HttpException(int responseCode, String responseMessage, String url, Throwable cause) { - super("Server returned HTTP response code: " + responseCode + ", message: '" + responseMessage + "'" + - " for URL: " + url); + super("Server returned HTTP response code: " + responseCode + ", message: '" + responseMessage + "'" + + " for URL: " + url); initCause(cause); this.responseCode = responseCode; this.responseMessage = responseMessage; @@ -75,12 +83,15 @@ public HttpException(int responseCode, String responseMessage, String url, Throw } /** - * @param responseCode Http response code. {@code -1} if no code can be discerned. - * @param responseMessage Http response message - * @param url The url that was invoked - * @param cause The cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is permitted, - * and indicates that the cause is nonexistent or unknown.) + * @param responseCode + * Http response code. {@code -1} if no code can be discerned. + * @param responseMessage + * Http response message + * @param url + * The url that was invoked + * @param cause + * The cause (which is saved for later retrieval by the {@link #getCause()} method). (A null value is + * permitted, and indicates that the cause is nonexistent or unknown.) * @see HttpURLConnection#getResponseCode() * @see HttpURLConnection#getResponseMessage() */ diff --git a/src/main/java/org/kohsuke/github/MarkdownMode.java b/src/main/java/org/kohsuke/github/MarkdownMode.java index 1d63760555..f986a3d559 100644 --- a/src/main/java/org/kohsuke/github/MarkdownMode.java +++ b/src/main/java/org/kohsuke/github/MarkdownMode.java @@ -15,9 +15,8 @@ public enum MarkdownMode { */ MARKDOWN, /** - * Render a document as user-content, e.g. like user comments or issues are rendered. - * In GFM mode, hard line breaks are always taken into account, and issue and user - * mentions are linked accordingly. + * Render a document as user-content, e.g. like user comments or issues are rendered. In GFM mode, hard line breaks + * are always taken into account, and issue and user mentions are linked accordingly. * * @see GHRepository#renderMarkdown(String, MarkdownMode) */ diff --git a/src/main/java/org/kohsuke/github/PagedIterable.java b/src/main/java/org/kohsuke/github/PagedIterable.java index 1c6eccea36..e90ec27fe2 100644 --- a/src/main/java/org/kohsuke/github/PagedIterable.java +++ b/src/main/java/org/kohsuke/github/PagedIterable.java @@ -38,7 +38,7 @@ public final PagedIterator iterator() { */ public List asList() { List r = new ArrayList(); - for(PagedIterator i = iterator(); i.hasNext();) { + for (PagedIterator i = iterator(); i.hasNext();) { r.addAll(i.nextPage()); } return r; @@ -49,7 +49,7 @@ public List asList() { */ public Set asSet() { LinkedHashSet r = new LinkedHashSet(); - for(PagedIterator i = iterator(); i.hasNext();) { + for (PagedIterator i = iterator(); i.hasNext();) { r.addAll(i.nextPage()); } return r; diff --git a/src/main/java/org/kohsuke/github/PagedIterator.java b/src/main/java/org/kohsuke/github/PagedIterator.java index aaa8182076..28b2360b3d 100644 --- a/src/main/java/org/kohsuke/github/PagedIterator.java +++ b/src/main/java/org/kohsuke/github/PagedIterator.java @@ -8,8 +8,8 @@ /** * Iterator over a paginated data source. * - * Aside from the normal iterator operation, this method exposes {@link #nextPage()} - * that allows the caller to retrieve items per page. + * Aside from the normal iterator operation, this method exposes {@link #nextPage()} that allows the caller to retrieve + * items per page. * * @author Kohsuke Kawaguchi */ @@ -22,7 +22,7 @@ public abstract class PagedIterator implements Iterator { private T[] current; private int pos; - /*package*/ PagedIterator(Iterator base) { + PagedIterator(Iterator base) { this.base = base; } @@ -30,17 +30,18 @@ public abstract class PagedIterator implements Iterator { public boolean hasNext() { fetch(); - return current!=null; + return current != null; } public T next() { fetch(); - if (current==null) throw new NoSuchElementException(); + if (current == null) + throw new NoSuchElementException(); return current[pos++]; } private void fetch() { - while (current==null || current.length<=pos) { + while (current == null || current.length <= pos) { if (!base.hasNext()) {// no more to retrieve current = null; pos = 0; @@ -64,7 +65,7 @@ public void remove() { public List nextPage() { fetch(); List r = Arrays.asList(current); - r = r.subList(pos,r.size()); + r = r.subList(pos, r.size()); current = null; pos = 0; return r; diff --git a/src/main/java/org/kohsuke/github/PagedSearchIterable.java b/src/main/java/org/kohsuke/github/PagedSearchIterable.java index f23bd6b58c..974cf46762 100644 --- a/src/main/java/org/kohsuke/github/PagedSearchIterable.java +++ b/src/main/java/org/kohsuke/github/PagedSearchIterable.java @@ -9,8 +9,8 @@ * * @author Kohsuke Kawaguchi */ -@SuppressFBWarnings(value = {"UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", - "UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR"}, justification = "Constructed by JSON API") +@SuppressFBWarnings(value = { "UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", + "UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR" }, justification = "Constructed by JSON API") public abstract class PagedSearchIterable extends PagedIterable { private final GitHub root; @@ -19,13 +19,13 @@ public abstract class PagedSearchIterable extends PagedIterable { */ private SearchResult result; - /*package*/ PagedSearchIterable(GitHub root) { + PagedSearchIterable(GitHub root) { this.root = root; } @Override public PagedSearchIterable withPageSize(int size) { - return (PagedSearchIterable)super.withPageSize(size); + return (PagedSearchIterable) super.withPageSize(size); } /** @@ -42,7 +42,7 @@ public boolean isIncomplete() { } private void populate() { - if (result==null) + if (result == null) iterator().hasNext(); } @@ -57,7 +57,8 @@ public boolean hasNext() { public T[] next() { SearchResult v = base.next(); - if (result==null) result = v; + if (result == null) + result = v; return v.getItems(root); } diff --git a/src/main/java/org/kohsuke/github/Preview.java b/src/main/java/org/kohsuke/github/Preview.java index 2eeed60456..dec90e9cb4 100644 --- a/src/main/java/org/kohsuke/github/Preview.java +++ b/src/main/java/org/kohsuke/github/Preview.java @@ -7,8 +7,8 @@ /** * Indicates that the method/class/etc marked maps to GitHub API in the preview period. * - * These APIs are subject to change and not a part of the backward compatibility commitment. - * Always used in conjunction with 'deprecated' to raise awareness to clients. + * These APIs are subject to change and not a part of the backward compatibility commitment. Always used in conjunction + * with 'deprecated' to raise awareness to clients. * * @author Kohsuke Kawaguchi */ diff --git a/src/main/java/org/kohsuke/github/Previews.java b/src/main/java/org/kohsuke/github/Previews.java index cbdd3cf068..2468ac94cb 100644 --- a/src/main/java/org/kohsuke/github/Previews.java +++ b/src/main/java/org/kohsuke/github/Previews.java @@ -7,7 +7,7 @@ * * @author Kohsuke Kawaguchi */ -/*package*/ class Previews { +class Previews { /** * Commit Search @@ -33,7 +33,8 @@ /** * Require multiple approving reviews * - * @see GitHub API Previews + * @see GitHub API + * Previews */ static final String LUKE_CAGE = "application/vnd.github.luke-cage-preview+json"; @@ -68,7 +69,8 @@ /** * Label emoji, search, and descriptions * - * @see GitHub API Previews + * @see GitHub API + * Previews */ static final String SYMMETRA = "application/vnd.github.symmetra-preview+json"; diff --git a/src/main/java/org/kohsuke/github/RateLimitHandler.java b/src/main/java/org/kohsuke/github/RateLimitHandler.java index e5351da541..0395aadffd 100644 --- a/src/main/java/org/kohsuke/github/RateLimitHandler.java +++ b/src/main/java/org/kohsuke/github/RateLimitHandler.java @@ -16,16 +16,16 @@ public abstract class RateLimitHandler { * Called when the library encounters HTTP error indicating that the API rate limit is reached. * *

- * Any exception thrown from this method will cause the request to fail, and the caller of github-api - * will receive an exception. If this method returns normally, another request will be attempted. - * For that to make sense, the implementation needs to wait for some time. + * Any exception thrown from this method will cause the request to fail, and the caller of github-api will receive + * an exception. If this method returns normally, another request will be attempted. For that to make sense, the + * implementation needs to wait for some time. * * @see API documentation from GitHub * @param e - * Exception from Java I/O layer. If you decide to fail the processing, you can throw - * this exception (or wrap this exception into another exception and throw it.) + * Exception from Java I/O layer. If you decide to fail the processing, you can throw this exception (or + * wrap this exception into another exception and throw it.) * @param uc - * Connection that resulted in an error. Useful for accessing other response headers. + * Connection that resulted in an error. Useful for accessing other response headers. */ public abstract void onError(IOException e, HttpURLConnection uc) throws IOException; @@ -38,15 +38,16 @@ public void onError(IOException e, HttpURLConnection uc) throws IOException { try { Thread.sleep(parseWaitTime(uc)); } catch (InterruptedException x) { - throw (InterruptedIOException)new InterruptedIOException().initCause(e); + throw (InterruptedIOException) new InterruptedIOException().initCause(e); } } private long parseWaitTime(HttpURLConnection uc) { String v = uc.getHeaderField("X-RateLimit-Reset"); - if (v==null) return 10000; // can't tell + if (v == null) + return 10000; // can't tell - return Math.max(10000, Long.parseLong(v)*1000 - System.currentTimeMillis()); + return Math.max(10000, Long.parseLong(v) * 1000 - System.currentTimeMillis()); } }; @@ -56,7 +57,7 @@ private long parseWaitTime(HttpURLConnection uc) { public static final RateLimitHandler FAIL = new RateLimitHandler() { @Override public void onError(IOException e, HttpURLConnection uc) throws IOException { - throw (IOException)new IOException("API rate limit reached").initCause(e); + throw (IOException) new IOException("API rate limit reached").initCause(e); } }; } diff --git a/src/main/java/org/kohsuke/github/Reactable.java b/src/main/java/org/kohsuke/github/Reactable.java index d8821362cf..f0beddca16 100644 --- a/src/main/java/org/kohsuke/github/Reactable.java +++ b/src/main/java/org/kohsuke/github/Reactable.java @@ -7,17 +7,20 @@ * * @author Kohsuke Kawaguchi */ -@Preview @Deprecated +@Preview +@Deprecated public interface Reactable { /** * List all the reactions left to this object. */ - @Preview @Deprecated + @Preview + @Deprecated PagedIterable listReactions(); /** * Leaves a reaction to this object. */ - @Preview @Deprecated + @Preview + @Deprecated GHReaction createReaction(ReactionContent content) throws IOException; } diff --git a/src/main/java/org/kohsuke/github/ReactionContent.java b/src/main/java/org/kohsuke/github/ReactionContent.java index 57a204b56d..b9dc3e9add 100644 --- a/src/main/java/org/kohsuke/github/ReactionContent.java +++ b/src/main/java/org/kohsuke/github/ReactionContent.java @@ -11,12 +11,7 @@ * @see GHReaction */ public enum ReactionContent { - PLUS_ONE("+1"), - MINUS_ONE("-1"), - LAUGH("laugh"), - CONFUSED("confused"), - HEART("heart"), - HOORAY("hooray"); + PLUS_ONE("+1"), MINUS_ONE("-1"), LAUGH("laugh"), CONFUSED("confused"), HEART("heart"), HOORAY("hooray"); private final String content; diff --git a/src/main/java/org/kohsuke/github/Refreshable.java b/src/main/java/org/kohsuke/github/Refreshable.java index 6c75ad63c6..05299dc7f8 100644 --- a/src/main/java/org/kohsuke/github/Refreshable.java +++ b/src/main/java/org/kohsuke/github/Refreshable.java @@ -18,7 +18,6 @@ public interface Refreshable { */ void refresh() throws IOException; - /** * Calls refresh if the provided value is null */ diff --git a/src/main/java/org/kohsuke/github/Requester.java b/src/main/java/org/kohsuke/github/Requester.java index 12765bd453..5513345ff7 100644 --- a/src/main/java/org/kohsuke/github/Requester.java +++ b/src/main/java/org/kohsuke/github/Requester.java @@ -74,7 +74,7 @@ class Requester { private final GitHub root; private final List args = new ArrayList(); - private final Map headers = new LinkedHashMap(); + private final Map headers = new LinkedHashMap(); /** * Request method. @@ -109,16 +109,16 @@ private Entry(String key, Object value) { * If a header of the same name is already set, this method overrides it. */ public void setHeader(String name, String value) { - headers.put(name,value); + headers.put(name, value); } public Requester withHeader(String name, String value) { - setHeader(name,value); + setHeader(name, value); return this; } - /*package*/ Requester withPreview(String name) { - return withHeader("Accept",name); + Requester withPreview(String name) { + return withHeader("Accept", name); } /** @@ -140,7 +140,7 @@ public Requester with(String key, long value) { } public Requester with(String key, Integer value) { - if (value!=null) + if (value != null) _with(key, value); return this; } @@ -148,12 +148,14 @@ public Requester with(String key, Integer value) { public Requester with(String key, boolean value) { return _with(key, value); } + public Requester with(String key, Boolean value) { return _with(key, value); } public Requester with(String key, Enum e) { - if (e==null) return _with(key, null); + if (e == null) + return _with(key, null); return with(key, transformEnum(e)); } @@ -170,7 +172,7 @@ public Requester withLogins(String key, Collection users) { for (GHUser a : users) { names.add(a.getLogin()); } - return with(key,names); + return with(key, names); } public Requester with(String key, Map value) { @@ -178,26 +180,26 @@ public Requester with(String key, Map value) { } public Requester withPermissions(String key, Map value) { - Map retMap = new HashMap(); + Map retMap = new HashMap(); for (Map.Entry entry : value.entrySet()) { retMap.put(entry.getKey(), transformEnum(entry.getValue())); } return _with(key, retMap); } - public Requester with(@WillClose/*later*/ InputStream body) { + public Requester with(@WillClose /* later */ InputStream body) { this.body = body; return this; } - public Requester withNullable(String key, Object value) { - args.add(new Entry(key, value)); - return this; - } + public Requester withNullable(String key, Object value) { + args.add(new Entry(key, value)); + return this; + } public Requester _with(String key, Object value) { - if (value!=null) { - args.add(new Entry(key,value)); + if (value != null) { + args.add(new Entry(key, value)); } return this; } @@ -212,7 +214,7 @@ public Requester set(String key, Object value) { return this; } } - return _with(key,value); + return _with(key, value); } public Requester method(String method) { @@ -227,25 +229,24 @@ public Requester contentType(String contentType) { /** * Small number of GitHub APIs use HTTP methods somewhat inconsistently, and use a body where it's not expected. - * Normally whether parameters go as query parameters or a body depends on the HTTP verb in use, - * but this method forces the parameters to be sent as a body. + * Normally whether parameters go as query parameters or a body depends on the HTTP verb in use, but this method + * forces the parameters to be sent as a body. */ - /*package*/ Requester inBody() { + Requester inBody() { forceBody = true; return this; } public void to(String tailApiUrl) throws IOException { - to(tailApiUrl,null); + to(tailApiUrl, null); } /** * Sends a request to the specified URL, and parses the response into the given type via databinding. * * @throws IOException - * if the server returns 4xx/5xx responses. - * @return - * {@link Reader} that reads the response. + * if the server returns 4xx/5xx responses. + * @return {@link Reader} that reads the response. */ public T to(String tailApiUrl, Class type) throws IOException { return _to(tailApiUrl, type, null); @@ -273,7 +274,7 @@ private T _to(String tailApiUrl, Class type, T instance) throws IOExcepti tailApiUrl += questionMarkFound ? '&' : '?'; for (Iterator it = args.listIterator(); it.hasNext();) { Entry arg = it.next(); - tailApiUrl += arg.key + '=' + URLEncoder.encode(arg.value.toString(),"UTF-8"); + tailApiUrl += arg.key + '=' + URLEncoder.encode(arg.value.toString(), "UTF-8"); if (it.hasNext()) { tailApiUrl += '&'; } @@ -298,7 +299,8 @@ private T _to(String tailApiUrl, Class type, T instance) throws IOExcepti setResponseHeaders(nextResult); final int resultLength = Array.getLength(result); final int nextResultLength = Array.getLength(nextResult); - T concatResult = (T) Array.newInstance(type.getComponentType(), resultLength + nextResultLength); + T concatResult = (T) Array.newInstance(type.getComponentType(), + resultLength + nextResultLength); System.arraycopy(result, 0, concatResult, 0, resultLength); System.arraycopy(nextResult, 0, concatResult, resultLength, nextResultLength); result = concatResult; @@ -408,7 +410,6 @@ public String getResponseHeader(String header) { return uc.getHeaderField(header); } - /** * Set up the request parameters or POST payload. */ @@ -417,14 +418,14 @@ private void buildRequest() throws IOException { uc.setDoOutput(true); if (body == null) { - uc.setRequestProperty("Content-type", defaultString(contentType,"application/json")); + uc.setRequestProperty("Content-type", defaultString(contentType, "application/json")); Map json = new HashMap(); for (Entry e : args) { json.put(e.key, e.value); } MAPPER.writeValue(uc.getOutputStream(), json); } else { - uc.setRequestProperty("Content-type", defaultString(contentType,"application/x-www-form-urlencoded")); + uc.setRequestProperty("Content-type", defaultString(contentType, "application/x-www-form-urlencoded")); try { byte[] bytes = new byte[32768]; int read; @@ -442,7 +443,7 @@ private boolean isMethodWithBody() { return forceBody || !METHODS_WITHOUT_BODY.contains(method); } - /*package*/ PagedIterable asPagedIterable(String tailApiUrl, Class type, Consumer consumer) { + PagedIterable asPagedIterable(String tailApiUrl, Class type, Consumer consumer) { return new PagedIterableWithConsumer(type, this, tailApiUrl, consumer); } @@ -453,7 +454,8 @@ private static class PagedIterableWithConsumer extends PagedIterable { private final String tailApiUrl; private final Consumer consumer; - public PagedIterableWithConsumer(Class clazz, Requester requester, String tailApiUrl, Consumer consumer) { + public PagedIterableWithConsumer(Class clazz, Requester requester, String tailApiUrl, + Consumer consumer) { this.clazz = clazz; this.tailApiUrl = tailApiUrl; this.requester = requester; @@ -481,11 +483,11 @@ protected void wrapUp(S[] page) { * * Every iterator call reports a new batch. */ - /*package*/ Iterator asIterator(String tailApiUrl, Class type, int pageSize) { + Iterator asIterator(String tailApiUrl, Class type, int pageSize) { method("GET"); - if (pageSize!=0) - args.add(new Entry("per_page",pageSize)); + if (pageSize != 0) + args.add(new Entry("per_page", pageSize)); StringBuilder s = new StringBuilder(tailApiUrl); if (!args.isEmpty()) { @@ -499,14 +501,14 @@ protected void wrapUp(S[] page) { s.append(URLEncoder.encode(a.value.toString(), "UTF-8")); } } catch (UnsupportedEncodingException e) { - throw new AssertionError(e); // UTF-8 is mandatory + throw new AssertionError(e); // UTF-8 is mandatory } } try { return new PagingIterator(type, tailApiUrl, root.getApiURL(s.toString())); } catch (IOException e) { - throw new GHException("Unable to build github Api URL",e); + throw new GHException("Unable to build github Api URL", e); } } @@ -533,13 +535,14 @@ class PagingIterator implements Iterator { public boolean hasNext() { fetch(); - return next!=null; + return next != null; } public T next() { fetch(); T r = next; - if (r==null) throw new NoSuchElementException(); + if (r == null) + throw new NoSuchElementException(); next = null; return r; } @@ -549,15 +552,17 @@ public void remove() { } private void fetch() { - if (next!=null) return; // already fetched - if (url==null) return; // no more data to fetch + if (next != null) + return; // already fetched + if (url == null) + return; // no more data to fetch try { while (true) {// loop while API rate limit is hit setupConnection(url); try { - next = parse(type,null); - assert next!=null; + next = parse(type, null); + assert next != null; findNextURL(); return; } catch (IOException e) { @@ -577,14 +582,15 @@ private void fetch() { private void findNextURL() throws MalformedURLException { url = null; // start defensively String link = uc.getHeaderField("Link"); - if (link==null) return; + if (link == null) + return; for (String token : link.split(", ")) { if (token.endsWith("rel=\"next\"")) { // found the next page. This should look something like // ; rel="next" int idx = token.indexOf('>'); - url = new URL(token.substring(1,idx)); + url = new URL(token.substring(1, idx)); return; } } @@ -593,21 +599,21 @@ private void findNextURL() throws MalformedURLException { } } - private void setupConnection(URL url) throws IOException { if (LOGGER.isLoggable(FINE)) { - LOGGER.log(FINE, "GitHub API request [" + (root.login == null ? "anonymous" : root.login) + "]: " + method + " " + url.toString()); + LOGGER.log(FINE, "GitHub API request [" + (root.login == null ? "anonymous" : root.login) + "]: " + method + + " " + url.toString()); } uc = root.getConnector().connect(url); // if the authentication is needed but no credential is given, try it anyway (so that some calls // that do work with anonymous access in the reduced form should still work.) - if (root.encodedAuthorization!=null) + if (root.encodedAuthorization != null) uc.setRequestProperty("Authorization", root.encodedAuthorization); for (Map.Entry e : headers.entrySet()) { String v = e.getValue(); - if (v!=null) + if (v != null) uc.setRequestProperty(e.getKey(), v); } @@ -623,9 +629,9 @@ private void setRequestMethod(HttpURLConnection uc) throws IOException { try { Field $method = HttpURLConnection.class.getDeclaredField("method"); $method.setAccessible(true); - $method.set(uc,method); + $method.set(uc, method); } catch (Exception x) { - throw (IOException)new IOException("Failed to set the custom verb").initCause(x); + throw (IOException) new IOException("Failed to set the custom verb").initCause(x); } // sun.net.www.protocol.https.DelegatingHttpsURLConnection delegates to another HttpURLConnection try { @@ -639,11 +645,11 @@ private void setRequestMethod(HttpURLConnection uc) throws IOException { } catch (NoSuchFieldException x) { // no problem } catch (IllegalAccessException x) { - throw (IOException)new IOException("Failed to set the custom verb").initCause(x); + throw (IOException) new IOException("Failed to set the custom verb").initCause(x); } } if (!uc.getRequestMethod().equals(method)) - throw new IllegalStateException("Failed to set the request method to "+method); + throw new IllegalStateException("Failed to set the request method to " + method); } @CheckForNull @@ -659,11 +665,11 @@ private T parse(Class type, T instance, int timeouts) throws IOException responseCode = uc.getResponseCode(); responseMessage = uc.getResponseMessage(); if (responseCode == 304) { - return null; // special case handling for 304 unmodified, as the content will be "" + return null; // special case handling for 304 unmodified, as the content will be "" } - if (responseCode == 204 && type!=null && type.isArray()) { + if (responseCode == 204 && type != null && type.isArray()) { // no content - return type.cast(Array.newInstance(type.getComponentType(),0)); + return type.cast(Array.newInstance(type.getComponentType(), 0)); } // Response code 202 means the statistics are still being cached. @@ -676,18 +682,19 @@ private T parse(Class type, T instance, int timeouts) throws IOException r = new InputStreamReader(wrapStream(uc.getInputStream()), "UTF-8"); String data = IOUtils.toString(r); - if (type!=null) + if (type != null) try { return setResponseHeaders(MAPPER.readValue(data, type)); } catch (JsonMappingException e) { - throw (IOException)new IOException("Failed to deserialize " +data).initCause(e); + throw (IOException) new IOException("Failed to deserialize " + data).initCause(e); } - if (instance!=null) { - return setResponseHeaders(MAPPER.readerForUpdating(instance).readValue(data)); + if (instance != null) { + return setResponseHeaders(MAPPER.readerForUpdating(instance). readValue(data)); } return null; } catch (FileNotFoundException e) { - // java.net.URLConnection handles 404 exception has FileNotFoundException, don't wrap exception in HttpException + // java.net.URLConnection handles 404 exception has FileNotFoundException, don't wrap exception in + // HttpException // to preserve backward compatibility throw e; } catch (IOException e) { @@ -710,7 +717,7 @@ private T setResponseHeaders(T readValue) { setResponseHeaders((GHObject) readValue); } else if (readValue instanceof JsonRateLimit) { // if we're getting a GHRateLimit it needs the server date - ((JsonRateLimit)readValue).resources.getCore().recalculateResetDate(uc.getHeaderField("Date")); + ((JsonRateLimit) readValue).resources.getCore().recalculateResetDate(uc.getHeaderField("Date")); } return readValue; } @@ -724,16 +731,18 @@ private void setResponseHeaders(GHObject readValue) { */ private InputStream wrapStream(InputStream in) throws IOException { String encoding = uc.getContentEncoding(); - if (encoding==null || in==null) return in; - if (encoding.equals("gzip")) return new GZIPInputStream(in); + if (encoding == null || in == null) + return in; + if (encoding.equals("gzip")) + return new GZIPInputStream(in); - throw new UnsupportedOperationException("Unexpected Content-Encoding: "+encoding); + throw new UnsupportedOperationException("Unexpected Content-Encoding: " + encoding); } /** * Handle API error by either throwing it or by returning normally to retry. */ - /*package*/ void handleApiError(IOException e) throws IOException { + void handleApiError(IOException e) throws IOException { int responseCode; try { responseCode = uc.getResponseCode(); @@ -741,8 +750,8 @@ private InputStream wrapStream(InputStream in) throws IOException { // likely to be a network exception (e.g. SSLHandshakeException), // uc.getResponseCode() and any other getter on the response will cause an exception if (LOGGER.isLoggable(FINE)) - LOGGER.log(FINE, "Silently ignore exception retrieving response code for '" + uc.getURL() + "'" + - " handling exception " + e, e); + LOGGER.log(FINE, "Silently ignore exception retrieving response code for '" + uc.getURL() + "'" + + " handling exception " + e, e); throw e; } InputStream es = wrapStream(uc.getErrorStream()); @@ -754,8 +763,7 @@ private InputStream wrapStream(InputStream in) throws IOException { e = (IOException) new GHFileNotFoundException(error).withResponseHeaderFields(uc).initCause(e); } else if (e instanceof HttpException) { HttpException http = (HttpException) e; - e = new HttpException(error, http.getResponseCode(), http.getResponseMessage(), - http.getUrl(), e); + e = new HttpException(error, http.getResponseCode(), http.getResponseMessage(), http.getUrl(), e); } else { e = (IOException) new GHIOException(error).withResponseHeaderFields(uc).initCause(e); } @@ -764,22 +772,21 @@ private InputStream wrapStream(InputStream in) throws IOException { } } if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) // 401 Unauthorized == bad creds or OTP request - // In the case of a user with 2fa enabled, a header with X-GitHub-OTP - // will be returned indicating the user needs to respond with an otp - if(uc.getHeaderField("X-GitHub-OTP") != null) + // In the case of a user with 2fa enabled, a header with X-GitHub-OTP + // will be returned indicating the user needs to respond with an otp + if (uc.getHeaderField("X-GitHub-OTP") != null) throw (IOException) new GHOTPRequiredException().withResponseHeaderFields(uc).initCause(e); else throw e; // usually org.kohsuke.github.HttpException (which extends IOException) if ("0".equals(uc.getHeaderField("X-RateLimit-Remaining"))) { - root.rateLimitHandler.onError(e,uc); + root.rateLimitHandler.onError(e, uc); return; } // Retry-After is not documented but apparently that field exists - if (responseCode == HttpURLConnection.HTTP_FORBIDDEN && - uc.getHeaderField("Retry-After") != null) { - this.root.abuseLimitHandler.onError(e,uc); + if (responseCode == HttpURLConnection.HTTP_FORBIDDEN && uc.getHeaderField("Retry-After") != null) { + this.root.abuseLimitHandler.onError(e, uc); return; } @@ -788,10 +795,12 @@ private InputStream wrapStream(InputStream in) throws IOException { /** * Transform Java Enum into Github constants given its conventions - * @param en - Enum to be transformed + * + * @param en + * Enum to be transformed * @return a String containing the value of a Github constant */ - private String transformEnum(Enum en){ + private String transformEnum(Enum en) { // by convention Java constant names are upper cases, but github uses // lower-case constants. GitHub also uses '-', which in Java we always // replace by '_' diff --git a/src/main/java/org/kohsuke/github/SearchResult.java b/src/main/java/org/kohsuke/github/SearchResult.java index 2fb2dca06e..e3b86a9e97 100644 --- a/src/main/java/org/kohsuke/github/SearchResult.java +++ b/src/main/java/org/kohsuke/github/SearchResult.java @@ -10,12 +10,12 @@ abstract class SearchResult { @SuppressFBWarnings(value = "UWF_UNWRITTEN_FIELD", justification = "Field comes from JSON deserialization") int total_count; - + @SuppressFBWarnings(value = "UWF_UNWRITTEN_FIELD", justification = "Field comes from JSON deserialization") boolean incomplete_results; /** * Wraps up the retrieved object and return them. Only called once. */ - /*package*/ abstract T[] getItems(GitHub root); + abstract T[] getItems(GitHub root); } diff --git a/src/main/java/org/kohsuke/github/extras/ImpatientHttpConnector.java b/src/main/java/org/kohsuke/github/extras/ImpatientHttpConnector.java index 740b9a037d..9513b3d6f3 100644 --- a/src/main/java/org/kohsuke/github/extras/ImpatientHttpConnector.java +++ b/src/main/java/org/kohsuke/github/extras/ImpatientHttpConnector.java @@ -19,9 +19,9 @@ public class ImpatientHttpConnector implements HttpConnector { /** * @param connectTimeout - * HTTP connection timeout in milliseconds + * HTTP connection timeout in milliseconds * @param readTimeout - * HTTP read timeout in milliseconds + * HTTP read timeout in milliseconds */ public ImpatientHttpConnector(HttpConnector base, int connectTimeout, int readTimeout) { this.base = base; @@ -30,11 +30,11 @@ public ImpatientHttpConnector(HttpConnector base, int connectTimeout, int readTi } public ImpatientHttpConnector(HttpConnector base, int timeout) { - this(base,timeout,timeout); + this(base, timeout, timeout); } public ImpatientHttpConnector(HttpConnector base) { - this(base,CONNECT_TIMEOUT,READ_TIMEOUT); + this(base, CONNECT_TIMEOUT, READ_TIMEOUT); } public HttpURLConnection connect(URL url) throws IOException { diff --git a/src/main/java/org/kohsuke/github/extras/OkHttp3Connector.java b/src/main/java/org/kohsuke/github/extras/OkHttp3Connector.java index 17b93b3318..4edfd460ee 100644 --- a/src/main/java/org/kohsuke/github/extras/OkHttp3Connector.java +++ b/src/main/java/org/kohsuke/github/extras/OkHttp3Connector.java @@ -11,10 +11,8 @@ /** * {@link HttpConnector} for {@link OkHttpClient}. * - * Unlike {@link #DEFAULT}, OkHttp does response caching. - * Making a conditional request against GitHubAPI and receiving a 304 - * response does not count against the rate limit. - * See http://developer.github.com/v3/#conditional-requests + * Unlike {@link #DEFAULT}, OkHttp does response caching. Making a conditional request against GitHubAPI and receiving a + * 304 response does not count against the rate limit. See http://developer.github.com/v3/#conditional-requests * * @see org.kohsuke.github.extras.okhttp3.OkHttpConnector * @author Roberto Tyley diff --git a/src/main/java/org/kohsuke/github/extras/OkHttpConnector.java b/src/main/java/org/kohsuke/github/extras/OkHttpConnector.java index 60b41e18ea..1cb38e9f69 100644 --- a/src/main/java/org/kohsuke/github/extras/OkHttpConnector.java +++ b/src/main/java/org/kohsuke/github/extras/OkHttpConnector.java @@ -25,10 +25,8 @@ /** * {@link HttpConnector} for {@link OkHttpClient}. * - * Unlike {@link #DEFAULT}, OkHttp does response caching. - * Making a conditional request against GitHubAPI and receiving a 304 - * response does not count against the rate limit. - * See http://developer.github.com/v3/#conditional-requests + * Unlike {@link #DEFAULT}, OkHttp does response caching. Making a conditional request against GitHubAPI and receiving a + * 304 response does not count against the rate limit. See http://developer.github.com/v3/#conditional-requests * * @author Roberto Tyley * @author Kohsuke Kawaguchi @@ -45,6 +43,7 @@ public OkHttpConnector(OkUrlFactory urlFactory) { /** * package private for tests to be able to change max-age for cache. + * * @param urlFactory * @param cacheMaxAge */ @@ -54,16 +53,12 @@ public OkHttpConnector(OkUrlFactory urlFactory) { this.urlFactory = urlFactory; if (cacheMaxAge >= 0 && urlFactory.client() != null && urlFactory.client().getCache() != null) { - maxAgeHeaderValue = new CacheControl.Builder() - .maxAge(cacheMaxAge, TimeUnit.SECONDS) - .build() - .toString(); + maxAgeHeaderValue = new CacheControl.Builder().maxAge(cacheMaxAge, TimeUnit.SECONDS).build().toString(); } else { maxAgeHeaderValue = null; } } - public HttpURLConnection connect(URL url) throws IOException { HttpURLConnection urlConnection = urlFactory.open(url); if (maxAgeHeaderValue != null) { diff --git a/src/main/java/org/kohsuke/github/extras/okhttp3/ObsoleteUrlFactory.java b/src/main/java/org/kohsuke/github/extras/okhttp3/ObsoleteUrlFactory.java index c03587029c..a071e7e727 100644 --- a/src/main/java/org/kohsuke/github/extras/okhttp3/ObsoleteUrlFactory.java +++ b/src/main/java/org/kohsuke/github/extras/okhttp3/ObsoleteUrlFactory.java @@ -69,1135 +69,1249 @@ import static java.net.HttpURLConnection.HTTP_NO_CONTENT; /** - * OkHttp 3.14 dropped support for the long-deprecated OkUrlFactory class, which allows you to use - * the HttpURLConnection API with OkHttp's implementation. This class does the same thing using only - * public APIs in OkHttp. It requires OkHttp 3.14 or newer. + * OkHttp 3.14 dropped support for the long-deprecated OkUrlFactory class, which allows you to use the HttpURLConnection + * API with OkHttp's implementation. This class does the same thing using only public APIs in OkHttp. It requires OkHttp + * 3.14 or newer. * - *

Rather than pasting this 1100 line gist into your source code, please upgrade to OkHttp's - * request/response API. Your code will be shorter, easier to read, and you'll be able to use - * interceptors. + *

+ * Rather than pasting this 1100 line gist into your source code, please upgrade to OkHttp's request/response API. Your + * code will be shorter, easier to read, and you'll be able to use interceptors. */ public final class ObsoleteUrlFactory implements URLStreamHandlerFactory, Cloneable { - static final String SELECTED_PROTOCOL = "ObsoleteUrlFactory-Selected-Protocol"; - - static final String RESPONSE_SOURCE = "ObsoleteUrlFactory-Response-Source"; - - static final Set METHODS = new LinkedHashSet<>( - Arrays.asList("OPTIONS", "GET", "HEAD", "POST", "PUT", "DELETE", "TRACE", "PATCH")); - - static final TimeZone UTC = TimeZone.getTimeZone("GMT"); - - static final int HTTP_CONTINUE = 100; - - static final ThreadLocal STANDARD_DATE_FORMAT = ThreadLocal.withInitial(() -> { - // Date format specified by RFC 7231 section 7.1.1.1. - DateFormat rfc1123 = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US); - rfc1123.setLenient(false); - rfc1123.setTimeZone(UTC); - return rfc1123; - }); - - static final Comparator FIELD_NAME_COMPARATOR = (a, b) -> { - if (Objects.equals(a, b)) { - return 0; - } else if (Objects.isNull(a)) { - return -1; - } else if (Objects.isNull(b)) { - return 1; - } else { - return String.CASE_INSENSITIVE_ORDER.compare(a, b); - } - }; - - private OkHttpClient client; - - public ObsoleteUrlFactory(OkHttpClient client) { - this.client = client; - } - - public OkHttpClient client() { - return client; - } - - public ObsoleteUrlFactory setClient(OkHttpClient client) { - this.client = client; - return this; - } - - /** - * Returns a copy of this stream handler factory that includes a shallow copy of the internal - * {@linkplain OkHttpClient HTTP client}. - */ - @Override public ObsoleteUrlFactory clone() { - return new ObsoleteUrlFactory(client); - } - - public HttpURLConnection open(URL url) { - return open(url, client.proxy()); - } - - HttpURLConnection open(URL url, @Nullable Proxy proxy) { - String protocol = url.getProtocol(); - OkHttpClient copy = client.newBuilder() - .proxy(proxy) - .build(); - - if (protocol.equals("http")) return new OkHttpURLConnection(url, copy); - if (protocol.equals("https")) return new OkHttpsURLConnection(url, copy); - throw new IllegalArgumentException("Unexpected protocol: " + protocol); - } - - /** - * Creates a URLStreamHandler as a {@link java.net.URL#setURLStreamHandlerFactory}. - * - *

This code configures OkHttp to handle all HTTP and HTTPS connections - * created with {@link java.net.URL#openConnection()}:

   {@code
-   *
-   *   OkHttpClient okHttpClient = new OkHttpClient();
-   *   URL.setURLStreamHandlerFactory(new ObsoleteUrlFactory(okHttpClient));
-   * }
- */ - @Override public URLStreamHandler createURLStreamHandler(final String protocol) { - if (!protocol.equals("http") && !protocol.equals("https")) return null; - - return new URLStreamHandler() { - @Override protected URLConnection openConnection(URL url) { - return open(url); - } - - @Override protected URLConnection openConnection(URL url, Proxy proxy) { - return open(url, proxy); - } - - @Override protected int getDefaultPort() { - if (protocol.equals("http")) return 80; - if (protocol.equals("https")) return 443; - throw new AssertionError(); - } + static final String SELECTED_PROTOCOL = "ObsoleteUrlFactory-Selected-Protocol"; + + static final String RESPONSE_SOURCE = "ObsoleteUrlFactory-Response-Source"; + + static final Set METHODS = new LinkedHashSet<>( + Arrays.asList("OPTIONS", "GET", "HEAD", "POST", "PUT", "DELETE", "TRACE", "PATCH")); + + static final TimeZone UTC = TimeZone.getTimeZone("GMT"); + + static final int HTTP_CONTINUE = 100; + + static final ThreadLocal STANDARD_DATE_FORMAT = ThreadLocal.withInitial(() -> { + // Date format specified by RFC 7231 section 7.1.1.1. + DateFormat rfc1123 = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US); + rfc1123.setLenient(false); + rfc1123.setTimeZone(UTC); + return rfc1123; + }); + + static final Comparator FIELD_NAME_COMPARATOR = (a, b) -> { + if (Objects.equals(a, b)) { + return 0; + } else if (Objects.isNull(a)) { + return -1; + } else if (Objects.isNull(b)) { + return 1; + } else { + return String.CASE_INSENSITIVE_ORDER.compare(a, b); + } }; - } - static String format(Date value) { - return STANDARD_DATE_FORMAT.get().format(value); - } + private OkHttpClient client; - static boolean permitsRequestBody(String method) { - return !(method.equals("GET") || method.equals("HEAD")); - } - - /** Returns true if the response must have a (possibly 0-length) body. See RFC 7231. */ - static boolean hasBody(Response response) { - // HEAD requests never yield a body regardless of the response headers. - if (response.request().method().equals("HEAD")) { - return false; + public ObsoleteUrlFactory(OkHttpClient client) { + this.client = client; } - int responseCode = response.code(); - if ((responseCode < HTTP_CONTINUE || responseCode >= 200) - && responseCode != HTTP_NO_CONTENT - && responseCode != HTTP_NOT_MODIFIED) { - return true; + public OkHttpClient client() { + return client; } - // If the Content-Length or Transfer-Encoding headers disagree with the response code, the - // response is malformed. For best compatibility, we honor the headers. - if (contentLength(response.headers()) != -1 - || "chunked".equalsIgnoreCase(response.header("Transfer-Encoding"))) { - return true; + public ObsoleteUrlFactory setClient(OkHttpClient client) { + this.client = client; + return this; } - return false; - } - - static long contentLength(Headers headers) { - String s = headers.get("Content-Length"); - if (s == null) return -1; - try { - return Long.parseLong(s); - } catch (NumberFormatException e) { - return -1; - } - } - - static String responseSourceHeader(Response response) { - Response networkResponse = response.networkResponse(); - if (networkResponse == null) { - return response.cacheResponse() == null - ? "NONE" - : "CACHE " + response.code(); - } else { - return response.cacheResponse() == null - ? "NETWORK " + response.code() - : "CONDITIONAL_CACHE " + networkResponse.code(); - } - } - - static String statusLineToString(Response response) { - return (response.protocol() == Protocol.HTTP_1_0 ? "HTTP/1.0" : "HTTP/1.1") - + ' ' + response.code() - + ' ' + response.message(); - } - - static String toHumanReadableAscii(String s) { - for (int i = 0, length = s.length(), c; i < length; i += Character.charCount(c)) { - c = s.codePointAt(i); - if (c > '\u001f' && c < '\u007f') continue; - - Buffer buffer = new Buffer(); - buffer.writeUtf8(s, 0, i); - buffer.writeUtf8CodePoint('?'); - for (int j = i + Character.charCount(c); j < length; j += Character.charCount(c)) { - c = s.codePointAt(j); - buffer.writeUtf8CodePoint(c > '\u001f' && c < '\u007f' ? c : '?'); - } - return buffer.readUtf8(); - } - return s; - } - - static Map> toMultimap(Headers headers, @Nullable String valueForNullKey) { - Map> result = new TreeMap<>(FIELD_NAME_COMPARATOR); - for (int i = 0, size = headers.size(); i < size; i++) { - String fieldName = headers.name(i); - String value = headers.value(i); - - List allValues = new ArrayList<>(); - List otherValues = result.get(fieldName); - if (otherValues != null) { - allValues.addAll(otherValues); - } - allValues.add(value); - result.put(fieldName, Collections.unmodifiableList(allValues)); - } - if (valueForNullKey != null) { - result.put(null, Collections.unmodifiableList(Collections.singletonList(valueForNullKey))); - } - return Collections.unmodifiableMap(result); - } - - static String getSystemProperty(String key, @Nullable String defaultValue) { - String value; - try { - value = System.getProperty(key); - } catch (AccessControlException ex) { - return defaultValue; - } - return value != null ? value : defaultValue; - } - - static String defaultUserAgent() { - String agent = getSystemProperty("http.agent", null); - return agent != null ? toHumanReadableAscii(agent) : "ObsoleteUrlFactory"; - } - - static IOException propagate(Throwable throwable) throws IOException { - if (throwable instanceof IOException) throw (IOException) throwable; - if (throwable instanceof Error) throw (Error) throwable; - if (throwable instanceof RuntimeException) throw (RuntimeException) throwable; - throw new AssertionError(); - } - - static final class OkHttpURLConnection extends HttpURLConnection implements Callback { - // These fields are confined to the application thread that uses HttpURLConnection. - OkHttpClient client; - final NetworkInterceptor networkInterceptor = new NetworkInterceptor(); - Headers.Builder requestHeaders = new Headers.Builder(); - Headers responseHeaders; - boolean executed; - Call call; - - /** Like the superclass field of the same name, but a long and available on all platforms. */ - long fixedContentLength = -1L; - - // These fields are guarded by lock. - private final Object lock = new Object(); - private Response response; - private Throwable callFailure; - Response networkResponse; - boolean connectPending = true; - Proxy proxy; - Handshake handshake; - - OkHttpURLConnection(URL url, OkHttpClient client) { - super(url); - this.client = client; + /** + * Returns a copy of this stream handler factory that includes a shallow copy of the internal + * {@linkplain OkHttpClient HTTP client}. + */ + @Override + public ObsoleteUrlFactory clone() { + return new ObsoleteUrlFactory(client); } - @Override public void connect() throws IOException { - if (executed) return; + public HttpURLConnection open(URL url) { + return open(url, client.proxy()); + } - Call call = buildCall(); - executed = true; - call.enqueue(this); + HttpURLConnection open(URL url, @Nullable Proxy proxy) { + String protocol = url.getProtocol(); + OkHttpClient copy = client.newBuilder().proxy(proxy).build(); - synchronized (lock) { - try { - while (connectPending && response == null && callFailure == null) { - lock.wait(); // Wait 'til the network interceptor is reached or the call fails. - } - if (callFailure != null) { - throw propagate(callFailure); - } - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); // Retain interrupted status. - throw new InterruptedIOException(); - } - } + if (protocol.equals("http")) + return new OkHttpURLConnection(url, copy); + if (protocol.equals("https")) + return new OkHttpsURLConnection(url, copy); + throw new IllegalArgumentException("Unexpected protocol: " + protocol); } - @Override public void disconnect() { - // Calling disconnect() before a connection exists should have no effect. - if (call == null) return; + /** + * Creates a URLStreamHandler as a {@link java.net.URL#setURLStreamHandlerFactory}. + * + *

+ * This code configures OkHttp to handle all HTTP and HTTPS connections created with + * {@link java.net.URL#openConnection()}: + * + *

+     * {
+     *     @code
+     *
+     *     OkHttpClient okHttpClient = new OkHttpClient();
+     *     URL.setURLStreamHandlerFactory(new ObsoleteUrlFactory(okHttpClient));
+     * }
+     * 
+ */ + @Override + public URLStreamHandler createURLStreamHandler(final String protocol) { + if (!protocol.equals("http") && !protocol.equals("https")) + return null; - networkInterceptor.proceed(); // Unblock any waiting async thread. - call.cancel(); - } + return new URLStreamHandler() { + @Override + protected URLConnection openConnection(URL url) { + return open(url); + } - @SuppressFBWarnings(value = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE", - justification = "hasBody checks for this") - @Override public InputStream getErrorStream() { - try { - Response response = getResponse(true); - if (hasBody(response) && response.code() >= HTTP_BAD_REQUEST) { - return response.body().byteStream(); - } - return null; - } catch (IOException e) { - return null; - } - } + @Override + protected URLConnection openConnection(URL url, Proxy proxy) { + return open(url, proxy); + } - Headers getHeaders() throws IOException { - if (responseHeaders == null) { - Response response = getResponse(true); - Headers headers = response.headers(); - responseHeaders = headers.newBuilder() - .add(SELECTED_PROTOCOL, response.protocol().toString()) - .add(RESPONSE_SOURCE, responseSourceHeader(response)) - .build(); - } - return responseHeaders; + @Override + protected int getDefaultPort() { + if (protocol.equals("http")) + return 80; + if (protocol.equals("https")) + return 443; + throw new AssertionError(); + } + }; } - @Override public String getHeaderField(int position) { - try { - Headers headers = getHeaders(); - if (position < 0 || position >= headers.size()) return null; - return headers.value(position); - } catch (IOException e) { - return null; - } + static String format(Date value) { + return STANDARD_DATE_FORMAT.get().format(value); } - @Override public String getHeaderField(String fieldName) { - try { - return fieldName == null - ? statusLineToString(getResponse(true)) - : getHeaders().get(fieldName); - } catch (IOException e) { - return null; - } + static boolean permitsRequestBody(String method) { + return !(method.equals("GET") || method.equals("HEAD")); } - @Override public String getHeaderFieldKey(int position) { - try { - Headers headers = getHeaders(); - if (position < 0 || position >= headers.size()) return null; - return headers.name(position); - } catch (IOException e) { - return null; - } - } + /** Returns true if the response must have a (possibly 0-length) body. See RFC 7231. */ + static boolean hasBody(Response response) { + // HEAD requests never yield a body regardless of the response headers. + if (response.request().method().equals("HEAD")) { + return false; + } - @Override public Map> getHeaderFields() { - try { - return toMultimap(getHeaders(), statusLineToString(getResponse(true))); - } catch (IOException e) { - return Collections.emptyMap(); - } - } + int responseCode = response.code(); + if ((responseCode < HTTP_CONTINUE || responseCode >= 200) && responseCode != HTTP_NO_CONTENT + && responseCode != HTTP_NOT_MODIFIED) { + return true; + } - @Override public Map> getRequestProperties() { - if (connected) { - throw new IllegalStateException( - "Cannot access request header fields after connection is set"); - } + // If the Content-Length or Transfer-Encoding headers disagree with the response code, the + // response is malformed. For best compatibility, we honor the headers. + if (contentLength(response.headers()) != -1 + || "chunked".equalsIgnoreCase(response.header("Transfer-Encoding"))) { + return true; + } - return toMultimap(requestHeaders.build(), null); + return false; } - @SuppressFBWarnings(value = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE", - justification = "Good request will have body") - @Override public InputStream getInputStream() throws IOException { - if (!doInput) { - throw new ProtocolException("This protocol does not support input"); - } - - Response response = getResponse(false); - if (response.code() >= HTTP_BAD_REQUEST) throw new FileNotFoundException(url.toString()); - return response.body().byteStream(); + static long contentLength(Headers headers) { + String s = headers.get("Content-Length"); + if (s == null) + return -1; + try { + return Long.parseLong(s); + } catch (NumberFormatException e) { + return -1; + } } - @Override public OutputStream getOutputStream() throws IOException { - OutputStreamRequestBody requestBody = (OutputStreamRequestBody) buildCall().request().body(); - if (requestBody == null) { - throw new ProtocolException("method does not support a request body: " + method); - } + static String responseSourceHeader(Response response) { + Response networkResponse = response.networkResponse(); + if (networkResponse == null) { + return response.cacheResponse() == null ? "NONE" : "CACHE " + response.code(); + } else { + return response.cacheResponse() == null ? "NETWORK " + response.code() + : "CONDITIONAL_CACHE " + networkResponse.code(); + } + } - if (requestBody instanceof StreamedRequestBody) { - connect(); - networkInterceptor.proceed(); - } + static String statusLineToString(Response response) { + return (response.protocol() == Protocol.HTTP_1_0 ? "HTTP/1.0" : "HTTP/1.1") + ' ' + response.code() + ' ' + + response.message(); + } - if (requestBody.closed) { - throw new ProtocolException("cannot write request body after response has been read"); - } + static String toHumanReadableAscii(String s) { + for (int i = 0, length = s.length(), c; i < length; i += Character.charCount(c)) { + c = s.codePointAt(i); + if (c > '\u001f' && c < '\u007f') + continue; - return requestBody.outputStream; + Buffer buffer = new Buffer(); + buffer.writeUtf8(s, 0, i); + buffer.writeUtf8CodePoint('?'); + for (int j = i + Character.charCount(c); j < length; j += Character.charCount(c)) { + c = s.codePointAt(j); + buffer.writeUtf8CodePoint(c > '\u001f' && c < '\u007f' ? c : '?'); + } + return buffer.readUtf8(); + } + return s; } - @SuppressFBWarnings(value = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE", - justification = "usingProxy() handles this") - @Override public Permission getPermission() { - URL url = getURL(); - String hostname = url.getHost(); - int hostPort = url.getPort() != -1 - ? url.getPort() - : HttpUrl.defaultPort(url.getProtocol()); - if (usingProxy()) { - InetSocketAddress proxyAddress = (InetSocketAddress) client.proxy().address(); - hostname = proxyAddress.getHostName(); - hostPort = proxyAddress.getPort(); - } - return new SocketPermission(hostname + ":" + hostPort, "connect, resolve"); - } + static Map> toMultimap(Headers headers, @Nullable String valueForNullKey) { + Map> result = new TreeMap<>(FIELD_NAME_COMPARATOR); + for (int i = 0, size = headers.size(); i < size; i++) { + String fieldName = headers.name(i); + String value = headers.value(i); - @Override public String getRequestProperty(String field) { - if (field == null) return null; - return requestHeaders.get(field); + List allValues = new ArrayList<>(); + List otherValues = result.get(fieldName); + if (otherValues != null) { + allValues.addAll(otherValues); + } + allValues.add(value); + result.put(fieldName, Collections.unmodifiableList(allValues)); + } + if (valueForNullKey != null) { + result.put(null, Collections.unmodifiableList(Collections.singletonList(valueForNullKey))); + } + return Collections.unmodifiableMap(result); } - @Override public void setConnectTimeout(int timeoutMillis) { - client = client.newBuilder() - .connectTimeout(timeoutMillis, TimeUnit.MILLISECONDS) - .build(); + static String getSystemProperty(String key, @Nullable String defaultValue) { + String value; + try { + value = System.getProperty(key); + } catch (AccessControlException ex) { + return defaultValue; + } + return value != null ? value : defaultValue; } - @Override public void setInstanceFollowRedirects(boolean followRedirects) { - client = client.newBuilder() - .followRedirects(followRedirects) - .build(); + static String defaultUserAgent() { + String agent = getSystemProperty("http.agent", null); + return agent != null ? toHumanReadableAscii(agent) : "ObsoleteUrlFactory"; } - @Override public boolean getInstanceFollowRedirects() { - return client.followRedirects(); + static IOException propagate(Throwable throwable) throws IOException { + if (throwable instanceof IOException) + throw (IOException) throwable; + if (throwable instanceof Error) + throw (Error) throwable; + if (throwable instanceof RuntimeException) + throw (RuntimeException) throwable; + throw new AssertionError(); } - @Override public int getConnectTimeout() { - return client.connectTimeoutMillis(); - } + static final class OkHttpURLConnection extends HttpURLConnection implements Callback { + // These fields are confined to the application thread that uses HttpURLConnection. + OkHttpClient client; + final NetworkInterceptor networkInterceptor = new NetworkInterceptor(); + Headers.Builder requestHeaders = new Headers.Builder(); + Headers responseHeaders; + boolean executed; + Call call; + + /** Like the superclass field of the same name, but a long and available on all platforms. */ + long fixedContentLength = -1L; + + // These fields are guarded by lock. + private final Object lock = new Object(); + private Response response; + private Throwable callFailure; + Response networkResponse; + boolean connectPending = true; + Proxy proxy; + Handshake handshake; + + OkHttpURLConnection(URL url, OkHttpClient client) { + super(url); + this.client = client; + } - @Override public void setReadTimeout(int timeoutMillis) { - client = client.newBuilder() - .readTimeout(timeoutMillis, TimeUnit.MILLISECONDS) - .build(); - } + @Override + public void connect() throws IOException { + if (executed) + return; + + Call call = buildCall(); + executed = true; + call.enqueue(this); + + synchronized (lock) { + try { + while (connectPending && response == null && callFailure == null) { + lock.wait(); // Wait 'til the network interceptor is reached or the call fails. + } + if (callFailure != null) { + throw propagate(callFailure); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); // Retain interrupted status. + throw new InterruptedIOException(); + } + } + } - @Override public int getReadTimeout() { - return client.readTimeoutMillis(); - } + @Override + public void disconnect() { + // Calling disconnect() before a connection exists should have no effect. + if (call == null) + return; - @SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE") - private Call buildCall() throws IOException { - if (call != null) { - return call; - } + networkInterceptor.proceed(); // Unblock any waiting async thread. + call.cancel(); + } - connected = true; - if (doOutput) { - if (method.equals("GET")) { - method = "POST"; - } else if (!permitsRequestBody(method)) { - throw new ProtocolException(method + " does not support writing"); + @SuppressFBWarnings(value = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE", justification = "hasBody checks for this") + @Override + public InputStream getErrorStream() { + try { + Response response = getResponse(true); + if (hasBody(response) && response.code() >= HTTP_BAD_REQUEST) { + return response.body().byteStream(); + } + return null; + } catch (IOException e) { + return null; + } } - } - if (requestHeaders.get("User-Agent") == null) { - requestHeaders.add("User-Agent", defaultUserAgent()); - } + Headers getHeaders() throws IOException { + if (responseHeaders == null) { + Response response = getResponse(true); + Headers headers = response.headers(); + responseHeaders = headers.newBuilder().add(SELECTED_PROTOCOL, response.protocol().toString()) + .add(RESPONSE_SOURCE, responseSourceHeader(response)).build(); + } + return responseHeaders; + } - OutputStreamRequestBody requestBody = null; - if (permitsRequestBody(method)) { - String contentType = requestHeaders.get("Content-Type"); - if (contentType == null) { - contentType = "application/x-www-form-urlencoded"; - requestHeaders.add("Content-Type", contentType); + @Override + public String getHeaderField(int position) { + try { + Headers headers = getHeaders(); + if (position < 0 || position >= headers.size()) + return null; + return headers.value(position); + } catch (IOException e) { + return null; + } } - boolean stream = fixedContentLength != -1L || chunkLength > 0; + @Override + public String getHeaderField(String fieldName) { + try { + return fieldName == null ? statusLineToString(getResponse(true)) : getHeaders().get(fieldName); + } catch (IOException e) { + return null; + } + } - long contentLength = -1L; - String contentLengthString = requestHeaders.get("Content-Length"); - if (fixedContentLength != -1L) { - contentLength = fixedContentLength; - } else if (contentLengthString != null) { - contentLength = Long.parseLong(contentLengthString); - } - - requestBody = stream - ? new StreamedRequestBody(contentLength) - : new BufferedRequestBody(contentLength); - requestBody.timeout.timeout(client.writeTimeoutMillis(), TimeUnit.MILLISECONDS); - } - - HttpUrl url; - try { - url = HttpUrl.get(getURL().toString()); - } catch (IllegalArgumentException e) { - MalformedURLException malformedUrl = new MalformedURLException(); - malformedUrl.initCause(e); - throw malformedUrl; - } - - Request request = new Request.Builder() - .url(url) - .headers(requestHeaders.build()) - .method(method, requestBody) - .build(); - - OkHttpClient.Builder clientBuilder = client.newBuilder(); - clientBuilder.interceptors().clear(); - clientBuilder.interceptors().add(UnexpectedException.INTERCEPTOR); - clientBuilder.networkInterceptors().clear(); - clientBuilder.networkInterceptors().add(networkInterceptor); - - // Use a separate dispatcher so that limits aren't impacted. But use the same executor service! - clientBuilder.dispatcher(new Dispatcher(client.dispatcher().executorService())); - - // If we're currently not using caches, make sure the engine's client doesn't have one. - if (!getUseCaches()) { - clientBuilder.cache(null); - } - - return call = clientBuilder.build().newCall(request); - } + @Override + public String getHeaderFieldKey(int position) { + try { + Headers headers = getHeaders(); + if (position < 0 || position >= headers.size()) + return null; + return headers.name(position); + } catch (IOException e) { + return null; + } + } - private Response getResponse(boolean networkResponseOnError) throws IOException { - synchronized (lock) { - if (response != null) return response; - if (callFailure != null) { - if (networkResponseOnError && networkResponse != null) return networkResponse; - throw propagate(callFailure); + @Override + public Map> getHeaderFields() { + try { + return toMultimap(getHeaders(), statusLineToString(getResponse(true))); + } catch (IOException e) { + return Collections.emptyMap(); + } } - } - Call call = buildCall(); - networkInterceptor.proceed(); + @Override + public Map> getRequestProperties() { + if (connected) { + throw new IllegalStateException("Cannot access request header fields after connection is set"); + } - OutputStreamRequestBody requestBody = (OutputStreamRequestBody) call.request().body(); - if (requestBody != null) requestBody.outputStream.close(); + return toMultimap(requestHeaders.build(), null); + } - if (executed) { - synchronized (lock) { - try { - while (response == null && callFailure == null) { - lock.wait(); // Wait until the response is returned or the call fails. + @SuppressFBWarnings(value = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE", justification = "Good request will have body") + @Override + public InputStream getInputStream() throws IOException { + if (!doInput) { + throw new ProtocolException("This protocol does not support input"); } - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); // Retain interrupted status. - throw new InterruptedIOException(); - } + + Response response = getResponse(false); + if (response.code() >= HTTP_BAD_REQUEST) + throw new FileNotFoundException(url.toString()); + return response.body().byteStream(); } - } else { - executed = true; - try { - onResponse(call, call.execute()); - } catch (IOException e) { - onFailure(call, e); + + @Override + public OutputStream getOutputStream() throws IOException { + OutputStreamRequestBody requestBody = (OutputStreamRequestBody) buildCall().request().body(); + if (requestBody == null) { + throw new ProtocolException("method does not support a request body: " + method); + } + + if (requestBody instanceof StreamedRequestBody) { + connect(); + networkInterceptor.proceed(); + } + + if (requestBody.closed) { + throw new ProtocolException("cannot write request body after response has been read"); + } + + return requestBody.outputStream; } - } - synchronized (lock) { - if (callFailure != null) throw propagate(callFailure); - if (response != null) return response; - } + @SuppressFBWarnings(value = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE", justification = "usingProxy() handles this") + @Override + public Permission getPermission() { + URL url = getURL(); + String hostname = url.getHost(); + int hostPort = url.getPort() != -1 ? url.getPort() : HttpUrl.defaultPort(url.getProtocol()); + if (usingProxy()) { + InetSocketAddress proxyAddress = (InetSocketAddress) client.proxy().address(); + hostname = proxyAddress.getHostName(); + hostPort = proxyAddress.getPort(); + } + return new SocketPermission(hostname + ":" + hostPort, "connect, resolve"); + } - throw new AssertionError(); - } + @Override + public String getRequestProperty(String field) { + if (field == null) + return null; + return requestHeaders.get(field); + } - @Override public boolean usingProxy() { - if (proxy != null) return true; - Proxy clientProxy = client.proxy(); - return clientProxy != null && clientProxy.type() != Proxy.Type.DIRECT; - } + @Override + public void setConnectTimeout(int timeoutMillis) { + client = client.newBuilder().connectTimeout(timeoutMillis, TimeUnit.MILLISECONDS).build(); + } - @Override public String getResponseMessage() throws IOException { - return getResponse(true).message(); - } + @Override + public void setInstanceFollowRedirects(boolean followRedirects) { + client = client.newBuilder().followRedirects(followRedirects).build(); + } - @Override public int getResponseCode() throws IOException { - return getResponse(true).code(); - } + @Override + public boolean getInstanceFollowRedirects() { + return client.followRedirects(); + } - @Override public void setRequestProperty(String field, String newValue) { - if (connected) { - throw new IllegalStateException("Cannot set request property after connection is made"); - } - if (field == null) { - throw new NullPointerException("field == null"); - } - if (newValue == null) { - return; - } - - requestHeaders.set(field, newValue); - } + @Override + public int getConnectTimeout() { + return client.connectTimeoutMillis(); + } - @Override public void setIfModifiedSince(long newValue) { - super.setIfModifiedSince(newValue); - if (ifModifiedSince != 0) { - requestHeaders.set("If-Modified-Since", format(new Date(ifModifiedSince))); - } else { - requestHeaders.removeAll("If-Modified-Since"); - } - } + @Override + public void setReadTimeout(int timeoutMillis) { + client = client.newBuilder().readTimeout(timeoutMillis, TimeUnit.MILLISECONDS).build(); + } - @Override public void addRequestProperty(String field, String value) { - if (connected) { - throw new IllegalStateException("Cannot add request property after connection is made"); - } - if (field == null) { - throw new NullPointerException("field == null"); - } - if (value == null) { - return; - } - - requestHeaders.add(field, value); - } + @Override + public int getReadTimeout() { + return client.readTimeoutMillis(); + } - @Override public void setRequestMethod(String method) throws ProtocolException { - if (!METHODS.contains(method)) { - throw new ProtocolException("Expected one of " + METHODS + " but was " + method); - } - this.method = method; - } + @SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE") + private Call buildCall() throws IOException { + if (call != null) { + return call; + } - @Override public void setFixedLengthStreamingMode(int contentLength) { - setFixedLengthStreamingMode((long) contentLength); - } + connected = true; + if (doOutput) { + if (method.equals("GET")) { + method = "POST"; + } else if (!permitsRequestBody(method)) { + throw new ProtocolException(method + " does not support writing"); + } + } - @Override public void setFixedLengthStreamingMode(long contentLength) { - if (super.connected) throw new IllegalStateException("Already connected"); - if (chunkLength > 0) throw new IllegalStateException("Already in chunked mode"); - if (contentLength < 0) throw new IllegalArgumentException("contentLength < 0"); - this.fixedContentLength = contentLength; - super.fixedContentLength = (int) Math.min(contentLength, Integer.MAX_VALUE); - } + if (requestHeaders.get("User-Agent") == null) { + requestHeaders.add("User-Agent", defaultUserAgent()); + } - @Override public void onFailure(Call call, IOException e) { - synchronized (lock) { - this.callFailure = (e instanceof UnexpectedException) ? e.getCause() : e; - lock.notifyAll(); - } - } + OutputStreamRequestBody requestBody = null; + if (permitsRequestBody(method)) { + String contentType = requestHeaders.get("Content-Type"); + if (contentType == null) { + contentType = "application/x-www-form-urlencoded"; + requestHeaders.add("Content-Type", contentType); + } + + boolean stream = fixedContentLength != -1L || chunkLength > 0; + + long contentLength = -1L; + String contentLengthString = requestHeaders.get("Content-Length"); + if (fixedContentLength != -1L) { + contentLength = fixedContentLength; + } else if (contentLengthString != null) { + contentLength = Long.parseLong(contentLengthString); + } + + requestBody = stream ? new StreamedRequestBody(contentLength) : new BufferedRequestBody(contentLength); + requestBody.timeout.timeout(client.writeTimeoutMillis(), TimeUnit.MILLISECONDS); + } - @Override public void onResponse(Call call, Response response) { - synchronized (lock) { - this.response = response; - this.handshake = response.handshake(); - this.url = response.request().url().url(); - lock.notifyAll(); - } - } + HttpUrl url; + try { + url = HttpUrl.get(getURL().toString()); + } catch (IllegalArgumentException e) { + MalformedURLException malformedUrl = new MalformedURLException(); + malformedUrl.initCause(e); + throw malformedUrl; + } - final class NetworkInterceptor implements Interceptor { - // Guarded by HttpUrlConnection.this. - private boolean proceed; + Request request = new Request.Builder().url(url).headers(requestHeaders.build()).method(method, requestBody) + .build(); + + OkHttpClient.Builder clientBuilder = client.newBuilder(); + clientBuilder.interceptors().clear(); + clientBuilder.interceptors().add(UnexpectedException.INTERCEPTOR); + clientBuilder.networkInterceptors().clear(); + clientBuilder.networkInterceptors().add(networkInterceptor); + + // Use a separate dispatcher so that limits aren't impacted. But use the same executor service! + clientBuilder.dispatcher(new Dispatcher(client.dispatcher().executorService())); + + // If we're currently not using caches, make sure the engine's client doesn't have one. + if (!getUseCaches()) { + clientBuilder.cache(null); + } - public void proceed() { - synchronized (lock) { - this.proceed = true; - lock.notifyAll(); + return call = clientBuilder.build().newCall(request); } - } - @SuppressFBWarnings(value = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE", - justification = "If we get here there is a connection and request.body() is checked") - @Override public Response intercept(Chain chain) throws IOException { - Request request = chain.request(); + private Response getResponse(boolean networkResponseOnError) throws IOException { + synchronized (lock) { + if (response != null) + return response; + if (callFailure != null) { + if (networkResponseOnError && networkResponse != null) + return networkResponse; + throw propagate(callFailure); + } + } - synchronized (lock) { - connectPending = false; - proxy = chain.connection().route().proxy(); - handshake = chain.connection().handshake(); - lock.notifyAll(); + Call call = buildCall(); + networkInterceptor.proceed(); + + OutputStreamRequestBody requestBody = (OutputStreamRequestBody) call.request().body(); + if (requestBody != null) + requestBody.outputStream.close(); + + if (executed) { + synchronized (lock) { + try { + while (response == null && callFailure == null) { + lock.wait(); // Wait until the response is returned or the call fails. + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); // Retain interrupted status. + throw new InterruptedIOException(); + } + } + } else { + executed = true; + try { + onResponse(call, call.execute()); + } catch (IOException e) { + onFailure(call, e); + } + } - try { - while (!proceed) { - lock.wait(); // Wait until proceed() is called. + synchronized (lock) { + if (callFailure != null) + throw propagate(callFailure); + if (response != null) + return response; } - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); // Retain interrupted status. - throw new InterruptedIOException(); - } + + throw new AssertionError(); } - // Try to lock in the Content-Length before transmitting the request body. - if (request.body() instanceof OutputStreamRequestBody) { - OutputStreamRequestBody requestBody = (OutputStreamRequestBody) request.body(); - request = requestBody.prepareToSendRequest(request); + @Override + public boolean usingProxy() { + if (proxy != null) + return true; + Proxy clientProxy = client.proxy(); + return clientProxy != null && clientProxy.type() != Proxy.Type.DIRECT; } - Response response = chain.proceed(request); + @Override + public String getResponseMessage() throws IOException { + return getResponse(true).message(); + } - synchronized (lock) { - networkResponse = response; - url = response.request().url().url(); + @Override + public int getResponseCode() throws IOException { + return getResponse(true).code(); } - return response; - } - } - } + @Override + public void setRequestProperty(String field, String newValue) { + if (connected) { + throw new IllegalStateException("Cannot set request property after connection is made"); + } + if (field == null) { + throw new NullPointerException("field == null"); + } + if (newValue == null) { + return; + } - abstract static class OutputStreamRequestBody extends RequestBody { - Timeout timeout; - long expectedContentLength; - OutputStream outputStream; - boolean closed; + requestHeaders.set(field, newValue); + } - void initOutputStream(BufferedSink sink, long expectedContentLength) { - this.timeout = sink.timeout(); - this.expectedContentLength = expectedContentLength; + @Override + public void setIfModifiedSince(long newValue) { + super.setIfModifiedSince(newValue); + if (ifModifiedSince != 0) { + requestHeaders.set("If-Modified-Since", format(new Date(ifModifiedSince))); + } else { + requestHeaders.removeAll("If-Modified-Since"); + } + } - // An output stream that writes to sink. If expectedContentLength is not -1, then this expects - // exactly that many bytes to be written. - this.outputStream = new OutputStream() { - private long bytesReceived; + @Override + public void addRequestProperty(String field, String value) { + if (connected) { + throw new IllegalStateException("Cannot add request property after connection is made"); + } + if (field == null) { + throw new NullPointerException("field == null"); + } + if (value == null) { + return; + } + + requestHeaders.add(field, value); + } - @Override public void write(int b) throws IOException { - write(new byte[] {(byte) b}, 0, 1); + @Override + public void setRequestMethod(String method) throws ProtocolException { + if (!METHODS.contains(method)) { + throw new ProtocolException("Expected one of " + METHODS + " but was " + method); + } + this.method = method; } - @Override public void write(byte[] source, int offset, int byteCount) throws IOException { - if (closed) throw new IOException("closed"); // Not IllegalStateException! + @Override + public void setFixedLengthStreamingMode(int contentLength) { + setFixedLengthStreamingMode((long) contentLength); + } - if (expectedContentLength != -1L && bytesReceived + byteCount > expectedContentLength) { - throw new ProtocolException("expected " + expectedContentLength - + " bytes but received " + bytesReceived + byteCount); - } + @Override + public void setFixedLengthStreamingMode(long contentLength) { + if (super.connected) + throw new IllegalStateException("Already connected"); + if (chunkLength > 0) + throw new IllegalStateException("Already in chunked mode"); + if (contentLength < 0) + throw new IllegalArgumentException("contentLength < 0"); + this.fixedContentLength = contentLength; + super.fixedContentLength = (int) Math.min(contentLength, Integer.MAX_VALUE); + } - bytesReceived += byteCount; - try { - sink.write(source, offset, byteCount); - } catch (InterruptedIOException e) { - throw new SocketTimeoutException(e.getMessage()); - } + @Override + public void onFailure(Call call, IOException e) { + synchronized (lock) { + this.callFailure = (e instanceof UnexpectedException) ? e.getCause() : e; + lock.notifyAll(); + } } - @Override public void flush() throws IOException { - if (closed) return; // Weird, but consistent with historical behavior. - sink.flush(); + @Override + public void onResponse(Call call, Response response) { + synchronized (lock) { + this.response = response; + this.handshake = response.handshake(); + this.url = response.request().url().url(); + lock.notifyAll(); + } } - @Override public void close() throws IOException { - closed = true; + final class NetworkInterceptor implements Interceptor { + // Guarded by HttpUrlConnection.this. + private boolean proceed; - if (expectedContentLength != -1L && bytesReceived < expectedContentLength) { - throw new ProtocolException("expected " + expectedContentLength - + " bytes but received " + bytesReceived); - } + public void proceed() { + synchronized (lock) { + this.proceed = true; + lock.notifyAll(); + } + } - sink.close(); + @SuppressFBWarnings(value = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE", justification = "If we get here there is a connection and request.body() is checked") + @Override + public Response intercept(Chain chain) throws IOException { + Request request = chain.request(); + + synchronized (lock) { + connectPending = false; + proxy = chain.connection().route().proxy(); + handshake = chain.connection().handshake(); + lock.notifyAll(); + + try { + while (!proceed) { + lock.wait(); // Wait until proceed() is called. + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); // Retain interrupted status. + throw new InterruptedIOException(); + } + } + + // Try to lock in the Content-Length before transmitting the request body. + if (request.body() instanceof OutputStreamRequestBody) { + OutputStreamRequestBody requestBody = (OutputStreamRequestBody) request.body(); + request = requestBody.prepareToSendRequest(request); + } + + Response response = chain.proceed(request); + + synchronized (lock) { + networkResponse = response; + url = response.request().url().url(); + } + + return response; + } } - }; } - @Override public long contentLength() { - return expectedContentLength; - } + abstract static class OutputStreamRequestBody extends RequestBody { + Timeout timeout; + long expectedContentLength; + OutputStream outputStream; + boolean closed; + + void initOutputStream(BufferedSink sink, long expectedContentLength) { + this.timeout = sink.timeout(); + this.expectedContentLength = expectedContentLength; + + // An output stream that writes to sink. If expectedContentLength is not -1, then this expects + // exactly that many bytes to be written. + this.outputStream = new OutputStream() { + private long bytesReceived; + + @Override + public void write(int b) throws IOException { + write(new byte[] { (byte) b }, 0, 1); + } + + @Override + public void write(byte[] source, int offset, int byteCount) throws IOException { + if (closed) + throw new IOException("closed"); // Not IllegalStateException! + + if (expectedContentLength != -1L && bytesReceived + byteCount > expectedContentLength) { + throw new ProtocolException("expected " + expectedContentLength + " bytes but received " + + bytesReceived + byteCount); + } + + bytesReceived += byteCount; + try { + sink.write(source, offset, byteCount); + } catch (InterruptedIOException e) { + throw new SocketTimeoutException(e.getMessage()); + } + } + + @Override + public void flush() throws IOException { + if (closed) + return; // Weird, but consistent with historical behavior. + sink.flush(); + } + + @Override + public void close() throws IOException { + closed = true; + + if (expectedContentLength != -1L && bytesReceived < expectedContentLength) { + throw new ProtocolException( + "expected " + expectedContentLength + " bytes but received " + bytesReceived); + } + + sink.close(); + } + }; + } - @Override public final @Nullable MediaType contentType() { - return null; // Let the caller provide this in a regular header. - } + @Override + public long contentLength() { + return expectedContentLength; + } + + @Override + public final @Nullable MediaType contentType() { + return null; // Let the caller provide this in a regular header. + } - public Request prepareToSendRequest(Request request) throws IOException { - return request; + public Request prepareToSendRequest(Request request) throws IOException { + return request; + } } - } - static final class BufferedRequestBody extends OutputStreamRequestBody { - final Buffer buffer = new Buffer(); - long contentLength = -1L; + static final class BufferedRequestBody extends OutputStreamRequestBody { + final Buffer buffer = new Buffer(); + long contentLength = -1L; - BufferedRequestBody(long expectedContentLength) { - initOutputStream(buffer, expectedContentLength); - } + BufferedRequestBody(long expectedContentLength) { + initOutputStream(buffer, expectedContentLength); + } - @Override public long contentLength() { - return contentLength; - } + @Override + public long contentLength() { + return contentLength; + } - @Override public Request prepareToSendRequest(Request request) throws IOException { - if (request.header("Content-Length") != null) return request; + @Override + public Request prepareToSendRequest(Request request) throws IOException { + if (request.header("Content-Length") != null) + return request; - outputStream.close(); - contentLength = buffer.size(); - return request.newBuilder() - .removeHeader("Transfer-Encoding") - .header("Content-Length", Long.toString(buffer.size())) - .build(); - } + outputStream.close(); + contentLength = buffer.size(); + return request.newBuilder().removeHeader("Transfer-Encoding") + .header("Content-Length", Long.toString(buffer.size())).build(); + } - @Override public void writeTo(BufferedSink sink) { - buffer.copyTo(sink.buffer(), 0, buffer.size()); + @Override + public void writeTo(BufferedSink sink) { + buffer.copyTo(sink.buffer(), 0, buffer.size()); + } } - } - static final class StreamedRequestBody extends OutputStreamRequestBody { - private final Pipe pipe = new Pipe(8192); + static final class StreamedRequestBody extends OutputStreamRequestBody { + private final Pipe pipe = new Pipe(8192); - StreamedRequestBody(long expectedContentLength) { - initOutputStream(Okio.buffer(pipe.sink()), expectedContentLength); - } + StreamedRequestBody(long expectedContentLength) { + initOutputStream(Okio.buffer(pipe.sink()), expectedContentLength); + } - public boolean isOneShot() { - return true; - } + public boolean isOneShot() { + return true; + } - @Override public void writeTo(BufferedSink sink) throws IOException { - Buffer buffer = new Buffer(); - while (pipe.source().read(buffer, 8192) != -1L) { - sink.write(buffer, buffer.size()); - } + @Override + public void writeTo(BufferedSink sink) throws IOException { + Buffer buffer = new Buffer(); + while (pipe.source().read(buffer, 8192) != -1L) { + sink.write(buffer, buffer.size()); + } + } } - } - abstract static class DelegatingHttpsURLConnection extends HttpsURLConnection { - private final HttpURLConnection delegate; + abstract static class DelegatingHttpsURLConnection extends HttpsURLConnection { + private final HttpURLConnection delegate; - DelegatingHttpsURLConnection(HttpURLConnection delegate) { - super(delegate.getURL()); - this.delegate = delegate; - } + DelegatingHttpsURLConnection(HttpURLConnection delegate) { + super(delegate.getURL()); + this.delegate = delegate; + } - protected abstract Handshake handshake(); + protected abstract Handshake handshake(); - @Override public abstract void setHostnameVerifier(HostnameVerifier hostnameVerifier); + @Override + public abstract void setHostnameVerifier(HostnameVerifier hostnameVerifier); - @Override public abstract HostnameVerifier getHostnameVerifier(); + @Override + public abstract HostnameVerifier getHostnameVerifier(); - @Override public abstract void setSSLSocketFactory(SSLSocketFactory sslSocketFactory); + @Override + public abstract void setSSLSocketFactory(SSLSocketFactory sslSocketFactory); - @Override public abstract SSLSocketFactory getSSLSocketFactory(); + @Override + public abstract SSLSocketFactory getSSLSocketFactory(); - @Override public String getCipherSuite() { - Handshake handshake = handshake(); - return handshake != null ? handshake.cipherSuite().javaName() : null; - } + @Override + public String getCipherSuite() { + Handshake handshake = handshake(); + return handshake != null ? handshake.cipherSuite().javaName() : null; + } - @Override public Certificate[] getLocalCertificates() { - Handshake handshake = handshake(); - if (handshake == null) return null; - List result = handshake.localCertificates(); - return !result.isEmpty() ? result.toArray(new Certificate[result.size()]) : null; - } + @Override + public Certificate[] getLocalCertificates() { + Handshake handshake = handshake(); + if (handshake == null) + return null; + List result = handshake.localCertificates(); + return !result.isEmpty() ? result.toArray(new Certificate[result.size()]) : null; + } - @Override public Certificate[] getServerCertificates() { - Handshake handshake = handshake(); - if (handshake == null) return null; - List result = handshake.peerCertificates(); - return !result.isEmpty() ? result.toArray(new Certificate[result.size()]) : null; - } + @Override + public Certificate[] getServerCertificates() { + Handshake handshake = handshake(); + if (handshake == null) + return null; + List result = handshake.peerCertificates(); + return !result.isEmpty() ? result.toArray(new Certificate[result.size()]) : null; + } - @Override public Principal getPeerPrincipal() { - Handshake handshake = handshake(); - return handshake != null ? handshake.peerPrincipal() : null; - } + @Override + public Principal getPeerPrincipal() { + Handshake handshake = handshake(); + return handshake != null ? handshake.peerPrincipal() : null; + } - @Override public Principal getLocalPrincipal() { - Handshake handshake = handshake(); - return handshake != null ? handshake.localPrincipal() : null; - } + @Override + public Principal getLocalPrincipal() { + Handshake handshake = handshake(); + return handshake != null ? handshake.localPrincipal() : null; + } - @Override public void connect() throws IOException { - connected = true; - delegate.connect(); - } + @Override + public void connect() throws IOException { + connected = true; + delegate.connect(); + } - @Override public void disconnect() { - delegate.disconnect(); - } + @Override + public void disconnect() { + delegate.disconnect(); + } - @Override public InputStream getErrorStream() { - return delegate.getErrorStream(); - } + @Override + public InputStream getErrorStream() { + return delegate.getErrorStream(); + } - @Override public String getRequestMethod() { - return delegate.getRequestMethod(); - } + @Override + public String getRequestMethod() { + return delegate.getRequestMethod(); + } - @Override public int getResponseCode() throws IOException { - return delegate.getResponseCode(); - } + @Override + public int getResponseCode() throws IOException { + return delegate.getResponseCode(); + } - @Override public String getResponseMessage() throws IOException { - return delegate.getResponseMessage(); - } + @Override + public String getResponseMessage() throws IOException { + return delegate.getResponseMessage(); + } - @Override public void setRequestMethod(String method) throws ProtocolException { - delegate.setRequestMethod(method); - } + @Override + public void setRequestMethod(String method) throws ProtocolException { + delegate.setRequestMethod(method); + } - @Override public boolean usingProxy() { - return delegate.usingProxy(); - } + @Override + public boolean usingProxy() { + return delegate.usingProxy(); + } - @Override public boolean getInstanceFollowRedirects() { - return delegate.getInstanceFollowRedirects(); - } + @Override + public boolean getInstanceFollowRedirects() { + return delegate.getInstanceFollowRedirects(); + } - @Override public void setInstanceFollowRedirects(boolean followRedirects) { - delegate.setInstanceFollowRedirects(followRedirects); - } + @Override + public void setInstanceFollowRedirects(boolean followRedirects) { + delegate.setInstanceFollowRedirects(followRedirects); + } - @Override public boolean getAllowUserInteraction() { - return delegate.getAllowUserInteraction(); - } + @Override + public boolean getAllowUserInteraction() { + return delegate.getAllowUserInteraction(); + } - @Override public Object getContent() throws IOException { - return delegate.getContent(); - } + @Override + public Object getContent() throws IOException { + return delegate.getContent(); + } - @Override public Object getContent(Class[] types) throws IOException { - return delegate.getContent(types); - } + @Override + public Object getContent(Class[] types) throws IOException { + return delegate.getContent(types); + } - @Override public String getContentEncoding() { - return delegate.getContentEncoding(); - } + @Override + public String getContentEncoding() { + return delegate.getContentEncoding(); + } - @Override public int getContentLength() { - return delegate.getContentLength(); - } + @Override + public int getContentLength() { + return delegate.getContentLength(); + } - // Should only be invoked on Java 8+ or Android API 24+. - @Override public long getContentLengthLong() { - return delegate.getContentLengthLong(); - } + // Should only be invoked on Java 8+ or Android API 24+. + @Override + public long getContentLengthLong() { + return delegate.getContentLengthLong(); + } - @Override public String getContentType() { - return delegate.getContentType(); - } + @Override + public String getContentType() { + return delegate.getContentType(); + } - @Override public long getDate() { - return delegate.getDate(); - } + @Override + public long getDate() { + return delegate.getDate(); + } - @Override public boolean getDefaultUseCaches() { - return delegate.getDefaultUseCaches(); - } + @Override + public boolean getDefaultUseCaches() { + return delegate.getDefaultUseCaches(); + } - @Override public boolean getDoInput() { - return delegate.getDoInput(); - } + @Override + public boolean getDoInput() { + return delegate.getDoInput(); + } - @Override public boolean getDoOutput() { - return delegate.getDoOutput(); - } + @Override + public boolean getDoOutput() { + return delegate.getDoOutput(); + } - @Override public long getExpiration() { - return delegate.getExpiration(); - } + @Override + public long getExpiration() { + return delegate.getExpiration(); + } - @Override public String getHeaderField(int pos) { - return delegate.getHeaderField(pos); - } + @Override + public String getHeaderField(int pos) { + return delegate.getHeaderField(pos); + } - @Override public Map> getHeaderFields() { - return delegate.getHeaderFields(); - } + @Override + public Map> getHeaderFields() { + return delegate.getHeaderFields(); + } - @Override public Map> getRequestProperties() { - return delegate.getRequestProperties(); - } + @Override + public Map> getRequestProperties() { + return delegate.getRequestProperties(); + } - @Override public void addRequestProperty(String field, String newValue) { - delegate.addRequestProperty(field, newValue); - } + @Override + public void addRequestProperty(String field, String newValue) { + delegate.addRequestProperty(field, newValue); + } - @Override public String getHeaderField(String key) { - return delegate.getHeaderField(key); - } + @Override + public String getHeaderField(String key) { + return delegate.getHeaderField(key); + } - // Should only be invoked on Java 8+ or Android API 24+. - @Override public long getHeaderFieldLong(String field, long defaultValue) { - return delegate.getHeaderFieldLong(field, defaultValue); - } + // Should only be invoked on Java 8+ or Android API 24+. + @Override + public long getHeaderFieldLong(String field, long defaultValue) { + return delegate.getHeaderFieldLong(field, defaultValue); + } - @Override public long getHeaderFieldDate(String field, long defaultValue) { - return delegate.getHeaderFieldDate(field, defaultValue); - } + @Override + public long getHeaderFieldDate(String field, long defaultValue) { + return delegate.getHeaderFieldDate(field, defaultValue); + } - @Override public int getHeaderFieldInt(String field, int defaultValue) { - return delegate.getHeaderFieldInt(field, defaultValue); - } + @Override + public int getHeaderFieldInt(String field, int defaultValue) { + return delegate.getHeaderFieldInt(field, defaultValue); + } - @Override public String getHeaderFieldKey(int position) { - return delegate.getHeaderFieldKey(position); - } + @Override + public String getHeaderFieldKey(int position) { + return delegate.getHeaderFieldKey(position); + } - @Override public long getIfModifiedSince() { - return delegate.getIfModifiedSince(); - } + @Override + public long getIfModifiedSince() { + return delegate.getIfModifiedSince(); + } - @Override public InputStream getInputStream() throws IOException { - return delegate.getInputStream(); - } + @Override + public InputStream getInputStream() throws IOException { + return delegate.getInputStream(); + } - @Override public long getLastModified() { - return delegate.getLastModified(); - } + @Override + public long getLastModified() { + return delegate.getLastModified(); + } - @Override public OutputStream getOutputStream() throws IOException { - return delegate.getOutputStream(); - } + @Override + public OutputStream getOutputStream() throws IOException { + return delegate.getOutputStream(); + } - @Override public Permission getPermission() throws IOException { - return delegate.getPermission(); - } + @Override + public Permission getPermission() throws IOException { + return delegate.getPermission(); + } - @Override public String getRequestProperty(String field) { - return delegate.getRequestProperty(field); - } + @Override + public String getRequestProperty(String field) { + return delegate.getRequestProperty(field); + } - @Override public URL getURL() { - return delegate.getURL(); - } + @Override + public URL getURL() { + return delegate.getURL(); + } - @Override public boolean getUseCaches() { - return delegate.getUseCaches(); - } + @Override + public boolean getUseCaches() { + return delegate.getUseCaches(); + } - @Override public void setAllowUserInteraction(boolean newValue) { - delegate.setAllowUserInteraction(newValue); - } + @Override + public void setAllowUserInteraction(boolean newValue) { + delegate.setAllowUserInteraction(newValue); + } - @Override public void setDefaultUseCaches(boolean newValue) { - delegate.setDefaultUseCaches(newValue); - } + @Override + public void setDefaultUseCaches(boolean newValue) { + delegate.setDefaultUseCaches(newValue); + } - @Override public void setDoInput(boolean newValue) { - delegate.setDoInput(newValue); - } + @Override + public void setDoInput(boolean newValue) { + delegate.setDoInput(newValue); + } - @Override public void setDoOutput(boolean newValue) { - delegate.setDoOutput(newValue); - } + @Override + public void setDoOutput(boolean newValue) { + delegate.setDoOutput(newValue); + } - // Should only be invoked on Java 8+ or Android API 24+. - @Override public void setFixedLengthStreamingMode(long contentLength) { - delegate.setFixedLengthStreamingMode(contentLength); - } + // Should only be invoked on Java 8+ or Android API 24+. + @Override + public void setFixedLengthStreamingMode(long contentLength) { + delegate.setFixedLengthStreamingMode(contentLength); + } - @Override public void setIfModifiedSince(long newValue) { - delegate.setIfModifiedSince(newValue); - } + @Override + public void setIfModifiedSince(long newValue) { + delegate.setIfModifiedSince(newValue); + } - @Override public void setRequestProperty(String field, String newValue) { - delegate.setRequestProperty(field, newValue); - } + @Override + public void setRequestProperty(String field, String newValue) { + delegate.setRequestProperty(field, newValue); + } - @Override public void setUseCaches(boolean newValue) { - delegate.setUseCaches(newValue); - } + @Override + public void setUseCaches(boolean newValue) { + delegate.setUseCaches(newValue); + } - @Override public void setConnectTimeout(int timeoutMillis) { - delegate.setConnectTimeout(timeoutMillis); - } + @Override + public void setConnectTimeout(int timeoutMillis) { + delegate.setConnectTimeout(timeoutMillis); + } - @Override public int getConnectTimeout() { - return delegate.getConnectTimeout(); - } + @Override + public int getConnectTimeout() { + return delegate.getConnectTimeout(); + } - @Override public void setReadTimeout(int timeoutMillis) { - delegate.setReadTimeout(timeoutMillis); - } + @Override + public void setReadTimeout(int timeoutMillis) { + delegate.setReadTimeout(timeoutMillis); + } - @Override public int getReadTimeout() { - return delegate.getReadTimeout(); - } + @Override + public int getReadTimeout() { + return delegate.getReadTimeout(); + } - @Override public String toString() { - return delegate.toString(); - } + @Override + public String toString() { + return delegate.toString(); + } - @Override public void setFixedLengthStreamingMode(int contentLength) { - delegate.setFixedLengthStreamingMode(contentLength); - } + @Override + public void setFixedLengthStreamingMode(int contentLength) { + delegate.setFixedLengthStreamingMode(contentLength); + } - @Override public void setChunkedStreamingMode(int chunkLength) { - delegate.setChunkedStreamingMode(chunkLength); + @Override + public void setChunkedStreamingMode(int chunkLength) { + delegate.setChunkedStreamingMode(chunkLength); + } } - } - static final class OkHttpsURLConnection extends DelegatingHttpsURLConnection { - private final OkHttpURLConnection delegate; + static final class OkHttpsURLConnection extends DelegatingHttpsURLConnection { + private final OkHttpURLConnection delegate; - OkHttpsURLConnection(URL url, OkHttpClient client) { - this(new OkHttpURLConnection(url, client)); - } + OkHttpsURLConnection(URL url, OkHttpClient client) { + this(new OkHttpURLConnection(url, client)); + } - OkHttpsURLConnection(OkHttpURLConnection delegate) { - super(delegate); - this.delegate = delegate; - } + OkHttpsURLConnection(OkHttpURLConnection delegate) { + super(delegate); + this.delegate = delegate; + } - @Override protected Handshake handshake() { - if (delegate.call == null) { - throw new IllegalStateException("Connection has not yet been established"); - } + @Override + protected Handshake handshake() { + if (delegate.call == null) { + throw new IllegalStateException("Connection has not yet been established"); + } - return delegate.handshake; - } + return delegate.handshake; + } - @Override public void setHostnameVerifier(HostnameVerifier hostnameVerifier) { - delegate.client = delegate.client.newBuilder() - .hostnameVerifier(hostnameVerifier) - .build(); - } + @Override + public void setHostnameVerifier(HostnameVerifier hostnameVerifier) { + delegate.client = delegate.client.newBuilder().hostnameVerifier(hostnameVerifier).build(); + } - @Override public HostnameVerifier getHostnameVerifier() { - return delegate.client.hostnameVerifier(); - } + @Override + public HostnameVerifier getHostnameVerifier() { + return delegate.client.hostnameVerifier(); + } - @Override public void setSSLSocketFactory(SSLSocketFactory sslSocketFactory) { - if (sslSocketFactory == null) { - throw new IllegalArgumentException("sslSocketFactory == null"); - } - // This fails in JDK 9 because OkHttp is unable to extract the trust manager. - delegate.client = delegate.client.newBuilder() - .sslSocketFactory(sslSocketFactory) - .build(); - } + @Override + public void setSSLSocketFactory(SSLSocketFactory sslSocketFactory) { + if (sslSocketFactory == null) { + throw new IllegalArgumentException("sslSocketFactory == null"); + } + // This fails in JDK 9 because OkHttp is unable to extract the trust manager. + delegate.client = delegate.client.newBuilder().sslSocketFactory(sslSocketFactory).build(); + } - @Override public SSLSocketFactory getSSLSocketFactory() { - return delegate.client.sslSocketFactory(); + @Override + public SSLSocketFactory getSSLSocketFactory() { + return delegate.client.sslSocketFactory(); + } } - } - - static final class UnexpectedException extends IOException { - static final Interceptor INTERCEPTOR = chain -> { - try { - return chain.proceed(chain.request()); - } catch (Error | RuntimeException e) { - throw new UnexpectedException(e); - } - }; - UnexpectedException(Throwable cause) { - super(cause); + static final class UnexpectedException extends IOException { + static final Interceptor INTERCEPTOR = chain -> { + try { + return chain.proceed(chain.request()); + } catch (Error | RuntimeException e) { + throw new UnexpectedException(e); + } + }; + + UnexpectedException(Throwable cause) { + super(cause); + } } - } } \ No newline at end of file diff --git a/src/main/java/org/kohsuke/github/extras/okhttp3/OkHttpConnector.java b/src/main/java/org/kohsuke/github/extras/okhttp3/OkHttpConnector.java index 315ac0c352..e60b3455ca 100644 --- a/src/main/java/org/kohsuke/github/extras/okhttp3/OkHttpConnector.java +++ b/src/main/java/org/kohsuke/github/extras/okhttp3/OkHttpConnector.java @@ -14,14 +14,11 @@ import java.util.List; import java.util.concurrent.TimeUnit; - /** * {@link HttpConnector} for {@link OkHttpClient}. * - * Unlike {@link #DEFAULT}, OkHttp does response caching. - * Making a conditional request against GitHubAPI and receiving a 304 - * response does not count against the rate limit. - * See http://developer.github.com/v3/#conditional-requests + * Unlike {@link #DEFAULT}, OkHttp does response caching. Making a conditional request against GitHubAPI and receiving a + * 304 response does not count against the rate limit. See http://developer.github.com/v3/#conditional-requests * * @author Liam Newman * @author Kohsuke Kawaguchi @@ -33,7 +30,6 @@ public class OkHttpConnector implements HttpConnector { private final OkHttpClient client; private final ObsoleteUrlFactory urlFactory; - public OkHttpConnector(OkHttpClient client) { this(client, 0); } @@ -45,10 +41,7 @@ public OkHttpConnector(OkHttpClient client, int cacheMaxAge) { builder.connectionSpecs(TlsConnectionSpecs()); this.client = builder.build(); if (cacheMaxAge >= 0 && this.client != null && this.client.cache() != null) { - maxAgeHeaderValue = new CacheControl.Builder() - .maxAge(cacheMaxAge, TimeUnit.SECONDS) - .build() - .toString(); + maxAgeHeaderValue = new CacheControl.Builder().maxAge(cacheMaxAge, TimeUnit.SECONDS).build().toString(); } else { maxAgeHeaderValue = null; } diff --git a/src/test/java/org/kohsuke/HookApp.java b/src/test/java/org/kohsuke/HookApp.java index 4f8ced9685..32f2e0157b 100644 --- a/src/test/java/org/kohsuke/HookApp.java +++ b/src/test/java/org/kohsuke/HookApp.java @@ -9,15 +9,15 @@ import java.io.StringReader; /** - * App to test the hook script. You need some internet-facing server that can forward the request to you - * (typically via SSH reverse port forwarding.) + * App to test the hook script. You need some internet-facing server that can forward the request to you (typically via + * SSH reverse port forwarding.) * * @author Kohsuke Kawaguchi */ public class HookApp { public static void main(String[] args) throws Exception { -// GitHub.connect().getMyself().getRepository("sandbox").createWebHook( -// new URL("http://173.203.118.45:18080/"), EnumSet.of(GHEvent.PULL_REQUEST)); + // GitHub.connect().getMyself().getRepository("sandbox").createWebHook( + // new URL("http://173.203.118.45:18080/"), EnumSet.of(GHEvent.PULL_REQUEST)); JettyRunner jr = new JettyRunner(new HookApp()); jr.addHttpListener(8080); jr.start(); @@ -26,7 +26,8 @@ public static void main(String[] args) throws Exception { public void doIndex(StaplerRequest req) throws IOException { String str = req.getParameter("payload"); // System.out.println(str); - GHEventPayload.PullRequest o = GitHub.connect().parseEventPayload(new StringReader(str), GHEventPayload.PullRequest.class); + GHEventPayload.PullRequest o = GitHub.connect().parseEventPayload(new StringReader(str), + GHEventPayload.PullRequest.class); // System.out.println(o); } } diff --git a/src/test/java/org/kohsuke/github/AbstractGitHubApiTestBase.java b/src/test/java/org/kohsuke/github/AbstractGitHubApiTestBase.java index 0c5010c32c..797362e500 100644 --- a/src/test/java/org/kohsuke/github/AbstractGitHubApiTestBase.java +++ b/src/test/java/org/kohsuke/github/AbstractGitHubApiTestBase.java @@ -21,7 +21,8 @@ public abstract class AbstractGitHubApiTestBase extends AbstractGitHubWireMockTe @Before public void setUp() throws Exception { - assumeTrue("All tests inheriting from this class are not guaranteed to work without proxy", mockGitHub.isUseProxy()); + assumeTrue("All tests inheriting from this class are not guaranteed to work without proxy", + mockGitHub.isUseProxy()); } protected void kohsuke() { diff --git a/src/test/java/org/kohsuke/github/AbstractGitHubWireMockTest.java b/src/test/java/org/kohsuke/github/AbstractGitHubWireMockTest.java index 7c5892eea9..39abf6a36d 100644 --- a/src/test/java/org/kohsuke/github/AbstractGitHubWireMockTest.java +++ b/src/test/java/org/kohsuke/github/AbstractGitHubWireMockTest.java @@ -33,15 +33,13 @@ public abstract class AbstractGitHubWireMockTest extends Assert { protected final Set tempGitHubRepositories = new HashSet<>(); /** - * {@link GitHub} instance for use during test. - * Traffic will be part of snapshot when taken. + * {@link GitHub} instance for use during test. Traffic will be part of snapshot when taken. */ protected GitHub gitHub; /** - * {@link GitHub} instance for use before/after test. - * Traffic will not be part of snapshot when taken. - * Should only be used when isUseProxy() or isTakeSnapShot(). + * {@link GitHub} instance for use before/after test. Traffic will not be part of snapshot when taken. Should only + * be used when isUseProxy() or isTakeSnapShot(). */ protected GitHub gitHubBeforeAfter; @@ -52,15 +50,11 @@ public abstract class AbstractGitHubWireMockTest extends Assert { public final GitHubWireMockRule mockGitHub; public AbstractGitHubWireMockTest() { - mockGitHub = new GitHubWireMockRule( - this.getWireMockOptions() - ); + mockGitHub = new GitHubWireMockRule(this.getWireMockOptions()); } protected WireMockConfiguration getWireMockOptions() { - return WireMockConfiguration.options() - .dynamicPort() - .usingFilesUnderDirectory(baseRecordPath); + return WireMockConfiguration.options().dynamicPort().usingFilesUnderDirectory(baseRecordPath); } private static GitHubBuilder createGitHubBuilder() { @@ -109,29 +103,27 @@ protected GitHubBuilder getGitHubBuilder() { @Before public void wireMockSetup() throws Exception { - GitHubBuilder builder = getGitHubBuilder() - .withEndpoint(mockGitHub.apiServer().baseUrl()); + GitHubBuilder builder = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()); if (useDefaultGitHub) { - gitHub = builder - .build(); + gitHub = builder.build(); } if (mockGitHub.isUseProxy()) { - gitHubBeforeAfter = getGitHubBuilder() - .withEndpoint("https://api.github.com/") - .build(); + gitHubBeforeAfter = getGitHubBuilder().withEndpoint("https://api.github.com/").build(); } else { gitHubBeforeAfter = null; } } protected void snapshotNotAllowed() { - assumeFalse("Test contains hand written mappings. Only valid when not taking a snapshot.", mockGitHub.isTakeSnapshot()); + assumeFalse("Test contains hand written mappings. Only valid when not taking a snapshot.", + mockGitHub.isTakeSnapshot()); } protected void requireProxy(String reason) { - assumeTrue("Test only valid when proxying (-Dtest.github.useProxy to enable): " + reason, mockGitHub.isUseProxy()); + assumeTrue("Test only valid when proxying (-Dtest.github.useProxy to enable): " + reason, + mockGitHub.isUseProxy()); } protected GHUser getUser() { @@ -147,26 +139,35 @@ protected static GHUser getUser(GitHub gitHub) { } /** + * Creates a temporary repository that will be deleted at the end of the test. Repository name is based on the + * current test method. * + * @return a temporary repository + * @throws IOException + * if repository could not be created or retrieved. */ - protected GHRepository getTempRepository() throws IOException{ + protected GHRepository getTempRepository() throws IOException { return getTempRepository("temp-" + this.mockGitHub.getMethodName()); } /** - * Creates + * Creates a temporary repository that will be deleted at the end of the test. + * + * @param name + * string name of the the repository + * + * @return a temporary repository + * @throws IOException + * if repository could not be created or retrieved. */ protected GHRepository getTempRepository(String name) throws IOException { - String fullName = GITHUB_API_TEST_ORG +'/' + name; + String fullName = GITHUB_API_TEST_ORG + '/' + name; if (mockGitHub.isUseProxy()) { cleanupRepository(fullName); - GHRepository repository = gitHubBeforeAfter.getOrganization(GITHUB_API_TEST_ORG) - .createRepository(name) - .description("A test repository for testing the github-api project: " + name) - .homepage("http://github-api.kohsuke.org/") - .autoInit(true) - .create(); + GHRepository repository = gitHubBeforeAfter.getOrganization(GITHUB_API_TEST_ORG).createRepository(name) + .description("A test repository for testing the github-api project: " + name) + .homepage("http://github-api.kohsuke.org/").autoInit(true).create(); try { Thread.sleep(3000); } catch (InterruptedException e) { @@ -189,7 +190,7 @@ protected void configureTempRepository(GHRepository repository) throws IOExcepti @After public void cleanupTempRepositories() throws IOException { if (mockGitHub.isUseProxy()) { - for(String fullName : tempGitHubRepositories) { + for (String fullName : tempGitHubRepositories) { cleanupRepository(fullName); } } @@ -215,8 +216,8 @@ protected void kohsuke() { // Generally this means the test is doing something that requires additional access rights // Not always clear which ones. // TODO: Add helpers that assert the expected rights using gitHubBeforeAfter and only when proxy is enabled -// String login = getUserTest().getLogin(); -// assumeTrue(login.equals("kohsuke") || login.equals("kohsuke2")); + // String login = getUserTest().getLogin(); + // assumeTrue(login.equals("kohsuke") || login.equals("kohsuke2")); } } diff --git a/src/test/java/org/kohsuke/github/AppTest.java b/src/test/java/org/kohsuke/github/AppTest.java index 9f4d253ef5..6fba815f70 100755 --- a/src/test/java/org/kohsuke/github/AppTest.java +++ b/src/test/java/org/kohsuke/github/AppTest.java @@ -34,7 +34,8 @@ public void testRepoCRUD() throws Exception { cleanupUserRepository("github-api-test-rename"); cleanupUserRepository(targetName); - GHRepository r = gitHub.createRepository("github-api-test-rename", "a test repository", "http://github-api.kohsuke.org/", true); + GHRepository r = gitHub.createRepository("github-api-test-rename", "a test repository", + "http://github-api.kohsuke.org/", true); assertThat(r.hasIssues(), is(true)); r.enableIssueTracker(false); @@ -48,10 +49,8 @@ public void testRepoCRUD() throws Exception { public void testRepositoryWithAutoInitializationCRUD() throws Exception { String name = "github-api-test-autoinit"; cleanupUserRepository(name); - GHRepository r = gitHub.createRepository(name) - .description("a test repository for auto init") - .homepage("http://github-api.kohsuke.org/") - .autoInit(true).create(); + GHRepository r = gitHub.createRepository(name).description("a test repository for auto init") + .homepage("http://github-api.kohsuke.org/").autoInit(true).create(); r.enableIssueTracker(false); r.enableDownloads(false); r.enableWiki(false); @@ -79,11 +78,11 @@ public void testCredentialValid() throws IOException { public void testIssueWithNoComment() throws IOException { GHRepository repository = gitHub.getRepository("kohsuke/test"); List v = repository.getIssue(4).getComments(); - //System.out.println(v); + // System.out.println(v); assertTrue(v.isEmpty()); v = repository.getIssue(3).getComments(); - //System.out.println(v); + // System.out.println(v); assertTrue(v.size() == 3); } @@ -92,13 +91,8 @@ public void testCreateIssue() throws IOException { GHUser u = getUser(); GHRepository repository = getTestRepository(); GHMilestone milestone = repository.createMilestone("Test Milestone Title3", "Test Milestone"); - GHIssue o = repository.createIssue("testing") - .body("this is body") - .assignee(u) - .label("bug") - .label("question") - .milestone(milestone) - .create(); + GHIssue o = repository.createIssue("testing").body("this is body").assignee(u).label("bug").label("question") + .milestone(milestone).create(); assertNotNull(o); o.close(); } @@ -107,10 +101,8 @@ public void testCreateIssue() throws IOException { public void testCreateAndListDeployments() throws IOException { GHRepository repository = getTestRepository(); GHDeployment deployment = repository.createDeployment("master") - .payload("{\"user\":\"atmos\",\"room_id\":123456}") - .description("question") - .environment("unittest") - .create(); + .payload("{\"user\":\"atmos\",\"room_id\":123456}").description("question").environment("unittest") + .create(); assertNotNull(deployment.getCreator()); assertNotNull(deployment.getId()); List deployments = repository.listDeployments(null, "master", null, "unittest").asList(); @@ -125,13 +117,10 @@ public void testCreateAndListDeployments() throws IOException { @Test public void testGetDeploymentStatuses() throws IOException { GHRepository repository = getTestRepository(); - GHDeployment deployment = repository.createDeployment("master") - .description("question") - .payload("{\"user\":\"atmos\",\"room_id\":123456}") - .create(); + GHDeployment deployment = repository.createDeployment("master").description("question") + .payload("{\"user\":\"atmos\",\"room_id\":123456}").create(); GHDeploymentStatus ghDeploymentStatus = deployment.createStatus(GHDeploymentState.SUCCESS) - .description("success") - .targetUrl("http://www.github.com").create(); + .description("success").targetUrl("http://www.github.com").create(); Iterable deploymentStatuses = deployment.listStatuses(); assertNotNull(deploymentStatuses); assertEquals(1, Iterables.size(deploymentStatuses)); @@ -140,7 +129,8 @@ public void testGetDeploymentStatuses() throws IOException { @Test public void testGetIssues() throws Exception { - List closedIssues = gitHub.getOrganization("github-api").getRepository("github-api").getIssues(GHIssueState.CLOSED); + List closedIssues = gitHub.getOrganization("github-api").getRepository("github-api") + .getIssues(GHIssueState.CLOSED); // prior to using PagedIterable GHRepository.getIssues(GHIssueState) would only retrieve 30 issues assertTrue(closedIssues.size() > 150); } @@ -160,18 +150,11 @@ public void testListIssues() throws IOException { GHIssue unhomed = null; GHIssue homed = null; try { - unhomed = repository.createIssue("testing").body("this is body") - .assignee(u) - .label("bug") - .label("question") - .create(); + unhomed = repository.createIssue("testing").body("this is body").assignee(u).label("bug").label("question") + .create(); assertEquals(unhomed.getNumber(), repository.getIssues(GHIssueState.OPEN, null).get(0).getNumber()); - homed = repository.createIssue("testing").body("this is body") - .assignee(u) - .label("bug") - .label("question") - .milestone(milestone) - .create(); + homed = repository.createIssue("testing").body("this is body").assignee(u).label("bug").label("question") + .milestone(milestone).create(); assertEquals(homed.getNumber(), repository.getIssues(GHIssueState.OPEN, milestone).get(0).getNumber()); } finally { if (unhomed != null) { @@ -192,15 +175,15 @@ public void testRateLimit() throws IOException { public void testMyOrganizations() throws IOException { Map org = gitHub.getMyOrganizations(); assertFalse(org.keySet().contains(null)); - //System.out.println(org); + // System.out.println(org); } @Test public void testMyOrganizationsContainMyTeams() throws IOException { Map> teams = gitHub.getMyTeams(); Map myOrganizations = gitHub.getMyOrganizations(); - //GitHub no longer has default 'owners' team, so there may be organization memberships without a team - //https://help.github.com/articles/about-improved-organization-permissions/ + // GitHub no longer has default 'owners' team, so there may be organization memberships without a team + // https://help.github.com/articles/about-improved-organization-permissions/ assertTrue(myOrganizations.keySet().containsAll(teams.keySet())); } @@ -211,30 +194,29 @@ public void testMyTeamsShouldIncludeMyself() throws IOException { String organizationName = teamsPerOrg.getKey(); for (GHTeam team : teamsPerOrg.getValue()) { String teamName = team.getName(); - assertTrue("Team " + teamName + " in organization " + organizationName - + " does not contain myself", - shouldBelongToTeam(organizationName, teamName)); + assertTrue("Team " + teamName + " in organization " + organizationName + " does not contain myself", + shouldBelongToTeam(organizationName, teamName)); } } } - + @Test public void testUserPublicOrganizationsWhenThereAreSome() throws IOException { - // kohsuke had some public org memberships at the time Wiremock recorded the GitHub API responses - GHUser user = new GHUser(); - user.login = "kohsuke"; - - Map orgs = gitHub.getUserPublicOrganizations( user ); + // kohsuke had some public org memberships at the time Wiremock recorded the GitHub API responses + GHUser user = new GHUser(); + user.login = "kohsuke"; + + Map orgs = gitHub.getUserPublicOrganizations(user); assertFalse(orgs.isEmpty()); } - + @Test public void testUserPublicOrganizationsWhenThereAreNone() throws IOException { - // bitwiseman had no public org memberships at the time Wiremock recorded the GitHub API responses - GHUser user = new GHUser(); - user.login = "bitwiseman"; - - Map orgs = gitHub.getUserPublicOrganizations( user ); + // bitwiseman had no public org memberships at the time Wiremock recorded the GitHub API responses + GHUser user = new GHUser(); + user.login = "bitwiseman"; + + Map orgs = gitHub.getUserPublicOrganizations(user); assertTrue(orgs.isEmpty()); } @@ -318,12 +300,14 @@ public void testOrgFork() throws Exception { public void testGetTeamsForRepo() throws Exception { kohsuke(); // 'Core Developers' and 'Owners' - assertEquals(2, gitHub.getOrganization(GITHUB_API_TEST_ORG).getRepository("testGetTeamsForRepo").getTeams().size()); + assertEquals(2, + gitHub.getOrganization(GITHUB_API_TEST_ORG).getRepository("testGetTeamsForRepo").getTeams().size()); } @Test public void testMembership() throws Exception { - Set members = gitHub.getOrganization(GITHUB_API_TEST_ORG).getRepository("jenkins").getCollaboratorNames(); + Set members = gitHub.getOrganization(GITHUB_API_TEST_ORG).getRepository("jenkins") + .getCollaboratorNames(); // System.out.println(members.contains("kohsuke")); } @@ -360,11 +344,12 @@ public void testOrgTeamBySlug() throws Exception { @Test public void testCommit() throws Exception { - GHCommit commit = gitHub.getUser("jenkinsci").getRepository("jenkins").getCommit("08c1c9970af4d609ae754fbe803e06186e3206f7"); + GHCommit commit = gitHub.getUser("jenkinsci").getRepository("jenkins") + .getCommit("08c1c9970af4d609ae754fbe803e06186e3206f7"); assertEquals(1, commit.getParents().size()); assertEquals(1, commit.getFiles().size()); assertEquals("https://github.com/jenkinsci/jenkins/commit/08c1c9970af4d609ae754fbe803e06186e3206f7", - commit.getHtmlUrl().toString()); + commit.getHtmlUrl().toString()); File f = commit.getFiles().get(0); assertEquals(48, f.getLinesChanged()); @@ -390,7 +375,7 @@ public void testListCommits() throws Exception { public void testQueryCommits() throws Exception { List sha1 = new ArrayList(); for (GHCommit c : gitHub.getUser("jenkinsci").getRepository("jenkins").queryCommits() - .since(new Date(1199174400000L)).until(1201852800000L).path("pom.xml").list()) { + .since(new Date(1199174400000L)).until(1201852800000L).path("pom.xml").list()) { // System.out.println(c.getSHA1()); sha1.add(c.getSHA1()); } @@ -401,8 +386,7 @@ public void testQueryCommits() throws Exception { @Ignore("Needs mocking check") @Test public void testBranches() throws Exception { - Map b = - gitHub.getUser("jenkinsci").getRepository("jenkins").getBranches(); + Map b = gitHub.getUser("jenkinsci").getRepository("jenkins").getBranches(); // System.out.println(b); } @@ -419,7 +403,8 @@ public void testCommitComment() throws Exception { @Test public void testCreateCommitComment() throws Exception { - GHCommit commit = gitHub.getUser("kohsuke").getRepository("sandbox-ant").getCommit("8ae38db0ea5837313ab5f39d43a6f73de3bd9000"); + GHCommit commit = gitHub.getUser("kohsuke").getRepository("sandbox-ant") + .getCommit("8ae38db0ea5837313ab5f39d43a6f73de3bd9000"); GHCommitComment c = commit.createComment("[testing](http://kohsuse.org/)"); // System.out.println(c); c.update("updated text"); @@ -457,48 +442,50 @@ public void testEventApi() throws Exception { public void testApp() throws IOException { // System.out.println(gitHub.getMyself().getEmails()); -// GHRepository r = gitHub.getOrganization("jenkinsci").createRepository("kktest4", "Kohsuke's test", "http://kohsuke.org/", "Everyone", true); -// r.fork(); + // GHRepository r = gitHub.getOrganization("jenkinsci").createRepository("kktest4", "Kohsuke's test", + // "http://kohsuke.org/", "Everyone", true); + // r.fork(); -// tryDisablingIssueTrackers(gitHub); + // tryDisablingIssueTrackers(gitHub); -// tryDisablingWiki(gitHub); + // tryDisablingWiki(gitHub); -// GHPullRequest i = gitHub.getOrganization("jenkinsci").getRepository("sandbox").getPullRequest(1); -// for (GHIssueComment c : i.getComments()) -// // System.out.println(c); -// // System.out.println(i); + // GHPullRequest i = gitHub.getOrganization("jenkinsci").getRepository("sandbox").getPullRequest(1); + // for (GHIssueComment c : i.getComments()) + // // System.out.println(c); + // // System.out.println(i); -// gitHub.getMyself().getRepository("perforce-plugin").setEmailServiceHook("kk@kohsuke.org"); + // gitHub.getMyself().getRepository("perforce-plugin").setEmailServiceHook("kk@kohsuke.org"); -// tryRenaming(gitHub); -// tryOrgFork(gitHub); + // tryRenaming(gitHub); + // tryOrgFork(gitHub); -// testOrganization(gitHub); -// testPostCommitHook(gitHub); + // testOrganization(gitHub); + // testPostCommitHook(gitHub); -// tryTeamCreation(gitHub); + // tryTeamCreation(gitHub); -// t.add(gitHub.getMyself()); -// // System.out.println(t.getMembers()); -// t.remove(gitHub.getMyself()); -// // System.out.println(t.getMembers()); + // t.add(gitHub.getMyself()); + // // System.out.println(t.getMembers()); + // t.remove(gitHub.getMyself()); + // // System.out.println(t.getMembers()); -// GHRepository r = gitHub.getOrganization("HudsonLabs").createRepository("auto-test", "some description", "http://kohsuke.org/", "Plugin Developers", true); + // GHRepository r = gitHub.getOrganization("HudsonLabs").createRepository("auto-test", "some description", + // "http://kohsuke.org/", "Plugin Developers", true); -// r. -// GitHub hub = GitHub.connectAnonymously(); -//// hub.createRepository("test","test repository",null,true); -//// hub.getUserTest("kohsuke").getRepository("test").delete(); -// -// // System.out.println(hub.getUserTest("kohsuke").getRepository("hudson").getCollaborators()); + // r. + // GitHub hub = GitHub.connectAnonymously(); + //// hub.createRepository("test","test repository",null,true); + //// hub.getUserTest("kohsuke").getRepository("test").delete(); + // + // // System.out.println(hub.getUserTest("kohsuke").getRepository("hudson").getCollaborators()); } private void tryDisablingIssueTrackers(GitHub gitHub) throws IOException { for (GHRepository r : gitHub.getOrganization("jenkinsci").getRepositories().values()) { if (r.hasIssues()) { if (r.getOpenIssueCount() == 0) { - // System.out.println("DISABLED " + r.getName()); + // System.out.println("DISABLED " + r.getName()); r.enableIssueTracker(false); } else { // System.out.println("UNTOUCHED " + r.getName()); @@ -510,7 +497,7 @@ private void tryDisablingIssueTrackers(GitHub gitHub) throws IOException { private void tryDisablingWiki(GitHub gitHub) throws IOException { for (GHRepository r : gitHub.getOrganization("jenkinsci").getRepositories().values()) { if (r.hasWiki()) { - // System.out.println("DISABLED " + r.getName()); + // System.out.println("DISABLED " + r.getName()); r.enableWiki(false); } } @@ -560,7 +547,7 @@ public void testOrganization() throws IOException { assertNotNull(j.getRepository("jenkins")); -// t.add(labs.getRepository("xyz")); + // t.add(labs.getRepository("xyz")); } @Test @@ -569,7 +556,8 @@ public void testCommitStatus() throws Exception { GHCommitStatus state; -// state = r.createCommitStatus("ecbfdd7315ef2cf04b2be7f11a072ce0bd00c396", GHCommitState.FAILURE, "http://kohsuke.org/", "testing!"); + // state = r.createCommitStatus("ecbfdd7315ef2cf04b2be7f11a072ce0bd00c396", GHCommitState.FAILURE, + // "http://kohsuke.org/", "testing!"); List lst = r.listCommitStatuses("ecbfdd7315ef2cf04b2be7f11a072ce0bd00c396").asList(); state = lst.get(0); @@ -619,10 +607,7 @@ public void testCreateRelease() throws Exception { String tagName = UUID.randomUUID().toString(); String releaseName = "release-" + tagName; - GHRelease rel = r.createRelease(tagName) - .name(releaseName) - .prerelease(false) - .create(); + GHRelease rel = r.createRelease(tagName).name(releaseName).prerelease(false).create(); Thread.sleep(3000); @@ -652,7 +637,8 @@ public void testCreateRelease() throws Exception { @Test public void testRef() throws IOException { GHRef masterRef = gitHub.getRepository("jenkinsci/jenkins").getRef("heads/master"); - assertEquals(mockGitHub.apiServer().baseUrl() + "/repos/jenkinsci/jenkins/git/refs/heads/master", masterRef.getUrl().toString()); + assertEquals(mockGitHub.apiServer().baseUrl() + "/repos/jenkinsci/jenkins/git/refs/heads/master", + masterRef.getUrl().toString()); } @Test @@ -662,7 +648,7 @@ public void directoryListing() throws IOException { // System.out.println(c.getName()); if (c.isDirectory()) { for (GHContent d : c.listDirectoryContent()) { - // System.out.println(" " + d.getName()); + // System.out.println(" " + d.getName()); } } } @@ -672,7 +658,8 @@ public void directoryListing() throws IOException { @Test public void testAddDeployKey() throws IOException { GHRepository myRepository = getTestRepository(); - final GHDeployKey newDeployKey = myRepository.addDeployKey("test", "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDUt0RAycC5cS42JKh6SecfFZBR1RrF+2hYMctz4mk74/arBE+wFb7fnSHGzdGKX2h5CFOWODifRCJVhB7hlVxodxe+QkQQYAEL/x1WVCJnGgTGQGOrhOMj95V3UE5pQKhsKD608C+u5tSofcWXLToP1/wZ7U4/AHjqYi08OLsWToHCax55TZkvdt2jo0hbIoYU+XI9Q8Uv4ONDN1oabiOdgeKi8+crvHAuvNleiBhWVBzFh8KdfzaH5uNdw7ihhFjEd1vzqACsjCINCjdMfzl6jD9ExuWuE92nZJnucls2cEoNC6k2aPmrZDg9hA32FXVpyseY+bDUWFU6LO2LG6PB kohsuke@atlas"); + final GHDeployKey newDeployKey = myRepository.addDeployKey("test", + "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDUt0RAycC5cS42JKh6SecfFZBR1RrF+2hYMctz4mk74/arBE+wFb7fnSHGzdGKX2h5CFOWODifRCJVhB7hlVxodxe+QkQQYAEL/x1WVCJnGgTGQGOrhOMj95V3UE5pQKhsKD608C+u5tSofcWXLToP1/wZ7U4/AHjqYi08OLsWToHCax55TZkvdt2jo0hbIoYU+XI9Q8Uv4ONDN1oabiOdgeKi8+crvHAuvNleiBhWVBzFh8KdfzaH5uNdw7ihhFjEd1vzqACsjCINCjdMfzl6jD9ExuWuE92nZJnucls2cEoNC6k2aPmrZDg9hA32FXVpyseY+bDUWFU6LO2LG6PB kohsuke@atlas"); try { assertNotNull(newDeployKey.getId()); @@ -692,7 +679,8 @@ public boolean apply(GHDeployKey deployKey) { public void testCommitStatusContext() throws IOException { GHRepository myRepository = getTestRepository(); GHRef masterRef = myRepository.getRef("heads/master"); - GHCommitStatus commitStatus = myRepository.createCommitStatus(masterRef.getObject().getSha(), GHCommitState.SUCCESS, "http://www.example.com", "test", "test/context"); + GHCommitStatus commitStatus = myRepository.createCommitStatus(masterRef.getObject().getSha(), + GHCommitState.SUCCESS, "http://www.example.com", "test", "test/context"); assertEquals("test/context", commitStatus.getContext()); } @@ -728,14 +716,13 @@ public void testIssueSearch() throws IOException { } @Ignore("Needs mocking check") - @Test // issue #99 + @Test // issue #99 public void testReadme() throws IOException { GHContent readme = gitHub.getRepository("github-api-test-org/test-readme").getReadme(); assertEquals(readme.getName(), "README.md"); assertEquals(readme.getContent(), "This is a markdown readme.\n"); } - @Ignore("Needs mocking check") @Test public void testTrees() throws IOException { @@ -861,12 +848,10 @@ public void notifications() throws Exception { gitHub.listNotifications().markAsRead(); } - /** - * Just basic code coverage to make sure toString() doesn't blow up - */ @Ignore("Needs mocking check") @Test public void checkToString() throws Exception { + // Just basic code coverage to make sure toString() doesn't blow up GHUser u = gitHub.getUser("rails"); // System.out.println(u); GHRepository r = u.getRepository("rails"); diff --git a/src/test/java/org/kohsuke/github/BridgeMethodTest.java b/src/test/java/org/kohsuke/github/BridgeMethodTest.java index 9e840f5fbf..0256b72515 100644 --- a/src/test/java/org/kohsuke/github/BridgeMethodTest.java +++ b/src/test/java/org/kohsuke/github/BridgeMethodTest.java @@ -24,7 +24,7 @@ public void lastStatus() throws IOException { List createdAtMethods = new ArrayList<>(); for (Method method : obj.getClass().getMethods()) { if (method.getName().equalsIgnoreCase("getCreatedAt")) { - if(method.getReturnType() == Date.class) { + if (method.getReturnType() == Date.class) { createdAtMethods.add(0, method); } else { createdAtMethods.add(method); diff --git a/src/test/java/org/kohsuke/github/GHAppTest.java b/src/test/java/org/kohsuke/github/GHAppTest.java index 3c9bd0ff0f..eb9f96be75 100644 --- a/src/test/java/org/kohsuke/github/GHAppTest.java +++ b/src/test/java/org/kohsuke/github/GHAppTest.java @@ -20,8 +20,7 @@ public class GHAppTest extends AbstractGitHubWireMockTest { protected GitHubBuilder getGitHubBuilder() { return super.getGitHubBuilder() // ensure that only JWT will be used against the tests below - .withPassword(null, null) - .withJwtToken("bogus"); + .withPassword(null, null).withJwtToken("bogus"); } @Test @@ -41,7 +40,6 @@ public void getGitHubApp() throws IOException { assertThat(app.getInstallationsCount(), is((long) 1)); } - @Test public void listInstallations() throws IOException { GHApp app = gitHub.getApp(); @@ -103,12 +101,11 @@ public void createToken() throws IOException { permissions.put("metadata", GHPermissionType.READ); GHAppInstallationToken installationToken = installation.createToken(permissions) - .repositoryIds(Arrays.asList((long)111111111)) - .create(); + .repositoryIds(Arrays.asList((long) 111111111)).create(); assertThat(installationToken.getToken(), is("bogus")); assertThat(installation.getPermissions(), is(permissions)); - assertThat(installationToken.getRepositorySelection(),is(GHRepositorySelection.SELECTED)); + assertThat(installationToken.getRepositorySelection(), is(GHRepositorySelection.SELECTED)); assertThat(installationToken.getExpiresAt(), is(GitHub.parseDate("2019-08-10T05:54:58Z"))); GHRepository repository = installationToken.getRepositories().get(0); diff --git a/src/test/java/org/kohsuke/github/GHBranchProtectionTest.java b/src/test/java/org/kohsuke/github/GHBranchProtectionTest.java index 63f142a3fd..8717d6775c 100644 --- a/src/test/java/org/kohsuke/github/GHBranchProtectionTest.java +++ b/src/test/java/org/kohsuke/github/GHBranchProtectionTest.java @@ -48,14 +48,9 @@ public void setUp() throws Exception { @Test public void testEnableBranchProtections() throws Exception { // team/user restrictions require an organization repo to test against - GHBranchProtection protection = branch.enableProtection() - .addRequiredChecks("test-status-check") - .requireBranchIsUpToDate() - .requireCodeOwnReviews() - .dismissStaleReviews() - .requiredReviewers(2) - .includeAdmins() - .enable(); + GHBranchProtection protection = branch.enableProtection().addRequiredChecks("test-status-check") + .requireBranchIsUpToDate().requireCodeOwnReviews().dismissStaleReviews().requiredReviewers(2) + .includeAdmins().enable(); RequiredStatusChecks statusChecks = protection.getRequiredStatusChecks(); assertNotNull(statusChecks); @@ -81,9 +76,7 @@ public void testEnableProtectionOnly() throws Exception { @Test public void testEnableRequireReviewsOnly() throws Exception { - GHBranchProtection protection = branch.enableProtection() - .requireReviews() - .enable(); + GHBranchProtection protection = branch.enableProtection().requireReviews().enable(); assertNotNull(protection.getRequiredReviews()); } diff --git a/src/test/java/org/kohsuke/github/GHContentIntegrationTest.java b/src/test/java/org/kohsuke/github/GHContentIntegrationTest.java index e3a37f80d0..32e0f0090d 100644 --- a/src/test/java/org/kohsuke/github/GHContentIntegrationTest.java +++ b/src/test/java/org/kohsuke/github/GHContentIntegrationTest.java @@ -21,14 +21,15 @@ public class GHContentIntegrationTest extends AbstractGitHubWireMockTest { @Before @After public void cleanup() throws Exception { - if(mockGitHub.isUseProxy()) { + if (mockGitHub.isUseProxy()) { repo = gitHubBeforeAfter.getRepository("github-api-test-org/GHContentIntegrationTest"); try { GHContent content = repo.getFileContent(createdFilename); if (content != null) { content.delete("Cleanup"); } - } catch (IOException e) {} + } catch (IOException e) { + } } } @@ -37,7 +38,6 @@ public void setUp() throws Exception { repo = gitHub.getRepository("github-api-test-org/GHContentIntegrationTest"); } - @Test public void testGetFileContent() throws Exception { repo = gitHub.getRepository("github-api-test-org/GHContentIntegrationTest"); @@ -64,7 +64,7 @@ public void testGetDirectoryContent() throws Exception { @Test public void testGetDirectoryContentTrailingSlash() throws Exception { - //Used to truncate the ?ref=master, see gh-224 https://github.com/kohsuke/github-api/pull/224 + // Used to truncate the ?ref=master, see gh-224 https://github.com/kohsuke/github-api/pull/224 List entries = repo.getDirectoryContent("ghcontent-ro/a-dir-with-3-entries/", "master"); assertTrue(entries.get(0).getUrl().endsWith("?ref=master")); @@ -72,8 +72,8 @@ public void testGetDirectoryContentTrailingSlash() throws Exception { @Test public void testCRUDContent() throws Exception { - GHContentUpdateResponse created = - repo.createContent("this is an awesome file I created\n", "Creating a file for integration tests.", createdFilename); + GHContentUpdateResponse created = repo.createContent("this is an awesome file I created\n", + "Creating a file for integration tests.", createdFilename); GHContent createdContent = created.getContent(); assertNotNull(created.getCommit()); @@ -81,13 +81,15 @@ public void testCRUDContent() throws Exception { assertNotNull(createdContent.getContent()); assertEquals("this is an awesome file I created\n", createdContent.getContent()); - GHContentUpdateResponse updatedContentResponse = createdContent.update("this is some new content\n", "Updated file for integration tests."); + GHContentUpdateResponse updatedContentResponse = createdContent.update("this is some new content\n", + "Updated file for integration tests."); GHContent updatedContent = updatedContentResponse.getContent(); assertNotNull(updatedContentResponse.getCommit()); assertNotNull(updatedContentResponse.getContent()); // due to what appears to be a cache propagation delay, this test is too flaky - assertEquals("this is some new content", new BufferedReader(new InputStreamReader(updatedContent.read())).readLine()); + assertEquals("this is some new content", + new BufferedReader(new InputStreamReader(updatedContent.read())).readLine()); assertEquals("this is some new content\n", updatedContent.getContent()); GHContentUpdateResponse deleteResponse = updatedContent.delete("Enough of this foolishness!"); diff --git a/src/test/java/org/kohsuke/github/GHEventPayloadTest.java b/src/test/java/org/kohsuke/github/GHEventPayloadTest.java index 5287f4dab1..4f3b92a075 100644 --- a/src/test/java/org/kohsuke/github/GHEventPayloadTest.java +++ b/src/test/java/org/kohsuke/github/GHEventPayloadTest.java @@ -14,8 +14,8 @@ public class GHEventPayloadTest { @Test public void commit_comment() throws Exception { - GHEventPayload.CommitComment event = - GitHub.offline().parseEventPayload(payload.asReader(), GHEventPayload.CommitComment.class); + GHEventPayload.CommitComment event = GitHub.offline().parseEventPayload(payload.asReader(), + GHEventPayload.CommitComment.class); assertThat(event.getAction(), is("created")); assertThat(event.getComment().getSHA1(), is("9049f1265b7d61be4a8904a9a27120d2064dab3b")); assertThat(event.getComment().getUser().getLogin(), is("baxterthehacker")); @@ -26,8 +26,8 @@ public void commit_comment() throws Exception { @Test public void create() throws Exception { - GHEventPayload.Create event = - GitHub.offline().parseEventPayload(payload.asReader(), GHEventPayload.Create.class); + GHEventPayload.Create event = GitHub.offline().parseEventPayload(payload.asReader(), + GHEventPayload.Create.class); assertThat(event.getRef(), is("0.0.1")); assertThat(event.getRefType(), is("tag")); assertThat(event.getMasterBranch(), is("master")); @@ -39,8 +39,8 @@ public void create() throws Exception { @Test public void delete() throws Exception { - GHEventPayload.Delete event = - GitHub.offline().parseEventPayload(payload.asReader(), GHEventPayload.Delete.class); + GHEventPayload.Delete event = GitHub.offline().parseEventPayload(payload.asReader(), + GHEventPayload.Delete.class); assertThat(event.getRef(), is("simple-tag")); assertThat(event.getRefType(), is("tag")); assertThat(event.getRepository().getName(), is("public-repo")); @@ -50,8 +50,8 @@ public void delete() throws Exception { @Test public void deployment() throws Exception { - GHEventPayload.Deployment event = - GitHub.offline().parseEventPayload(payload.asReader(), GHEventPayload.Deployment.class); + GHEventPayload.Deployment event = GitHub.offline().parseEventPayload(payload.asReader(), + GHEventPayload.Deployment.class); assertThat(event.getDeployment().getSha(), is("9049f1265b7d61be4a8904a9a27120d2064dab3b")); assertThat(event.getDeployment().getEnvironment(), is("production")); assertThat(event.getDeployment().getCreator().getLogin(), is("baxterthehacker")); @@ -62,8 +62,8 @@ public void deployment() throws Exception { @Test public void deployment_status() throws Exception { - GHEventPayload.DeploymentStatus event = - GitHub.offline().parseEventPayload(payload.asReader(), GHEventPayload.DeploymentStatus.class); + GHEventPayload.DeploymentStatus event = GitHub.offline().parseEventPayload(payload.asReader(), + GHEventPayload.DeploymentStatus.class); assertThat(event.getDeploymentStatus().getState(), is(GHDeploymentState.SUCCESS)); assertThat(event.getDeploymentStatus().getTargetUrl(), nullValue()); assertThat(event.getDeployment().getSha(), is("9049f1265b7d61be4a8904a9a27120d2064dab3b")); @@ -76,8 +76,7 @@ public void deployment_status() throws Exception { @Test public void fork() throws Exception { - GHEventPayload.Fork event = - GitHub.offline().parseEventPayload(payload.asReader(), GHEventPayload.Fork.class); + GHEventPayload.Fork event = GitHub.offline().parseEventPayload(payload.asReader(), GHEventPayload.Fork.class); assertThat(event.getForkee().getName(), is("public-repo")); assertThat(event.getForkee().getOwner().getLogin(), is("baxterandthehackers")); assertThat(event.getRepository().getName(), is("public-repo")); @@ -85,28 +84,28 @@ public void fork() throws Exception { assertThat(event.getSender().getLogin(), is("baxterandthehackers")); } -// TODO uncomment when we have GHPage implemented -// @Test -// public void gollum() throws Exception { -// GHEventPayload.Gollum event = -// GitHub.offline().parseEventPayload(payload.asReader(), GHEventPayload.Gollum.class); -// assertThat(event.getPages().size(), is(1)); -// GHPage page = event.getPages().get(0); -// assertThat(page.getName(), is("Home")); -// assertThat(page.getTitle(), is("Home")); -// assertThat(page.getSummary(), nullValue()); -// assertThat(page.getAction(), is("created")); -// assertThat(page.getSha(), is("91ea1bd42aa2ba166b86e8aefe049e9837214e67")); -// assertThat(page.getHtmlUrl(), is("https://github.com/baxterthehacker/public-repo/wiki/Home")); -// assertThat(event.getRepository().getName(), is("public-repo")); -// assertThat(event.getRepository().getOwner().getLogin(), is("baxterthehacker")); -// assertThat(event.getSender().getLogin(), is("baxterthehacker")); -// } + // TODO uncomment when we have GHPage implemented + // @Test + // public void gollum() throws Exception { + // GHEventPayload.Gollum event = + // GitHub.offline().parseEventPayload(payload.asReader(), GHEventPayload.Gollum.class); + // assertThat(event.getPages().size(), is(1)); + // GHPage page = event.getPages().get(0); + // assertThat(page.getName(), is("Home")); + // assertThat(page.getTitle(), is("Home")); + // assertThat(page.getSummary(), nullValue()); + // assertThat(page.getAction(), is("created")); + // assertThat(page.getSha(), is("91ea1bd42aa2ba166b86e8aefe049e9837214e67")); + // assertThat(page.getHtmlUrl(), is("https://github.com/baxterthehacker/public-repo/wiki/Home")); + // assertThat(event.getRepository().getName(), is("public-repo")); + // assertThat(event.getRepository().getOwner().getLogin(), is("baxterthehacker")); + // assertThat(event.getSender().getLogin(), is("baxterthehacker")); + // } @Test public void issue_comment() throws Exception { - GHEventPayload.IssueComment event = - GitHub.offline().parseEventPayload(payload.asReader(), GHEventPayload.IssueComment.class); + GHEventPayload.IssueComment event = GitHub.offline().parseEventPayload(payload.asReader(), + GHEventPayload.IssueComment.class); assertThat(event.getAction(), is("created")); assertThat(event.getIssue().getNumber(), is(2)); assertThat(event.getIssue().getTitle(), is("Spelling error in the README file")); @@ -134,31 +133,31 @@ public void issues() throws Exception { assertThat(event.getSender().getLogin(), is("baxterthehacker")); } -// TODO implement support classes and write test -// @Test -// public void label() throws Exception {} + // TODO implement support classes and write test + // @Test + // public void label() throws Exception {} -// TODO implement support classes and write test -// @Test -// public void member() throws Exception {} + // TODO implement support classes and write test + // @Test + // public void member() throws Exception {} -// TODO implement support classes and write test -// @Test -// public void membership() throws Exception {} + // TODO implement support classes and write test + // @Test + // public void membership() throws Exception {} -// TODO implement support classes and write test -// @Test -// public void milestone() throws Exception {} + // TODO implement support classes and write test + // @Test + // public void milestone() throws Exception {} -// TODO implement support classes and write test -// @Test -// public void page_build() throws Exception {} + // TODO implement support classes and write test + // @Test + // public void page_build() throws Exception {} @Test @Payload("public") public void public_() throws Exception { - GHEventPayload.Public event = - GitHub.offline().parseEventPayload(payload.asReader(), GHEventPayload.Public.class); + GHEventPayload.Public event = GitHub.offline().parseEventPayload(payload.asReader(), + GHEventPayload.Public.class); assertThat(event.getRepository().getName(), is("public-repo")); assertThat(event.getRepository().getOwner().getLogin(), is("baxterthehacker")); assertThat(event.getSender().getLogin(), is("baxterthehacker")); @@ -166,14 +165,14 @@ public void public_() throws Exception { @Test public void pull_request() throws Exception { - GHEventPayload.PullRequest event = - GitHub.offline().parseEventPayload(payload.asReader(), GHEventPayload.PullRequest.class); + GHEventPayload.PullRequest event = GitHub.offline().parseEventPayload(payload.asReader(), + GHEventPayload.PullRequest.class); assertThat(event.getAction(), is("opened")); assertThat(event.getNumber(), is(1)); assertThat(event.getPullRequest().getNumber(), is(1)); assertThat(event.getPullRequest().getTitle(), is("Update the README with new information")); - assertThat(event.getPullRequest().getBody(), is("This is a pretty simple change that we need to pull into " - + "master.")); + assertThat(event.getPullRequest().getBody(), + is("This is a pretty simple change that we need to pull into " + "master.")); assertThat(event.getPullRequest().getUser().getLogin(), is("baxterthehacker")); assertThat(event.getPullRequest().getHead().getUser().getLogin(), is("baxterthehacker")); assertThat(event.getPullRequest().getHead().getRef(), is("changes")); @@ -199,8 +198,8 @@ public void pull_request() throws Exception { @Test public void pull_request_review() throws Exception { - GHEventPayload.PullRequestReview event = - GitHub.offline().parseEventPayload(payload.asReader(), GHEventPayload.PullRequestReview.class); + GHEventPayload.PullRequestReview event = GitHub.offline().parseEventPayload(payload.asReader(), + GHEventPayload.PullRequestReview.class); assertThat(event.getAction(), is("submitted")); assertThat(event.getReview().getId(), is(2626884L)); @@ -228,15 +227,16 @@ public void pull_request_review() throws Exception { @Test public void pull_request_review_comment() throws Exception { - GHEventPayload.PullRequestReviewComment event = - GitHub.offline().parseEventPayload(payload.asReader(), GHEventPayload.PullRequestReviewComment.class); + GHEventPayload.PullRequestReviewComment event = GitHub.offline().parseEventPayload(payload.asReader(), + GHEventPayload.PullRequestReviewComment.class); assertThat(event.getAction(), is("created")); assertThat(event.getComment().getBody(), is("Maybe you should use more emojji on this line.")); assertThat(event.getPullRequest().getNumber(), is(1)); assertThat(event.getPullRequest().getTitle(), is("Update the README with new information")); - assertThat(event.getPullRequest().getBody(), is("This is a pretty simple change that we need to pull into master.")); + assertThat(event.getPullRequest().getBody(), + is("This is a pretty simple change that we need to pull into master.")); assertThat(event.getPullRequest().getUser().getLogin(), is("baxterthehacker")); assertThat(event.getPullRequest().getHead().getUser().getLogin(), is("baxterthehacker")); assertThat(event.getPullRequest().getHead().getRef(), is("changes")); @@ -255,8 +255,7 @@ public void pull_request_review_comment() throws Exception { @Test public void push() throws Exception { - GHEventPayload.Push event = - GitHub.offline().parseEventPayload(payload.asReader(), GHEventPayload.Push.class); + GHEventPayload.Push event = GitHub.offline().parseEventPayload(payload.asReader(), GHEventPayload.Push.class); assertThat(event.getRef(), is("refs/heads/changes")); assertThat(event.getBefore(), is("9049f1265b7d61be4a8904a9a27120d2064dab3b")); assertThat(event.getHead(), is("0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c")); @@ -273,20 +272,21 @@ public void push() throws Exception { assertThat(event.getCommits().get(0).getModified().get(0), is("README.md")); assertThat(event.getRepository().getName(), is("public-repo")); assertThat(event.getRepository().getOwnerName(), is("baxterthehacker")); - assertThat(event.getRepository().getUrl().toExternalForm(), is("https://github.com/baxterthehacker/public-repo")); + assertThat(event.getRepository().getUrl().toExternalForm(), + is("https://github.com/baxterthehacker/public-repo")); assertThat(event.getPusher().getName(), is("baxterthehacker")); assertThat(event.getPusher().getEmail(), is("baxterthehacker@users.noreply.github.com")); assertThat(event.getSender().getLogin(), is("baxterthehacker")); } -// TODO implement support classes and write test -// @Test -// public void release() throws Exception {} + // TODO implement support classes and write test + // @Test + // public void release() throws Exception {} @Test public void repository() throws Exception { - GHEventPayload.Repository event = - GitHub.offline().parseEventPayload(payload.asReader(), GHEventPayload.Repository.class); + GHEventPayload.Repository event = GitHub.offline().parseEventPayload(payload.asReader(), + GHEventPayload.Repository.class); assertThat(event.getAction(), is("created")); assertThat(event.getRepository().getName(), is("new-repository")); assertThat(event.getRepository().getOwner().getLogin(), is("baxterandthehackers")); @@ -294,16 +294,16 @@ public void repository() throws Exception { assertThat(event.getSender().getLogin(), is("baxterthehacker")); } -// TODO implement support classes and write test -// @Test -// public void status() throws Exception {} + // TODO implement support classes and write test + // @Test + // public void status() throws Exception {} -// TODO implement support classes and write test -// @Test -// public void team_add() throws Exception {} + // TODO implement support classes and write test + // @Test + // public void team_add() throws Exception {} -// TODO implement support classes and write test -// @Test -// public void watch() throws Exception {} + // TODO implement support classes and write test + // @Test + // public void watch() throws Exception {} } diff --git a/src/test/java/org/kohsuke/github/GHGistUpdaterTest.java b/src/test/java/org/kohsuke/github/GHGistUpdaterTest.java index 23bd4622f3..89d5b0f3e6 100644 --- a/src/test/java/org/kohsuke/github/GHGistUpdaterTest.java +++ b/src/test/java/org/kohsuke/github/GHGistUpdaterTest.java @@ -21,13 +21,9 @@ public class GHGistUpdaterTest extends AbstractGitHubWireMockTest { @Before public void setUp() throws IOException { GHGistBuilder builder = new GHGistBuilder(gitHub); - gist = builder.description("Test for the API") - .file("unmodified.txt", "Should be unmodified") - //.file("delete-me.txt", "To be deleted") - .file("rename-me.py", "print 'hello'") - .file("update-me.txt", "To be updated") - .public_(true) - .create(); + gist = builder.description("Test for the API").file("unmodified.txt", "Should be unmodified") + // .file("delete-me.txt", "To be deleted") + .file("rename-me.py", "print 'hello'").file("update-me.txt", "To be updated").public_(true).create(); } @After @@ -45,21 +41,20 @@ public void testGitUpdater() throws Exception { GHGistUpdater updater = gist.update(); GHGist updatedGist = updater.description("Description updated by API") .addFile("new-file.txt", "Added by updater") - //.deleteFile("delete-me.txt") - .renameFile("rename-me.py", "renamed.py") - .updateFile("update-me.txt", "Content updated by API") + // .deleteFile("delete-me.txt") + .renameFile("rename-me.py", "renamed.py").updateFile("update-me.txt", "Content updated by API") .update(); assertEquals("Description updated by API", updatedGist.getDescription()); - Map files = updatedGist.getFiles(); + Map files = updatedGist.getFiles(); // Check that the unmodified file stays intact. assertTrue(files.containsKey("unmodified.txt")); assertEquals("Should be unmodified", files.get("unmodified.txt").getContent()); // Check that the files are updated as expected. - //assertFalse("File was not deleted.", files.containsKey("delete-me.txt")); + // assertFalse("File was not deleted.", files.containsKey("delete-me.txt")); assertTrue(files.containsKey("new-file.txt")); assertEquals("Added by updater", files.get("new-file.txt").getContent()); diff --git a/src/test/java/org/kohsuke/github/GHHookTest.java b/src/test/java/org/kohsuke/github/GHHookTest.java index b27484b5e5..6fee386ca1 100644 --- a/src/test/java/org/kohsuke/github/GHHookTest.java +++ b/src/test/java/org/kohsuke/github/GHHookTest.java @@ -17,7 +17,6 @@ import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.junit.Assert.assertThat; - /** * @author Kanstantsin Shautsou */ @@ -59,20 +58,15 @@ public void exposeResponceHeaders() throws Exception { try { // fails because application isn't approved in organisation and you can find it only after doing real call - final GHHook hook = repository.createHook( - "my-hook", - singletonMap("url", "http://localhost"), - singletonList(GHEvent.PUSH), - true - ); + final GHHook hook = repository.createHook("my-hook", singletonMap("url", "http://localhost"), + singletonList(GHEvent.PUSH), true); } catch (IOException ex) { assertThat(ex, instanceOf(GHFileNotFoundException.class)); final GHFileNotFoundException ghFileNotFoundException = (GHFileNotFoundException) ex; final Map> responseHeaderFields = ghFileNotFoundException.getResponseHeaderFields(); assertThat(responseHeaderFields, hasKey("X-Accepted-OAuth-Scopes")); assertThat(responseHeaderFields.get("X-Accepted-OAuth-Scopes"), - hasItem("admin:repo_hook, public_repo, repo, write:repo_hook") - ); + hasItem("admin:repo_hook, public_repo, repo, write:repo_hook")); } } } diff --git a/src/test/java/org/kohsuke/github/GHIssueEventTest.java b/src/test/java/org/kohsuke/github/GHIssueEventTest.java index bee82f0928..82417e3219 100644 --- a/src/test/java/org/kohsuke/github/GHIssueEventTest.java +++ b/src/test/java/org/kohsuke/github/GHIssueEventTest.java @@ -45,7 +45,8 @@ public void testRepositoryEvents() throws Exception { int i = 0; for (GHIssueEvent event : list) { assertNotNull(event.getIssue()); - if (i++ > 10) break; + if (i++ > 10) + break; } } diff --git a/src/test/java/org/kohsuke/github/GHLicenseTest.java b/src/test/java/org/kohsuke/github/GHLicenseTest.java index 9a77972c34..301ba58d77 100644 --- a/src/test/java/org/kohsuke/github/GHLicenseTest.java +++ b/src/test/java/org/kohsuke/github/GHLicenseTest.java @@ -39,6 +39,7 @@ public class GHLicenseTest extends AbstractGitHubWireMockTest { * Basic test to ensure that the list of licenses from {@link GitHub#listLicenses()} is returned * * @throws IOException + * if test fails */ @Test public void listLicenses() throws IOException { @@ -47,10 +48,10 @@ public void listLicenses() throws IOException { } /** - * Tests that {@link GitHub#listLicenses()} returns the MIT license - * in the expected manner. + * Tests that {@link GitHub#listLicenses()} returns the MIT license in the expected manner. * * @throws IOException + * if test fails */ @Test public void listLicensesCheckIndividualLicense() throws IOException { @@ -65,10 +66,11 @@ public void listLicensesCheckIndividualLicense() throws IOException { } /** - * Checks that the request for an individual license using {@link GitHub#getLicense(String)} - * returns expected values (not all properties are checked) + * Checks that the request for an individual license using {@link GitHub#getLicense(String)} returns expected values + * (not all properties are checked) * * @throws IOException + * if test fails */ @Test public void getLicense() throws IOException { @@ -76,14 +78,16 @@ public void getLicense() throws IOException { GHLicense license = gitHub.getLicense(key); assertNotNull(license); assertTrue("The name is correct", license.getName().equals("MIT License")); - assertTrue("The HTML URL is correct", license.getHtmlUrl().equals(new URL("http://choosealicense.com/licenses/mit/"))); + assertTrue("The HTML URL is correct", + license.getHtmlUrl().equals(new URL("http://choosealicense.com/licenses/mit/"))); } /** - * Accesses the 'kohsuke/github-api' repo using {@link GitHub#getRepository(String)} - * and checks that the license is correct + * Accesses the 'kohsuke/github-api' repo using {@link GitHub#getRepository(String)} and checks that the license is + * correct * * @throws IOException + * if test failss */ @Test public void checkRepositoryLicense() throws IOException { @@ -92,14 +96,15 @@ public void checkRepositoryLicense() throws IOException { assertNotNull("The license is populated", license); assertTrue("The key is correct", license.getKey().equals("mit")); assertTrue("The name is correct", license.getName().equals("MIT License")); - assertTrue("The URL is correct", license.getUrl().equals(new URL(mockGitHub.apiServer().baseUrl() + "/licenses/mit"))); + assertTrue("The URL is correct", + license.getUrl().equals(new URL(mockGitHub.apiServer().baseUrl() + "/licenses/mit"))); } /** - * Accesses the 'atom/atom' repo using {@link GitHub#getRepository(String)} - * and checks that the license is correct + * Accesses the 'atom/atom' repo using {@link GitHub#getRepository(String)} and checks that the license is correct * * @throws IOException + * if test fails */ @Test public void checkRepositoryLicenseAtom() throws IOException { @@ -108,14 +113,15 @@ public void checkRepositoryLicenseAtom() throws IOException { assertNotNull("The license is populated", license); assertTrue("The key is correct", license.getKey().equals("mit")); assertTrue("The name is correct", license.getName().equals("MIT License")); - assertTrue("The URL is correct", license.getUrl().equals(new URL(mockGitHub.apiServer().baseUrl() + "/licenses/mit"))); + assertTrue("The URL is correct", + license.getUrl().equals(new URL(mockGitHub.apiServer().baseUrl() + "/licenses/mit"))); } /** - * Accesses the 'pomes/pomes' repo using {@link GitHub#getRepository(String)} - * and checks that the license is correct + * Accesses the 'pomes/pomes' repo using {@link GitHub#getRepository(String)} and checks that the license is correct * * @throws IOException + * if test fails */ @Test public void checkRepositoryLicensePomes() throws IOException { @@ -124,14 +130,16 @@ public void checkRepositoryLicensePomes() throws IOException { assertNotNull("The license is populated", license); assertTrue("The key is correct", license.getKey().equals("apache-2.0")); assertTrue("The name is correct", license.getName().equals("Apache License 2.0")); - assertTrue("The URL is correct", license.getUrl().equals(new URL(mockGitHub.apiServer().baseUrl() + "/licenses/apache-2.0"))); + assertTrue("The URL is correct", + license.getUrl().equals(new URL(mockGitHub.apiServer().baseUrl() + "/licenses/apache-2.0"))); } /** - * Accesses the 'dedickinson/test-repo' repo using {@link GitHub#getRepository(String)} - * and checks that *no* license is returned as the repo doesn't have one + * Accesses the 'dedickinson/test-repo' repo using {@link GitHub#getRepository(String)} and checks that *no* license + * is returned as the repo doesn't have one * * @throws IOException + * if test fails */ @Test public void checkRepositoryWithoutLicense() throws IOException { @@ -141,11 +149,11 @@ public void checkRepositoryWithoutLicense() throws IOException { } /** - * Accesses the 'kohsuke/github-api' repo using {@link GitHub#getRepository(String)} - * and then calls {@link GHRepository#getLicense()} and checks that certain - * properties are correct + * Accesses the 'kohsuke/github-api' repo using {@link GitHub#getRepository(String)} and then calls + * {@link GHRepository#getLicense()} and checks that certain properties are correct * * @throws IOException + * if test fails */ @Test public void checkRepositoryFullLicense() throws IOException { @@ -154,16 +162,18 @@ public void checkRepositoryFullLicense() throws IOException { assertNotNull("The license is populated", license); assertTrue("The key is correct", license.getKey().equals("mit")); assertTrue("The name is correct", license.getName().equals("MIT License")); - assertTrue("The URL is correct", license.getUrl().equals(new URL(mockGitHub.apiServer().baseUrl() + "/licenses/mit"))); - assertTrue("The HTML URL is correct", license.getHtmlUrl().equals(new URL("http://choosealicense.com/licenses/mit/"))); + assertTrue("The URL is correct", + license.getUrl().equals(new URL(mockGitHub.apiServer().baseUrl() + "/licenses/mit"))); + assertTrue("The HTML URL is correct", + license.getHtmlUrl().equals(new URL("http://choosealicense.com/licenses/mit/"))); } /** - * Accesses the 'pomes/pomes' repo using {@link GitHub#getRepository(String)} - * and then calls {@link GHRepository#getLicenseContent()} and checks that certain - * properties are correct + * Accesses the 'pomes/pomes' repo using {@link GitHub#getRepository(String)} and then calls + * {@link GHRepository#getLicenseContent()} and checks that certain properties are correct * * @throws IOException + * if test fails */ @Test public void checkRepositoryLicenseContent() throws IOException { diff --git a/src/test/java/org/kohsuke/github/GHMilestoneTest.java b/src/test/java/org/kohsuke/github/GHMilestoneTest.java index c0ab886743..10ccc9a1a2 100644 --- a/src/test/java/org/kohsuke/github/GHMilestoneTest.java +++ b/src/test/java/org/kohsuke/github/GHMilestoneTest.java @@ -21,8 +21,7 @@ public void cleanUp() throws Exception { } for (GHMilestone milestone : getRepository(gitHubBeforeAfter).listMilestones(GHIssueState.ALL)) { - if ("Original Title".equals(milestone.getTitle()) || - "Updated Title".equals(milestone.getTitle())) { + if ("Original Title".equals(milestone.getTitle()) || "Updated Title".equals(milestone.getTitle())) { milestone.delete(); } } @@ -31,8 +30,7 @@ public void cleanUp() throws Exception { @Test public void testUpdateMilestone() throws Exception { GHRepository repo = getRepository(); - GHMilestone milestone = repo.createMilestone("Original Title", - "To test the update methods"); + GHMilestone milestone = repo.createMilestone("Original Title", "To test the update methods"); String NEW_TITLE = "Updated Title"; String NEW_DESCRIPTION = "Updated Description"; diff --git a/src/test/java/org/kohsuke/github/GHOrganizationTest.java b/src/test/java/org/kohsuke/github/GHOrganizationTest.java index dd9d3335ee..d9f693edee 100644 --- a/src/test/java/org/kohsuke/github/GHOrganizationTest.java +++ b/src/test/java/org/kohsuke/github/GHOrganizationTest.java @@ -13,7 +13,6 @@ public class GHOrganizationTest extends AbstractGitHubWireMockTest { public static final String GITHUB_API_TEST = "github-api-test"; public static final String TEAM_NAME_CREATE = "create-team-test"; - @Before @After public void cleanUpTeam() throws IOException { @@ -22,8 +21,7 @@ public void cleanUpTeam() throws IOException { return; } - GHTeam team = gitHubBeforeAfter.getOrganization(GITHUB_API_TEST_ORG). - getTeamByName(TEAM_NAME_CREATE); + GHTeam team = gitHubBeforeAfter.getOrganization(GITHUB_API_TEST_ORG).getTeamByName(TEAM_NAME_CREATE); if (team != null) { team.delete(); } @@ -35,7 +33,8 @@ public void testCreateRepository() throws IOException { GHOrganization org = gitHub.getOrganization(GITHUB_API_TEST_ORG); GHRepository repository = org.createRepository(GITHUB_API_TEST, - "a test repository used to test kohsuke's github-api", "http://github-api.kohsuke.org/", "Core Developers", true); + "a test repository used to test kohsuke's github-api", "http://github-api.kohsuke.org/", + "Core Developers", true); Assert.assertNotNull(repository); } @@ -45,10 +44,9 @@ public void testCreateRepositoryWithAutoInitialization() throws IOException { GHOrganization org = gitHub.getOrganization(GITHUB_API_TEST_ORG); GHRepository repository = org.createRepository(GITHUB_API_TEST) - .description("a test repository used to test kohsuke's github-api") - .homepage("http://github-api.kohsuke.org/") - .team(org.getTeamByName("Core Developers")) - .autoInit(true).create(); + .description("a test repository used to test kohsuke's github-api") + .homepage("http://github-api.kohsuke.org/").team(org.getTeamByName("Core Developers")).autoInit(true) + .create(); Assert.assertNotNull(repository); Assert.assertNotNull(repository.getReadme()); } @@ -74,7 +72,6 @@ public void testInviteUser() throws IOException { // assertTrue(org.hasMember(user)); } - @Test public void testCreateTeamWithRepoAccess() throws IOException { String REPO_NAME = "github-api"; diff --git a/src/test/java/org/kohsuke/github/GHProjectCardTest.java b/src/test/java/org/kohsuke/github/GHProjectCardTest.java index e155f86024..e6bf0b06b3 100644 --- a/src/test/java/org/kohsuke/github/GHProjectCardTest.java +++ b/src/test/java/org/kohsuke/github/GHProjectCardTest.java @@ -12,96 +12,94 @@ * @author Gunnar Skjold */ public class GHProjectCardTest extends AbstractGitHubWireMockTest { - private GHOrganization org; - private GHProject project; - private GHProjectColumn column; - private GHProjectCard card; + private GHOrganization org; + private GHProject project; + private GHProjectColumn column; + private GHProjectCard card; - @Before - public void setUp() throws Exception { - org = gitHub.getOrganization(GITHUB_API_TEST_ORG); - project = org.createProject("test-project", "This is a test project"); - column = project.createColumn("column-one"); - card = column.createCard("This is a card"); - } + @Before + public void setUp() throws Exception { + org = gitHub.getOrganization(GITHUB_API_TEST_ORG); + project = org.createProject("test-project", "This is a test project"); + column = project.createColumn("column-one"); + card = column.createCard("This is a card"); + } - @Test - public void testCreatedCard() { - Assert.assertEquals("This is a card", card.getNote()); - Assert.assertFalse(card.isArchived()); - } + @Test + public void testCreatedCard() { + Assert.assertEquals("This is a card", card.getNote()); + Assert.assertFalse(card.isArchived()); + } - @Test - public void testEditCardNote() throws IOException { - card.setNote("New note"); - card = gitHub.getProjectCard(card.getId()); - Assert.assertEquals("New note", card.getNote()); - Assert.assertFalse(card.isArchived()); - } + @Test + public void testEditCardNote() throws IOException { + card.setNote("New note"); + card = gitHub.getProjectCard(card.getId()); + Assert.assertEquals("New note", card.getNote()); + Assert.assertFalse(card.isArchived()); + } - @Test - public void testArchiveCard() throws IOException { - card.setArchived(true); - card = gitHub.getProjectCard(card.getId()); - Assert.assertEquals("This is a card", card.getNote()); - Assert.assertTrue(card.isArchived()); - } + @Test + public void testArchiveCard() throws IOException { + card.setArchived(true); + card = gitHub.getProjectCard(card.getId()); + Assert.assertEquals("This is a card", card.getNote()); + Assert.assertTrue(card.isArchived()); + } - @Test - public void testCreateCardFromIssue() throws IOException { - GHRepository repo = org.createRepository("repo-for-project-card").create(); - try { - GHIssue issue = repo.createIssue("new-issue").body("With body").create(); - GHProjectCard card = column.createCard(issue); - Assert.assertEquals(issue.getUrl(), card.getContentUrl()); - } finally { - repo.delete(); - } - } + @Test + public void testCreateCardFromIssue() throws IOException { + GHRepository repo = org.createRepository("repo-for-project-card").create(); + try { + GHIssue issue = repo.createIssue("new-issue").body("With body").create(); + GHProjectCard card = column.createCard(issue); + Assert.assertEquals(issue.getUrl(), card.getContentUrl()); + } finally { + repo.delete(); + } + } - @Test - public void testDeleteCard() throws IOException { - card.delete(); - try { - card = gitHub.getProjectCard(card.getId()); - Assert.assertNull(card); - } catch (FileNotFoundException e) { - card = null; - } - } + @Test + public void testDeleteCard() throws IOException { + card.delete(); + try { + card = gitHub.getProjectCard(card.getId()); + Assert.assertNull(card); + } catch (FileNotFoundException e) { + card = null; + } + } - @After - public void after() throws IOException { - if(mockGitHub.isUseProxy()) { - if (card != null) { - card = gitHubBeforeAfter.getProjectCard(card.getId()); - try { - card.delete(); - card = null; - } catch (FileNotFoundException e) { - card = null; - } - } - if (column != null) { - column = gitHubBeforeAfter - .getProjectColumn(column.getId()); - try { - column.delete(); - column = null; - } catch (FileNotFoundException e) { - column = null; - } - } - if (project != null) { - project = gitHubBeforeAfter - .getProject(project.getId()); - try { - project.delete(); - project = null; - } catch (FileNotFoundException e) { - project = null; - } - } - } - } + @After + public void after() throws IOException { + if (mockGitHub.isUseProxy()) { + if (card != null) { + card = gitHubBeforeAfter.getProjectCard(card.getId()); + try { + card.delete(); + card = null; + } catch (FileNotFoundException e) { + card = null; + } + } + if (column != null) { + column = gitHubBeforeAfter.getProjectColumn(column.getId()); + try { + column.delete(); + column = null; + } catch (FileNotFoundException e) { + column = null; + } + } + if (project != null) { + project = gitHubBeforeAfter.getProject(project.getId()); + try { + project.delete(); + project = null; + } catch (FileNotFoundException e) { + project = null; + } + } + } + } } diff --git a/src/test/java/org/kohsuke/github/GHProjectColumnTest.java b/src/test/java/org/kohsuke/github/GHProjectColumnTest.java index db3003da61..29c7e0fd8e 100644 --- a/src/test/java/org/kohsuke/github/GHProjectColumnTest.java +++ b/src/test/java/org/kohsuke/github/GHProjectColumnTest.java @@ -12,63 +12,59 @@ * @author Gunnar Skjold */ public class GHProjectColumnTest extends AbstractGitHubWireMockTest { - private GHProject project; - private GHProjectColumn column; + private GHProject project; + private GHProjectColumn column; - @Before - public void setUp() throws Exception { - project = gitHub - .getOrganization(GITHUB_API_TEST_ORG) - .createProject("test-project", "This is a test project"); - column = project.createColumn("column-one"); - } + @Before + public void setUp() throws Exception { + project = gitHub.getOrganization(GITHUB_API_TEST_ORG).createProject("test-project", "This is a test project"); + column = project.createColumn("column-one"); + } - @Test - public void testCreatedColumn() { - Assert.assertEquals("column-one", column.getName()); - } + @Test + public void testCreatedColumn() { + Assert.assertEquals("column-one", column.getName()); + } - @Test - public void testEditColumnName() throws IOException { - column.setName("new-name"); - column = gitHub.getProjectColumn(column.getId()); - Assert.assertEquals("new-name", column.getName()); - } + @Test + public void testEditColumnName() throws IOException { + column.setName("new-name"); + column = gitHub.getProjectColumn(column.getId()); + Assert.assertEquals("new-name", column.getName()); + } - @Test - public void testDeleteColumn() throws IOException { - column.delete(); - try { - column = gitHub.getProjectColumn(column.getId()); - Assert.assertNull(column); - } catch (FileNotFoundException e) { - column = null; - } - } + @Test + public void testDeleteColumn() throws IOException { + column.delete(); + try { + column = gitHub.getProjectColumn(column.getId()); + Assert.assertNull(column); + } catch (FileNotFoundException e) { + column = null; + } + } - @After - public void after() throws IOException { - if(mockGitHub.isUseProxy()) { - if (column != null) { - column = gitHubBeforeAfter - .getProjectColumn(column.getId()); - try { - column.delete(); - column = null; - } catch (FileNotFoundException e) { - column = null; - } - } - if (project != null) { - project = gitHubBeforeAfter - .getProject(project.getId()); - try { - project.delete(); - project = null; - } catch (FileNotFoundException e) { - project = null; - } - } - } - } + @After + public void after() throws IOException { + if (mockGitHub.isUseProxy()) { + if (column != null) { + column = gitHubBeforeAfter.getProjectColumn(column.getId()); + try { + column.delete(); + column = null; + } catch (FileNotFoundException e) { + column = null; + } + } + if (project != null) { + project = gitHubBeforeAfter.getProject(project.getId()); + try { + project.delete(); + project = null; + } catch (FileNotFoundException e) { + project = null; + } + } + } + } } diff --git a/src/test/java/org/kohsuke/github/GHProjectTest.java b/src/test/java/org/kohsuke/github/GHProjectTest.java index fe1722576d..178a1d2b54 100644 --- a/src/test/java/org/kohsuke/github/GHProjectTest.java +++ b/src/test/java/org/kohsuke/github/GHProjectTest.java @@ -12,74 +12,71 @@ * @author Gunnar Skjold */ public class GHProjectTest extends AbstractGitHubWireMockTest { - private GHProject project; + private GHProject project; - @Before - public void setUp() throws Exception { - project = gitHub - .getOrganization(GITHUB_API_TEST_ORG) - .createProject("test-project", "This is a test project"); - } + @Before + public void setUp() throws Exception { + project = gitHub.getOrganization(GITHUB_API_TEST_ORG).createProject("test-project", "This is a test project"); + } - @Test - public void testCreatedProject() { - Assert.assertNotNull(project); - Assert.assertEquals("test-project", project.getName()); - Assert.assertEquals("This is a test project", project.getBody()); - Assert.assertEquals(GHProject.ProjectState.OPEN, project.getState()); - } + @Test + public void testCreatedProject() { + Assert.assertNotNull(project); + Assert.assertEquals("test-project", project.getName()); + Assert.assertEquals("This is a test project", project.getBody()); + Assert.assertEquals(GHProject.ProjectState.OPEN, project.getState()); + } - @Test - public void testEditProjectName() throws IOException { - project.setName("new-name"); - project = gitHub.getProject(project.getId()); - Assert.assertEquals("new-name", project.getName()); - Assert.assertEquals("This is a test project", project.getBody()); - Assert.assertEquals(GHProject.ProjectState.OPEN, project.getState()); - } + @Test + public void testEditProjectName() throws IOException { + project.setName("new-name"); + project = gitHub.getProject(project.getId()); + Assert.assertEquals("new-name", project.getName()); + Assert.assertEquals("This is a test project", project.getBody()); + Assert.assertEquals(GHProject.ProjectState.OPEN, project.getState()); + } - @Test - public void testEditProjectBody() throws IOException { - project.setBody("New body"); - project = gitHub.getProject(project.getId()); - Assert.assertEquals("test-project", project.getName()); - Assert.assertEquals("New body", project.getBody()); - Assert.assertEquals(GHProject.ProjectState.OPEN, project.getState()); - } + @Test + public void testEditProjectBody() throws IOException { + project.setBody("New body"); + project = gitHub.getProject(project.getId()); + Assert.assertEquals("test-project", project.getName()); + Assert.assertEquals("New body", project.getBody()); + Assert.assertEquals(GHProject.ProjectState.OPEN, project.getState()); + } - @Test - public void testEditProjectState() throws IOException { - project.setState(GHProject.ProjectState.CLOSED); - project = gitHub.getProject(project.getId()); - Assert.assertEquals("test-project", project.getName()); - Assert.assertEquals("This is a test project", project.getBody()); - Assert.assertEquals(GHProject.ProjectState.CLOSED, project.getState()); - } + @Test + public void testEditProjectState() throws IOException { + project.setState(GHProject.ProjectState.CLOSED); + project = gitHub.getProject(project.getId()); + Assert.assertEquals("test-project", project.getName()); + Assert.assertEquals("This is a test project", project.getBody()); + Assert.assertEquals(GHProject.ProjectState.CLOSED, project.getState()); + } - @Test - public void testDeleteProject() throws IOException { - project.delete(); - try { - project = gitHub.getProject(project.getId()); - Assert.assertNull(project); - } catch (FileNotFoundException e) { - project = null; - } - } + @Test + public void testDeleteProject() throws IOException { + project.delete(); + try { + project = gitHub.getProject(project.getId()); + Assert.assertNull(project); + } catch (FileNotFoundException e) { + project = null; + } + } - @After - public void after() throws IOException { - if (mockGitHub.isUseProxy()) { - if (project != null) { - project = gitHubBeforeAfter - .getProject(project.getId()); - try { - project.delete(); - project = null; - } catch (FileNotFoundException e) { - project = null; - } - } - } - } + @After + public void after() throws IOException { + if (mockGitHub.isUseProxy()) { + if (project != null) { + project = gitHubBeforeAfter.getProject(project.getId()); + try { + project.delete(); + project = null; + } catch (FileNotFoundException e) { + project = null; + } + } + } + } } diff --git a/src/test/java/org/kohsuke/github/GHPullRequestTest.java b/src/test/java/org/kohsuke/github/GHPullRequestTest.java index 4c9ebe4130..71ae5db660 100644 --- a/src/test/java/org/kohsuke/github/GHPullRequestTest.java +++ b/src/test/java/org/kohsuke/github/GHPullRequestTest.java @@ -57,17 +57,10 @@ public void createDraftPullRequest() throws Exception { assertThat(p2.getNumber(), is(p.getNumber())); assertThat(p2.isDraft(), is(true)); - p = repo.queryPullRequests() - .state(GHIssueState.OPEN) - .head("test/stable") - .list().asList().get(0); + p = repo.queryPullRequests().state(GHIssueState.OPEN).head("test/stable").list().asList().get(0); assertThat(p2.getNumber(), is(p.getNumber())); assertThat(p.isDraft(), is(true)); - - - - } @Test @@ -88,15 +81,12 @@ public void closePullRequest() throws Exception { assertEquals(GHIssueState.CLOSED, getRepository().getPullRequest(p.getNumber()).getState()); } - @Test public void pullRequestReviews() throws Exception { String name = "testPullRequestReviews"; GHPullRequest p = getRepository().createPullRequest(name, "test/stable", "master", "## test"); - GHPullRequestReview draftReview = p.createReview() - .body("Some draft review") - .comment("Some niggle", "README.md", 1) - .create(); + GHPullRequestReview draftReview = p.createReview().body("Some draft review") + .comment("Some niggle", "README.md", 1).create(); assertThat(draftReview.getState(), is(GHPullRequestReviewState.PENDING)); assertThat(draftReview.getBody(), is("Some draft review")); assertThat(draftReview.getCommitId(), notNullValue()); @@ -111,10 +101,7 @@ public void pullRequestReviews() throws Exception { assertEquals(1, comments.size()); GHPullRequestReviewComment comment = comments.get(0); assertEquals("Some niggle", comment.getBody()); - draftReview = p.createReview() - .body("Some new review") - .comment("Some niggle", "README.md", 1) - .create(); + draftReview = p.createReview().body("Some new review").comment("Some niggle", "README.md", 1).create(); draftReview.delete(); } @@ -169,14 +156,14 @@ public void testPullRequestTeamReviewRequests() throws Exception { int baseRequestCount = mockGitHub.getRequestCount(); p.refresh(); assertThat("We should not eagerly load organizations for teams", - mockGitHub.getRequestCount() - baseRequestCount , equalTo(1)); + mockGitHub.getRequestCount() - baseRequestCount, equalTo(1)); assertThat(p.getRequestedTeams().size(), equalTo(1)); assertThat("We should not eagerly load organizations for teams", - mockGitHub.getRequestCount() - baseRequestCount , equalTo(1)); + mockGitHub.getRequestCount() - baseRequestCount, equalTo(1)); assertThat("Org should be queried for automatically if asked for", - p.getRequestedTeams().get(0).getOrganization(), notNullValue()); - assertThat("Request count should show lazy load occurred", - mockGitHub.getRequestCount() - baseRequestCount , equalTo(2)); + p.getRequestedTeams().get(0).getOrganization(), notNullValue()); + assertThat("Request count should show lazy load occurred", mockGitHub.getRequestCount() - baseRequestCount, + equalTo(2)); } @Test @@ -186,25 +173,21 @@ public void mergeCommitSHA() throws Exception { GHPullRequest p = repo.createPullRequest(name, "test/mergeable_branch", "master", "## test"); int baseRequestCount = mockGitHub.getRequestCount(); assertThat(p.getMergeableNoRefresh(), nullValue()); - assertThat("Used existing value", - mockGitHub.getRequestCount() - baseRequestCount , equalTo(0)); + assertThat("Used existing value", mockGitHub.getRequestCount() - baseRequestCount, equalTo(0)); // mergeability computation takes time, this should still be null immediately after creation assertThat(p.getMergeable(), nullValue()); - assertThat("Asked for PR information", - mockGitHub.getRequestCount() - baseRequestCount , equalTo(1)); + assertThat("Asked for PR information", mockGitHub.getRequestCount() - baseRequestCount, equalTo(1)); for (int i = 2; i <= 10; i++) { if (Boolean.TRUE.equals(p.getMergeable()) && p.getMergeCommitSha() != null) { - assertThat("Asked for PR information", - mockGitHub.getRequestCount() - baseRequestCount , equalTo(i)); + assertThat("Asked for PR information", mockGitHub.getRequestCount() - baseRequestCount, equalTo(i)); // make sure commit exists GHCommit commit = repo.getCommit(p.getMergeCommitSha()); assertNotNull(commit); - assertThat("Asked for PR information", - mockGitHub.getRequestCount() - baseRequestCount , equalTo(i + 1)); + assertThat("Asked for PR information", mockGitHub.getRequestCount() - baseRequestCount, equalTo(i + 1)); return; } @@ -241,13 +224,8 @@ public void updateContentSquashMerge() throws Exception { GHContentUpdateResponse response = getRepository().createContent(name, name, name, branchName); Thread.sleep(1000); - getRepository().createContent() - .content(name + name) - .path(name) - .branch(branchName) - .message(name) - .sha(response.getContent().getSha()) - .commit(); + getRepository().createContent().content(name + name).path(name).branch(branchName).message(name) + .sha(response.getContent().getSha()).commit(); GHPullRequest p = getRepository().createPullRequest(name, branchName, "master", "## test squash"); Thread.sleep(1000); p.merge("squash merge", null, GHPullRequest.MergeMethod.SQUASH); @@ -261,7 +239,8 @@ public void queryPullRequestsQualifiedHead() throws Exception { repo.createPullRequest("queryPullRequestsQualifiedHead_rc", "test/rc", "master", null); // Query by one of the heads and make sure we only get that branch's PR back. - List prs = repo.queryPullRequests().state(GHIssueState.OPEN).head("github-api-test-org:test/stable").base("master").list().asList(); + List prs = repo.queryPullRequests().state(GHIssueState.OPEN) + .head("github-api-test-org:test/stable").base("master").list().asList(); assertNotNull(prs); assertEquals(1, prs.size()); assertEquals("test/stable", prs.get(0).getHead().getRef()); @@ -275,7 +254,8 @@ public void queryPullRequestsUnqualifiedHead() throws Exception { repo.createPullRequest("queryPullRequestsUnqualifiedHead_rc", "test/rc", "master", null); // Query by one of the heads and make sure we only get that branch's PR back. - List prs = repo.queryPullRequests().state(GHIssueState.OPEN).head("test/stable").base("master").list().asList(); + List prs = repo.queryPullRequests().state(GHIssueState.OPEN).head("test/stable").base("master") + .list().asList(); assertNotNull(prs); assertEquals(1, prs.size()); assertEquals("test/stable", prs.get(0).getHead().getRef()); diff --git a/src/test/java/org/kohsuke/github/GHRateLimitTest.java b/src/test/java/org/kohsuke/github/GHRateLimitTest.java index 4206e86a2a..9ad89e7cbe 100644 --- a/src/test/java/org/kohsuke/github/GHRateLimitTest.java +++ b/src/test/java/org/kohsuke/github/GHRateLimitTest.java @@ -24,16 +24,16 @@ * Key take aways: * *
    - *
  • These tests are artificial and intended to highlight the differences - * in behavior between scenarios. However, the differences they indicate are stark.
  • + *
  • These tests are artificial and intended to highlight the differences in behavior between scenarios. However, the + * differences they indicate are stark.
  • *
  • Caching reduces rate limit consumption by at least a factor of two in even the simplest case.
  • - *
  • The OkHttp cache is pretty smart and will often connect read and write requests made - * on the same client and invalidate caches.
  • - *
  • Changes made outside the current client cause the OkHttp cache to return stale data. - * This is expected and correct behavior.
  • - *
  • "max-age=0" addresses the problem of external changes by revalidating caches for each request. - * This produces the same number of requests as OkHttp without caching, but those requests only - * count towards the GitHub rate limit if data has changes.
  • + *
  • The OkHttp cache is pretty smart and will often connect read and write requests made on the same client and + * invalidate caches.
  • + *
  • Changes made outside the current client cause the OkHttp cache to return stale data. This is expected and correct + * behavior.
  • + *
  • "max-age=0" addresses the problem of external changes by revalidating caches for each request. This produces the + * same number of requests as OkHttp without caching, but those requests only count towards the GitHub rate limit if + * data has changes.
  • *
* * @author Liam Newman @@ -47,11 +47,7 @@ public GHRateLimitTest() { @Override protected WireMockConfiguration getWireMockOptions() { return super.getWireMockOptions() - .extensions(ResponseTemplateTransformer.builder() - .global(true) - .maxCacheEntries(0L) - .build() - ); + .extensions(ResponseTemplateTransformer.builder().global(true).maxCacheEntries(0L).build()); } @Test @@ -70,8 +66,7 @@ public void testGitHubRateLimit() throws Exception { // ------------------------------------------------------------- // /user gets response with rate limit information - gitHub = getGitHubBuilder() - .withEndpoint(mockGitHub.apiServer().baseUrl()).build(); + gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()).build(); gitHub.getMyself(); assertThat(mockGitHub.getRequestCount(), equalTo(1)); @@ -125,11 +120,9 @@ public void testGitHubRateLimit() throws Exception { assertThat(rateLimit.getRemaining(), equalTo(lastRemaining)); assertThat(rateLimit.getResetDate().compareTo(lastReset), greaterThanOrEqualTo(0)); - gitHub.getOrganization(GITHUB_API_TEST_ORG); assertThat(mockGitHub.getRequestCount(), equalTo(4)); - assertThat(gitHub.lastRateLimit(), not(equalTo(headerRateLimit))); rateLimit = gitHub.lastRateLimit(); assertThat(rateLimit, notNullValue()); @@ -253,7 +246,6 @@ public void testGitHubEnterpriseDoesNotHaveRateLimit() throws Exception { // Give this a moment Thread.sleep(1000); - // last is still null, because it actually means lastHeaderRateLimit assertThat(gitHub.lastRateLimit(), CoreMatchers.nullValue()); @@ -310,7 +302,6 @@ public void testGitHubEnterpriseDoesNotHaveRateLimit() throws Exception { Thread.sleep(1000); } - // These tests should behave the same, showing server time adjustment working @Test public void testGitHubRateLimitExpirationServerFiveMinutesAhead() throws Exception { @@ -322,7 +313,7 @@ public void testGitHubRateLimitExpirationServerFiveMinutesBehind() throws Except executeExpirationTest(); } - private void executeExpirationTest() throws Exception { + private void executeExpirationTest() throws Exception { // Customized response that templates the date to keep things working snapshotNotAllowed(); @@ -330,14 +321,12 @@ private void executeExpirationTest() throws Exception { GHRateLimit rateLimit = null; GHRateLimit headerRateLimit = null; - // Give this a moment Thread.sleep(1000); // ------------------------------------------------------------- // /user gets response with rate limit information - gitHub = getGitHubBuilder() - .withEndpoint(mockGitHub.apiServer().baseUrl()).build(); + gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()).build(); gitHub.getMyself(); assertThat(mockGitHub.getRequestCount(), equalTo(1)); @@ -347,57 +336,52 @@ private void executeExpirationTest() throws Exception { rateLimit = gitHub.rateLimit(); assertThat(rateLimit, notNullValue()); - assertThat("rateLimit() selects header instance when not expired, does not ask server", - rateLimit, sameInstance(headerRateLimit)); + assertThat("rateLimit() selects header instance when not expired, does not ask server", rateLimit, + sameInstance(headerRateLimit)); // Nothing changes still valid Thread.sleep(1000); - assertThat("rateLimit() selects header instance when not expired, does not ask server", - gitHub.rateLimit(), sameInstance(headerRateLimit)); - assertThat("rateLimit() selects header instance when not expired, does not ask server", - gitHub.lastRateLimit(), sameInstance(headerRateLimit)); + assertThat("rateLimit() selects header instance when not expired, does not ask server", gitHub.rateLimit(), + sameInstance(headerRateLimit)); + assertThat("rateLimit() selects header instance when not expired, does not ask server", gitHub.lastRateLimit(), + sameInstance(headerRateLimit)); assertThat(mockGitHub.getRequestCount(), equalTo(1)); // This time, rateLimit() should find an expired record and get a new one. Thread.sleep(3000); - assertThat("Header instance has expired", - gitHub.lastRateLimit().isExpired(), is(true)); + assertThat("Header instance has expired", gitHub.lastRateLimit().isExpired(), is(true)); assertThat("rateLimit() will ask server when header instance expires and it has not called getRateLimit() yet", - gitHub.rateLimit(), not(sameInstance(rateLimit))); + gitHub.rateLimit(), not(sameInstance(rateLimit))); assertThat("lastRateLimit() (header instance) is populated as part of internal call to getRateLimit()", - gitHub.lastRateLimit(), not(sameInstance(rateLimit))); + gitHub.lastRateLimit(), not(sameInstance(rateLimit))); - assertThat("After request, rateLimit() selects header instance since it has been refreshed", - gitHub.rateLimit(), sameInstance(gitHub.lastRateLimit())); + assertThat("After request, rateLimit() selects header instance since it has been refreshed", gitHub.rateLimit(), + sameInstance(gitHub.lastRateLimit())); headerRateLimit = gitHub.lastRateLimit(); assertThat(mockGitHub.getRequestCount(), equalTo(2)); - // This time, rateLimit() should find an expired header record, but a valid returned record Thread.sleep(4000); rateLimit = gitHub.rateLimit(); // Using custom data to have a header instance that expires before the queried instance - assertThat("if header instance expires but queried instance is valid, ratelimit() uses it without asking server", - gitHub.rateLimit(), not(sameInstance(gitHub.lastRateLimit()))); + assertThat( + "if header instance expires but queried instance is valid, ratelimit() uses it without asking server", + gitHub.rateLimit(), not(sameInstance(gitHub.lastRateLimit()))); assertThat("ratelimit() should almost never return a return a GHRateLimit that is already expired", - gitHub.rateLimit().isExpired(), is(false)); - - - assertThat("Header instance hasn't been reloaded", - gitHub.lastRateLimit(), sameInstance(headerRateLimit)); - assertThat("Header instance has expired", - gitHub.lastRateLimit().isExpired(), is(true)); + gitHub.rateLimit().isExpired(), is(false)); + assertThat("Header instance hasn't been reloaded", gitHub.lastRateLimit(), sameInstance(headerRateLimit)); + assertThat("Header instance has expired", gitHub.lastRateLimit().isExpired(), is(true)); assertThat(mockGitHub.getRequestCount(), equalTo(2)); @@ -406,14 +390,13 @@ private void executeExpirationTest() throws Exception { headerRateLimit = gitHub.rateLimit(); - assertThat("rateLimit() has asked server for new information", - gitHub.rateLimit(), not(sameInstance(rateLimit))); - assertThat("rateLimit() has asked server for new information", - gitHub.lastRateLimit(), not(sameInstance(rateLimit))); - + assertThat("rateLimit() has asked server for new information", gitHub.rateLimit(), + not(sameInstance(rateLimit))); + assertThat("rateLimit() has asked server for new information", gitHub.lastRateLimit(), + not(sameInstance(rateLimit))); - assertThat("rateLimit() selects header instance when not expired, does not ask server", - gitHub.rateLimit(), sameInstance((gitHub.lastRateLimit()))); + assertThat("rateLimit() selects header instance when not expired, does not ask server", gitHub.rateLimit(), + sameInstance((gitHub.lastRateLimit()))); assertThat(mockGitHub.getRequestCount(), equalTo(3)); } diff --git a/src/test/java/org/kohsuke/github/GHRepositoryStatisticsTest.java b/src/test/java/org/kohsuke/github/GHRepositoryStatisticsTest.java index 71d14d02dc..057a09ee3b 100644 --- a/src/test/java/org/kohsuke/github/GHRepositoryStatisticsTest.java +++ b/src/test/java/org/kohsuke/github/GHRepositoryStatisticsTest.java @@ -14,8 +14,8 @@ public class GHRepositoryStatisticsTest extends AbstractGitHubWireMockTest { @Test public void testContributorStats() throws IOException, InterruptedException { // get the statistics - PagedIterable stats = - getRepository().getStatistics().getContributorStats(); + PagedIterable stats = getRepository().getStatistics() + .getContributorStats(); // check that the statistics were eventually retrieved if (stats == null) { @@ -31,25 +31,22 @@ public void testContributorStats() throws IOException, InterruptedException { // TODO: Add an accessor method for this instead of having use a loop. boolean developerFound = false; final String authorLogin = "kohsuke"; - for (GHRepositoryStatistics.ContributorStats statsForAuthor: list) { + for (GHRepositoryStatistics.ContributorStats statsForAuthor : list) { if (authorLogin.equals(statsForAuthor.getAuthor().getLogin())) { assertEquals(715, statsForAuthor.getTotal()); - List weeks = - statsForAuthor.getWeeks(); + List weeks = statsForAuthor.getWeeks(); assertEquals(494, weeks.size()); try { // check a particular week // TODO: Maybe add a convenience method to get the week // containing a certain date (Java.Util.Date). - GHRepositoryStatistics.ContributorStats.Week week = - statsForAuthor.getWeek(1541289600); + GHRepositoryStatistics.ContributorStats.Week week = statsForAuthor.getWeek(1541289600); assertEquals(63, week.getNumberOfAdditions()); assertEquals(56, week.getNumberOfDeletions()); assertEquals(5, week.getNumberOfCommits()); - } - catch(NoSuchElementException e) { + } catch (NoSuchElementException e) { fail("Did not find week 1546128000"); } developerFound = true; @@ -68,10 +65,9 @@ public void testCommitActivity() throws IOException, InterruptedException { for (int i = 0; i < MAX_ITERATIONS; i += 1) { stats = getRepository().getStatistics().getCommitActivity(); - if(stats == null) { + if (stats == null) { Thread.sleep(SLEEP_INTERVAL); - } - else { + } else { break; } } @@ -88,17 +84,17 @@ public void testCommitActivity() throws IOException, InterruptedException { // TODO: Return this as a map with the timestamp as the key. // Either that or wrap in an object an accessor method. Boolean foundWeek = false; - for (GHRepositoryStatistics.CommitActivity item: list) { + for (GHRepositoryStatistics.CommitActivity item : list) { if (item.getWeek() == 1566691200) { assertEquals(6, item.getTotal()); List days = item.getDays(); - assertEquals(0, (long)days.get(0)); - assertEquals(0, (long)days.get(1)); - assertEquals(1, (long)days.get(2)); - assertEquals(0, (long)days.get(3)); - assertEquals(0, (long)days.get(4)); - assertEquals(1, (long)days.get(5)); - assertEquals(4, (long)days.get(6)); + assertEquals(0, (long) days.get(0)); + assertEquals(0, (long) days.get(1)); + assertEquals(1, (long) days.get(2)); + assertEquals(0, (long) days.get(3)); + assertEquals(0, (long) days.get(4)); + assertEquals(1, (long) days.get(5)); + assertEquals(4, (long) days.get(6)); foundWeek = true; break; } @@ -114,10 +110,9 @@ public void testCodeFrequency() throws IOException, InterruptedException { for (int i = 0; i < MAX_ITERATIONS; i += 1) { stats = getRepository().getStatistics().getCodeFrequency(); - if(stats == null) { + if (stats == null) { Thread.sleep(SLEEP_INTERVAL); - } - else { + } else { break; } } @@ -132,7 +127,7 @@ public void testCodeFrequency() throws IOException, InterruptedException { // TODO: Perhaps return this as a map with the timestamp as the key? // Either that or wrap in an object with accessor methods. Boolean foundWeek = false; - for (GHRepositoryStatistics.CodeFrequency item: stats) { + for (GHRepositoryStatistics.CodeFrequency item : stats) { if (item.getWeekTimestamp() == 1535241600) { assertEquals(185, item.getAdditions()); assertEquals(-243, item.getDeletions()); @@ -150,10 +145,9 @@ public void testParticipation() throws IOException, InterruptedException { for (int i = 0; i < MAX_ITERATIONS; i += 1) { stats = getRepository().getStatistics().getParticipation(); - if(stats == null) { + if (stats == null) { Thread.sleep(SLEEP_INTERVAL); - } - else { + } else { break; } } @@ -167,7 +161,7 @@ public void testParticipation() throws IOException, InterruptedException { // check the statistics are accurate List allCommits = stats.getAllCommits(); assertEquals(52, allCommits.size()); - assertEquals(2, (int)allCommits.get(2)); + assertEquals(2, (int) allCommits.get(2)); List ownerCommits = stats.getOwnerCommits(); assertEquals(52, ownerCommits.size()); @@ -181,11 +175,10 @@ public void testPunchCard() throws IOException, InterruptedException { List stats = null; for (int i = 0; i < MAX_ITERATIONS; i += 1) { - stats = getRepository().getStatistics().getPunchCard(); - if(stats == null) { + stats = getRepository().getStatistics().getPunchCard(); + if (stats == null) { Thread.sleep(SLEEP_INTERVAL); - } - else { + } else { break; } } @@ -198,8 +191,8 @@ public void testPunchCard() throws IOException, InterruptedException { // check the statistics are accurate Boolean hourFound = false; - for (GHRepositoryStatistics.PunchCardItem item: stats) { - if(item.getDayOfWeek() == 2 && item.getHourOfDay() == 10) { + for (GHRepositoryStatistics.PunchCardItem item : stats) { + if (item.getDayOfWeek() == 2 && item.getHourOfDay() == 10) { // TODO: Make an easier access method. Perhaps wrap in an // object and have a method such as GetCommits(1, 16). assertEquals(16, item.getNumberOfCommits()); diff --git a/src/test/java/org/kohsuke/github/GHRepositoryTest.java b/src/test/java/org/kohsuke/github/GHRepositoryTest.java index f19955be9e..ca3e145733 100644 --- a/src/test/java/org/kohsuke/github/GHRepositoryTest.java +++ b/src/test/java/org/kohsuke/github/GHRepositoryTest.java @@ -26,7 +26,6 @@ private GHRepository getRepository(GitHub gitHub) throws IOException { return gitHub.getOrganization("github-api-test-org").getRepository("github-api"); } - @Test public void archive() throws Exception { snapshotNotAllowed(); @@ -110,7 +109,7 @@ public void getPermission() throws Exception { r.getPermission("jglick"); fail(); } catch (HttpException x) { - //x.printStackTrace(); // good + // x.printStackTrace(); // good assertEquals(403, x.getResponseCode()); } @@ -126,7 +125,6 @@ public void getPermission() throws Exception { } } - @Test public void LatestRepositoryExist() { try { @@ -199,7 +197,8 @@ public void listEmptyContributors() throws IOException { @Test public void searchRepositories() throws Exception { - PagedSearchIterable r = gitHub.searchRepositories().q("tetris").language("assembly").sort(GHRepositorySearchBuilder.Sort.STARS).list(); + PagedSearchIterable r = gitHub.searchRepositories().q("tetris").language("assembly") + .sort(GHRepositorySearchBuilder.Sort.STARS).list(); GHRepository u = r.iterator().next(); // System.out.println(u.getName()); assertNotNull(u.getId()); @@ -207,7 +206,6 @@ public void searchRepositories() throws Exception { assertTrue(r.getTotalCount() > 0); } - @Test // issue #162 public void testIssue162() throws Exception { GHRepository r = gitHub.getRepository("github-api/github-api"); @@ -226,7 +224,8 @@ public void testIssue162() throws Exception { public void markDown() throws Exception { assertEquals("

Test日本語

", IOUtils.toString(gitHub.renderMarkdown("**Test日本語**")).trim()); - String actual = IOUtils.toString(gitHub.getRepository("github-api/github-api").renderMarkdown("@kohsuke to fix issue #1", MarkdownMode.GFM)); + String actual = IOUtils.toString(gitHub.getRepository("github-api/github-api") + .renderMarkdown("@kohsuke to fix issue #1", MarkdownMode.GFM)); // System.out.println(actual); assertTrue(actual.contains("href=\"https://github.com/kohsuke\"")); assertTrue(actual.contains("href=\"https://github.com/github-api/github-api/pull/1\"")); @@ -234,7 +233,7 @@ public void markDown() throws Exception { assertTrue(actual.contains("class=\"issue-link ")); assertTrue(actual.contains("to fix issue")); } - + @Test public void getMergeOptions() throws IOException { GHRepository r = getTempRepository(); @@ -242,7 +241,7 @@ public void getMergeOptions() throws IOException { assertNotNull(r.isAllowRebaseMerge()); assertNotNull(r.isAllowSquashMerge()); } - + @Test public void setMergeOptions() throws IOException { // String repoName = "github-api-test-org/test-mergeoptions"; @@ -280,27 +279,26 @@ public void testSetTopics() throws Exception { topics.add("java"); topics.add("api-test-dummy"); repo.setTopics(topics); - assertThat("Topics retain input order (are not sort when stored)", - repo.listTopics(), contains("java", "api-test-dummy")); + assertThat("Topics retain input order (are not sort when stored)", repo.listTopics(), + contains("java", "api-test-dummy")); topics = new ArrayList<>(); topics.add("ordered-state"); topics.add("api-test-dummy"); topics.add("java"); repo.setTopics(topics); - assertThat("Topics behave as a set and retain order from previous calls", - repo.listTopics(), contains("java", "api-test-dummy", "ordered-state")); + assertThat("Topics behave as a set and retain order from previous calls", repo.listTopics(), + contains("java", "api-test-dummy", "ordered-state")); topics = new ArrayList<>(); topics.add("ordered-state"); topics.add("api-test-dummy"); repo.setTopics(topics); - assertThat("Topics retain order even when some are removed", - repo.listTopics(), contains("api-test-dummy", "ordered-state")); + assertThat("Topics retain order even when some are removed", repo.listTopics(), + contains("api-test-dummy", "ordered-state")); topics = new ArrayList<>(); repo.setTopics(topics); - assertTrue("Topics can be set to empty", - repo.listTopics().isEmpty()); + assertTrue("Topics can be set to empty", repo.listTopics().isEmpty()); } } \ No newline at end of file diff --git a/src/test/java/org/kohsuke/github/GHTeamTest.java b/src/test/java/org/kohsuke/github/GHTeamTest.java index 208f07f7d1..8fbe267abb 100644 --- a/src/test/java/org/kohsuke/github/GHTeamTest.java +++ b/src/test/java/org/kohsuke/github/GHTeamTest.java @@ -31,5 +31,4 @@ public void testSetDescription() throws IOException { assertEquals(description, team.getDescription()); } - } diff --git a/src/test/java/org/kohsuke/github/GHUserTest.java b/src/test/java/org/kohsuke/github/GHUserTest.java index bdfa346d2e..e40db4ad2f 100644 --- a/src/test/java/org/kohsuke/github/GHUserTest.java +++ b/src/test/java/org/kohsuke/github/GHUserTest.java @@ -7,14 +7,11 @@ import static org.hamcrest.CoreMatchers.*; - public class GHUserTest extends AbstractGitHubWireMockTest { @Test public void listFollowsAndFollowers() throws IOException { GHUser u = gitHub.getUser("rtyler"); - assertNotEquals( - count30(u.listFollowers()), - count30(u.listFollows())); + assertNotEquals(count30(u.listFollowers()), count30(u.listFollows())); } private Set count30(PagedIterable l) { @@ -40,14 +37,17 @@ public int compare(GHKey ghKey, GHKey t1) { } }); assertEquals(1066173, ghKeys.get(0).getId()); - assertEquals("ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAueiy12T5bvFhsc9YjfLc3aVIxgySd3gDxQWy/bletIoZL8omKmzocBYJ7F58U1asoyfWsy2ToTOY8jJp1eToXmbD6L5+xvHba0A7djYh9aQRrFam7doKQ0zp0ZSUF6+R1v0OM4nnWqK4n2ECIYd+Bdzrp+xA5+XlW3ZSNzlnW2BeWznzmgRMcp6wI+zQ9GMHWviR1cxpml5Z6wrxTZ0aX91btvnNPqoOGva976B6e6403FOEkkIFTk6CC1TFKwc/VjbqxYBg4kU0JhiTP+iEZibcQrYjWdYUgAotYbFVe5/DneHMLNsMPdeihba4PUwt62rXyNegenuCRmCntLcaFQ==", - ghKeys.get(0).getKey()); + assertEquals( + "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAueiy12T5bvFhsc9YjfLc3aVIxgySd3gDxQWy/bletIoZL8omKmzocBYJ7F58U1asoyfWsy2ToTOY8jJp1eToXmbD6L5+xvHba0A7djYh9aQRrFam7doKQ0zp0ZSUF6+R1v0OM4nnWqK4n2ECIYd+Bdzrp+xA5+XlW3ZSNzlnW2BeWznzmgRMcp6wI+zQ9GMHWviR1cxpml5Z6wrxTZ0aX91btvnNPqoOGva976B6e6403FOEkkIFTk6CC1TFKwc/VjbqxYBg4kU0JhiTP+iEZibcQrYjWdYUgAotYbFVe5/DneHMLNsMPdeihba4PUwt62rXyNegenuCRmCntLcaFQ==", + ghKeys.get(0).getKey()); assertEquals(28136459, ghKeys.get(1).getId()); - assertEquals("ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDTU0s5OKCC6VpKZGL9NJD4mNLY0AtujkVB1JkkuQ4OkMi2YGUHJtGhTbTwEVhNxpm0x2dM5KSzse6MLDYuGBW0qkE/VVuD9+9I73hbq461KqP0+WlupNh+Qc86kbiLBDv64+vWc+50mp1dbINpoM5xvaPYxgjnemydPv7vu5bhCHBugW7aN8VcLgfFgcp8vZCEanMtd3hIRjRU8v8Skk233ZGu1bXkG8iIOBQPabvEtZ0VDMg9pT3Q1R6lnnKqfCwHXd6zP6uAtejFSxvKRGKpu3OLGQMHwk7NlImVuhkVdaEFBq7pQtpOaGuP2eLKcN1wy5jsTYE+ZB6pvHCi2ecb", - ghKeys.get(1).getKey()); + assertEquals( + "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDTU0s5OKCC6VpKZGL9NJD4mNLY0AtujkVB1JkkuQ4OkMi2YGUHJtGhTbTwEVhNxpm0x2dM5KSzse6MLDYuGBW0qkE/VVuD9+9I73hbq461KqP0+WlupNh+Qc86kbiLBDv64+vWc+50mp1dbINpoM5xvaPYxgjnemydPv7vu5bhCHBugW7aN8VcLgfFgcp8vZCEanMtd3hIRjRU8v8Skk233ZGu1bXkG8iIOBQPabvEtZ0VDMg9pT3Q1R6lnnKqfCwHXd6zP6uAtejFSxvKRGKpu3OLGQMHwk7NlImVuhkVdaEFBq7pQtpOaGuP2eLKcN1wy5jsTYE+ZB6pvHCi2ecb", + ghKeys.get(1).getKey()); assertEquals(31452581, ghKeys.get(2).getId()); - assertEquals("ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC3JhH2FZBDmHLjXTcBoV6tdcYKmsQ7sgu8k1RsUhwxGsXm65+Cuas6GcMVoA1DncKfJGQkulHDFiTxIROIBmedh9/otHWBlZ4HqYZ4MQ1A8W5quULkXwX/kF+UdRBUxFvjigibEbuHB+LARVxRRzFlPnTSE9rAfAv8OOEsb3lNUGT/IGhN8w1vwe8GclB90tgqN1RBDgrVqwLFwn5AfrW9kUIa2f2oT4RjYu1OrhKhVIIzfHADo85aD+s8wEhqwI96BCJG3qTWrypoHwBUoj1O6Ak5CGc1iKz9o8XyTMjudRt2ddCjfOtxsuwSlTbVtQXJGIpgKviX1sgh4pPvGh7BVAFP+mdAK4F+mEugDnuj47GO/K5KGGDRCL56kh9+h28l4q/+fZvp7DhtmSN2EzrVAdQFskF8yY/6Xit/aAvjeKm03DcjbylSXbG26EJefaLHlwYFq2mUFRMak25wuuCZS71GF3RC3Sl/bMoxBKRYkyfYtGafeaYTFNGn8Dbd+hfVUCz31ebI8cvmlQR5b5AbCre3T7HTVgw8FKbAxWRf1Fio56PnqHsj+sT1KVj255Zo1F8iD9GrgERSVAlkh5bY/CKszQ8ZSd01c9Qp2a47/gR7XAAbxhzGHP+cSOlrqDlJ24fbPtcpVsM0llqKUcxpmoOBFNboRmE1QqnSmAf9ww==", - ghKeys.get(2).getKey()); + assertEquals( + "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC3JhH2FZBDmHLjXTcBoV6tdcYKmsQ7sgu8k1RsUhwxGsXm65+Cuas6GcMVoA1DncKfJGQkulHDFiTxIROIBmedh9/otHWBlZ4HqYZ4MQ1A8W5quULkXwX/kF+UdRBUxFvjigibEbuHB+LARVxRRzFlPnTSE9rAfAv8OOEsb3lNUGT/IGhN8w1vwe8GclB90tgqN1RBDgrVqwLFwn5AfrW9kUIa2f2oT4RjYu1OrhKhVIIzfHADo85aD+s8wEhqwI96BCJG3qTWrypoHwBUoj1O6Ak5CGc1iKz9o8XyTMjudRt2ddCjfOtxsuwSlTbVtQXJGIpgKviX1sgh4pPvGh7BVAFP+mdAK4F+mEugDnuj47GO/K5KGGDRCL56kh9+h28l4q/+fZvp7DhtmSN2EzrVAdQFskF8yY/6Xit/aAvjeKm03DcjbylSXbG26EJefaLHlwYFq2mUFRMak25wuuCZS71GF3RC3Sl/bMoxBKRYkyfYtGafeaYTFNGn8Dbd+hfVUCz31ebI8cvmlQR5b5AbCre3T7HTVgw8FKbAxWRf1Fio56PnqHsj+sT1KVj255Zo1F8iD9GrgERSVAlkh5bY/CKszQ8ZSd01c9Qp2a47/gR7XAAbxhzGHP+cSOlrqDlJ24fbPtcpVsM0llqKUcxpmoOBFNboRmE1QqnSmAf9ww==", + ghKeys.get(2).getKey()); } @Test diff --git a/src/test/java/org/kohsuke/github/GistTest.java b/src/test/java/org/kohsuke/github/GistTest.java index 5fbb75a400..b2987f4f13 100644 --- a/src/test/java/org/kohsuke/github/GistTest.java +++ b/src/test/java/org/kohsuke/github/GistTest.java @@ -12,17 +12,11 @@ * @author Kohsuke Kawaguchi */ public class GistTest extends AbstractGitHubWireMockTest { - /** - * CRUD operation. - */ @Test public void lifecycleTest() throws Exception { - GHGist gist = gitHub.createGist() - .public_(false) - .description("Test Gist") - .file("abc.txt", "abc") - .file("def.txt", "def") - .create(); + // CRUD operation + GHGist gist = gitHub.createGist().public_(false).description("Test Gist").file("abc.txt", "abc") + .file("def.txt", "def").create(); assertThat(gist.getCreatedAt(), is(notNullValue())); @@ -41,7 +35,6 @@ public void starTest() throws Exception { GHGist gist = gitHub.getGist("9903708"); assertEquals("rtyler", gist.getOwner().getLogin()); - gist.star(); assertTrue(gist.isStarred()); diff --git a/src/test/java/org/kohsuke/github/GitHubConnectionTest.java b/src/test/java/org/kohsuke/github/GitHubConnectionTest.java index 0cd4f718c9..6f5c7b7159 100644 --- a/src/test/java/org/kohsuke/github/GitHubConnectionTest.java +++ b/src/test/java/org/kohsuke/github/GitHubConnectionTest.java @@ -39,11 +39,13 @@ public void testGitHubServerWithHttps() throws Exception { GitHub hub = GitHub.connectToEnterprise("https://enterprise.kohsuke.org/api/v3", "bogus", "bogus"); assertEquals("https://enterprise.kohsuke.org/api/v3/test", hub.getApiURL("/test").toString()); } + @Test public void testGitHubServerWithoutServer() throws Exception { GitHub hub = GitHub.connectUsingPassword("kohsuke", "bogus"); assertEquals("https://api.github.com/test", hub.getApiURL("/test").toString()); } + @Test public void testGitHubBuilderFromEnvironment() throws IOException { @@ -76,29 +78,31 @@ public void testGitHubBuilderFromCustomEnvironment() throws IOException { setupEnvironment(props); - GitHubBuilder builder = GitHubBuilder.fromEnvironment("customLogin", "customPassword", "customOauth", "customEndpoint"); + GitHubBuilder builder = GitHubBuilder.fromEnvironment("customLogin", "customPassword", "customOauth", + "customEndpoint"); assertEquals("bogusLogin", builder.user); assertEquals("bogusOauth", builder.oauthToken); assertEquals("bogusPassword", builder.password); assertEquals("bogusEndpoint", builder.endpoint); } + @Test - public void testGithubBuilderWithAppInstallationToken() throws Exception{ + public void testGithubBuilderWithAppInstallationToken() throws Exception { GitHubBuilder builder = new GitHubBuilder().withAppInstallationToken("bogus"); assertEquals("bogus", builder.oauthToken); assertEquals("", builder.user); // test authorization header is set as in the RFC6749 GitHub github = builder.build(); - assertEquals("token bogus",github.encodedAuthorization); - assertEquals("",github.login); + assertEquals("token bogus", github.encodedAuthorization); + assertEquals("", github.login); } @Test public void testGitHubIsApiUrlValid() throws IOException { GitHub hub = GitHub.connectAnonymously(); - //GitHub github = GitHub.connectToEnterpriseAnonymously("https://github.mycompany.com/api/v3/"); + // GitHub github = GitHub.connectToEnterpriseAnonymously("https://github.mycompany.com/api/v3/"); try { hub.checkApiUrlValidity(); } catch (IOException ioe) { @@ -111,7 +115,8 @@ public void testGitHubIsApiUrlValid() throws IOException { * * This allows changing the in memory process environment. * - * Its used to wire in values for the github credentials to test that the GitHubBuilder works properly to resolve them. + * Its used to wire in values for the github credentials to test that the GitHubBuilder works properly to resolve + * them. */ private void setupEnvironment(Map newenv) { try { @@ -120,7 +125,8 @@ private void setupEnvironment(Map newenv) { theEnvironmentField.setAccessible(true); Map env = (Map) theEnvironmentField.get(null); env.putAll(newenv); - Field theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment"); + Field theCaseInsensitiveEnvironmentField = processEnvironmentClass + .getDeclaredField("theCaseInsensitiveEnvironment"); theCaseInsensitiveEnvironmentField.setAccessible(true); Map cienv = (Map) theCaseInsensitiveEnvironmentField.get(null); cienv.putAll(newenv); diff --git a/src/test/java/org/kohsuke/github/GitHubStaticTest.java b/src/test/java/org/kohsuke/github/GitHubStaticTest.java index 47e600aef2..101b04646b 100644 --- a/src/test/java/org/kohsuke/github/GitHubStaticTest.java +++ b/src/test/java/org/kohsuke/github/GitHubStaticTest.java @@ -41,29 +41,22 @@ public void timeRoundTrip() throws Exception { String instantSecondsFormatMillis = formatDate(instantSeconds, "yyyy-MM-dd'T'HH:mm:ss.S'Z'"); String instantBadFormat = formatDate(instantMillis, "yy-MM-dd'T'HH:mm'Z'"); - assertThat(GitHub.parseDate(GitHub.printDate(instantSeconds)), - equalTo(GitHub.parseDate(GitHub.printDate(instantMillis)))); + equalTo(GitHub.parseDate(GitHub.printDate(instantMillis)))); - assertThat(instantSeconds, - equalTo(GitHub.parseDate(GitHub.printDate(instantSeconds)))); + assertThat(instantSeconds, equalTo(GitHub.parseDate(GitHub.printDate(instantSeconds)))); // printDate will truncate to the nearest second, so it should not be equal - assertThat(instantMillis, - not(equalTo(GitHub.parseDate(GitHub.printDate(instantMillis))))); + assertThat(instantMillis, not(equalTo(GitHub.parseDate(GitHub.printDate(instantMillis))))); - assertThat(instantSeconds, - equalTo(GitHub.parseDate(instantFormatSlash))); + assertThat(instantSeconds, equalTo(GitHub.parseDate(instantFormatSlash))); - assertThat(instantSeconds, - equalTo(GitHub.parseDate(instantFormatDash))); + assertThat(instantSeconds, equalTo(GitHub.parseDate(instantFormatDash))); // This parser does not truncate to the nearest second, so it will be equal - assertThat(instantMillis, - equalTo(GitHub.parseDate(instantFormatMillis))); + assertThat(instantMillis, equalTo(GitHub.parseDate(instantFormatMillis))); - assertThat(instantSeconds, - equalTo(GitHub.parseDate(instantSecondsFormatMillis))); + assertThat(instantSeconds, equalTo(GitHub.parseDate(instantSecondsFormatMillis))); try { GitHub.parseDate(instantBadFormat); @@ -79,16 +72,12 @@ public void testGitHubRateLimitShouldReplaceRateLimit() throws Exception { GHRateLimit.Record unknown0 = GHRateLimit.Unknown().getCore(); GHRateLimit.Record unknown1 = GHRateLimit.Unknown().getCore(); - - - GHRateLimit.Record record0 = new GHRateLimit.Record(10, 10, 10L); GHRateLimit.Record record1 = new GHRateLimit.Record(10, 9, 10L); GHRateLimit.Record record2 = new GHRateLimit.Record(10, 2, 10L); GHRateLimit.Record record3 = new GHRateLimit.Record(10, 10, 20L); GHRateLimit.Record record4 = new GHRateLimit.Record(10, 5, 20L); - Thread.sleep(2000); GHRateLimit.Record recordWorst = new GHRateLimit.Record(Integer.MAX_VALUE, Integer.MAX_VALUE, Long.MIN_VALUE); @@ -109,7 +98,8 @@ public void testGitHubRateLimitShouldReplaceRateLimit() throws Exception { assertThat("Unknown should not replace worst record", GitHub.shouldReplace(unknown1, recordWorst), is(false)); assertThat("Earlier record should replace later worst", GitHub.shouldReplace(record0, recordWorst), is(true)); - assertThat("Later worst record should not replace earlier", GitHub.shouldReplace(recordWorst, record0), is(false)); + assertThat("Later worst record should not replace earlier", GitHub.shouldReplace(recordWorst, record0), + is(false)); assertThat("Equivalent record should not replace", GitHub.shouldReplace(record0, record00), is(false)); assertThat("Equivalent record should not replace", GitHub.shouldReplace(record00, record0), is(false)); @@ -119,16 +109,14 @@ public void testGitHubRateLimitShouldReplaceRateLimit() throws Exception { assertThat("Higher limit record should not replace lower", GitHub.shouldReplace(record1, record2), is(false)); - assertThat("Higher limit record with later reset should replace lower", GitHub.shouldReplace(record3, record2), is(true)); - - assertThat("Lower limit record with later reset should replace higher", GitHub.shouldReplace(record4, record1), is(true)); - - assertThat("Lower limit record with earlier reset should not replace higher", GitHub.shouldReplace(record2, record4), is(false)); - - - + assertThat("Higher limit record with later reset should replace lower", GitHub.shouldReplace(record3, record2), + is(true)); + assertThat("Lower limit record with later reset should replace higher", GitHub.shouldReplace(record4, record1), + is(true)); + assertThat("Lower limit record with earlier reset should not replace higher", + GitHub.shouldReplace(record2, record4), is(false)); } diff --git a/src/test/java/org/kohsuke/github/GitHubTest.java b/src/test/java/org/kohsuke/github/GitHubTest.java index bd37714b41..41e6ef9830 100644 --- a/src/test/java/org/kohsuke/github/GitHubTest.java +++ b/src/test/java/org/kohsuke/github/GitHubTest.java @@ -58,10 +58,11 @@ public void testListAllRepositories() throws Exception { assertNotEquals(0L, r.getId()); } } - + @Test public void searchContent() throws Exception { - PagedSearchIterable r = gitHub.searchContent().q("addClass").in("file").language("js").repo("jquery/jquery").list(); + PagedSearchIterable r = gitHub.searchContent().q("addClass").in("file").language("js") + .repo("jquery/jquery").list(); GHContent c = r.iterator().next(); // System.out.println(c.getName()); assertNotNull(c.getDownloadUrl()); @@ -71,11 +72,10 @@ public void searchContent() throws Exception { } @Test - public void testListMyAuthorizations() throws IOException - { + public void testListMyAuthorizations() throws IOException { PagedIterable list = gitHub.listMyAuthorizations(); - for (GHAuthorization auth: list) { + for (GHAuthorization auth : list) { assertNotNull(auth.getAppName()); } } diff --git a/src/test/java/org/kohsuke/github/Github2faTest.java b/src/test/java/org/kohsuke/github/Github2faTest.java index ebac9e6842..fe20355b19 100644 --- a/src/test/java/org/kohsuke/github/Github2faTest.java +++ b/src/test/java/org/kohsuke/github/Github2faTest.java @@ -5,34 +5,35 @@ import java.util.List; import org.junit.Test; + /** * @author Kevin Harrington mad.hephaestus@gmail.com */ -public class Github2faTest extends AbstractGitHubWireMockTest { - - @Test - public void test2faToken() throws IOException { - assertFalse("Test only valid when not proxying", mockGitHub.isUseProxy()); - - List asList = Arrays.asList("repo", "gist", "write:packages", "read:packages", "delete:packages", - "user", "delete_repo"); - String nameOfToken = "Test2faTokenCreate";//+timestamp;// use time stamp to ensure the token creations do not collide with older tokens - - GHAuthorization token=gitHub.createToken( - asList, - nameOfToken, - "this is a test token created by a unit test", () -> { - String data = "111878"; - // TO UPDATE run this in debugger mode, put a breakpoint here, and enter the OTP you get into the value of Data - return data; - }); - assert token!=null; - for(int i=0;i asList = Arrays.asList("repo", "gist", "write:packages", "read:packages", "delete:packages", + "user", "delete_repo"); + String nameOfToken = "Test2faTokenCreate";// +timestamp;// use time stamp to ensure the token creations do not + // collide with older tokens + + GHAuthorization token = gitHub.createToken(asList, nameOfToken, "this is a test token created by a unit test", + () -> { + String data = "111878"; + // TO UPDATE run this in debugger mode, put a breakpoint here, and enter the OTP you get into the + // value of Data + return data; + }); + assert token != null; + for (int i = 0; i < asList.size(); i++) { + assertTrue(token.getScopes().get(i).contentEquals(asList.get(i))); + } + + String p = token.getToken(); + + assert p != null; + } } diff --git a/src/test/java/org/kohsuke/github/LifecycleTest.java b/src/test/java/org/kohsuke/github/LifecycleTest.java index 629ccebc94..ad892a1de5 100644 --- a/src/test/java/org/kohsuke/github/LifecycleTest.java +++ b/src/test/java/org/kohsuke/github/LifecycleTest.java @@ -25,31 +25,22 @@ public void testCreateRepository() throws IOException, GitAPIException, Interrup repository.delete(); Thread.sleep(1000); } - repository = org.createRepository("github-api-test", - "a test repository used to test kohsuke's github-api", "http://github-api.kohsuke.org/", "Core Developers", true); + repository = org.createRepository("github-api-test", "a test repository used to test kohsuke's github-api", + "http://github-api.kohsuke.org/", "Core Developers", true); Thread.sleep(1000); // wait for the repository to become ready assertTrue(repository.getReleases().isEmpty()); try { GHMilestone milestone = repository.createMilestone("Initial Release", "first one"); - GHIssue issue = repository.createIssue("Test Issue") - .body("issue body just for grins") - .milestone(milestone) - .assignee(myself) - .label("bug") - .create(); + GHIssue issue = repository.createIssue("Test Issue").body("issue body just for grins").milestone(milestone) + .assignee(myself).label("bug").create(); File repoDir = new File(System.getProperty("java.io.tmpdir"), "github-api-test"); delete(repoDir); - Git origin = Git.cloneRepository() - .setBare(false) - .setURI(repository.getSshUrl()) - .setDirectory(repoDir) - .setCredentialsProvider(getCredentialsProvider(myself)) - .call(); + Git origin = Git.cloneRepository().setBare(false).setURI(repository.getSshUrl()).setDirectory(repoDir) + .setCredentialsProvider(getCredentialsProvider(myself)).call(); commitTestFile(myself, repoDir, origin); - GHRelease release = createRelease(repository); GHAsset asset = uploadAsset(release); @@ -83,10 +74,8 @@ private GHAsset uploadAsset(GHRelease release) throws IOException { } private GHRelease createRelease(GHRepository repository) throws IOException { - GHRelease builder = repository.createRelease("release_tag") - .name("Test Release") - .body("How exciting! To be able to programmatically create releases is a dream come true!") - .create(); + GHRelease builder = repository.createRelease("release_tag").name("Test Release") + .body("How exciting! To be able to programmatically create releases is a dream come true!").create(); List releases = repository.getReleases(); assertEquals(1, releases.size()); GHRelease release = releases.get(0); diff --git a/src/test/java/org/kohsuke/github/PayloadRule.java b/src/test/java/org/kohsuke/github/PayloadRule.java index 20a6f46acc..6a24a8e5c2 100644 --- a/src/test/java/org/kohsuke/github/PayloadRule.java +++ b/src/test/java/org/kohsuke/github/PayloadRule.java @@ -44,9 +44,8 @@ public void evaluate() throws Throwable { } public InputStream asInputStream() throws FileNotFoundException { - String name = resourceName.startsWith("/") - ? resourceName + type - : testClass.getSimpleName() + "/" + resourceName + type; + String name = resourceName.startsWith("/") ? resourceName + type + : testClass.getSimpleName() + "/" + resourceName + type; InputStream stream = testClass.getResourceAsStream(name); if (stream == null) { throw new FileNotFoundException(String.format("Resource %s from class %s", name, testClass)); diff --git a/src/test/java/org/kohsuke/github/RepositoryMockTest.java b/src/test/java/org/kohsuke/github/RepositoryMockTest.java index c9c65f3c4a..5805ba66ec 100644 --- a/src/test/java/org/kohsuke/github/RepositoryMockTest.java +++ b/src/test/java/org/kohsuke/github/RepositoryMockTest.java @@ -25,7 +25,6 @@ public class RepositoryMockTest { @Mock GHRepository mockRepository; - @Before public void setUp() { MockitoAnnotations.initMocks(this); @@ -39,17 +38,13 @@ public void listCollaborators() throws Exception { GHUser user2 = new GHUser(); user2.login = "login2"; - when(iterator.hasNext()).thenReturn(true, false, true); - when(iterator.next()).thenReturn(new GHUser[] {user1}, new GHUser[] {user2}); + when(iterator.next()).thenReturn(new GHUser[] { user1 }, new GHUser[] { user2 }); Requester requester = Mockito.mock(Requester.class); when(mockGitHub.retrieve()).thenReturn(requester); - - when(requester.asIterator("/repos/*/*/collaborators", - GHUser[].class, 0)).thenReturn(iterator, iterator); - + when(requester.asIterator("/repos/*/*/collaborators", GHUser[].class, 0)).thenReturn(iterator, iterator); PagedIterable pagedIterable = Mockito.mock(PagedIterable.class); when(mockRepository.listCollaborators()).thenReturn(pagedIterable); @@ -67,21 +62,17 @@ protected void wrapUp(GHUser[] page) { } }; - when(pagedIterable.iterator()).thenReturn(userPagedIterator, userPagedIterator2); Iterator returnIterator1 = mockRepository.listCollaborators().iterator(); - Assert.assertTrue(returnIterator1.hasNext()); GHUser user = returnIterator1.next(); Assert.assertEquals(user, user1); Assert.assertFalse(returnIterator1.hasNext()); - Iterator returnIterator2 = mockRepository.listCollaborators().iterator(); - Assert.assertTrue(returnIterator2.hasNext()); user = returnIterator1.next(); Assert.assertEquals(user, user2); diff --git a/src/test/java/org/kohsuke/github/RepositoryTrafficTest.java b/src/test/java/org/kohsuke/github/RepositoryTrafficTest.java index 5c8f6d35e3..b921d5ea4d 100644 --- a/src/test/java/org/kohsuke/github/RepositoryTrafficTest.java +++ b/src/test/java/org/kohsuke/github/RepositoryTrafficTest.java @@ -22,8 +22,7 @@ public class RepositoryTrafficTest extends AbstractGitHubApiTestBase { @Override protected GitHubBuilder getGitHubBuilder() { - return new GitHubBuilder() - .withPassword(login, null); + return new GitHubBuilder().withPassword(login, null); } @SuppressWarnings("unchecked") @@ -58,30 +57,23 @@ private void testTraffic(T expectedResult) throw GitHub gitHubSpy = Mockito.spy(gitHub); GHRepository repo = gitHubSpy.getUser(login).getRepository(repositoryName); - // accessing traffic info requires push access to the repo // since we don't have that, let the mocking begin... HttpConnector connectorSpy = Mockito.spy(gitHubSpy.getConnector()); Mockito.doReturn(connectorSpy).when(gitHubSpy).getConnector(); - // also known as the "uc" in the Requester class HttpURLConnection mockHttpURLConnection = Mockito.mock(HttpURLConnection.class); - // needed for Requester.setRequestMethod Mockito.doReturn("GET").when(mockHttpURLConnection).getRequestMethod(); - // this covers calls on "uc" in Requester.setupConnection and Requester.buildRequest - URL trafficURL = gitHub.getApiURL( - "/repos/" + login + "/" + repositoryName + "/traffic/" + - ((expectedResult instanceof GHRepositoryViewTraffic) ? "views" : "clones") - ); + URL trafficURL = gitHub.getApiURL("/repos/" + login + "/" + repositoryName + "/traffic/" + + ((expectedResult instanceof GHRepositoryViewTraffic) ? "views" : "clones")); Mockito.doReturn(mockHttpURLConnection).when(connectorSpy).connect(Mockito.eq(trafficURL)); - // make Requester.parse work Mockito.doReturn(200).when(mockHttpURLConnection).getResponseCode(); Mockito.doReturn("OK").when(mockHttpURLConnection).getResponseMessage(); @@ -99,53 +91,43 @@ private void testTraffic(T expectedResult) throw @Test public void testGetViews() throws IOException { - GHRepositoryViewTraffic expectedResult = new GHRepositoryViewTraffic( - 21523359, - 65534, - Arrays.asList( - new GHRepositoryViewTraffic.DailyInfo("2016-10-10T00:00:00Z", 3, 2), - new GHRepositoryViewTraffic.DailyInfo("2016-10-11T00:00:00Z", 9, 4), - new GHRepositoryViewTraffic.DailyInfo("2016-10-12T00:00:00Z", 27, 8), - new GHRepositoryViewTraffic.DailyInfo("2016-10-13T00:00:00Z", 81, 16), - new GHRepositoryViewTraffic.DailyInfo("2016-10-14T00:00:00Z", 243, 32), - new GHRepositoryViewTraffic.DailyInfo("2016-10-15T00:00:00Z", 729, 64), - new GHRepositoryViewTraffic.DailyInfo("2016-10-16T00:00:00Z", 2187, 128), - new GHRepositoryViewTraffic.DailyInfo("2016-10-17T00:00:00Z", 6561, 256), - new GHRepositoryViewTraffic.DailyInfo("2016-10-18T00:00:00Z", 19683, 512), - new GHRepositoryViewTraffic.DailyInfo("2016-10-19T00:00:00Z", 59049, 1024), - new GHRepositoryViewTraffic.DailyInfo("2016-10-20T00:00:00Z", 177147, 2048), - new GHRepositoryViewTraffic.DailyInfo("2016-10-21T00:00:00Z", 531441, 4096), - new GHRepositoryViewTraffic.DailyInfo("2016-10-22T00:00:00Z", 1594323, 8192), - new GHRepositoryViewTraffic.DailyInfo("2016-10-23T00:00:00Z", 4782969, 16384), - new GHRepositoryViewTraffic.DailyInfo("2016-10-24T00:00:00Z", 14348907, 32768) - ) - ); + GHRepositoryViewTraffic expectedResult = new GHRepositoryViewTraffic(21523359, 65534, + Arrays.asList(new GHRepositoryViewTraffic.DailyInfo("2016-10-10T00:00:00Z", 3, 2), + new GHRepositoryViewTraffic.DailyInfo("2016-10-11T00:00:00Z", 9, 4), + new GHRepositoryViewTraffic.DailyInfo("2016-10-12T00:00:00Z", 27, 8), + new GHRepositoryViewTraffic.DailyInfo("2016-10-13T00:00:00Z", 81, 16), + new GHRepositoryViewTraffic.DailyInfo("2016-10-14T00:00:00Z", 243, 32), + new GHRepositoryViewTraffic.DailyInfo("2016-10-15T00:00:00Z", 729, 64), + new GHRepositoryViewTraffic.DailyInfo("2016-10-16T00:00:00Z", 2187, 128), + new GHRepositoryViewTraffic.DailyInfo("2016-10-17T00:00:00Z", 6561, 256), + new GHRepositoryViewTraffic.DailyInfo("2016-10-18T00:00:00Z", 19683, 512), + new GHRepositoryViewTraffic.DailyInfo("2016-10-19T00:00:00Z", 59049, 1024), + new GHRepositoryViewTraffic.DailyInfo("2016-10-20T00:00:00Z", 177147, 2048), + new GHRepositoryViewTraffic.DailyInfo("2016-10-21T00:00:00Z", 531441, 4096), + new GHRepositoryViewTraffic.DailyInfo("2016-10-22T00:00:00Z", 1594323, 8192), + new GHRepositoryViewTraffic.DailyInfo("2016-10-23T00:00:00Z", 4782969, 16384), + new GHRepositoryViewTraffic.DailyInfo("2016-10-24T00:00:00Z", 14348907, 32768))); testTraffic(expectedResult); } @Test public void testGetClones() throws IOException { - GHRepositoryCloneTraffic expectedResult = new GHRepositoryCloneTraffic( - 1500, - 455, - Arrays.asList( - new GHRepositoryCloneTraffic.DailyInfo("2016-10-10T00:00:00Z", 10, 3), - new GHRepositoryCloneTraffic.DailyInfo("2016-10-11T00:00:00Z", 20, 6), - new GHRepositoryCloneTraffic.DailyInfo("2016-10-12T00:00:00Z", 30, 5), - new GHRepositoryCloneTraffic.DailyInfo("2016-10-13T00:00:00Z", 40, 7), - new GHRepositoryCloneTraffic.DailyInfo("2016-10-14T00:00:00Z", 50, 11), - new GHRepositoryCloneTraffic.DailyInfo("2016-10-15T00:00:00Z", 60, 12), - new GHRepositoryCloneTraffic.DailyInfo("2016-10-16T00:00:00Z", 70, 19), - new GHRepositoryCloneTraffic.DailyInfo("2016-10-17T00:00:00Z", 170, 111), - new GHRepositoryCloneTraffic.DailyInfo("2016-10-18T00:00:00Z", 180, 70), - new GHRepositoryCloneTraffic.DailyInfo("2016-10-19T00:00:00Z", 190, 10), - new GHRepositoryCloneTraffic.DailyInfo("2016-10-20T00:00:00Z", 200, 18), - new GHRepositoryCloneTraffic.DailyInfo("2016-10-21T00:00:00Z", 210, 8), - new GHRepositoryCloneTraffic.DailyInfo("2016-10-22T00:00:00Z", 220, 168), - new GHRepositoryCloneTraffic.DailyInfo("2016-10-23T00:00:00Z", 5, 2), - new GHRepositoryCloneTraffic.DailyInfo("2016-10-24T00:00:00Z", 45, 5) - ) - ); + GHRepositoryCloneTraffic expectedResult = new GHRepositoryCloneTraffic(1500, 455, + Arrays.asList(new GHRepositoryCloneTraffic.DailyInfo("2016-10-10T00:00:00Z", 10, 3), + new GHRepositoryCloneTraffic.DailyInfo("2016-10-11T00:00:00Z", 20, 6), + new GHRepositoryCloneTraffic.DailyInfo("2016-10-12T00:00:00Z", 30, 5), + new GHRepositoryCloneTraffic.DailyInfo("2016-10-13T00:00:00Z", 40, 7), + new GHRepositoryCloneTraffic.DailyInfo("2016-10-14T00:00:00Z", 50, 11), + new GHRepositoryCloneTraffic.DailyInfo("2016-10-15T00:00:00Z", 60, 12), + new GHRepositoryCloneTraffic.DailyInfo("2016-10-16T00:00:00Z", 70, 19), + new GHRepositoryCloneTraffic.DailyInfo("2016-10-17T00:00:00Z", 170, 111), + new GHRepositoryCloneTraffic.DailyInfo("2016-10-18T00:00:00Z", 180, 70), + new GHRepositoryCloneTraffic.DailyInfo("2016-10-19T00:00:00Z", 190, 10), + new GHRepositoryCloneTraffic.DailyInfo("2016-10-20T00:00:00Z", 200, 18), + new GHRepositoryCloneTraffic.DailyInfo("2016-10-21T00:00:00Z", 210, 8), + new GHRepositoryCloneTraffic.DailyInfo("2016-10-22T00:00:00Z", 220, 168), + new GHRepositoryCloneTraffic.DailyInfo("2016-10-23T00:00:00Z", 5, 2), + new GHRepositoryCloneTraffic.DailyInfo("2016-10-24T00:00:00Z", 45, 5))); testTraffic(expectedResult); } diff --git a/src/test/java/org/kohsuke/github/WireMockStatusReporterTest.java b/src/test/java/org/kohsuke/github/WireMockStatusReporterTest.java index f8d21dad5a..975881ac71 100644 --- a/src/test/java/org/kohsuke/github/WireMockStatusReporterTest.java +++ b/src/test/java/org/kohsuke/github/WireMockStatusReporterTest.java @@ -9,7 +9,6 @@ import static org.junit.Assume.assumeFalse; import static org.junit.Assume.assumeTrue; - /** * Tests in this class are meant to show the behavior of {@link AbstractGitHubWireMockTest} with proxying on or off. *

@@ -25,8 +24,8 @@ public void user_whenProxying_AuthCorrectlyConfigured() throws Exception { requireProxy("Tests proper configuration when proxying."); assertThat( - "GitHub connection believes it is anonymous. Make sure you set GITHUB_OAUTH or both GITHUB_USER and GITHUB_PASSWORD environment variables", - gitHub.isAnonymous(), is(false)); + "GitHub connection believes it is anonymous. Make sure you set GITHUB_OAUTH or both GITHUB_USER and GITHUB_PASSWORD environment variables", + gitHub.isAnonymous(), is(false)); assertThat(gitHub.login, not(equalTo(STUBBED_USER_LOGIN))); @@ -37,7 +36,8 @@ public void user_whenProxying_AuthCorrectlyConfigured() throws Exception { assertThat(user.getLogin(), notNullValue()); // System.out.println(); - // System.out.println("WireMockStatusReporterTest: GitHub proxying and user auth correctly configured for user login: " + user.getLogin()); + // System.out.println("WireMockStatusReporterTest: GitHub proxying and user auth correctly configured for user + // login: " + user.getLogin()); // System.out.println(); } @@ -80,7 +80,7 @@ public void BasicBehaviors_whenNotProxying() throws Exception { e = ex; } - assertThat(e, Matchers.instanceOf(GHFileNotFoundException.class)); + assertThat(e, Matchers. instanceOf(GHFileNotFoundException.class)); assertThat(e.getMessage(), containsString("Request was not matched")); // Invalid repository, without stub - fails 404 when not proxying @@ -92,7 +92,7 @@ public void BasicBehaviors_whenNotProxying() throws Exception { e = ex; } - assertThat(e, Matchers.instanceOf(GHFileNotFoundException.class)); + assertThat(e, Matchers. instanceOf(GHFileNotFoundException.class)); assertThat(e.getMessage(), containsString("Request was not matched")); } @@ -120,13 +120,15 @@ public void BasicBehaviors_whenProxying() throws Exception { e = ex; } - assertThat(e, Matchers.instanceOf(GHFileNotFoundException.class)); - assertThat(e.getMessage(), equalTo("{\"message\":\"Not Found\",\"documentation_url\":\"https://developer.github.com/v3/repos/#get\"}")); + assertThat(e, Matchers. instanceOf(GHFileNotFoundException.class)); + assertThat(e.getMessage(), equalTo( + "{\"message\":\"Not Found\",\"documentation_url\":\"https://developer.github.com/v3/repos/#get\"}")); } @Test public void whenSnapshot_EnsureProxy() throws Exception { - assumeTrue("Test only valid when Snapshotting (-Dtest.github.takeSnapshot to enable)", mockGitHub.isTakeSnapshot()); + assumeTrue("Test only valid when Snapshotting (-Dtest.github.takeSnapshot to enable)", + mockGitHub.isTakeSnapshot()); assertTrue("When taking a snapshot, proxy should automatically be enabled", mockGitHub.isUseProxy()); } @@ -134,7 +136,8 @@ public void whenSnapshot_EnsureProxy() throws Exception { @Ignore("Not implemented yet") @Test public void whenSnapshot_EnsureRecordToExpectedLocation() throws Exception { - assumeTrue("Test only valid when Snapshotting (-Dtest.github.takeSnapshot to enable)", mockGitHub.isTakeSnapshot()); + assumeTrue("Test only valid when Snapshotting (-Dtest.github.takeSnapshot to enable)", + mockGitHub.isTakeSnapshot()); } } diff --git a/src/test/java/org/kohsuke/github/extras/OkHttpConnectorTest.java b/src/test/java/org/kohsuke/github/extras/OkHttpConnectorTest.java index 3e6c217579..d0eac990d0 100644 --- a/src/test/java/org/kohsuke/github/extras/OkHttpConnectorTest.java +++ b/src/test/java/org/kohsuke/github/extras/OkHttpConnectorTest.java @@ -26,16 +26,16 @@ * Key take aways: * *

    - *
  • These tests are artificial and intended to highlight the differences - * in behavior between scenarios. However, the differences they indicate are stark.
  • + *
  • These tests are artificial and intended to highlight the differences in behavior between scenarios. However, the + * differences they indicate are stark.
  • *
  • Caching reduces rate limit consumption by at least a factor of two in even the simplest case.
  • - *
  • The OkHttp cache is pretty smart and will often connect read and write requests made - * on the same client and invalidate caches.
  • - *
  • Changes made outside the current client cause the OkHttp cache to return stale data. - * This is expected and correct behavior.
  • - *
  • "max-age=0" addresses the problem of external changes by revalidating caches for each request. - * This produces the same number of requests as OkHttp without caching, but those requests only - * count towards the GitHub rate limit if data has changes.
  • + *
  • The OkHttp cache is pretty smart and will often connect read and write requests made on the same client and + * invalidate caches.
  • + *
  • Changes made outside the current client cause the OkHttp cache to return stale data. This is expected and correct + * behavior.
  • + *
  • "max-age=0" addresses the problem of external changes by revalidating caches for each request. This produces the + * same number of requests as OkHttp without caching, but those requests only count towards the GitHub rate limit if + * data has changes.
  • *
* * @author Liam Newman @@ -69,11 +69,7 @@ public OkHttpConnectorTest() { @Override protected WireMockConfiguration getWireMockOptions() { return super.getWireMockOptions() - .extensions(ResponseTemplateTransformer.builder() - .global(true) - .maxCacheEntries(0L) - .build() - ); + .extensions(ResponseTemplateTransformer.builder().global(true).maxCacheEntries(0L).build()); } @Before @@ -91,9 +87,7 @@ public void setupRepo() throws Exception { @Test public void DefaultConnector() throws Exception { - this.gitHub = getGitHubBuilder() - .withEndpoint(mockGitHub.apiServer().baseUrl()) - .build(); + this.gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()).build(); doTestActions(); @@ -110,10 +104,8 @@ public void OkHttpConnector_NoCache() throws Exception { OkHttpClient client = createClient(false); OkHttpConnector connector = new OkHttpConnector(new OkUrlFactory(client)); - this.gitHub = getGitHubBuilder() - .withEndpoint(mockGitHub.apiServer().baseUrl()) - .withConnector(connector) - .build(); + this.gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()).withConnector(connector) + .build(); doTestActions(); @@ -137,15 +129,13 @@ public void OkHttpConnector_Cache_MaxAgeNone() throws Exception { OkHttpClient client = createClient(true); OkHttpConnector connector = new OkHttpConnector(new OkUrlFactory(client), -1); - this.gitHub = getGitHubBuilder() - .withEndpoint(mockGitHub.apiServer().baseUrl()) - .withConnector(connector) - .build(); + this.gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()).withConnector(connector) + .build(); doTestActions(); // Testing behavior after change - // NOTE: this is wrong! The live data changed! + // NOTE: this is wrong! The live data changed! // Due to max-age (default 60 from response) the cache returns the old data. assertThat(getRepository(gitHub).getDescription(), is(mockGitHub.getMethodName())); @@ -166,14 +156,11 @@ public void OkHttpConnector_Cache_MaxAge_Three() throws Exception { assumeFalse("Test only valid when not taking a snapshot", mockGitHub.isTakeSnapshot()); assumeTrue("Test only valid when proxying (-Dtest.github.useProxy to enable)", mockGitHub.isUseProxy()); - OkHttpClient client = createClient(true); OkHttpConnector connector = new OkHttpConnector(new OkUrlFactory(client), 3); - this.gitHub = getGitHubBuilder() - .withEndpoint(mockGitHub.apiServer().baseUrl()) - .withConnector(connector) - .build(); + this.gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()).withConnector(connector) + .build(); doTestActions(); @@ -197,10 +184,8 @@ public void OkHttpConnector_Cache_MaxAgeDefault_Zero() throws Exception { OkHttpClient client = createClient(true); OkHttpConnector connector = new OkHttpConnector(new OkUrlFactory(client)); - this.gitHub = getGitHubBuilder() - .withEndpoint(mockGitHub.apiServer().baseUrl()) - .withConnector(connector) - .build(); + this.gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()).withConnector(connector) + .build(); doTestActions(); @@ -216,14 +201,11 @@ public void OkHttpConnector_Cache_MaxAgeDefault_Zero() throws Exception { private void checkRequestAndLimit(int networkRequestCount, int rateLimitUsed) throws IOException { GHRateLimit rateLimitAfter = gitHub.rateLimit(); - assertThat("Request Count", - mockGitHub.getRequestCount(), - is(networkRequestCount + userRequestCount)); + assertThat("Request Count", mockGitHub.getRequestCount(), is(networkRequestCount + userRequestCount)); // Rate limit must be under this value, but if it wiggles we don't care - assertThat("Rate Limit Change", - rateLimitBefore.remaining - rateLimitAfter.remaining, - is(lessThanOrEqualTo(rateLimitUsed + userRequestCount))); + assertThat("Rate Limit Change", rateLimitBefore.remaining - rateLimitAfter.remaining, + is(lessThanOrEqualTo(rateLimitUsed + userRequestCount))); } @@ -242,7 +224,6 @@ private OkHttpClient createClient(boolean useCache) throws IOException { return client; } - /** * This is a standard set of actions to be performed with each connector * @@ -253,7 +234,6 @@ private void doTestActions() throws Exception { String name = mockGitHub.getMethodName(); - GHRepository repo = getRepository(gitHub); // Testing behavior when nothing has changed. @@ -267,7 +247,6 @@ private void doTestActions() throws Exception { // Test behavior after change assertThat(getRepository(gitHub).getDescription(), is(name)); - // Get Tricky - make a change via a different client if (mockGitHub.isUseProxy()) { GHRepository altRepo = getRepository(gitHubBeforeAfter); @@ -282,14 +261,14 @@ private void pollForChange(String name) throws IOException, InterruptedException getRepository(gitHub).getDescription(); Thread.sleep(500); getRepository(gitHub).getDescription(); - //This is only interesting when running the max-age=3 test which currently only runs with proxy - //Disabled to speed up the tests + // This is only interesting when running the max-age=3 test which currently only runs with proxy + // Disabled to speed up the tests if (mockGitHub.isUseProxy()) { Thread.sleep(1000); } getRepository(gitHub).getDescription(); - //This is only interesting when running the max-age=3 test which currently only runs with proxy - //Disabled to speed up the tests + // This is only interesting when running the max-age=3 test which currently only runs with proxy + // Disabled to speed up the tests if (mockGitHub.isUseProxy()) { Thread.sleep(4000); } diff --git a/src/test/java/org/kohsuke/github/extras/okhttp3/OkHttpConnectorTest.java b/src/test/java/org/kohsuke/github/extras/okhttp3/OkHttpConnectorTest.java index a8abb68025..5992bf84c8 100644 --- a/src/test/java/org/kohsuke/github/extras/okhttp3/OkHttpConnectorTest.java +++ b/src/test/java/org/kohsuke/github/extras/okhttp3/OkHttpConnectorTest.java @@ -28,16 +28,16 @@ * Key take aways: * *
    - *
  • These tests are artificial and intended to highlight the differences - * in behavior between scenarios. However, the differences they indicate are stark.
  • + *
  • These tests are artificial and intended to highlight the differences in behavior between scenarios. However, the + * differences they indicate are stark.
  • *
  • Caching reduces rate limit consumption by at least a factor of two in even the simplest case.
  • - *
  • The OkHttp cache is pretty smart and will often connect read and write requests made - * on the same client and invalidate caches.
  • - *
  • Changes made outside the current client cause the OkHttp cache to return stale data. - * This is expected and correct behavior.
  • - *
  • "max-age=0" addresses the problem of external changes by revalidating caches for each request. - * This produces the same number of requests as OkHttp without caching, but those requests only - * count towards the GitHub rate limit if data has changes.
  • + *
  • The OkHttp cache is pretty smart and will often connect read and write requests made on the same client and + * invalidate caches.
  • + *
  • Changes made outside the current client cause the OkHttp cache to return stale data. This is expected and correct + * behavior.
  • + *
  • "max-age=0" addresses the problem of external changes by revalidating caches for each request. This produces the + * same number of requests as OkHttp without caching, but those requests only count towards the GitHub rate limit if + * data has changes.
  • *
* * @author Liam Newman @@ -71,13 +71,9 @@ public OkHttpConnectorTest() { @Override protected WireMockConfiguration getWireMockOptions() { return super.getWireMockOptions() - // Use the same data files as the 2.x test - .usingFilesUnderDirectory(baseRecordPath.replace("/okhttp3/", "/")) - .extensions(ResponseTemplateTransformer.builder() - .global(true) - .maxCacheEntries(0L) - .build() - ); + // Use the same data files as the 2.x test + .usingFilesUnderDirectory(baseRecordPath.replace("/okhttp3/", "/")) + .extensions(ResponseTemplateTransformer.builder().global(true).maxCacheEntries(0L).build()); } @Before @@ -95,9 +91,7 @@ public void setupRepo() throws Exception { @Test public void DefaultConnector() throws Exception { - this.gitHub = getGitHubBuilder() - .withEndpoint(mockGitHub.apiServer().baseUrl()) - .build(); + this.gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()).build(); doTestActions(); @@ -114,10 +108,8 @@ public void OkHttpConnector_NoCache() throws Exception { OkHttpClient client = createClient(false); OkHttpConnector connector = new OkHttpConnector(client); - this.gitHub = getGitHubBuilder() - .withEndpoint(mockGitHub.apiServer().baseUrl()) - .withConnector(connector) - .build(); + this.gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()).withConnector(connector) + .build(); doTestActions(); @@ -141,15 +133,13 @@ public void OkHttpConnector_Cache_MaxAgeNone() throws Exception { OkHttpClient client = createClient(true); OkHttpConnector connector = new OkHttpConnector(client, -1); - this.gitHub = getGitHubBuilder() - .withEndpoint(mockGitHub.apiServer().baseUrl()) - .withConnector(connector) - .build(); + this.gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()).withConnector(connector) + .build(); doTestActions(); // Testing behavior after change - // NOTE: this is wrong! The live data changed! + // NOTE: this is wrong! The live data changed! // Due to max-age (default 60 from response) the cache returns the old data. assertThat(getRepository(gitHub).getDescription(), is(mockGitHub.getMethodName())); @@ -170,14 +160,11 @@ public void OkHttpConnector_Cache_MaxAge_Three() throws Exception { assumeFalse("Test only valid when not taking a snapshot", mockGitHub.isTakeSnapshot()); assumeTrue("Test only valid when proxying (-Dtest.github.useProxy to enable)", mockGitHub.isUseProxy()); - OkHttpClient client = createClient(true); OkHttpConnector connector = new OkHttpConnector(client, 3); - this.gitHub = getGitHubBuilder() - .withEndpoint(mockGitHub.apiServer().baseUrl()) - .withConnector(connector) - .build(); + this.gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()).withConnector(connector) + .build(); doTestActions(); @@ -200,10 +187,8 @@ public void OkHttpConnector_Cache_MaxAgeDefault_Zero() throws Exception { OkHttpClient client = createClient(true); OkHttpConnector connector = new OkHttpConnector(client); - this.gitHub = getGitHubBuilder() - .withEndpoint(mockGitHub.apiServer().baseUrl()) - .withConnector(connector) - .build(); + this.gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()).withConnector(connector) + .build(); doTestActions(); @@ -219,14 +204,11 @@ public void OkHttpConnector_Cache_MaxAgeDefault_Zero() throws Exception { private void checkRequestAndLimit(int networkRequestCount, int rateLimitUsed) throws IOException { GHRateLimit rateLimitAfter = gitHub.rateLimit(); - assertThat("Request Count", - getRequestCount(), - is(networkRequestCount + userRequestCount)); + assertThat("Request Count", getRequestCount(), is(networkRequestCount + userRequestCount)); // Rate limit must be under this value, but if it wiggles we don't care - assertThat("Rate Limit Change", - rateLimitBefore.remaining - rateLimitAfter.remaining, - is(lessThanOrEqualTo(rateLimitUsed + userRequestCount))); + assertThat("Rate Limit Change", rateLimitBefore.remaining - rateLimitAfter.remaining, + is(lessThanOrEqualTo(rateLimitUsed + userRequestCount))); } @@ -249,7 +231,6 @@ private OkHttpClient createClient(boolean useCache) throws IOException { return builder.build(); } - /** * This is a standard set of actions to be performed with each connector * @@ -260,7 +241,6 @@ private void doTestActions() throws Exception { String name = mockGitHub.getMethodName(); - GHRepository repo = getRepository(gitHub); // Testing behavior when nothing has changed. @@ -274,7 +254,6 @@ private void doTestActions() throws Exception { // Test behavior after change assertThat(getRepository(gitHub).getDescription(), is(name)); - // Get Tricky - make a change via a different client if (mockGitHub.isUseProxy()) { GHRepository altRepo = getRepository(gitHubBeforeAfter); @@ -289,14 +268,14 @@ private void pollForChange(String name) throws IOException, InterruptedException getRepository(gitHub).getDescription(); Thread.sleep(500); getRepository(gitHub).getDescription(); - //This is only interesting when running the max-age=3 test which currently only runs with proxy - //Disabled to speed up the tests + // This is only interesting when running the max-age=3 test which currently only runs with proxy + // Disabled to speed up the tests if (mockGitHub.isUseProxy()) { Thread.sleep(1000); } getRepository(gitHub).getDescription(); - //This is only interesting when running the max-age=3 test which currently only runs with proxy - //Disabled to speed up the tests + // This is only interesting when running the max-age=3 test which currently only runs with proxy + // Disabled to speed up the tests if (mockGitHub.isUseProxy()) { Thread.sleep(4000); } diff --git a/src/test/java/org/kohsuke/github/junit/GitHubWireMockRule.java b/src/test/java/org/kohsuke/github/junit/GitHubWireMockRule.java index 7d008fdfff..47600bf0aa 100644 --- a/src/test/java/org/kohsuke/github/junit/GitHubWireMockRule.java +++ b/src/test/java/org/kohsuke/github/junit/GitHubWireMockRule.java @@ -31,9 +31,8 @@ import static com.github.tomakehurst.wiremock.common.Gzip.unGzipToString; /** - * The standard WireMockRule eagerly initializes a WireMockServer. - * This version suptakes a laze approach allowing us to automatically isolate snapshots - * for each method. + * The standard WireMockRule eagerly initializes a WireMockServer. This version suptakes a laze approach allowing us to + * automatically isolate snapshots for each method. * * @author Liam Newman */ @@ -44,8 +43,8 @@ public class GitHubWireMockRule extends WireMockMultiServerRule { // You can use the proxy without taking a snapshot while writing and debugging tests. // You cannot take a snapshot without proxying. private final static boolean takeSnapshot = System.getProperty("test.github.takeSnapshot", "false") != "false"; - private final static boolean useProxy = takeSnapshot || System.getProperty("test.github.useProxy", "false") != "false"; - + private final static boolean useProxy = takeSnapshot + || System.getProperty("test.github.useProxy", "false") != "false"; public GitHubWireMockRule() { this(WireMockConfiguration.options()); @@ -86,14 +85,8 @@ protected void initializeServers() { protected void before() { super.before(); if (isUseProxy()) { - this.apiServer().stubFor( - proxyAllTo("https://api.github.com") - .atPriority(100) - ); - this.rawServer().stubFor( - proxyAllTo("https://raw.githubusercontent.com") - .atPriority(100) - ); + this.apiServer().stubFor(proxyAllTo("https://api.github.com").atPriority(100)); + this.rawServer().stubFor(proxyAllTo("https://raw.githubusercontent.com").atPriority(100)); } } @@ -101,15 +94,11 @@ protected void before() { protected void after() { super.after(); if (isTakeSnapshot()) { - this.apiServer().snapshotRecord(recordSpec() - .forTarget("https://api.github.com") - .captureHeader("If-None-Match") - .extractTextBodiesOver(255)); + this.apiServer().snapshotRecord(recordSpec().forTarget("https://api.github.com") + .captureHeader("If-None-Match").extractTextBodiesOver(255)); - this.rawServer().snapshotRecord(recordSpec() - .forTarget("https://raw.githubusercontent.com") - .captureHeader("If-None-Match") - .extractTextBodiesOver(255)); + this.rawServer().snapshotRecord(recordSpec().forTarget("https://raw.githubusercontent.com") + .captureHeader("If-None-Match").extractTextBodiesOver(255)); // After taking the snapshot, format the output formatJsonFiles(new File(this.apiServer().getOptions().filesRoot().getPath()).toPath()); @@ -127,45 +116,41 @@ public static int getRequestCount(WireMockServer server) { return server.countRequestsMatching(RequestPatternBuilder.allRequests().build()).getCount(); } - private void formatJsonFiles(Path path) { // The more consistent we can make the json output the more meaningful it will be. Gson g = new Gson().newBuilder().serializeNulls().disableHtmlEscaping().setPrettyPrinting() - .registerTypeAdapter(Double.class, new JsonSerializer() { - @Override - public JsonElement serialize(Double src, Type typeOfSrc, JsonSerializationContext context) { - // Gson by default output numbers as doubles - 0.0 - // Remove the tailing .0, as most most numbers are integer value - if(src == src.longValue()) - return new JsonPrimitive(src.longValue()); - return new JsonPrimitive(src); - } - }) - .create(); + .registerTypeAdapter(Double.class, new JsonSerializer() { + @Override + public JsonElement serialize(Double src, Type typeOfSrc, JsonSerializationContext context) { + // Gson by default output numbers as doubles - 0.0 + // Remove the tailing .0, as most most numbers are integer value + if (src == src.longValue()) + return new JsonPrimitive(src.longValue()); + return new JsonPrimitive(src); + } + }).create(); try { - Files.walk(path) - .forEach(filePath -> { - try { - if (filePath.toString().endsWith(".json")) { - String fileText = new String(Files.readAllBytes(filePath)); - // while recording responses we replaced all github calls localhost - // now we reverse that for storage. - fileText = fileText - .replace(this.apiServer().baseUrl(), "https://api.github.com") + Files.walk(path).forEach(filePath -> { + try { + if (filePath.toString().endsWith(".json")) { + String fileText = new String(Files.readAllBytes(filePath)); + // while recording responses we replaced all github calls localhost + // now we reverse that for storage. + fileText = fileText.replace(this.apiServer().baseUrl(), "https://api.github.com") .replace(this.rawServer().baseUrl(), "https://raw.githubusercontent.com"); - // Can be Array or Map - Object parsedObject = g.fromJson(fileText, Object.class); - if (parsedObject instanceof Map && filePath.toString().contains("mappings")) { - filePath = renameMappingFile(filePath, (Map) parsedObject); - } - fileText = g.toJson(parsedObject); - Files.write(filePath, fileText.getBytes()); + // Can be Array or Map + Object parsedObject = g.fromJson(fileText, Object.class); + if (parsedObject instanceof Map && filePath.toString().contains("mappings")) { + filePath = renameMappingFile(filePath, (Map) parsedObject); } - } catch (Exception e) { - throw new RuntimeException("Files could not be written", e); + fileText = g.toJson(parsedObject); + Files.write(filePath, fileText.getBytes()); } - }); + } catch (Exception e) { + throw new RuntimeException("Files could not be written", e); + } + }); } catch (IOException e) { throw new RuntimeException("Files could not be written"); } @@ -175,12 +160,13 @@ private Path renameMappingFile(Path filePath, Map parsedObject) // Shorten the file names // For understandability, rename the files to include the response order Path targetPath = filePath; - String id = (String)parsedObject.getOrDefault("id", null); - Long insertionIndex = ((Double)parsedObject.getOrDefault("insertionIndex", 0.0)).longValue(); + String id = (String) parsedObject.getOrDefault("id", null); + Long insertionIndex = ((Double) parsedObject.getOrDefault("insertionIndex", 0.0)).longValue(); if (id != null && insertionIndex > 0) { String filePathString = filePath.toString(); if (filePathString.contains(id)) { - targetPath = new File(filePathString.replace(id, insertionIndex.toString() + "-" + id.substring(0, 6))).toPath(); + targetPath = new File(filePathString.replace(id, insertionIndex.toString() + "-" + id.substring(0, 6))) + .toPath(); Files.move(filePath, targetPath); } } @@ -188,11 +174,9 @@ private Path renameMappingFile(Path filePath, Map parsedObject) return targetPath; } - /** - * A number of modifications are needed as runtime to make responses - * target the WireMock server and not accidentally switch to using the live - * github servers. + * A number of modifications are needed as runtime to make responses target the WireMock server and not accidentally + * switch to using the live github servers. */ private static class GitHubApiResponseTransformer extends ResponseTransformer { private final GitHubWireMockRule rule; @@ -202,22 +186,19 @@ public GitHubApiResponseTransformer(GitHubWireMockRule rule) { } @Override - public Response transform(Request request, Response response, FileSource files, - Parameters parameters) { + public Response transform(Request request, Response response, FileSource files, Parameters parameters) { Response.Builder builder = Response.Builder.like(response); Collection headers = response.getHeaders().all(); fixListTraversalHeader(response, headers); - if ("application/json" - .equals(response.getHeaders().getContentTypeHeader().mimeTypePart())) { + if ("application/json".equals(response.getHeaders().getContentTypeHeader().mimeTypePart())) { String body; body = getBodyAsString(response, headers); - builder.body(body - .replace("https://api.github.com", rule.apiServer().baseUrl()) - .replace("https://raw.githubusercontent.com", rule.rawServer().baseUrl())); + builder.body(body.replace("https://api.github.com", rule.apiServer().baseUrl()) + .replace("https://raw.githubusercontent.com", rule.rawServer().baseUrl())); } builder.headers(new HttpHeaders(headers)); @@ -240,9 +221,8 @@ private void fixListTraversalHeader(Response response, Collection he HttpHeader linkHeader = response.getHeaders().getHeader("Link"); if (linkHeader.isPresent()) { headers.removeIf(item -> item.keyEquals("Link")); - headers.add(HttpHeader.httpHeader("Link", linkHeader.firstValue() - .replace("https://api.github.com", - rule.apiServer().baseUrl()))); + headers.add(HttpHeader.httpHeader("Link", + linkHeader.firstValue().replace("https://api.github.com", rule.apiServer().baseUrl()))); } } diff --git a/src/test/java/org/kohsuke/github/junit/WireMockMultiServerRule.java b/src/test/java/org/kohsuke/github/junit/WireMockMultiServerRule.java index 660782272f..f11b4ca025 100644 --- a/src/test/java/org/kohsuke/github/junit/WireMockMultiServerRule.java +++ b/src/test/java/org/kohsuke/github/junit/WireMockMultiServerRule.java @@ -19,10 +19,8 @@ import java.util.Map; /** - * The standard WireMockRule eagerly initializes a WireMockServer. - * This version supports multiple servers in one rule and - * takes a lazy approach to intitialization allowing us to - * isolate files snapshots for each method. + * The standard WireMockRule eagerly initializes a WireMockServer. This version supports multiple servers in one rule + * and takes a lazy approach to intitialization allowing us to isolate files snapshots for each method. * * @author Liam Newman */ @@ -38,7 +36,6 @@ public String getMethodName() { private String methodName = null; - public WireMockMultiServerRule(Options options) { this(options, true); } @@ -65,8 +62,7 @@ private Statement apply(final Statement base, final String methodName) { public void evaluate() throws Throwable { WireMockMultiServerRule.this.methodName = methodName; initializeServers(); - WireMock.configureFor("localhost", - WireMockMultiServerRule.this.servers.get("default").port()); + WireMock.configureFor("localhost", WireMockMultiServerRule.this.servers.get("default").port()); try { WireMockMultiServerRule.this.before(); @@ -92,9 +88,8 @@ protected final void initializeServer(String serverId, Extension... extensions) directoryName += "_" + serverId; } - final Options localOptions = new WireMockRuleConfiguration( - WireMockMultiServerRule.this.options, - directoryName, extensions); + final Options localOptions = new WireMockRuleConfiguration(WireMockMultiServerRule.this.options, directoryName, + extensions); new File(localOptions.filesRoot().getPath(), "mappings").mkdirs(); new File(localOptions.filesRoot().getPath(), "__files").mkdirs(); @@ -160,6 +155,4 @@ private void stop() { }); } - - } diff --git a/src/test/java/org/kohsuke/github/junit/WireMockRule.java b/src/test/java/org/kohsuke/github/junit/WireMockRule.java index aa60691379..2f5dc3c3f8 100644 --- a/src/test/java/org/kohsuke/github/junit/WireMockRule.java +++ b/src/test/java/org/kohsuke/github/junit/WireMockRule.java @@ -93,9 +93,7 @@ private Statement apply(final Statement base, final String methodName) { return new Statement() { public void evaluate() throws Throwable { WireMockRule.this.methodName = methodName; - final Options localOptions = new WireMockRuleConfiguration( - WireMockRule.this.options, - methodName); + final Options localOptions = new WireMockRuleConfiguration(WireMockRule.this.options, methodName); new File(localOptions.filesRoot().getPath(), "mappings").mkdirs(); new File(localOptions.filesRoot().getPath(), "__files").mkdirs(); diff --git a/src/test/java/org/kohsuke/github/junit/WireMockRuleConfiguration.java b/src/test/java/org/kohsuke/github/junit/WireMockRuleConfiguration.java index 330afc2aaf..c8ddbf5f2f 100644 --- a/src/test/java/org/kohsuke/github/junit/WireMockRuleConfiguration.java +++ b/src/test/java/org/kohsuke/github/junit/WireMockRuleConfiguration.java @@ -78,14 +78,13 @@ public WireMockRuleConfiguration mappingSource(MappingsSource mappingsSource) { public Map extensionsOfType(Class extensionType) { Map result = Maps.newLinkedHashMap(this.parent.extensionsOfType(extensionType)); - result.putAll((Map)Maps.filterEntries(this.extensions, ExtensionLoader.valueAssignableFrom(extensionType))); + result.putAll((Map) Maps.filterEntries(this.extensions, + ExtensionLoader.valueAssignableFrom(extensionType))); return result; } - // Simple wrappers - public int portNumber() { return parent.portNumber(); }