diff --git a/pom.xml b/pom.xml index b37b2585e7..4672d119d4 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 org.kohsuke - github-api + github-api2 2.0-alpha1-SNAPSHOT GitHub API for Java https://github-api.kohsuke.org/ @@ -118,9 +118,6 @@ /org/kohsuke/github/extras/HttpClient* /org/kohsuke/github/example/* - /org/kohsuke/github/extras/OkHttpConnector* - /org/kohsuke/github/extras/OkHttp3Connector* - /org/kohsuke/github/extras/okhttp3/ObsoleteUrlFactory* @@ -175,20 +172,14 @@ org.kohsuke.github.extras.HttpClientGitHubConnector.** org.kohsuke.github.extras.HttpClientGitHubConnector - - org.kohsuke.github.extras.okhttp3.ObsoleteUrlFactory.** - org.kohsuke.github.extras.okhttp3.ObsoleteUrlFactory + + org.kohsuke.github.connector.GitHubConnectorResponseHttpUrlConnectionAdapter + oorg.kohsuke.github.GHPerson.* + org.kohsuke.github.GHRepositorySearchBuilder.Fork org.kohsuke.github.example.* - - org.kohsuke.github.extras.OkHttpConnector - org.kohsuke.github.extras.OkHttp3Connector - org.kohsuke.github.EnforcementLevel - org.kohsuke.github.GHPerson.1 - org.kohsuke.github.GHCompare.User - org.kohsuke.github.GHCommit.GHAuthor @@ -600,20 +591,6 @@ ${okhttp3.version} true - - - - com.squareup.okhttp3 - okhttp-urlconnection - 3.12.3 - true - - - com.squareup.okhttp - okhttp-urlconnection - 2.7.5 - true - org.kohsuke wordnet-random-name @@ -706,23 +683,6 @@ - - java11-urlconnection-test - integration-test - - test - - - ${project.basedir}/target/${project.artifactId}-${project.version}.jar - false - src/test/resources/slow-or-flaky-tests.txt - @{jacoco.surefire.argLine} ${surefire.argLine} -Dtest.github.connector=urlconnection - - - src/test/resources/test-trace-logging.properties - - - slow-or-flaky-test integration-test diff --git a/src/main/java/org/kohsuke/github/AbuseLimitHandler.java b/src/main/java/org/kohsuke/github/AbuseLimitHandler.java deleted file mode 100644 index d6894adf9a..0000000000 --- a/src/main/java/org/kohsuke/github/AbuseLimitHandler.java +++ /dev/null @@ -1,108 +0,0 @@ -package org.kohsuke.github; - -import org.kohsuke.github.connector.GitHubConnectorResponse; - -import java.io.IOException; -import java.io.InterruptedIOException; -import java.net.HttpURLConnection; - -import javax.annotation.Nonnull; - -// TODO: Auto-generated Javadoc -/** - * Pluggable strategy to determine what to do when the API abuse limit is hit. - * - * @author Kohsuke Kawaguchi - * @see GitHubBuilder#withAbuseLimitHandler(GitHubAbuseLimitHandler) - * GitHubBuilder#withAbuseLimitHandler(GitHubAbuseLimitHandler) - * @see documentation - * @see RateLimitHandler - * @deprecated Switch to {@link GitHubAbuseLimitHandler}. - */ -@Deprecated -public abstract class AbuseLimitHandler extends GitHubAbuseLimitHandler { - - /** - * 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. - * - * @param connectorResponse - * Response information for this request. - * @throws IOException - * on failure - * @see API documentation from GitHub - * @see Dealing - * with abuse rate limits - * - */ - public void onError(@Nonnull GitHubConnectorResponse connectorResponse) throws IOException { - GHIOException e = new HttpException("Abuse limit reached", - connectorResponse.statusCode(), - connectorResponse.header("Status"), - connectorResponse.request().url().toString()).withResponseHeaderFields(connectorResponse.allHeaders()); - onError(e, connectorResponse.toHttpURLConnection()); - } - - /** - * 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. - * - * @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). - * @param uc - * Connection that resulted in an error. Useful for accessing other response headers. - * @throws IOException - * on failure - * @see API documentation from GitHub - * @see Dealing - * with abuse rate limits - * - */ - @Deprecated - public abstract void onError(IOException e, HttpURLConnection uc) throws IOException; - - /** - * Wait until the API abuse "wait time" is passed. - */ - @Deprecated - public static final AbuseLimitHandler WAIT = new AbuseLimitHandler() { - @Override - public void onError(IOException e, HttpURLConnection uc) throws IOException { - try { - Thread.sleep(parseWaitTime(uc)); - } catch (InterruptedException ex) { - 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 - - return Math.max(1000, Long.parseLong(v) * 1000); - } - }; - - /** - * Fail immediately. - */ - @Deprecated - public static final AbuseLimitHandler FAIL = new AbuseLimitHandler() { - @Override - public void onError(IOException e, HttpURLConnection uc) throws IOException { - throw e; - } - }; -} diff --git a/src/main/java/org/kohsuke/github/EnforcementLevel.java b/src/main/java/org/kohsuke/github/EnforcementLevel.java deleted file mode 100644 index 0cc69500a9..0000000000 --- a/src/main/java/org/kohsuke/github/EnforcementLevel.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.kohsuke.github; - -import java.util.Locale; - -// TODO: Auto-generated Javadoc -/** - * This was added during preview API period but it has changed since then. - * - * @author Kohsuke Kawaguchi - */ -@Deprecated -public enum EnforcementLevel { - - /** The off. */ - OFF, - /** The non admins. */ - NON_ADMINS, - /** The everyone. */ - EVERYONE; - - /** - * To string. - * - * @return the string - */ - public String toString() { - return name().toLowerCase(Locale.ENGLISH); - } -} diff --git a/src/main/java/org/kohsuke/github/GHApp.java b/src/main/java/org/kohsuke/github/GHApp.java index 91b24b275b..0cbb3d4933 100644 --- a/src/main/java/org/kohsuke/github/GHApp.java +++ b/src/main/java/org/kohsuke/github/GHApp.java @@ -41,18 +41,6 @@ public GHUser getOwner() { return owner; } - /** - * Sets owner. - * - * @param owner - * the owner - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setOwner(GHUser owner) { - throw new RuntimeException("Do not use this method."); - } - /** * Gets name. * @@ -71,18 +59,6 @@ public String getSlug() { return slug; } - /** - * Sets name. - * - * @param name - * the name - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setName(String name) { - throw new RuntimeException("Do not use this method."); - } - /** * Gets description. * @@ -92,18 +68,6 @@ public String getDescription() { return description; } - /** - * Sets description. - * - * @param description - * the description - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setDescription(String description) { - throw new RuntimeException("Do not use this method."); - } - /** * Gets external url. * @@ -113,18 +77,6 @@ public String getExternalUrl() { return externalUrl; } - /** - * Sets external url. - * - * @param externalUrl - * the external url - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setExternalUrl(String externalUrl) { - throw new RuntimeException("Do not use this method."); - } - /** * Gets events. * @@ -136,18 +88,6 @@ public List getEvents() { .collect(Collectors.toList()); } - /** - * Sets events. - * - * @param events - * the events - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setEvents(List events) { - throw new RuntimeException("Do not use this method."); - } - /** * Gets installations count. * @@ -157,18 +97,6 @@ public long getInstallationsCount() { return installationsCount; } - /** - * Sets installations count. - * - * @param installationsCount - * the installations count - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setInstallationsCount(long installationsCount) { - throw new RuntimeException("Do not use this method."); - } - /** * Gets the html url. * @@ -187,18 +115,6 @@ public Map getPermissions() { return Collections.unmodifiableMap(permissions); } - /** - * Sets permissions. - * - * @param permissions - * the permissions - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setPermissions(Map permissions) { - throw new RuntimeException("Do not use this method."); - } - /** * Obtains all the installations associated with this app. *

diff --git a/src/main/java/org/kohsuke/github/GHAppInstallation.java b/src/main/java/org/kohsuke/github/GHAppInstallation.java index cf5bda32b0..0c1ecba823 100644 --- a/src/main/java/org/kohsuke/github/GHAppInstallation.java +++ b/src/main/java/org/kohsuke/github/GHAppInstallation.java @@ -55,18 +55,6 @@ public URL getHtmlUrl() { return GitHubClient.parseURL(htmlUrl); } - /** - * Sets root. - * - * @param root - * the root - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setRoot(GitHub root) { - throw new RuntimeException("Do not use this method."); - } - /** * Gets account. * @@ -77,18 +65,6 @@ public GHUser getAccount() { return account; } - /** - * Sets account. - * - * @param account - * the account - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setAccount(GHUser account) { - throw new RuntimeException("Do not use this method."); - } - /** * Gets access token url. * @@ -98,18 +74,6 @@ public String getAccessTokenUrl() { return accessTokenUrl; } - /** - * Sets access token url. - * - * @param accessTokenUrl - * the access token url - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setAccessTokenUrl(String accessTokenUrl) { - throw new RuntimeException("Do not use this method."); - } - /** * Gets repositories url. * @@ -150,18 +114,6 @@ GHRepository[] getItems(GitHub root) { } } - /** - * Sets repositories url. - * - * @param repositoriesUrl - * the repositories url - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setRepositoriesUrl(String repositoriesUrl) { - throw new RuntimeException("Do not use this method."); - } - /** * Gets app id. * @@ -171,18 +123,6 @@ public long getAppId() { return appId; } - /** - * Sets app id. - * - * @param appId - * the app id - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setAppId(long appId) { - throw new RuntimeException("Do not use this method."); - } - /** * Gets target id. * @@ -192,18 +132,6 @@ public long getTargetId() { return targetId; } - /** - * Sets target id. - * - * @param targetId - * the target id - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setTargetId(long targetId) { - throw new RuntimeException("Do not use this method."); - } - /** * Gets target type. * @@ -213,18 +141,6 @@ public GHTargetType getTargetType() { return targetType; } - /** - * Sets target type. - * - * @param targetType - * the target type - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setTargetType(GHTargetType targetType) { - throw new RuntimeException("Do not use this method."); - } - /** * Gets permissions. * @@ -234,18 +150,6 @@ public Map getPermissions() { return Collections.unmodifiableMap(permissions); } - /** - * Sets permissions. - * - * @param permissions - * the permissions - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setPermissions(Map permissions) { - throw new RuntimeException("Do not use this method."); - } - /** * Gets events. * @@ -257,18 +161,6 @@ public List getEvents() { .collect(Collectors.toList()); } - /** - * Sets events. - * - * @param events - * the events - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setEvents(List events) { - throw new RuntimeException("Do not use this method."); - } - /** * Gets single file name. * @@ -278,18 +170,6 @@ public String getSingleFileName() { return singleFileName; } - /** - * Sets single file name. - * - * @param singleFileName - * the single file name - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setSingleFileName(String singleFileName) { - throw new RuntimeException("Do not use this method."); - } - /** * Gets repository selection. * @@ -299,18 +179,6 @@ public GHRepositorySelection getRepositorySelection() { return repositorySelection; } - /** - * Sets repository selection. - * - * @param repositorySelection - * the repository selection - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setRepositorySelection(GHRepositorySelection repositorySelection) { - throw new RuntimeException("Do not use this method."); - } - /** * Delete a Github App installation *

diff --git a/src/main/java/org/kohsuke/github/GHAppInstallationToken.java b/src/main/java/org/kohsuke/github/GHAppInstallationToken.java index 415cc996bc..261001d6d1 100644 --- a/src/main/java/org/kohsuke/github/GHAppInstallationToken.java +++ b/src/main/java/org/kohsuke/github/GHAppInstallationToken.java @@ -22,18 +22,6 @@ public class GHAppInstallationToken extends GitHubInteractiveObject { private List repositories; private GHRepositorySelection repositorySelection; - /** - * Sets root. - * - * @param root - * the root - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setRoot(GitHub root) { - throw new RuntimeException("Do not use this method."); - } - /** * Gets permissions. * @@ -43,18 +31,6 @@ public Map getPermissions() { return Collections.unmodifiableMap(permissions); } - /** - * Sets permissions. - * - * @param permissions - * the permissions - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setPermissions(Map permissions) { - throw new RuntimeException("Do not use this method."); - } - /** * Gets token. * @@ -64,18 +40,6 @@ public String getToken() { return token; } - /** - * Sets token. - * - * @param token - * the token - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setToken(String token) { - throw new RuntimeException("Do not use this method."); - } - /** * Gets repositories. * @@ -85,18 +49,6 @@ public List getRepositories() { return GitHubClient.unmodifiableListOrNull(repositories); } - /** - * Sets repositories. - * - * @param repositories - * the repositories - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setRepositories(List repositories) { - throw new RuntimeException("Do not use this method."); - } - /** * Gets repository selection. * @@ -106,18 +58,6 @@ public GHRepositorySelection getRepositorySelection() { return repositorySelection; } - /** - * Sets repository selection. - * - * @param repositorySelection - * the repository selection - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setRepositorySelection(GHRepositorySelection repositorySelection) { - throw new RuntimeException("Do not use this method."); - } - /** * Gets expires at. * diff --git a/src/main/java/org/kohsuke/github/GHAuthorization.java b/src/main/java/org/kohsuke/github/GHAuthorization.java index 5286750ed7..4cbd6ce818 100644 --- a/src/main/java/org/kohsuke/github/GHAuthorization.java +++ b/src/main/java/org/kohsuke/github/GHAuthorization.java @@ -136,18 +136,6 @@ public String getAppName() { return app.name; } - /** - * Gets api url. - * - * @return the api url - * @deprecated use {@link #getUrl()} - */ - @Deprecated - @SuppressFBWarnings(value = "NM_CONFUSING", justification = "It's a part of the library API, cannot be changed") - public URL getApiURL() { - return getUrl(); - } - /** * Gets the html url. * diff --git a/src/main/java/org/kohsuke/github/GHBranch.java b/src/main/java/org/kohsuke/github/GHBranch.java index 3a88231394..f31b662f25 100644 --- a/src/main/java/org/kohsuke/github/GHBranch.java +++ b/src/main/java/org/kohsuke/github/GHBranch.java @@ -7,7 +7,6 @@ import java.io.IOException; import java.net.URL; -import java.util.Collection; import java.util.Objects; import javax.annotation.CheckForNull; @@ -142,32 +141,6 @@ public GHBranchProtectionBuilder enableProtection() { return new GHBranchProtectionBuilder(this); } - /** - * Enable protection. - * - * @param level - * the level - * @param contexts - * the contexts - * @throws IOException - * the io exception - */ - // backward compatibility with previous signature - @Deprecated - public void enableProtection(EnforcementLevel level, Collection contexts) throws IOException { - switch (level) { - case OFF : - disableProtection(); - break; - case NON_ADMINS : - case EVERYONE : - enableProtection().addRequiredChecks(contexts) - .includeAdmins(level == EnforcementLevel.EVERYONE) - .enable(); - break; - } - } - /** * Merge a branch into this branch. * diff --git a/src/main/java/org/kohsuke/github/GHCommit.java b/src/main/java/org/kohsuke/github/GHCommit.java index 250dbe7755..df1844cc6d 100644 --- a/src/main/java/org/kohsuke/github/GHCommit.java +++ b/src/main/java/org/kohsuke/github/GHCommit.java @@ -410,19 +410,6 @@ public URL getUrl() { return GitHubClient.parseURL(url); } - /** - * List of files changed/added/removed in this commit. - * - * @return Can be empty but never null. - * @throws IOException - * on error - * @deprecated Use {@link #listFiles()} instead. - */ - @Deprecated - public List getFiles() throws IOException { - return listFiles().toList(); - } - /** * List of files changed/added/removed in this commit. Uses a paginated list if the files returned by GitHub exceed * 300 in quantity. diff --git a/src/main/java/org/kohsuke/github/GHCompare.java b/src/main/java/org/kohsuke/github/GHCompare.java index 08c6f051b1..8f25369886 100644 --- a/src/main/java/org/kohsuke/github/GHCompare.java +++ b/src/main/java/org/kohsuke/github/GHCompare.java @@ -198,18 +198,6 @@ public GHCommit.File[] getFiles() { return newValue; } - /** - * Wrap gh compare. - * - * @param owner - * the owner - * @return the gh compare - */ - @Deprecated - public GHCompare wrap(GHRepository owner) { - throw new RuntimeException("Do not use this method."); - } - /** * Wrap gh compare. * diff --git a/src/main/java/org/kohsuke/github/GHContent.java b/src/main/java/org/kohsuke/github/GHContent.java index c476a89d8c..d6b29a090d 100644 --- a/src/main/java/org/kohsuke/github/GHContent.java +++ b/src/main/java/org/kohsuke/github/GHContent.java @@ -121,6 +121,7 @@ public String getTarget() { * the io exception * @deprecated Use {@link #read()} */ + @Deprecated @SuppressFBWarnings("DM_DEFAULT_ENCODING") public String getContent() throws IOException { return new String(Base64.getMimeDecoder().decode(getEncodedContent())); diff --git a/src/main/java/org/kohsuke/github/GHContentSearchBuilder.java b/src/main/java/org/kohsuke/github/GHContentSearchBuilder.java index 305c61b36a..e29449e6bb 100644 --- a/src/main/java/org/kohsuke/github/GHContentSearchBuilder.java +++ b/src/main/java/org/kohsuke/github/GHContentSearchBuilder.java @@ -59,19 +59,6 @@ public GHContentSearchBuilder language(String v) { return q("language:" + v); } - /** - * Fork gh content search builder. - * - * @param v - * the v - * @return the gh content search builder - * @deprecated use {@link #fork(GHFork)}. - */ - @Deprecated - public GHContentSearchBuilder fork(String v) { - return q("fork", v); - } - /** * Fork gh content search builder. * diff --git a/src/main/java/org/kohsuke/github/GHCreateRepositoryBuilder.java b/src/main/java/org/kohsuke/github/GHCreateRepositoryBuilder.java index f2ec24a14b..1a2b46cc82 100644 --- a/src/main/java/org/kohsuke/github/GHCreateRepositoryBuilder.java +++ b/src/main/java/org/kohsuke/github/GHCreateRepositoryBuilder.java @@ -87,21 +87,6 @@ public GHCreateRepositoryBuilder team(GHTeam team) throws IOException { return this; } - /** - * Specifies whether the repository is a template. - * - * @param enabled - * true if enabled - * @return a builder to continue with building - * @throws IOException - * In case of any networking error or error from the server. - * @deprecated Use {@link #isTemplate(boolean)} method instead - */ - @Deprecated - public GHCreateRepositoryBuilder templateRepository(boolean enabled) throws IOException { - return isTemplate(enabled); - } - /** * Specifies the ownership of the repository. * diff --git a/src/main/java/org/kohsuke/github/GHDeployKey.java b/src/main/java/org/kohsuke/github/GHDeployKey.java index 2af3b9d7ee..ac743ba9cf 100644 --- a/src/main/java/org/kohsuke/github/GHDeployKey.java +++ b/src/main/java/org/kohsuke/github/GHDeployKey.java @@ -114,18 +114,6 @@ public boolean isRead_only() { return read_only; } - /** - * Wrap gh deploy key. - * - * @param repo - * the repo - * @return the gh deploy key - */ - @Deprecated - public GHDeployKey wrap(GHRepository repo) { - throw new RuntimeException("Do not use this method."); - } - /** * Wrap gh deploy key. * diff --git a/src/main/java/org/kohsuke/github/GHDeploymentStatus.java b/src/main/java/org/kohsuke/github/GHDeploymentStatus.java index 208b5e92cf..060ab96b23 100644 --- a/src/main/java/org/kohsuke/github/GHDeploymentStatus.java +++ b/src/main/java/org/kohsuke/github/GHDeploymentStatus.java @@ -36,19 +36,6 @@ public class GHDeploymentStatus extends GHObject { /** The environment url. */ protected String environment_url; - /** - * Wrap gh deployment status. - * - * @param owner - * the owner - * - * @return the gh deployment status - */ - @Deprecated - public GHDeploymentStatus wrap(GHRepository owner) { - throw new RuntimeException("Do not use this method."); - } - /** * Wrap gh deployment status. * @@ -62,17 +49,6 @@ GHDeploymentStatus lateBind(GHRepository owner) { return this; } - /** - * Gets target url. - * - * @return the target url - * @deprecated Target url is deprecated in favor of {@link #getLogUrl() getLogUrl} - */ - @Deprecated - public URL getTargetUrl() { - return GitHubClient.parseURL(target_url); - } - /** * Gets target url. *

diff --git a/src/main/java/org/kohsuke/github/GHDeploymentStatusBuilder.java b/src/main/java/org/kohsuke/github/GHDeploymentStatusBuilder.java index 8cfc9ad5eb..33afa36d84 100644 --- a/src/main/java/org/kohsuke/github/GHDeploymentStatusBuilder.java +++ b/src/main/java/org/kohsuke/github/GHDeploymentStatusBuilder.java @@ -15,23 +15,6 @@ public class GHDeploymentStatusBuilder { private GHRepository repo; private long deploymentId; - /** - * Instantiates a new Gh deployment status builder. - * - * @param repo - * the repo - * @param deploymentId - * the deployment id - * @param state - * the state - * - * @deprecated Use {@link GHDeployment#createStatus(GHDeploymentState)} - */ - @Deprecated - public GHDeploymentStatusBuilder(GHRepository repo, int deploymentId, GHDeploymentState state) { - this(repo, (long) deploymentId, state); - } - /** * Instantiates a new GH deployment status builder. * @@ -126,20 +109,6 @@ public GHDeploymentStatusBuilder logUrl(String logUrl) { return this; } - /** - * Target url gh deployment status builder. - * - * @param targetUrl - * the target url - * @return the gh deployment status builder - * @deprecated Target url is deprecated in favor of {@link #logUrl(String) logUrl} - */ - @Deprecated - public GHDeploymentStatusBuilder targetUrl(String targetUrl) { - this.builder.with("target_url", targetUrl); - return this; - } - /** * Create gh deployment status. * diff --git a/src/main/java/org/kohsuke/github/GHEventPayload.java b/src/main/java/org/kohsuke/github/GHEventPayload.java index b6549faadd..abb267f205 100644 --- a/src/main/java/org/kohsuke/github/GHEventPayload.java +++ b/src/main/java/org/kohsuke/github/GHEventPayload.java @@ -55,18 +55,6 @@ public GHUser getSender() { return sender; } - /** - * Sets sender. - * - * @param sender - * the sender - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setSender(GHUser sender) { - throw new RuntimeException("Do not use this method."); - } - /** * Gets repository. * @@ -77,18 +65,6 @@ public GHRepository getRepository() { return repository; } - /** - * Sets repository. - * - * @param repository - * the repository - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setRepository(GHRepository repository) { - throw new RuntimeException("Do not use this method."); - } - /** * Gets organization. * @@ -99,18 +75,6 @@ public GHOrganization getOrganization() { return organization; } - /** - * Sets organization. - * - * @param organization - * the organization - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setOrganization(GHOrganization organization) { - throw new RuntimeException("Do not use this method."); - } - /** * Gets installation. * @@ -156,18 +120,6 @@ public int getNumber() { return number; } - /** - * Sets Check Run object. - * - * @param currentCheckRun - * the check run object - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setCheckRun(GHCheckRun currentCheckRun) { - throw new RuntimeException("Do not use this method."); - } - /** * Gets Check Run object. * @@ -178,18 +130,6 @@ public GHCheckRun getCheckRun() { return checkRun; } - /** - * Sets the Requested Action object. - * - * @param currentRequestedAction - * the current action - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setRequestedAction(GHRequestedAction currentRequestedAction) { - throw new RuntimeException("Do not use this method."); - } - /** * Gets the Requested Action object. * @@ -612,18 +552,6 @@ public GHIssue getIssue() { return issue; } - /** - * Sets issue. - * - * @param issue - * the issue - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setIssue(GHIssue issue) { - throw new RuntimeException("Do not use this method."); - } - /** * Gets the added or removed label for labeled/unlabeled events. * @@ -689,18 +617,6 @@ public CommentChanges getChanges() { return changes; } - /** - * Sets comment. - * - * @param comment - * the comment - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setComment(GHIssueComment comment) { - throw new RuntimeException("Do not use this method."); - } - /** * Gets issue. * @@ -711,18 +627,6 @@ public GHIssue getIssue() { return issue; } - /** - * Sets issue. - * - * @param issue - * the issue - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setIssue(GHIssue issue) { - throw new RuntimeException("Do not use this method."); - } - /** * Late bind. */ @@ -758,18 +662,6 @@ public GHCommitComment getComment() { return comment; } - /** - * Sets comment. - * - * @param comment - * the comment - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setComment(GHCommitComment comment) { - throw new RuntimeException("Do not use this method."); - } - /** * Late bind. */ @@ -885,18 +777,6 @@ public GHDeployment getDeployment() { return deployment; } - /** - * Sets deployment. - * - * @param deployment - * the deployment - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setDeployment(GHDeployment deployment) { - throw new RuntimeException("Do not use this method."); - } - /** * Late bind. */ @@ -932,18 +812,6 @@ public GHDeploymentStatus getDeploymentStatus() { return deploymentStatus; } - /** - * Sets deployment status. - * - * @param deploymentStatus - * the deployment status - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setDeploymentStatus(GHDeploymentStatus deploymentStatus) { - throw new RuntimeException("Do not use this method."); - } - /** * Gets deployment. * @@ -954,18 +822,6 @@ public GHDeployment getDeployment() { return deployment; } - /** - * Sets deployment. - * - * @param deployment - * the deployment - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setDeployment(GHDeployment deployment) { - throw new RuntimeException("Do not use this method."); - } - /** * Late bind. */ @@ -999,18 +855,6 @@ public static class Fork extends GHEventPayload { public GHRepository getForkee() { return forkee; } - - /** - * Sets forkee. - * - * @param forkee - * the forkee - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setForkee(GHRepository forkee) { - throw new RuntimeException("Do not use this method."); - } } /** @@ -1145,18 +989,6 @@ public Pusher getPusher() { return pusher; } - /** - * Sets pusher. - * - * @param pusher - * the pusher - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setPusher(Pusher pusher) { - throw new RuntimeException("Do not use this method."); - } - /** * Gets compare. * @@ -1181,18 +1013,6 @@ public String getName() { return name; } - /** - * Sets name. - * - * @param name - * the name - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setName(String name) { - throw new RuntimeException("Do not use this method."); - } - /** * Gets email. * @@ -1201,18 +1021,6 @@ public void setName(String name) { public String getEmail() { return email; } - - /** - * Sets email. - * - * @param email - * the email - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setEmail(String email) { - throw new RuntimeException("Do not use this method."); - } } /** @@ -1343,18 +1151,6 @@ public static class Release extends GHEventPayload { public GHRelease getRelease() { return release; } - - /** - * Sets release. - * - * @param release - * the release - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setRelease(GHRelease release) { - throw new RuntimeException("Do not use this method."); - } } /** @@ -1418,18 +1214,6 @@ public GHCommitState getState() { return state; } - /** - * Sets the status stage. - * - * @param state - * status state - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setState(GHCommitState state) { - throw new RuntimeException("Do not use this method."); - } - /** * Gets the commit associated with the status event. * @@ -1440,18 +1224,6 @@ public GHCommit getCommit() { return commit; } - /** - * Sets the commit associated with the status event. - * - * @param commit - * commit - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setCommit(GHCommit commit) { - throw new RuntimeException("Do not use this method."); - } - /** * Late bind. */ diff --git a/src/main/java/org/kohsuke/github/GHIssue.java b/src/main/java/org/kohsuke/github/GHIssue.java index 9d6027f331..b09d74e2d7 100644 --- a/src/main/java/org/kohsuke/github/GHIssue.java +++ b/src/main/java/org/kohsuke/github/GHIssue.java @@ -219,17 +219,6 @@ public Date getClosedAt() { return GitHubClient.parseDate(closed_at); } - /** - * Gets api url. - * - * @return API URL of this object. - * @deprecated use {@link #getUrl()} - */ - @Deprecated - public URL getApiURL() { - return getUrl(); - } - /** * Lock. * diff --git a/src/main/java/org/kohsuke/github/GHIssueComment.java b/src/main/java/org/kohsuke/github/GHIssueComment.java index 37be280ce3..ec797854c2 100644 --- a/src/main/java/org/kohsuke/github/GHIssueComment.java +++ b/src/main/java/org/kohsuke/github/GHIssueComment.java @@ -77,16 +77,6 @@ public String getBody() { return body; } - /** - * Gets the ID of the user who posted this comment. - * - * @return the user name - */ - @Deprecated - public String getUserName() { - return user.getLogin(); - } - /** * Gets the user who posted this comment. * diff --git a/src/main/java/org/kohsuke/github/GHLabel.java b/src/main/java/org/kohsuke/github/GHLabel.java index 46c5af2069..fcc478693d 100644 --- a/src/main/java/org/kohsuke/github/GHLabel.java +++ b/src/main/java/org/kohsuke/github/GHLabel.java @@ -120,34 +120,6 @@ public boolean isDefault() { return default_; } - /** - * Sets color. - * - * @param newColor - * 6-letter hex color code, like "f29513" - * @throws IOException - * the io exception - * @deprecated use {@link #set()} or {@link #update()} instead - */ - @Deprecated - public void setColor(String newColor) throws IOException { - set().color(newColor); - } - - /** - * Sets description. - * - * @param newDescription - * Description of label - * @throws IOException - * the io exception - * @deprecated use {@link #set()} or {@link #update()} instead - */ - @Deprecated - public void setDescription(String newDescription) throws IOException { - set().description(newDescription); - } - /** * To names. * diff --git a/src/main/java/org/kohsuke/github/GHMilestone.java b/src/main/java/org/kohsuke/github/GHMilestone.java index 0bb7481a1a..44a290374b 100644 --- a/src/main/java/org/kohsuke/github/GHMilestone.java +++ b/src/main/java/org/kohsuke/github/GHMilestone.java @@ -211,18 +211,6 @@ protected String getApiRoute() { return "/repos/" + owner.getOwnerName() + "/" + owner.getName() + "/milestones/" + number; } - /** - * Wrap gh milestone. - * - * @param repo - * the repo - * @return the gh milestone - */ - @Deprecated - public GHMilestone wrap(GHRepository repo) { - throw new RuntimeException("Do not use this method."); - } - /** * Wrap gh milestone. * diff --git a/src/main/java/org/kohsuke/github/GHMyself.java b/src/main/java/org/kohsuke/github/GHMyself.java index 43914f2bd2..003f517ebd 100644 --- a/src/main/java/org/kohsuke/github/GHMyself.java +++ b/src/main/java/org/kohsuke/github/GHMyself.java @@ -151,7 +151,7 @@ public GHPersonSet getAllOrganizations() throws IOException { */ public synchronized Map getAllRepositories() throws IOException { Map repositories = new TreeMap(); - for (GHRepository r : listAllRepositories()) { + for (GHRepository r : listRepositories()) { repositories.put(r.getName(), r); } return Collections.unmodifiableMap(repositories); @@ -206,17 +206,6 @@ public PagedIterable listRepositories(final int pageSize, final Re .withPageSize(pageSize); } - /** - * List all repositories paged iterable. - * - * @return the paged iterable - * @deprecated Use {@link #listRepositories()} - */ - @Deprecated - public PagedIterable listAllRepositories() { - return listRepositories(); - } - /** * List your organization memberships. * diff --git a/src/main/java/org/kohsuke/github/GHOrganization.java b/src/main/java/org/kohsuke/github/GHOrganization.java index 0d881aff61..41fe8a44ce 100644 --- a/src/main/java/org/kohsuke/github/GHOrganization.java +++ b/src/main/java/org/kohsuke/github/GHOrganization.java @@ -3,7 +3,6 @@ import java.io.IOException; import java.net.URL; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; @@ -22,69 +21,6 @@ public class GHOrganization extends GHPerson { private boolean has_organization_projects; - /** - * Creates a new repository. - * - * @param name - * the name - * @param description - * the description - * @param homepage - * the homepage - * @param team - * the team - * @param isPublic - * the is public - * @return Newly created repository. - * @throws IOException - * the io exception - * @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, - String team, - boolean isPublic) throws IOException { - GHTeam t = getTeams().get(team); - if (t == null) - throw new IllegalArgumentException("No such team: " + team); - return createRepository(name, description, homepage, t, isPublic); - } - - /** - * Create repository gh repository. - * - * @param name - * the name - * @param description - * the description - * @param homepage - * the homepage - * @param team - * the team - * @param isPublic - * the is public - * @return the gh repository - * @throws IOException - * the io exception - * @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, - 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(); - } - /** * Starts a builder that creates a new repository. *

@@ -127,21 +63,6 @@ public PagedIterable listTeams() throws IOException { .toIterable(GHTeam[].class, item -> item.wrapUp(this)); } - /** - * Gets a single team by ID. - * - * @param teamId - * id of the team that we want to query for - * @return the team - * @throws IOException - * the io exception - * @deprecated Use {@link GHOrganization#getTeam(long)} - */ - @Deprecated - public GHTeam getTeam(int teamId) throws IOException { - return getTeam((long) teamId); - } - /** * Gets a single team by ID. * @@ -533,92 +454,6 @@ public String toString() { } } - /** - * Creates a new team and assigns the repositories. - * - * @param name - * the name - * @param p - * the p - * @param repositories - * the repositories - * @return the gh team - * @throws IOException - * the io exception - * @deprecated https://developer.github.com/v3/teams/#create-team deprecates permission field use - * {@link #createTeam(String)} - */ - @Deprecated - public GHTeam createTeam(String name, Permission p, Collection repositories) throws IOException { - Requester post = root().createRequest().method("POST").with("name", name).with("permission", p); - List repo_names = new ArrayList(); - for (GHRepository r : repositories) { - repo_names.add(login + "/" + r.getName()); - } - post.with("repo_names", repo_names); - return post.withUrlPath("/orgs/" + login + "/teams").fetch(GHTeam.class).wrapUp(this); - } - - /** - * Create team gh team. - * - * @param name - * the name - * @param p - * the p - * @param repositories - * the repositories - * @return the gh team - * @throws IOException - * the io exception - * @deprecated https://developer.github.com/v3/teams/#create-team deprecates permission field use - * {@link #createTeam(String)} - */ - @Deprecated - public GHTeam createTeam(String name, Permission p, GHRepository... repositories) throws IOException { - return createTeam(name, p, Arrays.asList(repositories)); - } - - /** - * Creates a new team and assigns the repositories. - * - * @param name - * the name - * @param repositories - * the repositories - * @return the gh team - * @throws IOException - * the io exception - * @deprecated Use {@link #createTeam(String)} that uses a builder pattern to let you control every aspect. - */ - @Deprecated - public GHTeam createTeam(String name, Collection repositories) throws IOException { - Requester post = root().createRequest().method("POST").with("name", name); - List repo_names = new ArrayList(); - for (GHRepository r : repositories) { - repo_names.add(login + "/" + r.getName()); - } - post.with("repo_names", repo_names); - return post.withUrlPath("/orgs/" + login + "/teams").fetch(GHTeam.class).wrapUp(this); - } - - /** - * Create team gh team. - * - * @param name - * the name - * @param repositories - * the repositories - * @return the gh team - * @throws IOException - * the io exception - * @deprecated Use {@link #createTeam(String)} that uses a builder pattern to let you control every aspect. - */ - @Deprecated - public GHTeam createTeam(String name, GHRepository... repositories) throws IOException { - return createTeam(name, Arrays.asList(repositories)); - } - /** * Starts a builder that creates a new team. *

diff --git a/src/main/java/org/kohsuke/github/GHPerson.java b/src/main/java/org/kohsuke/github/GHPerson.java index addcebfead..51a8df8680 100644 --- a/src/main/java/org/kohsuke/github/GHPerson.java +++ b/src/main/java/org/kohsuke/github/GHPerson.java @@ -168,17 +168,6 @@ public GHRepository getRepository(String name) throws IOException { */ public abstract PagedIterable listEvents() throws IOException; - /** - * Gravatar ID of this user, like 0cb9832a01c22c083390f3c5dcb64105. - * - * @return the gravatar id - * @deprecated No longer available in the v3 API. - */ - @Deprecated - public String getGravatarId() { - return ""; - } - /** * Returns a string of the avatar image URL. * diff --git a/src/main/java/org/kohsuke/github/GHProject.java b/src/main/java/org/kohsuke/github/GHProject.java index 8e89001298..ccf681a699 100644 --- a/src/main/java/org/kohsuke/github/GHProject.java +++ b/src/main/java/org/kohsuke/github/GHProject.java @@ -99,17 +99,6 @@ public URL getOwnerUrl() { return GitHubClient.parseURL(owner_url); } - /** - * Gets node id. - * - * @return the node id - * @deprecated Use {@link GHObject#getNodeId()} - */ - @Deprecated - public String getNode_id() { - return getNodeId(); - } - /** * Gets name. * @@ -156,30 +145,6 @@ public GHUser getCreator() { return creator; } - /** - * Wrap gh project. - * - * @param root - * the root - * @return the gh project - */ - @Deprecated - public GHProject wrap(GitHub root) { - throw new RuntimeException("Do not use this method."); - } - - /** - * Wrap gh project. - * - * @param repo - * the repo - * @return the gh project - */ - @Deprecated - public GHProject wrap(GHRepository repo) { - throw new RuntimeException("Do not use this method."); - } - /** * Wrap gh project. * diff --git a/src/main/java/org/kohsuke/github/GHProjectCard.java b/src/main/java/org/kohsuke/github/GHProjectCard.java index 9cb0f92f2f..780bb2d26c 100644 --- a/src/main/java/org/kohsuke/github/GHProjectCard.java +++ b/src/main/java/org/kohsuke/github/GHProjectCard.java @@ -35,18 +35,6 @@ public URL getHtmlUrl() throws IOException { return null; } - /** - * Wrap gh project card. - * - * @param root - * the root - * @return the gh project card - */ - @Deprecated - public GHProjectCard wrap(GitHub root) { - throw new RuntimeException("Do not use this method."); - } - /** * Wrap gh project card. * @@ -58,18 +46,6 @@ GHProjectCard lateBind(GitHub root) { return this; } - /** - * Wrap gh project card. - * - * @param column - * the column - * @return the gh project card - */ - @Deprecated - public GHProjectCard wrap(GHProjectColumn column) { - throw new RuntimeException("Do not use this method."); - } - /** * Wrap gh project card. * diff --git a/src/main/java/org/kohsuke/github/GHProjectColumn.java b/src/main/java/org/kohsuke/github/GHProjectColumn.java index 024e9a876f..75e7b7f2e3 100644 --- a/src/main/java/org/kohsuke/github/GHProjectColumn.java +++ b/src/main/java/org/kohsuke/github/GHProjectColumn.java @@ -34,18 +34,6 @@ public URL getHtmlUrl() throws IOException { return null; } - /** - * Wrap gh project column. - * - * @param root - * the root - * @return the gh project column - */ - @Deprecated - public GHProjectColumn wrap(GitHub root) { - throw new RuntimeException("Do not use this method."); - } - /** * Wrap gh project column. * @@ -57,18 +45,6 @@ GHProjectColumn lateBind(GitHub root) { return this; } - /** - * Wrap gh project column. - * - * @param project - * the project - * @return the gh project column - */ - @Deprecated - public GHProjectColumn wrap(GHProject project) { - throw new RuntimeException("Do not use this method."); - } - /** * Wrap gh project column. * diff --git a/src/main/java/org/kohsuke/github/GHPullRequest.java b/src/main/java/org/kohsuke/github/GHPullRequest.java index 44de034cad..53e7824353 100644 --- a/src/main/java/org/kohsuke/github/GHPullRequest.java +++ b/src/main/java/org/kohsuke/github/GHPullRequest.java @@ -35,8 +35,6 @@ import java.util.List; import java.util.Objects; -import javax.annotation.CheckForNull; - import static org.kohsuke.github.internal.Previews.LYDIAN; import static org.kohsuke.github.internal.Previews.SHADOW_CAT; @@ -150,18 +148,6 @@ public GHCommitPointer getHead() { return head; } - /** - * Gets issue updated at. - * - * @return the issue updated at - * @throws IOException - * the io exception - */ - @Deprecated - public Date getIssueUpdatedAt() throws IOException { - return super.getUpdatedAt(); - } - /** * The diff file, like https://github.com/jenkinsci/jenkins/pull/100.diff * @@ -465,52 +451,6 @@ public PagedIterable listCommits() { .toIterable(GHPullRequestCommitDetail[].class, item -> item.wrapUp(this)); } - /** - * Create review gh pull request review. - * - * @param body - * the body - * @param event - * the event - * @param comments - * the comments - * @return the gh pull request review - * @throws IOException - * the io exception - * @deprecated Use {@link #createReview()} - */ - @Deprecated - public GHPullRequestReview createReview(String body, - @CheckForNull GHPullRequestReviewState event, - GHPullRequestReviewComment... comments) throws IOException { - return createReview(body, event, Arrays.asList(comments)); - } - - /** - * Create review gh pull request review. - * - * @param body - * the body - * @param event - * the event - * @param comments - * the comments - * @return the gh pull request review - * @throws IOException - * the io exception - * @deprecated Use {@link #createReview()} - */ - @Deprecated - public GHPullRequestReview createReview(String body, - @CheckForNull GHPullRequestReviewState event, - List comments) throws IOException { - GHPullRequestReviewBuilder b = createReview().body(body); - for (GHPullRequestReviewComment c : comments) { - b.comment(c.getBody(), c.getPath(), c.getPosition()); - } - return b.create(); - } - /** * Create review gh pull request review builder. * diff --git a/src/main/java/org/kohsuke/github/GHPullRequestReview.java b/src/main/java/org/kohsuke/github/GHPullRequestReview.java index a72f462f1e..932a0ff142 100644 --- a/src/main/java/org/kohsuke/github/GHPullRequestReview.java +++ b/src/main/java/org/kohsuke/github/GHPullRequestReview.java @@ -157,23 +157,6 @@ public Date getCreatedAt() throws IOException { return getSubmittedAt(); } - /** - * Submit. - * - * @param body - * the body - * @param state - * the state - * @throws IOException - * the io exception - * @deprecated Former preview method that changed when it got public. Left here for backward compatibility. Use - * {@link #submit(String, GHPullRequestReviewEvent)} - */ - @Deprecated - public void submit(String body, GHPullRequestReviewState state) throws IOException { - submit(body, state.toEvent()); - } - /** * Updates the comment. * diff --git a/src/main/java/org/kohsuke/github/GHPullRequestReviewComment.java b/src/main/java/org/kohsuke/github/GHPullRequestReviewComment.java index 674adb6516..c3e5857163 100644 --- a/src/main/java/org/kohsuke/github/GHPullRequestReviewComment.java +++ b/src/main/java/org/kohsuke/github/GHPullRequestReviewComment.java @@ -70,27 +70,6 @@ public class GHPullRequestReviewComment extends GHObject implements Reactable { private GHPullRequestReviewCommentReactions reactions; private GHCommentAuthorAssociation author_association; - /** - * Draft gh pull request review comment. - * - * @param body - * the body - * @param path - * the path - * @param position - * the position - * @return the gh pull request review comment - * @deprecated You should be using {@link GHPullRequestReviewBuilder#comment(String, String, int)} - */ - @Deprecated - public static GHPullRequestReviewComment draft(String body, String path, int position) { - GHPullRequestReviewComment result = new GHPullRequestReviewComment(); - result.body = body; - result.path = path; - result.position = position; - return result; - } - /** * Wrap up. * diff --git a/src/main/java/org/kohsuke/github/GHReaction.java b/src/main/java/org/kohsuke/github/GHReaction.java index 11cdfc7817..29f55bd90f 100644 --- a/src/main/java/org/kohsuke/github/GHReaction.java +++ b/src/main/java/org/kohsuke/github/GHReaction.java @@ -2,7 +2,6 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import java.io.IOException; import java.net.URL; import static org.kohsuke.github.internal.Previews.SQUIRREL_GIRL; @@ -48,19 +47,4 @@ public GHUser getUser() { public URL getHtmlUrl() { return null; } - - /** - * Removes this reaction. - * - * @throws IOException - * the io exception - * @see Legacy Delete - * reactions REST API removed - * @deprecated this API is no longer supported by GitHub, keeping it as is for old versions of GitHub Enterprise - */ - @Deprecated - public void delete() throws IOException { - throw new UnsupportedOperationException( - "This method is not supported anymore. Please use Reactable#deleteReaction(GHReaction)."); - } } diff --git a/src/main/java/org/kohsuke/github/GHRelease.java b/src/main/java/org/kohsuke/github/GHRelease.java index 12971518ae..e17ef2c9a6 100644 --- a/src/main/java/org/kohsuke/github/GHRelease.java +++ b/src/main/java/org/kohsuke/github/GHRelease.java @@ -78,21 +78,6 @@ public boolean isDraft() { return draft; } - /** - * Sets draft. - * - * @param draft - * the draft - * @return the draft - * @throws IOException - * the io exception - * @deprecated Use {@link #update()} - */ - @Deprecated - public GHRelease setDraft(boolean draft) throws IOException { - return update().draft(draft).update(); - } - /** * Gets the html url. * @@ -131,18 +116,6 @@ public GHRepository getOwner() { return owner; } - /** - * Sets owner. - * - * @param owner - * the owner - * @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding. - */ - @Deprecated - public void setOwner(GHRepository owner) { - throw new RuntimeException("Do not use this method."); - } - /** * Is prerelease boolean. * diff --git a/src/main/java/org/kohsuke/github/GHRepository.java b/src/main/java/org/kohsuke/github/GHRepository.java index 6cc2eb7ad6..e33638f6a9 100644 --- a/src/main/java/org/kohsuke/github/GHRepository.java +++ b/src/main/java/org/kohsuke/github/GHRepository.java @@ -158,21 +158,6 @@ public GHDeploymentBuilder createDeployment(String ref) { return new GHDeploymentBuilder(this, ref); } - /** - * Gets deployment statuses. - * - * @param id - * the id - * @return the deployment statuses - * @throws IOException - * the io exception - * @deprecated Use {@code getDeployment(id).listStatuses()} - */ - @Deprecated - public PagedIterable getDeploymentStatuses(final int id) throws IOException { - return getDeployment(id).listStatuses(); - } - /** * List deployments paged iterable. * @@ -216,24 +201,6 @@ public GHDeployment getDeployment(long id) throws IOException { .wrap(this); } - /** - * Gets deploy status. - * - * @param deploymentId - * the deployment id - * @param ghDeploymentState - * the gh deployment state - * @return the deploy status - * @throws IOException - * the io exception - * @deprecated Use {@code getDeployment(deploymentId).createStatus(ghDeploymentState)} - */ - @Deprecated - public GHDeploymentStatusBuilder createDeployStatus(int deploymentId, GHDeploymentState ghDeploymentState) - throws IOException { - return getDeployment(deploymentId).createStatus(ghDeploymentState); - } - private static class GHRepoPermission { boolean pull, push, admin; } @@ -283,17 +250,6 @@ public String getHttpTransportUrl() { return clone_url; } - /** - * Git http transport url string. - * - * @return the string - * @deprecated Typo of {@link #getHttpTransportUrl()} - */ - @Deprecated - public String gitHttpTransportUrl() { - return clone_url; - } - /** * Gets the Subversion URL to access this repository: https://github.com/rails/rails * @@ -453,19 +409,6 @@ public List getIssues(GHIssueState state, GHMilestone milestone) throws .toList(); } - /** - * Lists up all the issues in this repository. - * - * @param state - * the state - * @return the paged iterable - * @deprecated Use {@link #queryIssues()} - */ - @Deprecated - public PagedIterable listIssues(final GHIssueState state) { - return queryIssues().state(state).list(); - } - /** * Retrieves issues. * @@ -735,18 +678,6 @@ public boolean isDeleteBranchOnMerge() { return delete_branch_on_merge; } - /** - * Returns the number of all forks of this repository. This not only counts direct forks, but also forks of forks, - * and so on. - * - * @return the forks - * @deprecated use {@link #getForksCount()} instead - */ - @Deprecated - public int getForks() { - return getForksCount(); - } - /** * Returns the number of all forks of this repository. This not only counts direct forks, but also forks of forks, * and so on. @@ -879,17 +810,6 @@ public boolean hasPages() { return has_pages; } - /** - * Gets watchers. - * - * @return the watchers - * @deprecated use {@link #getWatchersCount()} instead - */ - @Deprecated - public int getWatchers() { - return getWatchersCount(); - } - /** * Gets the count of watchers. * @@ -935,19 +855,6 @@ public String getDefaultBranch() { return default_branch; } - /** - * Gets default branch. - * - * Name is an artifact of when "master" was the most common default. - * - * @return the default branch - * @deprecated Renamed to {@link #getDefaultBranch()} - */ - @Deprecated - public String getMasterBranch() { - return default_branch; - } - /** * Gets size. * @@ -1165,22 +1072,6 @@ public Set getTeams() throws IOException { .toSet(); } - /** - * Add collaborators. - * - * @param permission - * the permission level - * @param users - * the users - * @throws IOException - * the io exception - * @deprecated #addCollaborators(GHOrganization.RolePermission, GHUser) - */ - @Deprecated - public void addCollaborators(GHOrganization.Permission permission, GHUser... users) throws IOException { - addCollaborators(asList(users), permission); - } - /** * Add collaborators. * @@ -1220,22 +1111,6 @@ public void addCollaborators(Collection users) throws IOException { modifyCollaborators(users, "PUT", null); } - /** - * Add collaborators. - * - * @param users - * the users - * @param permission - * the permission level - * @throws IOException - * the io exception - * @deprecated #addCollaborators(Collection, GHOrganization.RolePermission) - */ - @Deprecated - public void addCollaborators(Collection users, GHOrganization.Permission permission) throws IOException { - modifyCollaborators(users, "PUT", GHOrganization.RepositoryRole.from(permission)); - } - /** * Add collaborators. * @@ -1679,19 +1554,6 @@ public List getPullRequests(GHIssueState state) throws IOExceptio return queryPullRequests().state(state).list().toList(); } - /** - * Retrieves all the pull requests of a particular state. - * - * @param state - * the state - * @return the paged iterable - * @deprecated Use {@link #queryPullRequests()} - */ - @Deprecated - public PagedIterable listPullRequests(GHIssueState state) { - return queryPullRequests().state(state).list(); - } - /** * Retrieves pull requests. * @@ -2775,20 +2637,6 @@ public void createVariable(String name, String value) throws IOException { GHRepositoryVariable.create(this).name(name).value(value).done(); } - /** - * Gets a variable by name - * - * @param name - * the variable name (e.g. test-variable) - * @return the variable - * @throws IOException - * the io exception - */ - @Deprecated - public GHRepositoryVariable getRepoVariable(String name) throws IOException { - return getVariable(name); - } - /** * Gets a repository variable. * @@ -2811,85 +2659,6 @@ public GHContentBuilder createContent() { return new GHContentBuilder(this); } - /** - * Use {@link #createContent()}. - * - * @param content - * the content - * @param commitMessage - * the commit message - * @param path - * the path - * @return the gh content update response - * @throws IOException - * the io exception - */ - @Deprecated - public GHContentUpdateResponse createContent(String content, String commitMessage, String path) throws IOException { - return createContent().content(content).message(commitMessage).path(path).commit(); - } - - /** - * Use {@link #createContent()}. - * - * @param content - * the content - * @param commitMessage - * the commit message - * @param path - * the path - * @param branch - * the branch - * @return the gh content update response - * @throws IOException - * the io exception - */ - @Deprecated - public GHContentUpdateResponse createContent(String content, String commitMessage, String path, String branch) - throws IOException { - return createContent().content(content).message(commitMessage).path(path).branch(branch).commit(); - } - - /** - * Use {@link #createContent()}. - * - * @param contentBytes - * the content bytes - * @param commitMessage - * the commit message - * @param path - * the path - * @return the gh content update response - * @throws IOException - * the io exception - */ - @Deprecated - public GHContentUpdateResponse createContent(byte[] contentBytes, String commitMessage, String path) - throws IOException { - return createContent().content(contentBytes).message(commitMessage).path(path).commit(); - } - - /** - * Use {@link #createContent()}. - * - * @param contentBytes - * the content bytes - * @param commitMessage - * the commit message - * @param path - * the path - * @param branch - * the branch - * @return the gh content update response - * @throws IOException - * the io exception - */ - @Deprecated - public GHContentUpdateResponse createContent(byte[] contentBytes, String commitMessage, String path, String branch) - throws IOException { - return createContent().content(contentBytes).message(commitMessage).path(path).branch(branch).commit(); - } - /** * Create milestone gh milestone. * diff --git a/src/main/java/org/kohsuke/github/GHRepositorySearchBuilder.java b/src/main/java/org/kohsuke/github/GHRepositorySearchBuilder.java index 7a21cf941a..af28f4a1df 100644 --- a/src/main/java/org/kohsuke/github/GHRepositorySearchBuilder.java +++ b/src/main/java/org/kohsuke/github/GHRepositorySearchBuilder.java @@ -59,48 +59,6 @@ public GHRepositorySearchBuilder size(String v) { return q("size:" + v); } - /** - * Forks gh repository search builder. - * - * @param v - * the v - * @return the gh repository search builder - * @deprecated use {@link #fork(GHFork)} instead. - */ - @Deprecated - public GHRepositorySearchBuilder forks(String v) { - return q("fork", v); - } - - /** - * Searching in forks - * - * The default search mode is {@link Fork#PARENT_ONLY}. In that mode, forks are not included in search results. - * - *

- * Passing {@link Fork#PARENT_AND_FORKS} or {@link Fork#FORKS_ONLY} will show results from forks, but only if they - * have more stars than the parent repository. - * - *

- * IMPORTANT: Regardless of this setting, no search results will ever be returned for forks with equal or fewer - * stars than the parent repository. Forks with less stars than the parent repository are not included in the index - * for code searching. - * - * @param fork - * search mode for forks - * - * @return the gh repository search builder - * - * @see Searching - * in forks - * @deprecated use {@link #fork(GHFork)} instead. - */ - @Deprecated - public GHRepositorySearchBuilder fork(Fork fork) { - return q("fork", fork.toString()); - } - /** * Searching in forks * diff --git a/src/main/java/org/kohsuke/github/GHTeam.java b/src/main/java/org/kohsuke/github/GHTeam.java index d7083aaf6d..748d2ae813 100644 --- a/src/main/java/org/kohsuke/github/GHTeam.java +++ b/src/main/java/org/kohsuke/github/GHTeam.java @@ -336,22 +336,6 @@ public void add(GHRepository r) throws IOException { add(r, (GHOrganization.RepositoryRole) null); } - /** - * * Add. - * - * @param r - * the r - * @param permission - * the permission - * @throws IOException - * the io exception - * @deprecated use {@link GHTeam#add(GHRepository, org.kohsuke.github.GHOrganization.RepositoryRole)} - */ - @Deprecated - public void add(GHRepository r, GHOrganization.Permission permission) throws IOException { - add(r, GHOrganization.RepositoryRole.from(permission)); - } - /** * Add. * diff --git a/src/main/java/org/kohsuke/github/GHTeamBuilder.java b/src/main/java/org/kohsuke/github/GHTeamBuilder.java index f1583fb8db..53b1b8b446 100644 --- a/src/main/java/org/kohsuke/github/GHTeamBuilder.java +++ b/src/main/java/org/kohsuke/github/GHTeamBuilder.java @@ -70,6 +70,20 @@ public GHTeamBuilder repositories(String... repoNames) { return this; } + /** + * The permission that new repositories will be added to the team with when none is specified. + * + * @param permission + * permssion to be applied + * @return a builder to continue with building + * @deprecated https://docs.github.com/en/free-pro-team@latest/rest/teams/teams?apiVersion=2022-11-28#create-a-team + */ + @Deprecated + public GHTeamBuilder permission(GHOrganization.Permission permission) { + this.builder.with("permission", permission); + return this; + } + /** * Description for this team. * diff --git a/src/main/java/org/kohsuke/github/GHTreeBuilder.java b/src/main/java/org/kohsuke/github/GHTreeBuilder.java index 892afb7686..396ce2b7c8 100644 --- a/src/main/java/org/kohsuke/github/GHTreeBuilder.java +++ b/src/main/java/org/kohsuke/github/GHTreeBuilder.java @@ -76,31 +76,6 @@ public GHTreeBuilder baseTree(String baseTree) { return this; } - /** - * Adds a new entry to the tree. Exactly one of the parameters {@code sha} and {@code content} must be non-null. - * - * @param path - * the path - * @param mode - * the mode - * @param type - * the type - * @param sha - * the sha - * @param content - * the content - * @return the gh tree builder - * @deprecated use {@link #add(String, String, boolean)} or {@link #add(String, byte[], boolean)} instead. - */ - @Deprecated - public GHTreeBuilder entry(String path, String mode, String type, String sha, String content) { - TreeEntry entry = new TreeEntry(path, mode, type); - entry.sha = sha; - entry.content = content; - treeEntries.add(entry); - return this; - } - /** * Specialized version of {@link #entry(String, String, String, String, String)} for adding an existing blob * referred by its SHA. diff --git a/src/main/java/org/kohsuke/github/GitHub.java b/src/main/java/org/kohsuke/github/GitHub.java index 8bcd93b85f..f17b8c544f 100644 --- a/src/main/java/org/kohsuke/github/GitHub.java +++ b/src/main/java/org/kohsuke/github/GitHub.java @@ -31,7 +31,6 @@ import org.kohsuke.github.authorization.ImmutableAuthorizationProvider; import org.kohsuke.github.authorization.UserAuthorizationProvider; import org.kohsuke.github.connector.GitHubConnector; -import org.kohsuke.github.internal.GitHubConnectorHttpConnectorAdapter; import org.kohsuke.github.internal.Previews; import java.io.*; @@ -277,26 +276,6 @@ public static GitHub connect() throws IOException { return GitHubBuilder.fromCredentials().build(); } - /** - * 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. - * @param oauthAccessToken - * the oauth access token - * @return the git hub - * @throws IOException - * the io exception - * @deprecated Use {@link #connectToEnterpriseWithOAuth(String, String, String)} - */ - @Deprecated - public static GitHub connectToEnterprise(String apiUrl, String oauthAccessToken) throws IOException { - return connectToEnterpriseWithOAuth(apiUrl, null, oauthAccessToken); - } - /** * Version that connects to GitHub Enterprise. * @@ -318,25 +297,6 @@ public static GitHub connectToEnterpriseWithOAuth(String apiUrl, String login, S return new GitHubBuilder().withEndpoint(apiUrl).withOAuthToken(oauthAccessToken, login).build(); } - /** - * Version that connects to GitHub Enterprise. - * - * @param apiUrl - * the api url - * @param login - * the login - * @param password - * the password - * @return the git hub - * @throws IOException - * the io exception - * @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 { - return new GitHubBuilder().withEndpoint(apiUrl).withPassword(login, password).build(); - } - /** * Connect git hub. * @@ -352,45 +312,6 @@ public static GitHub connect(String login, String oauthAccessToken) throws IOExc return new GitHubBuilder().withOAuthToken(oauthAccessToken, login).build(); } - /** - * Connect git hub. - * - * @param login - * the login - * @param oauthAccessToken - * the oauth access token - * @param password - * the password - * @return the git hub - * @throws IOException - * the io exception - * @deprecated Use {@link #connectUsingOAuth(String)}. - */ - @Deprecated - public static GitHub connect(String login, String oauthAccessToken, String password) throws IOException { - return new GitHubBuilder().withOAuthToken(oauthAccessToken, login).withPassword(login, password).build(); - } - - /** - * Connect using password git hub. - * - * @param login - * the login - * @param password - * the password - * @return the git hub - * @throws IOException - * the io exception - * @see Deprecating - * password authentication and OAuth authorizations API - * @deprecated Use {@link #connectUsingOAuth(String)} instead. - */ - @Deprecated - public static GitHub connectUsingPassword(String login, String password) throws IOException { - return new GitHubBuilder().withPassword(login, password).build(); - } - /** * Connect using o auth git hub. * @@ -482,30 +403,6 @@ public boolean isOffline() { return client.isOffline(); } - /** - * Gets connector. - * - * @return the connector - * @deprecated HttpConnector has been replaced by GitHubConnector which is generally not useful outside of this - * library. If you are using this method, file an issue describing your use case. - */ - @Deprecated - public HttpConnector getConnector() { - return client.getConnector(); - } - - /** - * Sets the custom connector used to make requests to GitHub. - * - * @param connector - * the connector - * @deprecated HttpConnector should not be changed. If you find yourself needing to do this, file an issue. - */ - @Deprecated - public void setConnector(@Nonnull HttpConnector connector) { - client.setConnector(GitHubConnectorHttpConnectorAdapter.adapt(connector)); - } - /** * Gets api url. * @@ -687,22 +584,6 @@ public GHRepository getRepository(String name) throws IOException { return GHRepository.read(this, tokens[0], tokens[1]); } - /** - * Gets the repository object from its ID. - * - * @param id - * the id - * @return the repository by id - * @throws IOException - * the io exception - * @deprecated Do not use this method. It was added due to misunderstanding of the type of parameter. Use - * {@link #getRepositoryById(long)} instead - */ - @Deprecated - public GHRepository getRepositoryById(String id) throws IOException { - return createRequest().withUrlPath("/repositories/" + id).fetch(GHRepository.class); - } - /** * Gets the repository object from its ID. * @@ -886,27 +767,6 @@ public Map> getMyTeams() throws IOException { return allMyTeams; } - /** - * Gets a single team by ID. - *

- * This method is no longer supported and throws an UnsupportedOperationException. - * - * @param id - * the id - * @return the team - * @throws IOException - * the io exception - * @see deprecation notice - * @see sunset - * notice - * @deprecated Use {@link GHOrganization#getTeam(long)} - */ - @Deprecated - public GHTeam getTeam(int id) throws IOException { - throw new UnsupportedOperationException( - "This method is not supported anymore. Please use GHOrganization#getTeam(long)."); - } - /** * Public events visible to you. Equivalent of what's displayed on https://github.com/ * @@ -979,28 +839,6 @@ public T parseEventPayload(Reader r, Class type) t return t; } - /** - * Creates a new repository. - * - * @param name - * the name - * @param description - * the description - * @param homepage - * the homepage - * @param isPublic - * the is public - * @return Newly created repository. - * @throws IOException - * the io exception - * @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 { - return createRepository(name).description(description).homepage(homepage).private_(!isPublic).create(); - } - /** * Starts a builder that creates a new repository. * diff --git a/src/main/java/org/kohsuke/github/GitHubAbuseLimitHandler.java b/src/main/java/org/kohsuke/github/GitHubAbuseLimitHandler.java index 4b40ff0b1c..65c8e8d1b9 100644 --- a/src/main/java/org/kohsuke/github/GitHubAbuseLimitHandler.java +++ b/src/main/java/org/kohsuke/github/GitHubAbuseLimitHandler.java @@ -3,6 +3,7 @@ import org.kohsuke.github.connector.GitHubConnectorResponse; import java.io.IOException; +import java.io.InterruptedIOException; import java.net.HttpURLConnection; import javax.annotation.Nonnull; @@ -52,4 +53,40 @@ boolean isError(@Nonnull GitHubConnectorResponse connectorResponse) throws IOExc * */ public abstract void onError(@Nonnull GitHubConnectorResponse connectorResponse) throws IOException; + + /** + * Wait until the API abuse "wait time" is passed. + */ + public static final GitHubAbuseLimitHandler WAIT = new GitHubAbuseLimitHandler() { + @Override + public void onError(GitHubConnectorResponse connectorResponse) throws IOException { + try { + Thread.sleep(parseWaitTime(connectorResponse)); + } catch (InterruptedException ex) { + throw (InterruptedIOException) new InterruptedIOException().initCause(ex); + } + } + + private long parseWaitTime(GitHubConnectorResponse connectorResponse) { + String v = connectorResponse.header("Retry-After"); + if (v == null) + return 60 * 1000; // can't tell, return 1 min + + return Math.max(1000, Long.parseLong(v) * 1000); + } + }; + + /** + * Fail immediately. + */ + public static final GitHubAbuseLimitHandler FAIL = new GitHubAbuseLimitHandler() { + @Override + public void onError(GitHubConnectorResponse connectorResponse) throws IOException { + throw new HttpException("Abuse limit reached", + connectorResponse.statusCode(), + connectorResponse.header("Status"), + connectorResponse.request().url().toString()) + .withResponseHeaderFields(connectorResponse.allHeaders()); + } + }; } diff --git a/src/main/java/org/kohsuke/github/GitHubBuilder.java b/src/main/java/org/kohsuke/github/GitHubBuilder.java index b61be61f27..62ed96cab1 100644 --- a/src/main/java/org/kohsuke/github/GitHubBuilder.java +++ b/src/main/java/org/kohsuke/github/GitHubBuilder.java @@ -5,15 +5,12 @@ import org.kohsuke.github.authorization.ImmutableAuthorizationProvider; import org.kohsuke.github.connector.GitHubConnector; import org.kohsuke.github.connector.GitHubConnectorResponse; -import org.kohsuke.github.extras.ImpatientHttpConnector; import org.kohsuke.github.internal.GitHubConnectorHttpConnectorAdapter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.Proxy; import java.util.Locale; import java.util.Map.Entry; import java.util.Properties; @@ -38,8 +35,8 @@ public class GitHubBuilder implements Cloneable { private GitHubConnector connector; - private GitHubRateLimitHandler rateLimitHandler = RateLimitHandler.WAIT; - private GitHubAbuseLimitHandler abuseLimitHandler = AbuseLimitHandler.WAIT; + private GitHubRateLimitHandler rateLimitHandler = GitHubRateLimitHandler.WAIT; + private GitHubAbuseLimitHandler abuseLimitHandler = GitHubAbuseLimitHandler.WAIT; private GitHubRateLimitChecker rateLimitChecker = new GitHubRateLimitChecker(); /** The authorization provider. */ @@ -87,64 +84,12 @@ static GitHubBuilder fromCredentials() throws IOException { .initCause(cause); } - /** - * From environment git hub builder. - * - * @param loginVariableName - * the login variable name - * @param passwordVariableName - * the password variable name - * @param oauthVariableName - * the oauth variable name - * @return the git hub builder - * @throws IOException - * the io exception - * @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 - 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); } - /** - * From environment git hub builder. - * - * @param loginVariableName - * the login variable name - * @param passwordVariableName - * the password variable name - * @param oauthVariableName - * the oauth variable name - * @param endpointVariableName - * the endpoint variable name - * @return the git hub builder - * @throws IOException - * the io exception - * @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 - 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"); - return fromProperties(env); - } - /** * Creates {@link GitHubBuilder} by picking up coordinates from environment variables. * @@ -153,7 +98,6 @@ public static GitHubBuilder fromEnvironment(String loginVariableName, * *

    *
  • 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 @@ -162,10 +106,6 @@ public static GitHubBuilder fromEnvironment(String loginVariableName, *

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

    - * For backward compatibility, the following environment variables are recognized but discouraged: login, password, - * oauth - * * @return the git hub builder * @throws IOException * the io exception @@ -228,7 +168,6 @@ public static GitHubBuilder fromProperties(Properties props) { String oauth = props.getProperty("oauth"); String jwt = props.getProperty("jwt"); String login = props.getProperty("login"); - String password = props.getProperty("password"); if (oauth != null) { self.withOAuthToken(oauth, login); @@ -236,9 +175,6 @@ public static GitHubBuilder fromProperties(Properties props) { if (jwt != null) { self.withJwtToken(jwt); } - if (password != null) { - self.withPassword(login, password); - } self.withEndpoint(props.getProperty("endpoint", GitHubClient.GITHUB_URL)); return self; } @@ -258,19 +194,6 @@ public GitHubBuilder withEndpoint(String endpoint) { return this; } - /** - * With password git hub builder. - * - * @param user - * the user - * @param password - * the password - * @return the git hub builder - */ - public GitHubBuilder withPassword(String user, String password) { - return withAuthorizationProvider(ImmutableAuthorizationProvider.fromLoginAndPassword(user, password)); - } - /** * With o auth token git hub builder. * @@ -357,32 +280,6 @@ public GitHubBuilder withConnector(GitHubConnector connector) { return this; } - /** - * Adds a {@link RateLimitHandler} to this {@link GitHubBuilder}. - *

    - * GitHub allots a certain number of requests to each user or application per period of time (usually per hour). The - * number of requests remaining is returned in the response header and can also be requested using - * {@link GitHub#getRateLimit()}. This requests per interval is referred to as the "rate limit". - *

    - *

    - * When the remaining number of requests reaches zero, the next request will return an error. If this happens, - * {@link RateLimitHandler#onError(IOException, HttpURLConnection)} will be called. - *

    - *

    - * NOTE: GitHub treats clients that exceed their rate limit very harshly. If possible, clients should avoid - * exceeding their rate limit. Consider adding a {@link RateLimitChecker} to automatically check the rate limit for - * each request and wait if needed. - *

    - * - * @param handler - * the handler - * @return the git hub builder - * @see #withRateLimitChecker(RateLimitChecker) - */ - public GitHubBuilder withRateLimitHandler(RateLimitHandler handler) { - return withRateLimitHandler((GitHubRateLimitHandler) handler); - } - /** * Adds a {@link GitHubRateLimitHandler} to this {@link GitHubBuilder}. *

    @@ -410,23 +307,6 @@ public GitHubBuilder withRateLimitHandler(GitHubRateLimitHandler handler) { return this; } - /** - * Adds a {@link AbuseLimitHandler} to this {@link GitHubBuilder}. - *

    - * When a client sends too many requests in a short time span, GitHub may return an error and set a header telling - * the client to not make any more request for some period of time. If this happens, - * {@link AbuseLimitHandler#onError(IOException, HttpURLConnection)} will be called. - *

    - * - * @param handler - * the handler - * @return the git hub builder - */ - @Deprecated - public GitHubBuilder withAbuseLimitHandler(AbuseLimitHandler handler) { - return withAbuseLimitHandler((GitHubAbuseLimitHandler) handler); - } - /** * Adds a {@link GitHubAbuseLimitHandler} to this {@link GitHubBuilder}. *

    @@ -486,18 +366,6 @@ public GitHubBuilder withRateLimitChecker(@Nonnull RateLimitChecker rateLimitChe return this; } - /** - * Configures {@linkplain #withConnector(HttpConnector) connector} that uses HTTP library in JRE but use a specific - * proxy, instead of the system default one. - * - * @param p - * the p - * @return the git hub builder - */ - public GitHubBuilder withProxy(final Proxy p) { - return withConnector(new ImpatientHttpConnector(url -> (HttpURLConnection) url.openConnection(p))); - } - /** * Builds a {@link GitHub} instance. * diff --git a/src/main/java/org/kohsuke/github/GitHubClient.java b/src/main/java/org/kohsuke/github/GitHubClient.java index 09160fc119..93a7f591c1 100644 --- a/src/main/java/org/kohsuke/github/GitHubClient.java +++ b/src/main/java/org/kohsuke/github/GitHubClient.java @@ -208,19 +208,6 @@ public HttpConnector getConnector() { return (HttpConnector) connector; } - /** - * Sets the custom connector used to make requests to GitHub. - * - * @param connector - * the connector - * @deprecated HttpConnector should not be changed. - */ - @Deprecated - public void setConnector(GitHubConnector connector) { - LOGGER.warning("Connector should not be changed. Please file an issue describing your use case."); - this.connector = connector; - } - /** * Is this an anonymous connection. * diff --git a/src/main/java/org/kohsuke/github/GitHubInteractiveObject.java b/src/main/java/org/kohsuke/github/GitHubInteractiveObject.java index 036b53f7c1..274640bef4 100644 --- a/src/main/java/org/kohsuke/github/GitHubInteractiveObject.java +++ b/src/main/java/org/kohsuke/github/GitHubInteractiveObject.java @@ -3,7 +3,6 @@ import com.fasterxml.jackson.annotation.JacksonInject; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.Objects; @@ -39,19 +38,6 @@ abstract class GitHubInteractiveObject { this.root = root; } - /** - * Get the root {@link GitHub} instance for this object. - * - * @return the root {@link GitHub} instance - * - * @deprecated For access to the {@link GitHub} instance, use a local copy instead of pulling it out of objects. - */ - @Deprecated - @SuppressFBWarnings(value = { "EI_EXPOSE_REP" }, justification = "Expected behavior") - public GitHub getRoot() { - return root(); - } - /** * Get the root {@link GitHub} instance for this object. * diff --git a/src/main/java/org/kohsuke/github/GitHubRateLimitHandler.java b/src/main/java/org/kohsuke/github/GitHubRateLimitHandler.java index da4f6ad104..0c0c7dd3d5 100644 --- a/src/main/java/org/kohsuke/github/GitHubRateLimitHandler.java +++ b/src/main/java/org/kohsuke/github/GitHubRateLimitHandler.java @@ -4,6 +4,7 @@ import org.kohsuke.github.connector.GitHubConnectorResponse; import java.io.IOException; +import java.io.InterruptedIOException; import java.net.HttpURLConnection; import javax.annotation.Nonnull; @@ -50,4 +51,42 @@ boolean isError(@NotNull GitHubConnectorResponse connectorResponse) throws IOExc * @see API documentation from GitHub */ public abstract void onError(@Nonnull GitHubConnectorResponse connectorResponse) throws IOException; + + /** + * Wait until the API abuse "wait time" is passed. + */ + public static final GitHubRateLimitHandler WAIT = new GitHubRateLimitHandler() { + @Override + public void onError(GitHubConnectorResponse connectorResponse) throws IOException { + try { + Thread.sleep(parseWaitTime(connectorResponse)); + } catch (InterruptedException ex) { + throw (InterruptedIOException) new InterruptedIOException().initCause(ex); + } + } + + private long parseWaitTime(GitHubConnectorResponse connectorResponse) { + String v = connectorResponse.header("X-RateLimit-Reset"); + if (v == null) + return 60 * 1000; // can't tell, return 1 min + + return Math.max(1000, Long.parseLong(v) * 1000 - System.currentTimeMillis()); + } + }; + + /** + * Fail immediately. + */ + public static final GitHubRateLimitHandler FAIL = new GitHubRateLimitHandler() { + @Override + public void onError(GitHubConnectorResponse connectorResponse) throws IOException { + throw new HttpException("API rate limit reached", + connectorResponse.statusCode(), + connectorResponse.header("Status"), + connectorResponse.request().url().toString()) + .withResponseHeaderFields(connectorResponse.allHeaders()); + + } + }; + } diff --git a/src/main/java/org/kohsuke/github/RateLimitHandler.java b/src/main/java/org/kohsuke/github/RateLimitHandler.java deleted file mode 100644 index a17e9a33b3..0000000000 --- a/src/main/java/org/kohsuke/github/RateLimitHandler.java +++ /dev/null @@ -1,100 +0,0 @@ -package org.kohsuke.github; - -import org.kohsuke.github.connector.GitHubConnectorResponse; - -import java.io.IOException; -import java.io.InterruptedIOException; -import java.net.HttpURLConnection; - -import javax.annotation.Nonnull; - -// TODO: Auto-generated Javadoc -/** - * Pluggable strategy to determine what to do when the API rate limit is reached. - * - * @author Kohsuke Kawaguchi - * @see GitHubBuilder#withRateLimitHandler(GitHubRateLimitHandler) - * GitHubBuilder#withRateLimitHandler(GitHubRateLimitHandler) - * @see AbuseLimitHandler - * @deprecated Switch to {@link GitHubRateLimitHandler} or even better provide {@link RateLimitChecker}s. - */ -@Deprecated -public abstract class RateLimitHandler extends GitHubRateLimitHandler { - - /** - * Called when the library encounters HTTP error indicating that the API rate limit has been exceeded. - * - *

    - * 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. - * - * @param connectorResponse - * Response information for this request. - * - * @throws IOException - * the io exception - * @see API documentation from GitHub - */ - public void onError(@Nonnull GitHubConnectorResponse connectorResponse) throws IOException { - GHIOException e = new HttpException("API rate limit reached", - connectorResponse.statusCode(), - connectorResponse.header("Status"), - connectorResponse.request().url().toString()).withResponseHeaderFields(connectorResponse.allHeaders()); - onError(e, connectorResponse.toHttpURLConnection()); - } - - /** - * 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. - * - * @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.) - * @param uc - * Connection that resulted in an error. Useful for accessing other response headers. - * @throws IOException - * the io exception - * @see API documentation from GitHub - */ - @Deprecated - public abstract void onError(IOException e, HttpURLConnection uc) throws IOException; - - /** - * Block until the API rate limit is reset. Useful for long-running batch processing. - */ - @Deprecated - public static final RateLimitHandler WAIT = new RateLimitHandler() { - @Override - public void onError(IOException e, HttpURLConnection uc) throws IOException { - try { - Thread.sleep(parseWaitTime(uc)); - } catch (InterruptedException x) { - 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 - - return Math.max(10000, Long.parseLong(v) * 1000 - System.currentTimeMillis()); - } - }; - - /** - * Fail immediately. - */ - @Deprecated - public static final RateLimitHandler FAIL = new RateLimitHandler() { - @Override - public void onError(IOException e, HttpURLConnection uc) throws IOException { - throw e; - } - }; -} diff --git a/src/main/java/org/kohsuke/github/authorization/ImmutableAuthorizationProvider.java b/src/main/java/org/kohsuke/github/authorization/ImmutableAuthorizationProvider.java index ebab1bcaef..09ee6ae467 100644 --- a/src/main/java/org/kohsuke/github/authorization/ImmutableAuthorizationProvider.java +++ b/src/main/java/org/kohsuke/github/authorization/ImmutableAuthorizationProvider.java @@ -1,9 +1,5 @@ package org.kohsuke.github.authorization; -import java.io.UnsupportedEncodingException; -import java.nio.charset.StandardCharsets; -import java.util.Base64; - import javax.annotation.CheckForNull; /** @@ -72,31 +68,6 @@ public static AuthorizationProvider fromJwtToken(String jwtToken) { return new ImmutableAuthorizationProvider(String.format("Bearer %s", jwtToken)); } - /** - * Builds and returns a {@link AuthorizationProvider} from the given user/password pair - * - * @param login - * The login for the user, usually the same as the username - * @param password - * The password for the associated user - * @return a correctly configured {@link AuthorizationProvider} that will always return the credentials for the same - * user and password combo - * @deprecated Login with password credentials are no longer supported by GitHub - */ - @Deprecated - public static AuthorizationProvider fromLoginAndPassword(String login, String password) { - try { - String authorization = (String.format("%s:%s", login, password)); - String charsetName = StandardCharsets.UTF_8.name(); - String b64encoded = Base64.getEncoder().encodeToString(authorization.getBytes(charsetName)); - String encodedAuthorization = String.format("Basic %s", b64encoded); - return new UserProvider(encodedAuthorization, login); - } catch (UnsupportedEncodingException e) { - // If UTF-8 isn't supported, there are bigger problems - throw new IllegalStateException("Could not generate encoded authorization", e); - } - } - @Override public String getEncodedAuthorization() { return this.authorization; diff --git a/src/main/java/org/kohsuke/github/extras/OkHttp3Connector.java b/src/main/java/org/kohsuke/github/extras/OkHttp3Connector.java deleted file mode 100644 index 24819a7a4c..0000000000 --- a/src/main/java/org/kohsuke/github/extras/OkHttp3Connector.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.kohsuke.github.extras; - -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import okhttp3.OkHttpClient; -import okhttp3.OkUrlFactory; -import org.kohsuke.github.HttpConnector; -import org.kohsuke.github.extras.okhttp3.OkHttpGitHubConnector; - -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.URL; - -/** - * {@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 - * - * @author Roberto Tyley - * @author Kohsuke Kawaguchi - * @see OkHttpGitHubConnector - */ -@Deprecated -@SuppressFBWarnings(value = { "EI_EXPOSE_REP2" }, justification = "Deprecated") -public class OkHttp3Connector implements HttpConnector { - private final OkUrlFactory urlFactory; - - /** - * Instantiates a new Ok http 3 connector. - * - * @param urlFactory - * the url factory - */ - /* - * @see org.kohsuke.github.extras.okhttp3.OkHttpGitHubConnector - */ - @Deprecated - public OkHttp3Connector(OkUrlFactory urlFactory) { - this.urlFactory = urlFactory; - } - - public HttpURLConnection connect(URL url) throws IOException { - return urlFactory.open(url); - } -} diff --git a/src/main/java/org/kohsuke/github/extras/OkHttpConnector.java b/src/main/java/org/kohsuke/github/extras/OkHttpConnector.java deleted file mode 100644 index 4b9b5bb36f..0000000000 --- a/src/main/java/org/kohsuke/github/extras/OkHttpConnector.java +++ /dev/null @@ -1,103 +0,0 @@ -package org.kohsuke.github.extras; - -import com.squareup.okhttp.CacheControl; -import com.squareup.okhttp.ConnectionSpec; -import com.squareup.okhttp.OkHttpClient; -import com.squareup.okhttp.OkUrlFactory; -import org.kohsuke.github.HttpConnector; -import org.kohsuke.github.extras.okhttp3.OkHttpGitHubConnector; - -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.URL; -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSocketFactory; - -/** - * {@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 - * - * @author Roberto Tyley - * @author Kohsuke Kawaguchi - * @deprecated This class depends on an unsupported version of OkHttp. Switch to {@link OkHttpGitHubConnector}. - * @see OkHttpGitHubConnector - */ -@Deprecated -public class OkHttpConnector implements HttpConnector { - private static final String HEADER_NAME = "Cache-Control"; - private final OkUrlFactory urlFactory; - - private final String maxAgeHeaderValue; - - /** - * Instantiates a new Ok http connector. - * - * @param urlFactory - * the url factory - */ - public OkHttpConnector(OkUrlFactory urlFactory) { - this(urlFactory, 0); - } - - /** - * package private for tests to be able to change max-age for cache. - * - * @param urlFactory - * @param cacheMaxAge - */ - OkHttpConnector(OkUrlFactory urlFactory, int cacheMaxAge) { - urlFactory.client().setSslSocketFactory(TlsSocketFactory()); - urlFactory.client().setConnectionSpecs(TlsConnectionSpecs()); - this.urlFactory = urlFactory; - - if (cacheMaxAge >= 0 && urlFactory.client() != null && urlFactory.client().getCache() != null) { - 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) { - // By default OkHttp honors max-age, meaning it will use local cache - // without checking the network within that time frame. - // However, that can result in stale data being returned during that time so - // we force network-based checking no matter how often the query is made. - // OkHttp still automatically does ETag checking and returns cached data when - // GitHub reports 304, but those do not count against rate limit. - urlConnection.setRequestProperty(HEADER_NAME, maxAgeHeaderValue); - } - - return urlConnection; - } - - /** Returns TLSv1.2 only SSL Socket Factory. */ - private SSLSocketFactory TlsSocketFactory() { - SSLContext sc; - try { - sc = SSLContext.getInstance("TLSv1.2"); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException(e.getMessage(), e); - } - try { - sc.init(null, null, null); - return sc.getSocketFactory(); - } catch (KeyManagementException e) { - throw new RuntimeException(e.getMessage(), e); - } - } - - /** Returns connection spec with TLS v1.2 in it */ - private List TlsConnectionSpecs() { - return Arrays.asList(ConnectionSpec.MODERN_TLS, ConnectionSpec.CLEARTEXT); - } -} diff --git a/src/main/java/org/kohsuke/github/extras/okhttp3/ObsoleteUrlFactory.java b/src/main/java/org/kohsuke/github/extras/okhttp3/ObsoleteUrlFactory.java deleted file mode 100644 index dbbbae6a6c..0000000000 --- a/src/main/java/org/kohsuke/github/extras/okhttp3/ObsoleteUrlFactory.java +++ /dev/null @@ -1,1439 +0,0 @@ -package org.kohsuke.github.extras.okhttp3; - -/* - * Copyright (C) 2014 Square, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Dispatcher; -import okhttp3.Handshake; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.Interceptor; -import okhttp3.MediaType; -import okhttp3.OkHttpClient; -import okhttp3.Protocol; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import okio.Buffer; -import okio.BufferedSink; -import okio.Okio; -import okio.Pipe; -import okio.Timeout; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InterruptedIOException; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.InetSocketAddress; -import java.net.MalformedURLException; -import java.net.ProtocolException; -import java.net.Proxy; -import java.net.SocketPermission; -import java.net.SocketTimeoutException; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLStreamHandler; -import java.net.URLStreamHandlerFactory; -import java.security.Permission; -import java.security.Principal; -import java.security.cert.Certificate; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.*; -import java.util.concurrent.TimeUnit; - -import javax.annotation.Nullable; -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.SSLSocketFactory; - -import static java.net.HttpURLConnection.HTTP_NOT_MODIFIED; -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. - * - *

    - * 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. - */ -@SuppressFBWarnings(value = { "EI_EXPOSE_REP", "EI_EXPOSE_REP2" }, justification = "Deprecated external code") -@Deprecated -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; - - /** - * Instantiates a new Obsolete url factory. - * - * @param client - * the client - */ - public ObsoleteUrlFactory(OkHttpClient client) { - this.client = client; - } - - /** - * Client ok http client. - * - * @return the ok http client - */ - public OkHttpClient client() { - return client; - } - - /** - * Sets client. - * - * @param client - * the client - * @return the 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); - } - - /** - * Open http url connection. - * - * @param url - * the url - * @return the http url connection - */ - 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 String format(Date value) { - return STANDARD_DATE_FORMAT.get().format(value); - } - - 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; - } - - int responseCode = response.code(); - if ((responseCode < HTTP_CONTINUE || responseCode >= 200) && responseCode != HTTP_NO_CONTENT - && responseCode != HTTP_NOT_MODIFIED) { - return true; - } - - // 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 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; - - try (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 (SecurityException | IllegalArgumentException 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; - } - - @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 void disconnect() { - // Calling disconnect() before a connection exists should have no effect. - if (call == null) - return; - - networkInterceptor.proceed(); // Unblock any waiting async thread. - call.cancel(); - } - - @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 new ResponseBodyInputStream(response.body()); - } - return null; - } catch (IOException e) { - return null; - } - } - - 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 - 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; - } - } - - @Override - public String getHeaderField(String fieldName) { - try { - return fieldName == null ? statusLineToString(getResponse(true)) : getHeaders().get(fieldName); - } catch (IOException e) { - return null; - } - } - - @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; - } - } - - @Override - public Map> getHeaderFields() { - try { - return toMultimap(getHeaders(), statusLineToString(getResponse(true))); - } catch (IOException e) { - return Collections.emptyMap(); - } - } - - @Override - public Map> getRequestProperties() { - if (connected) { - throw new IllegalStateException("Cannot access request header fields after connection is set"); - } - - return toMultimap(requestHeaders.build(), null); - } - - @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 new ResponseBodyInputStream(response.body()); - } - - @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; - } - - @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"); - } - - @Override - public String getRequestProperty(String field) { - if (field == null) - return null; - return requestHeaders.get(field); - } - - @Override - public void setConnectTimeout(int timeoutMillis) { - client = client.newBuilder().connectTimeout(timeoutMillis, TimeUnit.MILLISECONDS).build(); - } - - @Override - public void setInstanceFollowRedirects(boolean followRedirects) { - client = client.newBuilder().followRedirects(followRedirects).build(); - } - - @Override - public boolean getInstanceFollowRedirects() { - return client.followRedirects(); - } - - @Override - public int getConnectTimeout() { - return client.connectTimeoutMillis(); - } - - @Override - public void setReadTimeout(int timeoutMillis) { - client = client.newBuilder().readTimeout(timeoutMillis, TimeUnit.MILLISECONDS).build(); - } - - @Override - public int getReadTimeout() { - return client.readTimeoutMillis(); - } - - @SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE") - private Call buildCall() throws IOException { - if (call != null) { - return call; - } - - connected = true; - if (doOutput) { - if (method.equals("GET")) { - method = "POST"; - } else if (!permitsRequestBody(method)) { - throw new ProtocolException(method + " does not support writing"); - } - } - - if (requestHeaders.get("User-Agent") == null) { - requestHeaders.add("User-Agent", defaultUserAgent()); - } - - 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); - } - - 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); - } - - 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); - } - } - - 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); - } - } - - synchronized (lock) { - if (callFailure != null) - throw propagate(callFailure); - if (response != null) - return response; - } - - throw new AssertionError(); - } - - @Override - public boolean usingProxy() { - if (proxy != null) - return true; - Proxy clientProxy = client.proxy(); - return clientProxy != null && clientProxy.type() != Proxy.Type.DIRECT; - } - - @Override - public String getResponseMessage() throws IOException { - return getResponse(true).message(); - } - - @Override - public int getResponseCode() throws IOException { - return getResponse(true).code(); - } - - @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 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 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 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 setFixedLengthStreamingMode(int contentLength) { - setFixedLengthStreamingMode((long) contentLength); - } - - @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); - } - - @Override - public void onFailure(Call call, IOException e) { - synchronized (lock) { - this.callFailure = (e instanceof UnexpectedException) ? e.getCause() : e; - lock.notifyAll(); - } - } - - @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(); - } - } - - final class NetworkInterceptor implements Interceptor { - // Guarded by HttpUrlConnection.this. - private boolean proceed; - - /** - * Proceed. - */ - public void proceed() { - synchronized (lock) { - this.proceed = true; - lock.notifyAll(); - } - } - - @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; - } - } - } - - 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 long contentLength() { - return expectedContentLength; - } - - @Override - public final @Nullable MediaType contentType() { - return null; // Let the caller provide this in a regular header. - } - - /** - * Prepare to send request request. - * - * @param request - * the request - * @return the request - * @throws IOException - * the io exception - */ - public Request prepareToSendRequest(Request request) throws IOException { - return request; - } - } - - static final class BufferedRequestBody extends OutputStreamRequestBody { - final Buffer buffer = new Buffer(); - long contentLength = -1L; - - BufferedRequestBody(long expectedContentLength) { - initOutputStream(buffer, expectedContentLength); - } - - @Override - public long contentLength() { - return contentLength; - } - - @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(); - } - - @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); - - StreamedRequestBody(long expectedContentLength) { - initOutputStream(Okio.buffer(pipe.sink()), expectedContentLength); - } - - @Override - 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()); - } - } - } - - abstract static class DelegatingHttpsURLConnection extends HttpsURLConnection { - private final HttpURLConnection delegate; - - DelegatingHttpsURLConnection(HttpURLConnection delegate) { - super(delegate.getURL()); - this.delegate = delegate; - } - - /** - * Handshake handshake. - * - * @return the handshake - */ - protected abstract Handshake handshake(); - - @Override - public abstract void setHostnameVerifier(HostnameVerifier hostnameVerifier); - - @Override - public abstract HostnameVerifier getHostnameVerifier(); - - @Override - public abstract void setSSLSocketFactory(SSLSocketFactory sslSocketFactory); - - @Override - public abstract SSLSocketFactory getSSLSocketFactory(); - - @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[] 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 getLocalPrincipal() { - Handshake handshake = handshake(); - return handshake != null ? handshake.localPrincipal() : null; - } - - @Override - public void connect() throws IOException { - connected = true; - delegate.connect(); - } - - @Override - public void disconnect() { - delegate.disconnect(); - } - - @Override - public InputStream getErrorStream() { - return delegate.getErrorStream(); - } - - @Override - public String getRequestMethod() { - return delegate.getRequestMethod(); - } - - @Override - public int getResponseCode() throws IOException { - return delegate.getResponseCode(); - } - - @Override - public String getResponseMessage() throws IOException { - return delegate.getResponseMessage(); - } - - @Override - public void setRequestMethod(String method) throws ProtocolException { - delegate.setRequestMethod(method); - } - - @Override - public boolean usingProxy() { - return delegate.usingProxy(); - } - - @Override - public boolean getInstanceFollowRedirects() { - return delegate.getInstanceFollowRedirects(); - } - - @Override - public void setInstanceFollowRedirects(boolean followRedirects) { - delegate.setInstanceFollowRedirects(followRedirects); - } - - @Override - public boolean getAllowUserInteraction() { - return delegate.getAllowUserInteraction(); - } - - @Override - public Object getContent() throws IOException { - return delegate.getContent(); - } - - @Override - public Object getContent(Class[] types) throws IOException { - return delegate.getContent(types); - } - - @Override - public String getContentEncoding() { - return delegate.getContentEncoding(); - } - - @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(); - } - - @Override - public String getContentType() { - return delegate.getContentType(); - } - - @Override - public long getDate() { - return delegate.getDate(); - } - - @Override - public boolean getDefaultUseCaches() { - return delegate.getDefaultUseCaches(); - } - - @Override - public boolean getDoInput() { - return delegate.getDoInput(); - } - - @Override - public boolean getDoOutput() { - return delegate.getDoOutput(); - } - - @Override - public long getExpiration() { - return delegate.getExpiration(); - } - - @Override - public String getHeaderField(int pos) { - return delegate.getHeaderField(pos); - } - - @Override - public Map> getHeaderFields() { - return delegate.getHeaderFields(); - } - - @Override - public Map> getRequestProperties() { - return delegate.getRequestProperties(); - } - - @Override - public void addRequestProperty(String field, String newValue) { - delegate.addRequestProperty(field, newValue); - } - - @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); - } - - @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 String getHeaderFieldKey(int position) { - return delegate.getHeaderFieldKey(position); - } - - @Override - public long getIfModifiedSince() { - return delegate.getIfModifiedSince(); - } - - @Override - public InputStream getInputStream() throws IOException { - return delegate.getInputStream(); - } - - @Override - public long getLastModified() { - return delegate.getLastModified(); - } - - @Override - public OutputStream getOutputStream() throws IOException { - return delegate.getOutputStream(); - } - - @Override - public Permission getPermission() throws IOException { - return delegate.getPermission(); - } - - @Override - public String getRequestProperty(String field) { - return delegate.getRequestProperty(field); - } - - @Override - public URL getURL() { - return delegate.getURL(); - } - - @Override - public boolean getUseCaches() { - return delegate.getUseCaches(); - } - - @Override - public void setAllowUserInteraction(boolean newValue) { - delegate.setAllowUserInteraction(newValue); - } - - @Override - public void setDefaultUseCaches(boolean newValue) { - delegate.setDefaultUseCaches(newValue); - } - - @Override - public void setDoInput(boolean newValue) { - delegate.setDoInput(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); - } - - @Override - public void setIfModifiedSince(long newValue) { - delegate.setIfModifiedSince(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 setConnectTimeout(int timeoutMillis) { - delegate.setConnectTimeout(timeoutMillis); - } - - @Override - public int getConnectTimeout() { - return delegate.getConnectTimeout(); - } - - @Override - public void setReadTimeout(int timeoutMillis) { - delegate.setReadTimeout(timeoutMillis); - } - - @Override - public int getReadTimeout() { - return delegate.getReadTimeout(); - } - - @Override - public String toString() { - return delegate.toString(); - } - - @Override - public void setFixedLengthStreamingMode(int contentLength) { - delegate.setFixedLengthStreamingMode(contentLength); - } - - @Override - public void setChunkedStreamingMode(int chunkLength) { - delegate.setChunkedStreamingMode(chunkLength); - } - } - - static final class OkHttpsURLConnection extends DelegatingHttpsURLConnection { - private final OkHttpURLConnection delegate; - - OkHttpsURLConnection(URL url, OkHttpClient client) { - this(new OkHttpURLConnection(url, client)); - } - - 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"); - } - - return delegate.handshake; - } - - @Override - public void setHostnameVerifier(HostnameVerifier hostnameVerifier) { - delegate.client = delegate.client.newBuilder().hostnameVerifier(hostnameVerifier).build(); - } - - @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 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); - } - } - - /** - * Make sure both the ResponseBody and the InputStream are closed when the InputStream coming from the ResponseBody - * is closed. - */ - private static final class ResponseBodyInputStream extends InputStream { - - private final ResponseBody responseBody; - - private final InputStream inputStream; - - private ResponseBodyInputStream(ResponseBody responseBody) { - this.responseBody = responseBody; - this.inputStream = responseBody.byteStream(); - } - - @Override - public int read() throws IOException { - return inputStream.read(); - } - - @Override - public int read(byte b[]) throws IOException { - return inputStream.read(b); - } - - @Override - public int read(byte b[], int off, int len) throws IOException { - return inputStream.read(b, off, len); - } - - @Override - public long skip(long n) throws IOException { - return inputStream.skip(n); - } - - @Override - public int available() throws IOException { - return inputStream.available(); - } - - @Override - public synchronized void mark(int readlimit) { - inputStream.mark(readlimit); - } - - @Override - public synchronized void reset() throws IOException { - inputStream.reset(); - } - - @Override - public boolean markSupported() { - return inputStream.markSupported(); - } - - @Override - public void close() throws IOException { - try { - inputStream.close(); - } finally { - responseBody.close(); - } - } - } -} diff --git a/src/main/java/org/kohsuke/github/extras/okhttp3/OkHttpConnector.java b/src/main/java/org/kohsuke/github/extras/okhttp3/OkHttpConnector.java deleted file mode 100644 index bc09891ea2..0000000000 --- a/src/main/java/org/kohsuke/github/extras/okhttp3/OkHttpConnector.java +++ /dev/null @@ -1,83 +0,0 @@ -package org.kohsuke.github.extras.okhttp3; - -import okhttp3.CacheControl; -import okhttp3.ConnectionSpec; -import okhttp3.OkHttpClient; -import org.kohsuke.github.HttpConnector; - -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.Arrays; -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 - * - * @author Liam Newman - * @deprecated Use {@link OkHttpGitHubConnector} instead. - */ -@Deprecated -public class OkHttpConnector implements HttpConnector { - private static final String HEADER_NAME = "Cache-Control"; - private final String maxAgeHeaderValue; - - private final OkHttpClient client; - private final ObsoleteUrlFactory urlFactory; - - /** - * Instantiates a new Ok http connector. - * - * @param client - * the client - */ - public OkHttpConnector(OkHttpClient client) { - this(client, 0); - } - - /** - * Instantiates a new Ok http connector. - * - * @param client - * the client - * @param cacheMaxAge - * the cache max age - */ - public OkHttpConnector(OkHttpClient client, int cacheMaxAge) { - - OkHttpClient.Builder builder = client.newBuilder(); - - 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(); - } else { - maxAgeHeaderValue = null; - } - this.urlFactory = new ObsoleteUrlFactory(this.client); - } - - public HttpURLConnection connect(URL url) throws IOException { - HttpURLConnection urlConnection = urlFactory.open(url); - if (maxAgeHeaderValue != null) { - // By default OkHttp honors max-age, meaning it will use local cache - // without checking the network within that timeframe. - // However, that can result in stale data being returned during that time so - // we force network-based checking no matter how often the query is made. - // OkHttp still automatically does ETag checking and returns cached data when - // GitHub reports 304, but those do not count against rate limit. - urlConnection.setRequestProperty(HEADER_NAME, maxAgeHeaderValue); - } - - return urlConnection; - } - - /** Returns connection spec with TLS v1.2 in it */ - private List TlsConnectionSpecs() { - return Arrays.asList(ConnectionSpec.MODERN_TLS, ConnectionSpec.CLEARTEXT); - } -} diff --git a/src/main/java/org/kohsuke/github/internal/DefaultGitHubConnector.java b/src/main/java/org/kohsuke/github/internal/DefaultGitHubConnector.java index 1b00b01596..28ffd469e1 100644 --- a/src/main/java/org/kohsuke/github/internal/DefaultGitHubConnector.java +++ b/src/main/java/org/kohsuke/github/internal/DefaultGitHubConnector.java @@ -4,7 +4,6 @@ import org.kohsuke.github.HttpConnector; import org.kohsuke.github.connector.GitHubConnector; import org.kohsuke.github.extras.HttpClientGitHubConnector; -import org.kohsuke.github.extras.okhttp3.OkHttpConnector; import org.kohsuke.github.extras.okhttp3.OkHttpGitHubConnector; /** @@ -43,10 +42,6 @@ static GitHubConnector create(String defaultConnectorProperty) { if (defaultConnectorProperty.equalsIgnoreCase("okhttp")) { return new OkHttpGitHubConnector(new OkHttpClient.Builder().build()); - } else if (defaultConnectorProperty.equalsIgnoreCase("okhttpconnector")) { - return new GitHubConnectorHttpConnectorAdapter(new OkHttpConnector(new OkHttpClient.Builder().build())); - } else if (defaultConnectorProperty.equalsIgnoreCase("urlconnection")) { - return new GitHubConnectorHttpConnectorAdapter(HttpConnector.DEFAULT); } else if (defaultConnectorProperty.equalsIgnoreCase("httpclient")) { return new HttpClientGitHubConnector(); } else if (defaultConnectorProperty.equalsIgnoreCase("default")) { @@ -57,7 +52,7 @@ static GitHubConnector create(String defaultConnectorProperty) { } } else { throw new IllegalStateException( - "Property 'test.github.connector' must reference a valid built-in connector - okhttp, okhttpconnector, urlconnection, or default."); + "Property 'test.github.connector' must reference a valid built-in connector - okhttp, httpclient, or default."); } } } diff --git a/src/test/java/org/kohsuke/github/AbstractGitHubWireMockTest.java b/src/test/java/org/kohsuke/github/AbstractGitHubWireMockTest.java index 044a7122ec..88a75d7af8 100644 --- a/src/test/java/org/kohsuke/github/AbstractGitHubWireMockTest.java +++ b/src/test/java/org/kohsuke/github/AbstractGitHubWireMockTest.java @@ -112,7 +112,7 @@ private static GitHubBuilder createGitHubBuilder() { } catch (IOException e) { } - return builder.withRateLimitHandler(RateLimitHandler.FAIL); + return builder.withRateLimitHandler(GitHubRateLimitHandler.FAIL); } /** @@ -127,7 +127,7 @@ protected GitHubBuilder getGitHubBuilder() { // This sets the user and password to a placeholder for wiremock testing // This makes the tests believe they are running with permissions // The recorded stubs will behave like they running with permissions - builder.withPassword(STUBBED_USER_LOGIN, STUBBED_USER_PASSWORD); + builder.withOAuthToken(STUBBED_USER_PASSWORD, STUBBED_USER_LOGIN); } return builder; diff --git a/src/test/java/org/kohsuke/github/AbuseLimitHandlerTest.java b/src/test/java/org/kohsuke/github/AbuseLimitHandlerTest.java index 646eca6d00..3cf4418a30 100644 --- a/src/test/java/org/kohsuke/github/AbuseLimitHandlerTest.java +++ b/src/test/java/org/kohsuke/github/AbuseLimitHandlerTest.java @@ -1,21 +1,16 @@ package org.kohsuke.github; import com.github.tomakehurst.wiremock.core.WireMockConfiguration; -import org.apache.commons.io.IOUtils; import org.hamcrest.Matchers; -import org.junit.Assert; +import org.jetbrains.annotations.NotNull; import org.junit.Test; +import org.kohsuke.github.connector.GitHubConnectorResponse; import java.io.IOException; -import java.io.InputStream; import java.net.HttpURLConnection; -import java.net.ProtocolException; -import java.nio.charset.StandardCharsets; -import java.util.Date; import java.util.Map; import static org.hamcrest.CoreMatchers.*; -import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.core.IsInstanceOf.instanceOf; // TODO: Auto-generated Javadoc @@ -71,131 +66,128 @@ public void testHandler_Fail() throws Exception { final HttpURLConnection[] savedConnection = new HttpURLConnection[1]; gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()) - .withAbuseLimitHandler(new AbuseLimitHandler() { + .withAbuseLimitHandler(new GitHubAbuseLimitHandler() { @Override - public void onError(IOException e, HttpURLConnection uc) throws IOException { - savedConnection[0] = uc; + public void onError(@NotNull GitHubConnectorResponse connectorResponse) throws IOException { + savedConnection[0] = null; + HttpURLConnection uc = null; // Verify - assertThat(uc.getDate(), Matchers.greaterThanOrEqualTo(new Date().getTime() - 10000)); - assertThat(uc.getExpiration(), equalTo(0L)); - assertThat(uc.getIfModifiedSince(), equalTo(0L)); - assertThat(uc.getLastModified(), equalTo(1581014017000L)); - assertThat(uc.getRequestMethod(), equalTo("GET")); - assertThat(uc.getResponseCode(), equalTo(403)); - assertThat(uc.getResponseMessage(), containsString("Forbidden")); - assertThat(uc.getURL().toString(), endsWith("/repos/hub4j-test-org/temp-testHandler_Fail")); - assertThat(uc.getHeaderFieldInt("X-RateLimit-Limit", 10), equalTo(5000)); - assertThat(uc.getHeaderFieldInt("X-RateLimit-Remaining", 10), equalTo(4000)); - assertThat(uc.getHeaderFieldInt("X-Foo", 20), equalTo(20)); - assertThat(uc.getHeaderFieldLong("X-RateLimit-Limit", 15L), equalTo(5000L)); - assertThat(uc.getHeaderFieldLong("X-RateLimit-Remaining", 15L), equalTo(4000L)); - assertThat(uc.getHeaderFieldLong("X-Foo", 20L), equalTo(20L)); - - assertThat(uc.getContentEncoding(), nullValue()); - assertThat(uc.getContentType(), equalTo("application/json; charset=utf-8")); - assertThat(uc.getContentLength(), equalTo(-1)); - - // getting an input stream in an error case should throw - IOException ioEx = Assert.assertThrows(IOException.class, () -> uc.getInputStream()); - - try (InputStream errorStream = uc.getErrorStream()) { - assertThat(errorStream, notNullValue()); - String errorString = IOUtils.toString(errorStream, StandardCharsets.UTF_8); - assertThat(errorString, containsString("Must have push access to repository")); - } - - // calling again should still error - ioEx = Assert.assertThrows(IOException.class, () -> uc.getInputStream()); - - // calling again on a GitHubConnectorResponse should yield the same value - if (uc.toString().contains("GitHubConnectorResponseHttpUrlConnectionAdapter")) { - try (InputStream errorStream = uc.getErrorStream()) { - assertThat(errorStream, notNullValue()); - String errorString = IOUtils.toString(errorStream, StandardCharsets.UTF_8); - assertThat(errorString, containsString("Must have push access to repository")); - } - } else { - try (InputStream errorStream = uc.getErrorStream()) { - assertThat(errorStream, notNullValue()); - String errorString = IOUtils.toString(errorStream, StandardCharsets.UTF_8); - fail(); - } catch (IOException ex) { - assertThat(ex, notNullValue()); - assertThat(ex.getMessage(), containsString("stream is closed")); - } - } - - assertThat(uc.getHeaderFields(), instanceOf(Map.class)); - assertThat(uc.getHeaderFields().size(), Matchers.greaterThan(25)); - assertThat(uc.getHeaderField("Status"), equalTo("403 Forbidden")); - - String key = uc.getHeaderFieldKey(1); - assertThat(key, notNullValue()); - assertThat(uc.getHeaderField(1), notNullValue()); - assertThat(uc.getHeaderField(1), equalTo(uc.getHeaderField(key))); - - assertThat(uc.getRequestProperty("Accept"), equalTo("application/vnd.github.v3+json")); - - Assert.assertThrows(IllegalStateException.class, () -> uc.getRequestProperties()); - - // Actions that are not allowed because connection already opened. - Assert.assertThrows(IllegalStateException.class, () -> uc.addRequestProperty("bogus", "item")); - - Assert.assertThrows(IllegalStateException.class, () -> uc.setAllowUserInteraction(true)); - Assert.assertThrows(IllegalStateException.class, () -> uc.setChunkedStreamingMode(1)); - Assert.assertThrows(IllegalStateException.class, () -> uc.setDoInput(true)); - Assert.assertThrows(IllegalStateException.class, () -> uc.setDoOutput(true)); - Assert.assertThrows(IllegalStateException.class, () -> uc.setFixedLengthStreamingMode(1)); - Assert.assertThrows(IllegalStateException.class, () -> uc.setFixedLengthStreamingMode(1L)); - Assert.assertThrows(IllegalStateException.class, () -> uc.setIfModifiedSince(1L)); - Assert.assertThrows(IllegalStateException.class, () -> uc.setRequestProperty("bogus", "thing")); - Assert.assertThrows(IllegalStateException.class, () -> uc.setUseCaches(true)); - - if (uc.toString().contains("GitHubConnectorResponseHttpUrlConnectionAdapter")) { - - Assert.assertThrows(UnsupportedOperationException.class, - () -> uc.getAllowUserInteraction()); - Assert.assertThrows(UnsupportedOperationException.class, () -> uc.getConnectTimeout()); - Assert.assertThrows(UnsupportedOperationException.class, () -> uc.getContent()); - Assert.assertThrows(UnsupportedOperationException.class, () -> uc.getContent(null)); - Assert.assertThrows(UnsupportedOperationException.class, () -> uc.getDefaultUseCaches()); - Assert.assertThrows(UnsupportedOperationException.class, () -> uc.getDoInput()); - Assert.assertThrows(UnsupportedOperationException.class, () -> uc.getDoOutput()); - Assert.assertThrows(UnsupportedOperationException.class, - () -> uc.getInstanceFollowRedirects()); - Assert.assertThrows(UnsupportedOperationException.class, () -> uc.getOutputStream()); - Assert.assertThrows(UnsupportedOperationException.class, () -> uc.getPermission()); - Assert.assertThrows(UnsupportedOperationException.class, () -> uc.getReadTimeout()); - Assert.assertThrows(UnsupportedOperationException.class, () -> uc.getUseCaches()); - Assert.assertThrows(UnsupportedOperationException.class, () -> uc.usingProxy()); - - Assert.assertThrows(UnsupportedOperationException.class, () -> uc.setConnectTimeout(10)); - Assert.assertThrows(UnsupportedOperationException.class, - () -> uc.setDefaultUseCaches(true)); - - Assert.assertThrows(UnsupportedOperationException.class, - () -> uc.setInstanceFollowRedirects(true)); - Assert.assertThrows(UnsupportedOperationException.class, () -> uc.setReadTimeout(10)); - Assert.assertThrows(ProtocolException.class, () -> uc.setRequestMethod("GET")); - } else { - uc.getDefaultUseCaches(); - assertThat(uc.getDoInput(), is(true)); - - // Depending on the underlying implementation, this may throw or not - // Assert.assertThrows(IllegalStateException.class, () -> uc.setRequestMethod("GET")); - } - - // ignored - uc.connect(); - - // disconnect does nothing, never throws - uc.disconnect(); - uc.disconnect(); - - // ignored - uc.connect(); - - AbuseLimitHandler.FAIL.onError(e, uc); + // assertThat(GitHubClient.parseInstant(connectorResponse.header("Date")).toEpochMilli(), + // Matchers.greaterThanOrEqualTo(new Date().getTime() - 10000)); + assertThat(connectorResponse.header("Expires"), nullValue()); + // assertThat(GitHubClient.parseInstant(connectorResponse.header("Last-Modified")).toEpochMilli(), + // equalTo(1581014017000L)); + assertThat(connectorResponse.statusCode(), equalTo(403)); + assertThat(connectorResponse.header("Status"), containsString("Forbidden")); + // assertThat(uc.getHeaderFieldInt("X-RateLimit-Limit", 10), equalTo(5000)); + // assertThat(uc.getHeaderFieldInt("X-RateLimit-Remaining", 10), equalTo(4000)); + // assertThat(uc.getHeaderFieldInt("X-Foo", 20), equalTo(20)); + // assertThat(uc.getHeaderFieldLong("X-RateLimit-Limit", 15L), equalTo(5000L)); + // assertThat(uc.getHeaderFieldLong("X-RateLimit-Remaining", 15L), equalTo(4000L)); + // assertThat(uc.getHeaderFieldLong("X-Foo", 20L), equalTo(20L)); + // + // assertThat(uc.getContentEncoding(), nullValue()); + // assertThat(uc.getContentType(), equalTo("application/json; charset=utf-8")); + // assertThat(uc.getContentLength(), equalTo(-1)); + // + // // getting an input stream in an error case should throw + // IOException ioEx = Assert.assertThrows(IOException.class, () -> uc.getInputStream()); + // + // try (InputStream errorStream = uc.getErrorStream()) { + // assertThat(errorStream, notNullValue()); + // String errorString = IOUtils.toString(errorStream, StandardCharsets.UTF_8); + // assertThat(errorString, containsString("Must have push access to repository")); + // } + // + // // calling again should still error + // ioEx = Assert.assertThrows(IOException.class, () -> uc.getInputStream()); + // + // // calling again on a GitHubConnectorResponse should yield the same value + // if (uc.toString().contains("GitHubConnectorResponseHttpUrlConnectionAdapter")) { + // try (InputStream errorStream = uc.getErrorStream()) { + // assertThat(errorStream, notNullValue()); + // String errorString = IOUtils.toString(errorStream, StandardCharsets.UTF_8); + // assertThat(errorString, containsString("Must have push access to repository")); + // } + // } else { + // try (InputStream errorStream = uc.getErrorStream()) { + // assertThat(errorStream, notNullValue()); + // String errorString = IOUtils.toString(errorStream, StandardCharsets.UTF_8); + // fail(); + // } catch (IOException ex) { + // assertThat(ex, notNullValue()); + // assertThat(ex.getMessage(), containsString("stream is closed")); + // } + // } + + assertThat(connectorResponse.allHeaders(), instanceOf(Map.class)); + assertThat(connectorResponse.allHeaders().size(), Matchers.greaterThan(25)); + assertThat(connectorResponse.header("Status"), equalTo("403 Forbidden")); + + // assertThat(uc.getRequestProperty("Accept"), equalTo("application/vnd.github.v3+json")); + + // Assert.assertThrows(IllegalStateException.class, () -> uc.getRequestProperties()); + // + // // Actions that are not allowed because connection already opened. + // Assert.assertThrows(IllegalStateException.class, () -> uc.addRequestProperty("bogus", + // "item")); + // + // Assert.assertThrows(IllegalStateException.class, () -> uc.setAllowUserInteraction(true)); + // Assert.assertThrows(IllegalStateException.class, () -> uc.setChunkedStreamingMode(1)); + // Assert.assertThrows(IllegalStateException.class, () -> uc.setDoInput(true)); + // Assert.assertThrows(IllegalStateException.class, () -> uc.setDoOutput(true)); + // Assert.assertThrows(IllegalStateException.class, () -> uc.setFixedLengthStreamingMode(1)); + // Assert.assertThrows(IllegalStateException.class, () -> uc.setFixedLengthStreamingMode(1L)); + // Assert.assertThrows(IllegalStateException.class, () -> uc.setIfModifiedSince(1L)); + // Assert.assertThrows(IllegalStateException.class, () -> uc.setRequestProperty("bogus", + // "thing")); + // Assert.assertThrows(IllegalStateException.class, () -> uc.setUseCaches(true)); + // + // if (uc.toString().contains("GitHubConnectorResponseHttpUrlConnectionAdapter")) { + // + // Assert.assertThrows(UnsupportedOperationException.class, + // () -> uc.getAllowUserInteraction()); + // Assert.assertThrows(UnsupportedOperationException.class, () -> uc.getConnectTimeout()); + // Assert.assertThrows(UnsupportedOperationException.class, () -> uc.getContent()); + // Assert.assertThrows(UnsupportedOperationException.class, () -> uc.getContent(null)); + // Assert.assertThrows(UnsupportedOperationException.class, () -> uc.getDefaultUseCaches()); + // Assert.assertThrows(UnsupportedOperationException.class, () -> uc.getDoInput()); + // Assert.assertThrows(UnsupportedOperationException.class, () -> uc.getDoOutput()); + // Assert.assertThrows(UnsupportedOperationException.class, + // () -> uc.getInstanceFollowRedirects()); + // Assert.assertThrows(UnsupportedOperationException.class, () -> uc.getOutputStream()); + // Assert.assertThrows(UnsupportedOperationException.class, () -> uc.getPermission()); + // Assert.assertThrows(UnsupportedOperationException.class, () -> uc.getReadTimeout()); + // Assert.assertThrows(UnsupportedOperationException.class, () -> uc.getUseCaches()); + // Assert.assertThrows(UnsupportedOperationException.class, () -> uc.usingProxy()); + // + // Assert.assertThrows(UnsupportedOperationException.class, () -> uc.setConnectTimeout(10)); + // Assert.assertThrows(UnsupportedOperationException.class, + // () -> uc.setDefaultUseCaches(true)); + // + // Assert.assertThrows(UnsupportedOperationException.class, + // () -> uc.setInstanceFollowRedirects(true)); + // Assert.assertThrows(UnsupportedOperationException.class, () -> uc.setReadTimeout(10)); + // Assert.assertThrows(ProtocolException.class, () -> uc.setRequestMethod("GET")); + // } else { + // uc.getDefaultUseCaches(); + // assertThat(uc.getDoInput(), is(true)); + // + // // Depending on the underlying implementation, this may throw or not + // // Assert.assertThrows(IllegalStateException.class, () -> uc.setRequestMethod("GET")); + // } + // + // // ignored + // uc.connect(); + // + // // disconnect does nothing, never throws + // uc.disconnect(); + // uc.disconnect(); + // + // // ignored + // uc.connect(); + + GitHubAbuseLimitHandler.FAIL.onError(connectorResponse); } }) .build(); @@ -211,11 +203,6 @@ public void onError(IOException e, HttpURLConnection uc) throws IOException { assertThat(e.getMessage(), equalTo("Abuse limit reached")); } - if (savedConnection[0].toString().contains("GitHubConnectorResponseHttpUrlConnectionAdapter")) { - // error stream is non-null above. null here because response has been closed. - assertThat(savedConnection[0].getErrorStream(), nullValue()); - } - assertThat(mockGitHub.getRequestCount(), equalTo(2)); } @@ -232,7 +219,7 @@ public void testHandler_HttpStatus_Fail() throws Exception { snapshotNotAllowed(); gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()) - .withAbuseLimitHandler(AbuseLimitHandler.FAIL) + .withAbuseLimitHandler(GitHubAbuseLimitHandler.FAIL) .build(); gitHub.getMyself(); @@ -265,7 +252,7 @@ public void testHandler_Wait() throws Exception { snapshotNotAllowed(); gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()) - .withAbuseLimitHandler(AbuseLimitHandler.WAIT) + .withAbuseLimitHandler(GitHubAbuseLimitHandler.WAIT) .build(); gitHub.getMyself(); @@ -287,9 +274,9 @@ public void testHandler_WaitStuck() throws Exception { snapshotNotAllowed(); gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()) - .withAbuseLimitHandler(new AbuseLimitHandler() { + .withAbuseLimitHandler(new GitHubAbuseLimitHandler() { @Override - public void onError(IOException e, HttpURLConnection uc) throws IOException { + public void onError(@NotNull GitHubConnectorResponse connectorResponse) throws IOException { } }) .build(); diff --git a/src/test/java/org/kohsuke/github/AppTest.java b/src/test/java/org/kohsuke/github/AppTest.java index 5f34fb91b5..33260f4838 100755 --- a/src/test/java/org/kohsuke/github/AppTest.java +++ b/src/test/java/org/kohsuke/github/AppTest.java @@ -21,7 +21,6 @@ import java.util.stream.Collectors; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThrows; // TODO: Auto-generated Javadoc /** @@ -222,10 +221,6 @@ public void testIssueWithComment() throws IOException { ReactionContent.HOORAY, ReactionContent.ROCKET)); - // test retired delete reaction API throws UnsupportedOperationException - final GHReaction reactionToDelete = reaction; - assertThrows(UnsupportedOperationException.class, () -> reactionToDelete.delete()); - // test new delete reaction API v.get(1).deleteReaction(reaction); reaction = null; @@ -322,7 +317,6 @@ public void testGetDeploymentStatuses() throws IOException { try { GHDeploymentStatus ghDeploymentStatus = deployment.createStatus(GHDeploymentState.QUEUED) .description("success") - .targetUrl("http://www.github.com") .logUrl("http://www.github.com/logurl") .environmentUrl("http://www.github.com/envurl") .environment("new-ci-env") @@ -334,9 +328,6 @@ public void testGetDeploymentStatuses() throws IOException { assertThat(actualStatus.getId(), equalTo(ghDeploymentStatus.getId())); assertThat(actualStatus.getState(), equalTo(ghDeploymentStatus.getState())); assertThat(actualStatus.getLogUrl(), equalTo(ghDeploymentStatus.getLogUrl())); - // Target url was deprecated and replaced with log url. The gh api will - // prefer the log url value and return it in place of target url. - assertThat(actualStatus.getLogUrl(), equalTo(ghDeploymentStatus.getTargetUrl())); assertThat(ghDeploymentStatus.getDeploymentUrl(), equalTo(deployment.getUrl())); assertThat(ghDeploymentStatus.getRepositoryUrl(), equalTo(repository.getUrl())); } finally { @@ -452,7 +443,9 @@ private GHRepository getTestRepository() throws IOException { public void testListIssues() throws IOException { Iterable closedIssues = gitHub.getOrganization("hub4j") .getRepository("github-api") - .listIssues(GHIssueState.CLOSED); + .queryIssues() + .state(GHIssueState.CLOSED) + .list(); int x = 0; for (GHIssue issue : closedIssues) { @@ -561,21 +554,6 @@ private boolean shouldBelongToTeam(String organizationName, String teamName) thr return team.hasMember(gitHub.getMyself()); } - /** - * Test fetching team from git hub instance throws exception. - * - * @throws Exception - * the exception - */ - @Test - @SuppressWarnings("deprecation") - public void testFetchingTeamFromGitHubInstanceThrowsException() throws Exception { - GHOrganization organization = gitHub.getOrganization(GITHUB_API_TEST_ORG); - GHTeam teamByName = organization.getTeams().get("Core Developers"); - - assertThrows(UnsupportedOperationException.class, () -> gitHub.getTeam((int) teamByName.getId())); - } - /** * Test should fetch team from organization. * @@ -611,7 +589,6 @@ public void testShouldFetchTeamFromOrganization() throws Exception { @Test public void testFetchPullRequest() throws Exception { GHRepository r = gitHub.getOrganization("jenkinsci").getRepository("jenkins"); - assertThat(r.getMasterBranch(), equalTo("main")); assertThat(r.getDefaultBranch(), equalTo("main")); r.getPullRequest(1); r.getPullRequests(GHIssueState.OPEN); @@ -627,8 +604,8 @@ public void testFetchPullRequest() throws Exception { @Test public void testFetchPullRequestAsList() throws Exception { GHRepository r = gitHub.getRepository("hub4j/github-api"); - assertThat(r.getMasterBranch(), equalTo("main")); - PagedIterable i = r.listPullRequests(GHIssueState.CLOSED); + assertThat(r.getDefaultBranch(), equalTo("main")); + PagedIterable i = r.queryPullRequests().state(GHIssueState.CLOSED).list(); List prs = i.toList(); assertThat(prs, notNullValue()); assertThat(prs, is(not(empty()))); @@ -808,7 +785,7 @@ public void testCommit() throws Exception { .getRepository("jenkins") .getCommit("08c1c9970af4d609ae754fbe803e06186e3206f7"); assertThat(commit.getParents().size(), equalTo(1)); - assertThat(commit.getFiles().size(), equalTo(1)); + assertThat(commit.listFiles().toList().size(), equalTo(1)); assertThat(commit.getHtmlUrl().toString(), equalTo("https://github.com/jenkinsci/jenkins/commit/08c1c9970af4d609ae754fbe803e06186e3206f7")); assertThat(commit.getLinesAdded(), equalTo(40)); @@ -822,7 +799,7 @@ public void testCommit() throws Exception { assertThat(commit.getCommitShortInfo().getCommitDate(), equalTo(commit.getCommitDate())); assertThat(commit.getCommitShortInfo().getMessage(), equalTo("creating an RC branch")); - File f = commit.getFiles().get(0); + File f = commit.listFiles().toList().get(0); assertThat(f.getLinesChanged(), equalTo(48)); assertThat(f.getLinesAdded(), equalTo(40)); assertThat(f.getLinesDeleted(), equalTo(8)); @@ -1145,7 +1122,7 @@ private void tryRenaming(GitHub gitHub) throws IOException { private void tryTeamCreation(GitHub gitHub) throws IOException { GHOrganization o = gitHub.getOrganization("HudsonLabs"); - GHTeam t = o.createTeam("auto team", Permission.PUSH); + GHTeam t = o.createTeam("auto team").permission(Permission.PUSH).create(); t.add(o.getRepository("auto-test")); } @@ -1403,7 +1380,7 @@ public void testCommitSearch() throws IOException { assertThat(r.getTotalCount(), greaterThan(0)); GHCommit firstCommit = r.iterator().next(); - assertThat(firstCommit.getFiles(), is(not(empty()))); + assertThat(firstCommit.listFiles().toList(), is(not(empty()))); } /** @@ -1594,7 +1571,7 @@ public void testRepoLabel() throws IOException { assertThat("It is dark!", equalTo(t3.getDescription())); // Test deprecated methods - t.setDescription("Deprecated"); + t.set().description("Deprecated"); t = r.getLabel("test"); // By using the old instance t when calling setDescription it also sets color to the old value @@ -1602,7 +1579,7 @@ public void testRepoLabel() throws IOException { assertThat("123456", equalTo(t.getColor())); assertThat("Deprecated", equalTo(t.getDescription())); - t.setColor("000000"); + t.set().color("000000"); t = r.getLabel("test"); assertThat("000000", equalTo(t.getColor())); assertThat("Deprecated", equalTo(t.getDescription())); diff --git a/src/test/java/org/kohsuke/github/ArchTests.java b/src/test/java/org/kohsuke/github/ArchTests.java index a460dc7db8..90e6464c14 100644 --- a/src/test/java/org/kohsuke/github/ArchTests.java +++ b/src/test/java/org/kohsuke/github/ArchTests.java @@ -13,10 +13,8 @@ import org.apache.commons.lang3.builder.ReflectionToStringBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; -import org.hamcrest.Matchers; import org.junit.BeforeClass; import org.junit.Test; -import org.kohsuke.github.extras.okhttp3.OkHttpConnector; import java.io.Closeable; import java.io.InputStream; @@ -94,16 +92,6 @@ public void testRequireUseOfAssertThat() { onlyAssertThatRule.check(testClassFiles); } - /** - * Test api stability. - */ - @Test - public void testApiStability() { - assertThat("OkHttpConnector must implement HttpConnector", - Arrays.asList(OkHttpConnector.class.getInterfaces()), - Matchers.containsInAnyOrder(HttpConnector.class)); - } - /** * Test require use of only specific apache commons. */ diff --git a/src/test/java/org/kohsuke/github/BridgeMethodTest.java b/src/test/java/org/kohsuke/github/BridgeMethodTest.java index 9de1951695..609e5a579a 100644 --- a/src/test/java/org/kohsuke/github/BridgeMethodTest.java +++ b/src/test/java/org/kohsuke/github/BridgeMethodTest.java @@ -1,16 +1,12 @@ package org.kohsuke.github; import org.junit.Assert; -import org.junit.Ignore; import org.junit.Test; import java.io.IOException; import java.lang.reflect.Method; -import java.net.URL; import java.util.ArrayList; -import java.util.Date; import java.util.List; -import java.util.Set; import javax.annotation.Nonnull; @@ -30,7 +26,6 @@ public class BridgeMethodTest extends Assert { * @throws IOException * Signals that an I/O exception has occurred. */ - @Ignore("Bridge methods disabled in this branch") @Test public void testBridgeMethods() throws IOException { @@ -41,29 +36,7 @@ public void testBridgeMethods() throws IOException { // verifyBridgeMethods(new GHCommit(), "getAuthor", GHCommit.GHAuthor.class, GitUser.class); // verifyBridgeMethods(new GHCommit(), "getCommitter", GHCommit.GHAuthor.class, GitUser.class); - verifyBridgeMethods(GHIssue.class, "getCreatedAt", Date.class, String.class); - verifyBridgeMethods(GHIssue.class, "getId", int.class, long.class, String.class); - verifyBridgeMethods(GHIssue.class, "getUrl", String.class, URL.class); - verifyBridgeMethods(GHIssue.class, "comment", 1, void.class, GHIssueComment.class); - - verifyBridgeMethods(GHOrganization.class, "getHtmlUrl", String.class, URL.class); - verifyBridgeMethods(GHOrganization.class, "getId", int.class, long.class, String.class); - verifyBridgeMethods(GHOrganization.class, "getUrl", String.class, URL.class); - - verifyBridgeMethods(GHRepository.class, "getCollaborators", GHPersonSet.class, Set.class); - verifyBridgeMethods(GHRepository.class, "getHtmlUrl", String.class, URL.class); - verifyBridgeMethods(GHRepository.class, "getId", int.class, long.class, String.class); - verifyBridgeMethods(GHRepository.class, "getUrl", String.class, URL.class); - - verifyBridgeMethods(GHUser.class, "getFollows", GHPersonSet.class, Set.class); - verifyBridgeMethods(GHUser.class, "getFollowers", GHPersonSet.class, Set.class); - verifyBridgeMethods(GHUser.class, "getOrganizations", GHPersonSet.class, Set.class); - verifyBridgeMethods(GHUser.class, "getId", int.class, long.class, String.class); - - verifyBridgeMethods(GHTeam.class, "getId", int.class, long.class, String.class); - - // verifyBridgeMethods(GitHub.class, "getMyself", GHMyself.class, GHUser.class); - + // verifyBridgeMethods(GHIssue.class, "getCreatedAt", Date.class, String.class); } /** diff --git a/src/test/java/org/kohsuke/github/CommitTest.java b/src/test/java/org/kohsuke/github/CommitTest.java index 257e681cca..1877c87b26 100644 --- a/src/test/java/org/kohsuke/github/CommitTest.java +++ b/src/test/java/org/kohsuke/github/CommitTest.java @@ -43,7 +43,7 @@ public void getFiles() throws Exception { PagedIterable commits = repo.queryCommits().path("pom.xml").list(); for (GHCommit commit : Iterables.limit(commits, 10)) { GHCommit expected = repo.getCommit(commit.getSHA1()); - assertThat(commit.getFiles().size(), equalTo(expected.getFiles().size())); + assertThat(commit.listFiles().toList().size(), equalTo(expected.listFiles().toList().size())); } } diff --git a/src/test/java/org/kohsuke/github/GHAppTest.java b/src/test/java/org/kohsuke/github/GHAppTest.java index 91c1bb9d17..769a7f46fe 100644 --- a/src/test/java/org/kohsuke/github/GHAppTest.java +++ b/src/test/java/org/kohsuke/github/GHAppTest.java @@ -10,7 +10,6 @@ import java.util.Map; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThrows; // TODO: Auto-generated Javadoc /** @@ -28,7 +27,7 @@ public class GHAppTest extends AbstractGHAppInstallationTest { protected GitHubBuilder getGitHubBuilder() { return super.getGitHubBuilder() // ensure that only JWT will be used against the tests below - .withPassword(null, null) + .withOAuthToken(null, null) // Note that we used to provide a bogus token here and to rely on (apparently) manually crafted/edited // Wiremock recordings, so most of the tests cannot actually be executed against GitHub without // relying on the Wiremock recordings. @@ -58,15 +57,6 @@ public void getGitHubApp() throws IOException { assertThat(app.getPermissions().size(), is(2)); assertThat(app.getEvents().size(), is(0)); assertThat(app.getInstallationsCount(), is((long) 1)); - - // Deprecated methods - assertThrows(RuntimeException.class, () -> app.setDescription("")); - assertThrows(RuntimeException.class, () -> app.setEvents(null)); - assertThrows(RuntimeException.class, () -> app.setExternalUrl("")); - assertThrows(RuntimeException.class, () -> app.setInstallationsCount(1)); - assertThrows(RuntimeException.class, () -> app.setName("")); - assertThrows(RuntimeException.class, () -> app.setOwner(null)); - assertThrows(RuntimeException.class, () -> app.setPermissions(null)); } /** @@ -182,13 +172,6 @@ public void createToken() throws IOException { assertThat(installationToken.getRepositorySelection(), is(GHRepositorySelection.SELECTED)); assertThat(installationToken.getExpiresAt(), is(GitHubClient.parseDate("2019-08-10T05:54:58Z"))); - // Deprecated methods - assertThrows(RuntimeException.class, () -> installationToken.setPermissions(null)); - assertThrows(RuntimeException.class, () -> installationToken.setRoot(null)); - assertThrows(RuntimeException.class, () -> installationToken.setRepositorySelection(null)); - assertThrows(RuntimeException.class, () -> installationToken.setRepositories(null)); - assertThrows(RuntimeException.class, () -> installationToken.setPermissions(null)); - GHRepository repository = installationToken.getRepositories().get(0); assertThat(installationToken.getRepositories().size(), is(1)); assertThat(repository.getId(), is((long) 111111111)); @@ -246,19 +229,6 @@ private void testAppInstallation(GHAppInstallation appInstallation) throws IOExc assertThat(appInstallation.getTargetId(), is((long) 111111111)); assertThat(appInstallation.getTargetType(), is(GHTargetType.ORGANIZATION)); - // Deprecated methods - assertThrows(RuntimeException.class, () -> appInstallation.setAccessTokenUrl("")); - assertThrows(RuntimeException.class, () -> appInstallation.setAccount(null)); - assertThrows(RuntimeException.class, () -> appInstallation.setAppId(0)); - assertThrows(RuntimeException.class, () -> appInstallation.setEvents(null)); - assertThrows(RuntimeException.class, () -> appInstallation.setPermissions(null)); - assertThrows(RuntimeException.class, () -> appInstallation.setRepositorySelection(null)); - assertThrows(RuntimeException.class, () -> appInstallation.setRepositoriesUrl(null)); - assertThrows(RuntimeException.class, () -> appInstallation.setRoot(null)); - assertThrows(RuntimeException.class, () -> appInstallation.setSingleFileName("")); - assertThrows(RuntimeException.class, () -> appInstallation.setTargetId(0)); - assertThrows(RuntimeException.class, () -> appInstallation.setTargetType(null)); - Map permissionsMap = new HashMap(); permissionsMap.put("checks", GHPermissionType.WRITE); permissionsMap.put("pull_requests", GHPermissionType.WRITE); diff --git a/src/test/java/org/kohsuke/github/GHContentIntegrationTest.java b/src/test/java/org/kohsuke/github/GHContentIntegrationTest.java index 828fd49ac4..40c7baeedd 100644 --- a/src/test/java/org/kohsuke/github/GHContentIntegrationTest.java +++ b/src/test/java/org/kohsuke/github/GHContentIntegrationTest.java @@ -70,8 +70,6 @@ public void setUp() throws Exception { public void testGetRepository() throws Exception { GHRepository testRepo = gitHub.getRepositoryById(repo.getId()); assertThat(testRepo.getName(), equalTo(repo.getName())); - testRepo = gitHub.getRepositoryById(Long.toString(repo.getId())); - assertThat(testRepo.getName(), equalTo(repo.getName())); } /** @@ -138,9 +136,11 @@ 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() + .content("this is an awesome file I created\n") + .message("Creating a file for integration tests.") + .path(createdFilename) + .commit(); int expectedRequestCount = mockGitHub.getRequestCount(); GHContent createdContent = created.getContent(); diff --git a/src/test/java/org/kohsuke/github/GHEventPayloadTest.java b/src/test/java/org/kohsuke/github/GHEventPayloadTest.java index 2400218a16..0187f5c8cd 100644 --- a/src/test/java/org/kohsuke/github/GHEventPayloadTest.java +++ b/src/test/java/org/kohsuke/github/GHEventPayloadTest.java @@ -25,7 +25,6 @@ import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.sameInstance; import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThrows; // TODO: Auto-generated Javadoc /** @@ -62,13 +61,6 @@ public void commit_comment() throws Exception { assertThat(event.getSender().getLogin(), is("baxterthehacker")); assertThat(event.getComment().getOwner(), sameInstance(event.getRepository())); - - assertThrows(RuntimeException.class, () -> event.setComment(null)); - - // EventPayload checks - assertThrows(RuntimeException.class, () -> event.setOrganization(null)); - assertThrows(RuntimeException.class, () -> event.setRepository(null)); - assertThrows(RuntimeException.class, () -> event.setSender(null)); } /** @@ -138,7 +130,7 @@ public void deployment_status() throws Exception { final 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.getDeploymentStatus().getLogUrl(), nullValue()); assertThat(event.getDeployment().getSha(), is("9049f1265b7d61be4a8904a9a27120d2064dab3b")); assertThat(event.getDeployment().getEnvironment(), is("production")); assertThat(event.getDeployment().getCreator().getLogin(), is("baxterthehacker")); @@ -148,9 +140,6 @@ public void deployment_status() throws Exception { assertThat(event.getDeployment().getOwner(), sameInstance(event.getRepository())); assertThat(event.getDeploymentStatus().getOwner(), sameInstance(event.getRepository())); - - assertThrows(RuntimeException.class, () -> event.setDeployment(null)); - assertThrows(RuntimeException.class, () -> event.setDeploymentStatus(null)); } /** @@ -168,8 +157,6 @@ public void fork() throws Exception { assertThat(event.getRepository().getName(), is("public-repo")); assertThat(event.getRepository().getOwner().getLogin(), is("baxterthehacker")); assertThat(event.getSender().getLogin(), is("baxterandthehackers")); - - assertThrows(RuntimeException.class, () -> event.setForkee(null)); } // TODO uncomment when we have GHPage implemented @@ -214,9 +201,6 @@ public void issue_comment() throws Exception { assertThat(event.getIssue().getRepository(), sameInstance(event.getRepository())); assertThat(event.getComment().getParent(), sameInstance(event.getIssue())); - - assertThrows(RuntimeException.class, () -> event.setComment(null)); - assertThrows(RuntimeException.class, () -> event.setIssue(null)); } /** @@ -648,11 +632,6 @@ public void push() throws Exception { assertThat(event.getSender().getLogin(), is("baxterthehacker")); assertThat(event.getCompare(), is("https://github.com/baxterthehacker/public-repo/compare/9049f1265b7d...0d1a26e67d8f")); - - assertThrows(RuntimeException.class, () -> event.setPusher(null)); - assertThrows(RuntimeException.class, () -> event.getPusher().setEmail(null)); - assertThrows(RuntimeException.class, () -> event.getPusher().setName(null)); - } /** @@ -750,8 +729,6 @@ public void release_published() throws Exception { assertThat(event.getRelease().getName(), is("4.2")); assertThat(event.getRelease().getTagName(), is("rest-api-framework-4.2")); assertThat(event.getRelease().getBody(), is("REST-269 - unique test executions (#86) Sergey Chernov")); - - assertThrows(RuntimeException.class, () -> event.setRelease(null)); } /** @@ -788,9 +765,6 @@ public void status() throws Exception { assertThat(event.getRepository().getOwner().getLogin(), is("baxterthehacker")); assertThat(event.getTargetUrl(), nullValue()); assertThat(event.getCommit().getOwner(), sameInstance(event.getRepository())); - - assertThrows(RuntimeException.class, () -> event.setCommit(null)); - assertThrows(RuntimeException.class, () -> event.setState(GHCommitState.ERROR)); } /** @@ -851,8 +825,6 @@ private GHCheckRun verifyBasicCheckRunEvent(final GHEventPayload.CheckRun event) assertThat(event.getRepository().getOwner().getLogin(), is("Codertocat")); assertThat(event.getAction(), is("created")); assertThat(event.getRequestedAction(), nullValue()); - assertThrows(RuntimeException.class, () -> event.setCheckRun(null)); - assertThrows(RuntimeException.class, () -> event.setRequestedAction(null)); // Checks the deserialization of check_run final GHCheckRun checkRun = event.getCheckRun(); diff --git a/src/test/java/org/kohsuke/github/GHHookTest.java b/src/test/java/org/kohsuke/github/GHHookTest.java index 247505fb1d..3dac2ed060 100644 --- a/src/test/java/org/kohsuke/github/GHHookTest.java +++ b/src/test/java/org/kohsuke/github/GHHookTest.java @@ -42,7 +42,7 @@ public void exposeResponceHeaders() throws Exception { String orgRepo = "KostyaSha-org/test"; // some login based user that has access to application - final GitHub gitHub = GitHub.connectUsingPassword(user1Login, user1Pass); + final GitHub gitHub = GitHub.connect(user1Login, user1Pass); gitHub.getMyself(); // we request read diff --git a/src/test/java/org/kohsuke/github/GHIssueTest.java b/src/test/java/org/kohsuke/github/GHIssueTest.java index b86910cf2f..c1d4dea2eb 100644 --- a/src/test/java/org/kohsuke/github/GHIssueTest.java +++ b/src/test/java/org/kohsuke/github/GHIssueTest.java @@ -312,7 +312,7 @@ public void getUserTest() throws IOException { GHIssue issueSingle = getRepository().getIssue(issue.getNumber()); assertThat(issueSingle.getUser().root(), notNullValue()); - PagedIterable ghIssues = getRepository().listIssues(GHIssueState.OPEN); + PagedIterable ghIssues = getRepository().queryIssues().state(GHIssueState.OPEN).list(); for (GHIssue otherIssue : ghIssues) { assertThat(otherIssue.getUser().root(), notNullValue()); } diff --git a/src/test/java/org/kohsuke/github/GHMarketplacePlanTest.java b/src/test/java/org/kohsuke/github/GHMarketplacePlanTest.java index 90e697ce37..d95ef2b0f9 100644 --- a/src/test/java/org/kohsuke/github/GHMarketplacePlanTest.java +++ b/src/test/java/org/kohsuke/github/GHMarketplacePlanTest.java @@ -28,7 +28,7 @@ public class GHMarketplacePlanTest extends AbstractGitHubWireMockTest { protected GitHubBuilder getGitHubBuilder() { return super.getGitHubBuilder() // ensure that only JWT will be used against the tests below - .withPassword(null, null) + .withOAuthToken(null, null) .withJwtToken("bogus"); } diff --git a/src/test/java/org/kohsuke/github/GHOrganizationTest.java b/src/test/java/org/kohsuke/github/GHOrganizationTest.java index 6edd1e172e..532c082dfe 100644 --- a/src/test/java/org/kohsuke/github/GHOrganizationTest.java +++ b/src/test/java/org/kohsuke/github/GHOrganizationTest.java @@ -314,7 +314,10 @@ public void testCreateTeamWithRepoAccess() throws IOException { GHRepository repo = org.getRepository(REPO_NAME); // Create team with access to repository. Check access was granted. - GHTeam team = org.createTeam(TEAM_NAME_CREATE, GHOrganization.Permission.PUSH, repo); + GHTeam team = org.createTeam(TEAM_NAME_CREATE) + .repositories(repo.getFullName()) + .permission(Permission.PUSH) + .create(); assertThat(team.getRepositories().containsKey(REPO_NAME), is(true)); assertThat(team.getPermission(), equalTo(Permission.PUSH.toString().toLowerCase())); } @@ -363,7 +366,7 @@ public void testCreateTeamWithRepoPerm() throws Exception { // Create team with access to repository. Check access was granted. GHTeam team = org.createTeam(TEAM_NAME_CREATE).create(); - team.add(repo, GHOrganization.Permission.PUSH); + team.add(repo, GHOrganization.RepositoryRole.from(Permission.PUSH)); assertThat( repo.getTeams() @@ -421,7 +424,7 @@ public void testCreateTeam() throws IOException { GHRepository repo = org.getRepository(REPO_NAME); // Create team with no permission field. Verify that default permission is pull - GHTeam team = org.createTeam(TEAM_NAME_CREATE, repo); + GHTeam team = org.createTeam(TEAM_NAME_CREATE).repositories(repo.getFullName()).create(); assertThat(team.getRepositories().containsKey(REPO_NAME), is(true)); assertThat(team.getPermission(), equalTo(DEFAULT_PERMISSION)); } diff --git a/src/test/java/org/kohsuke/github/GHPullRequestTest.java b/src/test/java/org/kohsuke/github/GHPullRequestTest.java index 98a50a8d09..6a82463670 100644 --- a/src/test/java/org/kohsuke/github/GHPullRequestTest.java +++ b/src/test/java/org/kohsuke/github/GHPullRequestTest.java @@ -559,7 +559,7 @@ public void squashMerge() throws Exception { GHRef mainRef = getRepository().getRef("heads/main"); GHRef branchRef = getRepository().createRef("refs/heads/" + branchName, mainRef.getObject().getSha()); - getRepository().createContent(name, name, name, branchName); + getRepository().createContent().content(name).path(name).message(name).branch(branchName).commit(); Thread.sleep(1000); GHPullRequest p = getRepository().createPullRequest(name, branchName, "main", "## test squash"); Thread.sleep(1000); @@ -580,7 +580,13 @@ public void updateContentSquashMerge() throws Exception { GHRef mainRef = getRepository().getRef("heads/main"); GHRef branchRef = getRepository().createRef("refs/heads/" + branchName, mainRef.getObject().getSha()); - GHContentUpdateResponse response = getRepository().createContent(name, name, name, branchName); + GHContentUpdateResponse response = getRepository().createContent() + .content(name) + .path(name) + .branch(branchName) + .message(name) + .commit(); + Thread.sleep(1000); getRepository().createContent() @@ -799,7 +805,9 @@ public void getUserTest() throws IOException { prSingle.getMergeable(); assertThat(prSingle.getUser().root(), notNullValue()); - PagedIterable ghPullRequests = getRepository().listPullRequests(GHIssueState.OPEN); + PagedIterable ghPullRequests = getRepository().queryPullRequests() + .state(GHIssueState.OPEN) + .list(); for (GHPullRequest pr : ghPullRequests) { assertThat(pr.getUser().root(), notNullValue()); pr.getMergeable(); diff --git a/src/test/java/org/kohsuke/github/GHRateLimitTest.java b/src/test/java/org/kohsuke/github/GHRateLimitTest.java index 7d3001b7a4..b87328b5d7 100644 --- a/src/test/java/org/kohsuke/github/GHRateLimitTest.java +++ b/src/test/java/org/kohsuke/github/GHRateLimitTest.java @@ -274,7 +274,7 @@ public void testGitHubEnterpriseDoesNotHaveRateLimit() throws Exception { // ------------------------------------------------------------- // Before any queries, rate limit starts as default but may be requested - gitHub = GitHub.connectToEnterprise(mockGitHub.apiServer().baseUrl(), "bogus", "bogus"); + gitHub = GitHub.connectToEnterpriseWithOAuth(mockGitHub.apiServer().baseUrl(), "bogus", "bogus"); assertThat(mockGitHub.getRequestCount(), equalTo(0)); assertThat(gitHub.lastRateLimit(), sameInstance(GHRateLimit.DEFAULT)); @@ -300,7 +300,7 @@ public void testGitHubEnterpriseDoesNotHaveRateLimit() throws Exception { // ------------------------------------------------------------- // Some versions of GHE include header rate limit information, some do not // This response mocks the behavior without header rate limit information - gitHub = GitHub.connectToEnterprise(mockGitHub.apiServer().baseUrl(), "bogus", "bogus"); + gitHub = GitHub.connectToEnterpriseWithOAuth(mockGitHub.apiServer().baseUrl(), "bogus", "bogus"); gitHub.getMyself(); assertThat(mockGitHub.getRequestCount(), equalTo(2)); @@ -344,7 +344,7 @@ public void testGitHubEnterpriseDoesNotHaveRateLimit() throws Exception { // ------------------------------------------------------------- // Some versions of GHE include header rate limit information, some do not // This response mocks the behavior with header rate limit information - gitHub = GitHub.connectToEnterprise(mockGitHub.apiServer().baseUrl(), "bogus", "bogus"); + gitHub = GitHub.connectToEnterpriseWithOAuth(mockGitHub.apiServer().baseUrl(), "bogus", "bogus"); gitHub.getMyself(); assertThat(mockGitHub.getRequestCount(), equalTo(5)); diff --git a/src/test/java/org/kohsuke/github/GHRepositoryTest.java b/src/test/java/org/kohsuke/github/GHRepositoryTest.java index 3ad8545c3c..cc880d4517 100644 --- a/src/test/java/org/kohsuke/github/GHRepositoryTest.java +++ b/src/test/java/org/kohsuke/github/GHRepositoryTest.java @@ -99,7 +99,6 @@ public void testGetters() throws IOException { String httpTransport = "https://github.com/hub4j-test-org/temp-testGetters.git"; assertThat(r.getHttpTransportUrl(), equalTo(httpTransport)); - assertThat(r.gitHttpTransportUrl(), equalTo(httpTransport)); assertThat(r.getName(), equalTo("temp-testGetters")); assertThat(r.getFullName(), equalTo("hub4j-test-org/temp-testGetters")); @@ -568,7 +567,7 @@ public void addCollaborators() throws Exception { users.add(user); users.add(gitHub.getUser("jimmysombrero2")); - repo.addCollaborators(users, GHOrganization.Permission.PUSH); + repo.addCollaborators(users, RepositoryRole.from(GHOrganization.Permission.PUSH)); GHPersonSet collabs = repo.getCollaborators(); GHUser colabUser = collabs.byLogin("jimmysombrero"); @@ -786,42 +785,6 @@ public void ghRepositorySearchBuilderForkDefaultResetForksSearchTerms() { assertThat(ghRepositorySearchBuilder.terms.stream().filter(item -> item.contains("fork:")).count(), is(0L)); } - /** - * Gh repository search builder fork deprecated enum. - */ - @Test - public void ghRepositorySearchBuilderForkDeprecatedEnum() { - GHRepositorySearchBuilder ghRepositorySearchBuilder = new GHRepositorySearchBuilder(gitHub); - ghRepositorySearchBuilder = ghRepositorySearchBuilder.fork(GHRepositorySearchBuilder.Fork.PARENT_AND_FORKS); - assertThat(ghRepositorySearchBuilder.terms.stream().filter(item -> item.contains("fork:true")).count(), is(1L)); - assertThat(ghRepositorySearchBuilder.terms.stream().filter(item -> item.contains("fork:")).count(), is(1L)); - - ghRepositorySearchBuilder = ghRepositorySearchBuilder.fork(GHRepositorySearchBuilder.Fork.FORKS_ONLY); - assertThat(ghRepositorySearchBuilder.terms.stream().filter(item -> item.contains("fork:only")).count(), is(1L)); - assertThat(ghRepositorySearchBuilder.terms.stream().filter(item -> item.contains("fork:")).count(), is(2L)); - - ghRepositorySearchBuilder = ghRepositorySearchBuilder.fork(GHRepositorySearchBuilder.Fork.PARENT_ONLY); - assertThat(ghRepositorySearchBuilder.terms.stream().filter(item -> item.contains("fork:")).count(), is(0L)); - } - - /** - * Gh repository search builder fork deprecated string. - */ - @Test - public void ghRepositorySearchBuilderForkDeprecatedString() { - GHRepositorySearchBuilder ghRepositorySearchBuilder = new GHRepositorySearchBuilder(gitHub); - ghRepositorySearchBuilder = ghRepositorySearchBuilder.forks(GHFork.PARENT_AND_FORKS.toString()); - assertThat(ghRepositorySearchBuilder.terms.stream().filter(item -> item.contains("fork:true")).count(), is(1L)); - assertThat(ghRepositorySearchBuilder.terms.stream().filter(item -> item.contains("fork:")).count(), is(1L)); - - ghRepositorySearchBuilder = ghRepositorySearchBuilder.forks(GHFork.FORKS_ONLY.toString()); - assertThat(ghRepositorySearchBuilder.terms.stream().filter(item -> item.contains("fork:only")).count(), is(1L)); - assertThat(ghRepositorySearchBuilder.terms.stream().filter(item -> item.contains("fork:")).count(), is(2L)); - - ghRepositorySearchBuilder = ghRepositorySearchBuilder.forks(null); - assertThat(ghRepositorySearchBuilder.terms.stream().filter(item -> item.contains("fork:")).count(), is(0L)); - } - /** * List commit comments some comments. * @@ -1635,19 +1598,6 @@ public void starTest() throws Exception { assertThat(repository.listStargazers().toList().size(), is(0)); } - /** - * Test to check getRepoVariable method. - * - * @throws Exception - * the exception - */ - @Test - public void testRepoActionVariable() throws Exception { - GHRepository repository = getRepository(); - GHRepositoryVariable variable = repository.getRepoVariable("myvar"); - assertThat(variable.getValue(), is("this is my var value")); - } - /** * Test create repo action variable. * diff --git a/src/test/java/org/kohsuke/github/GHTreeBuilderTest.java b/src/test/java/org/kohsuke/github/GHTreeBuilderTest.java index 9071477889..51787918c5 100644 --- a/src/test/java/org/kohsuke/github/GHTreeBuilderTest.java +++ b/src/test/java/org/kohsuke/github/GHTreeBuilderTest.java @@ -2,7 +2,6 @@ import org.junit.After; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; import java.io.IOException; @@ -71,44 +70,6 @@ public void setUp() throws Exception { treeBuilder = repo.createTree().baseTree(mainTreeSha); } - /** - * Test text entry. - * - * @throws Exception - * the exception - */ - @Test - @Ignore("It seems that GitHub no longer supports the 'content' parameter") - public void testTextEntry() throws Exception { - treeBuilder.textEntry(PATH_SCRIPT, CONTENT_SCRIPT, true); - treeBuilder.textEntry(PATH_README, CONTENT_README, false); - - updateTree(); - - assertThat(getFileSize(PATH_SCRIPT), equalTo(CONTENT_SCRIPT.length())); - assertThat(getFileSize(PATH_README), equalTo(CONTENT_README.length())); - } - - /** - * Test sha entry. - * - * @throws Exception - * the exception - */ - @Test - public void testShaEntry() throws Exception { - String dataSha1 = new GHBlobBuilder(repo).binaryContent(CONTENT_DATA1).create().getSha(); - treeBuilder.shaEntry(PATH_DATA1, dataSha1, false); - - String dataSha2 = new GHBlobBuilder(repo).binaryContent(CONTENT_DATA2).create().getSha(); - treeBuilder.shaEntry(PATH_DATA2, dataSha2, false); - - updateTree(); - - assertThat(getFileSize(PATH_DATA1), equalTo((long) CONTENT_DATA1.length)); - assertThat(getFileSize(PATH_DATA2), equalTo((long) CONTENT_DATA2.length)); - } - /** * Test add. * diff --git a/src/test/java/org/kohsuke/github/GitHubConnectionTest.java b/src/test/java/org/kohsuke/github/GitHubConnectionTest.java index fd3d6ebffb..bb863eae72 100644 --- a/src/test/java/org/kohsuke/github/GitHubConnectionTest.java +++ b/src/test/java/org/kohsuke/github/GitHubConnectionTest.java @@ -59,7 +59,7 @@ public void testOffline() throws Exception { */ @Test public void testGitHubServerWithHttp() throws Exception { - GitHub hub = GitHub.connectToEnterprise("http://enterprise.kohsuke.org/api/v3", "bogus", "bogus"); + GitHub hub = GitHub.connectToEnterpriseWithOAuth("http://enterprise.kohsuke.org/api/v3", "bogus", "bogus"); assertThat(GitHubRequest.getApiURL(hub.getClient().getApiUrl(), "/test").toString(), equalTo("http://enterprise.kohsuke.org/api/v3/test")); } @@ -72,7 +72,7 @@ public void testGitHubServerWithHttp() throws Exception { */ @Test public void testGitHubServerWithHttps() throws Exception { - GitHub hub = GitHub.connectToEnterprise("https://enterprise.kohsuke.org/api/v3", "bogus", "bogus"); + GitHub hub = GitHub.connectToEnterpriseWithOAuth("https://enterprise.kohsuke.org/api/v3", "bogus", "bogus"); assertThat(GitHubRequest.getApiURL(hub.getClient().getApiUrl(), "/test").toString(), equalTo("https://enterprise.kohsuke.org/api/v3/test")); } @@ -85,7 +85,7 @@ public void testGitHubServerWithHttps() throws Exception { */ @Test public void testGitHubServerWithoutServer() throws Exception { - GitHub hub = GitHub.connectUsingPassword("kohsuke", "bogus"); + GitHub hub = GitHub.connect("kohsuke", "bogus"); assertThat(GitHubRequest.getApiURL(hub.getClient().getApiUrl(), "/test").toString(), equalTo("https://api.github.com/test")); } @@ -129,60 +129,17 @@ public void testGitHubBuilderFromEnvironment() throws IOException { assertThat(builder.authorizationProvider, not(instanceOf(UserAuthorizationProvider.class))); assertThat(builder.authorizationProvider.getEncodedAuthorization(), equalTo("Bearer bogus jwt token string")); - props.put("password", "bogus weak password"); - setupEnvironment(props); - builder = GitHubBuilder.fromEnvironment(); + // props.put("password", "bogus weak password"); + // setupEnvironment(props); + // builder = GitHubBuilder.fromEnvironment(); - assertThat(builder.authorizationProvider, instanceOf(UserAuthorizationProvider.class)); - assertThat(builder.authorizationProvider.getEncodedAuthorization(), - equalTo("Basic Ym9ndXMgbG9naW46Ym9ndXMgd2VhayBwYXNzd29yZA==")); - assertThat(((UserAuthorizationProvider) builder.authorizationProvider).getLogin(), equalTo("bogus login")); + // assertThat(builder.authorizationProvider, instanceOf(UserAuthorizationProvider.class)); + // assertThat(builder.authorizationProvider.getEncodedAuthorization(), + // equalTo("Basic Ym9ndXMgbG9naW46Ym9ndXMgd2VhayBwYXNzd29yZA==")); + // assertThat(((UserAuthorizationProvider) builder.authorizationProvider).getLogin(), equalTo("bogus login")); } - /** - * Test git hub builder from custom environment. - * - * @throws IOException - * Signals that an I/O exception has occurred. - */ - @Test - public void testGitHubBuilderFromCustomEnvironment() throws IOException { - // we disable this test for JDK 16+ as the current hacks in setupEnvironment() don't work with JDK 16+ - Assume.assumeThat(Double.valueOf(System.getProperty("java.specification.version")), lessThan(16.0)); - - Map props = new HashMap(); - - props.put("customEndpoint", "bogus endpoint url"); - props.put("customOauth", "bogus oauth token string"); - setupEnvironment(props); - GitHubBuilder builder = GitHubBuilder - .fromEnvironment("customLogin", "customPassword", "customOauth", "customEndpoint"); - - assertThat(builder.endpoint, equalTo("bogus endpoint url")); - - assertThat(builder.authorizationProvider, instanceOf(UserAuthorizationProvider.class)); - assertThat(builder.authorizationProvider.getEncodedAuthorization(), equalTo("token bogus oauth token string")); - assertThat(((UserAuthorizationProvider) builder.authorizationProvider).getLogin(), nullValue()); - - props.put("customLogin", "bogus login"); - setupEnvironment(props); - builder = GitHubBuilder.fromEnvironment("customLogin", "customPassword", "customOauth", "customEndpoint"); - - assertThat(builder.authorizationProvider, instanceOf(UserAuthorizationProvider.class)); - assertThat(builder.authorizationProvider.getEncodedAuthorization(), equalTo("token bogus oauth token string")); - assertThat(((UserAuthorizationProvider) builder.authorizationProvider).getLogin(), equalTo("bogus login")); - - props.put("customPassword", "bogus weak password"); - setupEnvironment(props); - builder = GitHubBuilder.fromEnvironment("customLogin", "customPassword", "customOauth", "customEndpoint"); - - assertThat(builder.authorizationProvider, instanceOf(UserAuthorizationProvider.class)); - assertThat(builder.authorizationProvider.getEncodedAuthorization(), - equalTo("Basic Ym9ndXMgbG9naW46Ym9ndXMgd2VhayBwYXNzd29yZA==")); - assertThat(((UserAuthorizationProvider) builder.authorizationProvider).getLogin(), equalTo("bogus login")); - } - /** * Test git hub builder from credentials with environment. * @@ -204,7 +161,7 @@ public void testGitHubBuilderFromCredentialsWithEnvironment() throws IOException assertThat(builder.endpoint, equalTo("bogus endpoint url")); - assertThat(builder.authorizationProvider, instanceOf(UserAuthorizationProvider.class)); + // assertThat(builder.authorizationProvider, instanceOf(UserAuthorizationProvider.class)); assertThat(builder.authorizationProvider.getEncodedAuthorization(), equalTo("token bogus oauth token string")); assertThat(((UserAuthorizationProvider) builder.authorizationProvider).getLogin(), nullValue()); @@ -212,7 +169,7 @@ public void testGitHubBuilderFromCredentialsWithEnvironment() throws IOException setupEnvironment(props); builder = GitHubBuilder.fromCredentials(); - assertThat(builder.authorizationProvider, instanceOf(UserAuthorizationProvider.class)); + // assertThat(builder.authorizationProvider, instanceOf(UserAuthorizationProvider.class)); assertThat(builder.authorizationProvider.getEncodedAuthorization(), equalTo("token bogus oauth token string")); assertThat(((UserAuthorizationProvider) builder.authorizationProvider).getLogin(), equalTo("bogus login")); @@ -222,15 +179,6 @@ public void testGitHubBuilderFromCredentialsWithEnvironment() throws IOException assertThat(builder.authorizationProvider, not(instanceOf(UserAuthorizationProvider.class))); assertThat(builder.authorizationProvider.getEncodedAuthorization(), equalTo("Bearer bogus jwt token string")); - - props.put("password", "bogus weak password"); - setupEnvironment(props); - builder = GitHubBuilder.fromCredentials(); - - assertThat(builder.authorizationProvider, instanceOf(UserAuthorizationProvider.class)); - assertThat(builder.authorizationProvider.getEncodedAuthorization(), - equalTo("Basic Ym9ndXMgbG9naW46Ym9ndXMgd2VhayBwYXNzd29yZA==")); - assertThat(((UserAuthorizationProvider) builder.authorizationProvider).getLogin(), equalTo("bogus login")); } /** @@ -270,7 +218,7 @@ public void testGitHubBuilderFromCredentialsWithPropertyFile() throws IOExceptio assertThat(builder.endpoint, equalTo("bogus endpoint url")); - assertThat(builder.authorizationProvider, instanceOf(UserAuthorizationProvider.class)); + // assertThat(builder.authorizationProvider, instanceOf(UserAuthorizationProvider.class)); assertThat(builder.authorizationProvider.getEncodedAuthorization(), equalTo("token bogus oauth token string")); assertThat(((UserAuthorizationProvider) builder.authorizationProvider).getLogin(), nullValue()); @@ -279,7 +227,7 @@ public void testGitHubBuilderFromCredentialsWithPropertyFile() throws IOExceptio setupPropertyFile(props); builder = GitHubBuilder.fromCredentials(); - assertThat(builder.authorizationProvider, instanceOf(UserAuthorizationProvider.class)); + // assertThat(builder.authorizationProvider, instanceOf(UserAuthorizationProvider.class)); assertThat(builder.authorizationProvider.getEncodedAuthorization(), equalTo("token bogus oauth token string")); assertThat(((UserAuthorizationProvider) builder.authorizationProvider).getLogin(), equalTo("bogus login")); @@ -291,15 +239,6 @@ public void testGitHubBuilderFromCredentialsWithPropertyFile() throws IOExceptio assertThat(builder.authorizationProvider, not(instanceOf(UserAuthorizationProvider.class))); assertThat(builder.authorizationProvider.getEncodedAuthorization(), equalTo("Bearer bogus jwt token string")); - - props.put("password", "bogus weak password"); - setupPropertyFile(props); - builder = GitHubBuilder.fromCredentials(); - - assertThat(builder.authorizationProvider, instanceOf(UserAuthorizationProvider.class)); - assertThat(builder.authorizationProvider.getEncodedAuthorization(), - equalTo("Basic Ym9ndXMgbG9naW46Ym9ndXMgd2VhayBwYXNzd29yZA==")); - assertThat(((UserAuthorizationProvider) builder.authorizationProvider).getLogin(), equalTo("bogus login")); } finally { GitHubBuilder.HOME_DIRECTORY = null; File propertyFile = new File(getTestDirectory(), ".github"); @@ -335,8 +274,7 @@ public void testAnonymous() throws IOException { setupEnvironment(props); // No values present except endpoint - GitHubBuilder builder = GitHubBuilder - .fromEnvironment("customLogin", "customPassword", "customOauth", "endpoint"); + GitHubBuilder builder = GitHubBuilder.fromEnvironment(); assertThat(builder.endpoint, equalTo(mockGitHub.apiServer().baseUrl())); assertThat(builder.authorizationProvider, sameInstance(AuthorizationProvider.ANONYMOUS)); @@ -352,7 +290,7 @@ public void testAnonymous() throws IOException { public void testGithubBuilderWithAppInstallationToken() throws Exception { GitHubBuilder builder = new GitHubBuilder().withAppInstallationToken("bogus app token"); - assertThat(builder.authorizationProvider, instanceOf(UserAuthorizationProvider.class)); + // assertThat(builder.authorizationProvider, instanceOf(UserAuthorizationProvider.class)); assertThat(builder.authorizationProvider.getEncodedAuthorization(), equalTo("token bogus app token")); assertThat(((UserAuthorizationProvider) builder.authorizationProvider).getLogin(), is(emptyString())); diff --git a/src/test/java/org/kohsuke/github/GitHubStaticTest.java b/src/test/java/org/kohsuke/github/GitHubStaticTest.java index 16ac75b524..eebd847032 100644 --- a/src/test/java/org/kohsuke/github/GitHubStaticTest.java +++ b/src/test/java/org/kohsuke/github/GitHubStaticTest.java @@ -2,7 +2,6 @@ import org.junit.Assert; import org.junit.Test; -import org.kohsuke.github.connector.GitHubConnector; import org.kohsuke.github.connector.GitHubConnectorResponse; import java.net.MalformedURLException; @@ -375,7 +374,6 @@ public void testMappingReaderWriter() throws Exception { // This should never happen if the internal method isn't used final GHRepository readRepoFinal = readRepo; - assertThrows(NullPointerException.class, () -> readRepoFinal.getRoot()); assertThrows(NullPointerException.class, () -> readRepoFinal.root()); assertThat(readRepoFinal.isOffline(), is(true)); assertThat(readRepo.getResponseHeaderFields(), nullValue()); @@ -383,7 +381,6 @@ public void testMappingReaderWriter() throws Exception { readRepo = GitHub.getMappingObjectReader().forType(GHRepository.class).readValue(repoString); // This should never happen if the internal method isn't used - assertThat(readRepo.getRoot().getConnector(), equalTo(GitHubConnector.OFFLINE)); assertThat(readRepo.getResponseHeaderFields(), nullValue()); String readRepoString = GitHub.getMappingObjectWriter().writeValueAsString(readRepo); diff --git a/src/test/java/org/kohsuke/github/GitHubTest.java b/src/test/java/org/kohsuke/github/GitHubTest.java index 4b4a848545..0f9f6c4589 100644 --- a/src/test/java/org/kohsuke/github/GitHubTest.java +++ b/src/test/java/org/kohsuke/github/GitHubTest.java @@ -43,7 +43,7 @@ public void getRepository() throws IOException { assertThat(repo.getFullName(), equalTo("hub4j/github-api")); - GHRepository repo2 = gitHub.getRepositoryById(Long.toString(repo.getId())); + GHRepository repo2 = gitHub.getRepositoryById(repo.getId()); assertThat(repo2.getFullName(), equalTo("hub4j/github-api")); try { @@ -236,7 +236,7 @@ public void searchContentWithForks() { .language("js") .sort(GHContentSearchBuilder.Sort.INDEXED) .order(GHDirection.DESC) - .fork(GHFork.PARENT_ONLY.toString()) + .fork(GHFork.PARENT_ONLY) .list(); final PagedSearchIterable resultsWithForksDeprecated = gitHub.searchContent() @@ -244,7 +244,7 @@ public void searchContentWithForks() { .language("js") .sort(GHContentSearchBuilder.Sort.INDEXED) .order(GHDirection.DESC) - .fork(GHFork.PARENT_AND_FORKS.toString()) + .fork(GHFork.PARENT_AND_FORKS) .list(); assertThat(resultsDeprecated.getTotalCount(), equalTo(results.getTotalCount())); diff --git a/src/test/java/org/kohsuke/github/RateLimitHandlerTest.java b/src/test/java/org/kohsuke/github/RateLimitHandlerTest.java index b624409152..5606d00a07 100644 --- a/src/test/java/org/kohsuke/github/RateLimitHandlerTest.java +++ b/src/test/java/org/kohsuke/github/RateLimitHandlerTest.java @@ -2,9 +2,11 @@ import com.github.tomakehurst.wiremock.core.WireMockConfiguration; import org.junit.Test; +import org.kohsuke.github.connector.GitHubConnectorResponse; import java.io.IOException; -import java.net.HttpURLConnection; + +import javax.annotation.Nonnull; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.core.IsInstanceOf.instanceOf; @@ -61,7 +63,7 @@ public void testHandler_Fail() throws Exception { snapshotNotAllowed(); gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()) - .withRateLimitHandler(RateLimitHandler.FAIL) + .withRateLimitHandler(GitHubRateLimitHandler.FAIL) .build(); gitHub.getMyself(); @@ -91,7 +93,7 @@ public void testHandler_HttpStatus_Fail() throws Exception { snapshotNotAllowed(); gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()) - .withRateLimitHandler(RateLimitHandler.FAIL) + .withRateLimitHandler(GitHubRateLimitHandler.FAIL) .build(); gitHub.getMyself(); @@ -124,7 +126,7 @@ public void testHandler_Wait() throws Exception { snapshotNotAllowed(); gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()) - .withRateLimitHandler(RateLimitHandler.WAIT) + .withRateLimitHandler(GitHubRateLimitHandler.WAIT) .build(); gitHub.getMyself(); @@ -146,9 +148,9 @@ public void testHandler_WaitStuck() throws Exception { snapshotNotAllowed(); gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()) - .withRateLimitHandler(new RateLimitHandler() { + .withRateLimitHandler(new GitHubRateLimitHandler() { @Override - public void onError(IOException e, HttpURLConnection uc) throws IOException { + public void onError(@Nonnull GitHubConnectorResponse connectorResponse) throws IOException { } }) .build(); diff --git a/src/test/java/org/kohsuke/github/extras/GitHubCachingTest.java b/src/test/java/org/kohsuke/github/extras/GitHubCachingTest.java deleted file mode 100644 index 2ed356555a..0000000000 --- a/src/test/java/org/kohsuke/github/extras/GitHubCachingTest.java +++ /dev/null @@ -1,207 +0,0 @@ -package org.kohsuke.github.extras; - -import com.github.tomakehurst.wiremock.core.WireMockConfiguration; -import com.squareup.okhttp.Cache; -import com.squareup.okhttp.OkHttpClient; -import com.squareup.okhttp.OkUrlFactory; -import org.apache.commons.io.FileUtils; -import org.apache.commons.lang3.SystemUtils; -import org.junit.Assume; -import org.junit.Before; -import org.junit.Test; -import org.kohsuke.github.AbstractGitHubWireMockTest; -import org.kohsuke.github.GHFileNotFoundException; -import org.kohsuke.github.GHIssueState; -import org.kohsuke.github.GHPullRequest; -import org.kohsuke.github.GHRef; -import org.kohsuke.github.GHRepository; -import org.kohsuke.github.GitHub; - -import java.io.File; -import java.io.IOException; - -import static org.junit.Assert.fail; - -// TODO: Auto-generated Javadoc -/** - * Test showing the behavior of OkHttpGitHubConnector cache with GitHub 404 responses. - * - * @author Liam Newman - */ -public class GitHubCachingTest extends AbstractGitHubWireMockTest { - - /** - * Instantiates a new git hub caching test. - */ - public GitHubCachingTest() { - useDefaultGitHub = false; - } - - /** The test ref name. */ - String testRefName = "heads/test/content_ref_cache"; - - /** - * Gets the wire mock options. - * - * @return the wire mock options - */ - @Override - protected WireMockConfiguration getWireMockOptions() { - return super.getWireMockOptions().extensions(templating.newResponseTransformer()); - } - - /** - * Setup repo. - * - * @throws Exception - * the exception - */ - @Before - public void setupRepo() throws Exception { - if (mockGitHub.isUseProxy()) { - for (GHPullRequest pr : getRepository(this.getNonRecordingGitHub()).getPullRequests(GHIssueState.OPEN)) { - pr.close(); - } - try { - GHRef ref = getRepository(this.getNonRecordingGitHub()).getRef(testRefName); - ref.delete(); - } catch (IOException e) { - } - } - } - - /** - * Test cached 404. - * - * @throws Exception - * the exception - */ - @Test - public void testCached404() throws Exception { - Assume.assumeFalse(SystemUtils.IS_OS_WINDOWS); - - // ISSUE #669 - snapshotNotAllowed(); - - OkHttpClient client = createClient(true); - OkHttpConnector connector = new OkHttpConnector(new OkUrlFactory(client)); - - this.gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()) - .withConnector(connector) - .build(); - - // Alternate client also doing caching but staying in a good state - // We use this to do sanity checks and other information gathering - GitHub gitHub2 = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()) - .withConnector(new OkHttpConnector(new OkUrlFactory(createClient(true)))) - .build(); - - // Create a branch from a known conflicting branch - GHRepository repo = getRepository(gitHub); - - String baseSha = repo.getRef("heads/test/unmergeable").getObject().getSha(); - - GHRef ref; - ref = repo.createRef("refs/" + testRefName, baseSha); - - // Verify we can query the created ref - ref = repo.getRef(testRefName); - - // Verify we can query the created ref from cache - ref = repo.getRef(testRefName); - - // Delete the ref - ref.delete(); - - // This is just to show this isn't a race condition - Thread.sleep(2000); - - // Try to get the non-existant ref (GHFileNotFound) - try { - repo.getRef(testRefName); - fail(); - } catch (GHFileNotFoundException e) { - // expected - - // FYI: Querying again when the item is actually not present does not produce a 304 - // It produces another 404, - // Try to get the non-existant ref (GHFileNotFound) - try { - repo.getRef(testRefName); - fail(); - } catch (GHFileNotFoundException ex) { - // expected - } - - } - - // This is just to show this isn't a race condition - Thread.sleep(2000); - - ref = repo.createRef("refs/" + testRefName, baseSha); - - // Verify ref exists and can be queried from uncached connection - // Expected: success - // Actual: still GHFileNotFound due to caching: GitHub incorrectly returns 304 - // even though contents of the ref have changed. - // - // There source of this issue seems to be that 404's do not return an ETAG, - // so the cache falls back to using "If-Modified-Since" which is erroneously returns a 304. - // - // NOTE: This is even worse than you might think: 404 responses don't return an ETAG, but 304 responses do. - // - // Due erroneous 304 returned from "If-Modified-Since", the ETAG returned by the first 304 - // is actually the ETAG for the NEW state of the ref query (the one where the ref exists). - // This can be verified by comparing the ETAG from gitHub2 client to the ETAG in error. - // - // This means that server thinks it telling the client that the new state is stable - // while the cache thinks it confirming the old state hasn't changed. - // - // So, after the first 304, the failure is locked in via ETAG and won't until the ref is modified again - // or until the cache ages out entry without the URL being requeried (which is why users report that refreshing - // is now help). - - try { - repo.getRef(testRefName); - } catch (GHFileNotFoundException e) { - // Sanity check: ref exists and can be queried from other client - getRepository(gitHub2).getRef(testRefName); - - // We're going to fail, query again to see the incorrect ETAG cached from first query being used - // It is the same ETAG as the one returned to the second client. - // Now we're in trouble. - repo.getRef(testRefName); - - // We should never fail the first query and pass the second, - // the test has still failed if it get here. - fail(); - } - - // OMG, the workaround succeeded! - // This correct response should be generated from a 304. - repo.getRef(testRefName); - } - - private static int clientCount = 0; - - private OkHttpClient createClient(boolean useCache) throws IOException { - OkHttpClient client = new OkHttpClient(); - - if (useCache) { - File cacheDir = new File( - "target/cache/" + baseFilesClassPath + "/" + mockGitHub.getMethodName() + clientCount++); - cacheDir.mkdirs(); - FileUtils.cleanDirectory(cacheDir); - Cache cache = new Cache(cacheDir, 100 * 1024L * 1024L); - - client.setCache(cache); - } - - return client; - } - - private static GHRepository getRepository(GitHub gitHub) throws IOException { - return gitHub.getOrganization("hub4j-test-org").getRepository("github-api"); - } - -} diff --git a/src/test/java/org/kohsuke/github/extras/OkHttpConnectorTest.java b/src/test/java/org/kohsuke/github/extras/OkHttpConnectorTest.java deleted file mode 100644 index 454c2fb032..0000000000 --- a/src/test/java/org/kohsuke/github/extras/OkHttpConnectorTest.java +++ /dev/null @@ -1,329 +0,0 @@ -package org.kohsuke.github.extras; - -import com.github.tomakehurst.wiremock.core.WireMockConfiguration; -import com.squareup.okhttp.Cache; -import com.squareup.okhttp.OkHttpClient; -import com.squareup.okhttp.OkUrlFactory; -import org.apache.commons.io.FileUtils; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.kohsuke.github.*; - -import java.io.File; -import java.io.IOException; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.hamcrest.core.Is.is; -import static org.junit.Assume.assumeFalse; -import static org.junit.Assume.assumeTrue; - -// TODO: Auto-generated Javadoc -/** - * Test showing the behavior of OkHttpGitHubConnector with and without cache. - *

    - * Key take aways: - * - *

      - *
    • 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.
    • - *
    - * - * @author Liam Newman - */ -public class OkHttpConnectorTest extends AbstractGitHubWireMockTest { - - /** - * Instantiates a new ok http connector test. - */ - public OkHttpConnectorTest() { - useDefaultGitHub = false; - } - - private static int defaultRateLimitUsed = 17; - private static int okhttpRateLimitUsed = 17; - private static int maxAgeZeroRateLimitUsed = 7; - private static int maxAgeThreeRateLimitUsed = 7; - private static int maxAgeNoneRateLimitUsed = 4; - - private static int userRequestCount = 0; - - private static int defaultNetworkRequestCount = 16; - private static int okhttpNetworkRequestCount = 16; - private static int maxAgeZeroNetworkRequestCount = 16; - private static int maxAgeThreeNetworkRequestCount = 9; - private static int maxAgeNoneNetworkRequestCount = 5; - - private static int maxAgeZeroHitCount = 10; - private static int maxAgeThreeHitCount = 10; - private static int maxAgeNoneHitCount = 11; - - private GHRateLimit rateLimitBefore; - - /** - * Gets the wire mock options. - * - * @return the wire mock options - */ - @Override - protected WireMockConfiguration getWireMockOptions() { - return super.getWireMockOptions().extensions(templating.newResponseTransformer()); - } - - /** - * Setup repo. - * - * @throws Exception - * the exception - */ - @Before - public void setupRepo() throws Exception { - if (mockGitHub.isUseProxy()) { - GHRepository repo = getRepository(getNonRecordingGitHub()); - repo.setDescription("Resetting"); - - // Let things settle a bit between tests when working against the live site - Thread.sleep(5000); - userRequestCount = 1; - } - } - - /** - * Default connector. - * - * @throws Exception - * the exception - */ - @Test - public void DefaultConnector() throws Exception { - - this.gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()).build(); - - doTestActions(); - - // Testing behavior after change - // Uncached connection gets updated correctly but at cost of rate limit - assertThat(getRepository(gitHub).getDescription(), is("Tricky")); - - checkRequestAndLimit(defaultNetworkRequestCount, defaultRateLimitUsed); - } - - /** - * Ok http connector no cache. - * - * @throws Exception - * the exception - */ - @Test - 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(); - - doTestActions(); - - // Testing behavior after change - // Uncached okhttp connection gets updated correctly but at cost of rate limit - assertThat(getRepository(gitHub).getDescription(), is("Tricky")); - - checkRequestAndLimit(okhttpNetworkRequestCount, okhttpRateLimitUsed); - - Cache cache = client.getCache(); - assertThat("Cache", cache, is(nullValue())); - } - - /** - * Ok http connector cache max age none. - * - * @throws Exception - * the exception - */ - @Test - public void OkHttpConnector_Cache_MaxAgeNone() throws Exception { - // The responses were recorded from github, but the Date headers - // have been templated to make caching behavior work as expected. - // This is reasonable as long as the number of network requests matches up. - snapshotNotAllowed(); - - OkHttpClient client = createClient(true); - OkHttpConnector connector = new OkHttpConnector(new OkUrlFactory(client), -1); - - this.gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()) - .withConnector(connector) - .build(); - - doTestActions(); - - // Testing behavior after change - // 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())); - - checkRequestAndLimit(maxAgeNoneNetworkRequestCount, maxAgeNoneRateLimitUsed); - - Cache cache = client.getCache(); - - // NOTE: this is actually bad. - // This elevated hit count is the stale requests returning bad data took longer to detect a change. - assertThat("getHitCount", cache.getHitCount(), is(maxAgeNoneHitCount)); - } - - /** - * Ok http connector cache max age three. - * - * @throws Exception - * the exception - */ - @Test - public void OkHttpConnector_Cache_MaxAge_Three() throws Exception { - - // NOTE: This test is very timing sensitive. - // It can be run locally to verify behavior but snapshot data is to touchy - 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(); - - doTestActions(); - - // Due to max-age=3 this eventually checks the site and gets updated information. Yay? - assertThat(getRepository(gitHub).getDescription(), is("Tricky")); - - checkRequestAndLimit(maxAgeThreeNetworkRequestCount, maxAgeThreeRateLimitUsed); - - Cache cache = client.getCache(); - assertThat("getHitCount", cache.getHitCount(), is(maxAgeThreeHitCount)); - } - - /** - * Ok http connector cache max age default zero. - * - * @throws Exception - * the exception - */ - @Ignore("ISSUE #597 - Correctly formatted Last-Modified headers cause this test to fail") - @Test - public void OkHttpConnector_Cache_MaxAgeDefault_Zero() throws Exception { - // The responses were recorded from github, but the Date headers - // have been templated to make caching behavior work as expected. - // This is reasonable as long as the number of network requests matches up. - snapshotNotAllowed(); - - OkHttpClient client = createClient(true); - OkHttpConnector connector = new OkHttpConnector(new OkUrlFactory(client)); - - this.gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()) - .withConnector(connector) - .build(); - - doTestActions(); - - // Testing behavior after change - // NOTE: max-age=0 produces the same result at uncached without added rate-limit use. - assertThat(getRepository(gitHub).getDescription(), is("Tricky")); - - checkRequestAndLimit(maxAgeZeroNetworkRequestCount, maxAgeZeroRateLimitUsed); - - Cache cache = client.getCache(); - assertThat("getHitCount", cache.getHitCount(), is(maxAgeZeroHitCount)); - } - - private void checkRequestAndLimit(int networkRequestCount, int rateLimitUsed) throws IOException { - GHRateLimit rateLimitAfter = gitHub.rateLimit(); - 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))); - - } - - private OkHttpClient createClient(boolean useCache) throws IOException { - OkHttpClient client = new OkHttpClient(); - - if (useCache) { - File cacheDir = new File("target/cache/" + baseFilesClassPath + "/" + mockGitHub.getMethodName()); - cacheDir.mkdirs(); - FileUtils.cleanDirectory(cacheDir); - Cache cache = new Cache(cacheDir, 100 * 1024L * 1024L); - - client.setCache(cache); - } - - return client; - } - - /** - * This is a standard set of actions to be performed with each connector - * - * @throws Exception - */ - private void doTestActions() throws Exception { - rateLimitBefore = gitHub.getRateLimit(); - - String name = mockGitHub.getMethodName(); - - GHRepository repo = getRepository(gitHub); - - // Testing behavior when nothing has changed. - pollForChange("Resetting"); - assertThat(getRepository(gitHub).getDescription(), is("Resetting")); - - repo.setDescription(name); - - pollForChange(name); - - // 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(getNonRecordingGitHub()); - altRepo.setDescription("Tricky"); - } - - // Testing behavior after change - pollForChange("Tricky"); - } - - 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 - 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 - if (mockGitHub.isUseProxy()) { - Thread.sleep(4000); - } - } - - private static GHRepository getRepository(GitHub gitHub) throws IOException { - return gitHub.getOrganization("hub4j-test-org").getRepository("github-api"); - } - -} diff --git a/src/test/java/org/kohsuke/github/extras/authorization/AuthorizationTokenRefreshTest.java b/src/test/java/org/kohsuke/github/extras/authorization/AuthorizationTokenRefreshTest.java index 55c2431685..00b268912b 100644 --- a/src/test/java/org/kohsuke/github/extras/authorization/AuthorizationTokenRefreshTest.java +++ b/src/test/java/org/kohsuke/github/extras/authorization/AuthorizationTokenRefreshTest.java @@ -4,7 +4,7 @@ import org.junit.Test; import org.kohsuke.github.AbstractGitHubWireMockTest; import org.kohsuke.github.GHUser; -import org.kohsuke.github.RateLimitHandler; +import org.kohsuke.github.GitHubRateLimitHandler; import org.kohsuke.github.authorization.AuthorizationProvider; import java.io.IOException; @@ -42,7 +42,7 @@ public void testNewWhenOldOneExpires() throws IOException { snapshotNotAllowed(); gitHub = getGitHubBuilder().withAuthorizationProvider(new RefreshingAuthorizationProvider()) .withEndpoint(mockGitHub.apiServer().baseUrl()) - .withRateLimitHandler(RateLimitHandler.WAIT) + .withRateLimitHandler(GitHubRateLimitHandler.WAIT) .build(); final GHUser kohsuke = gitHub.getUser("kohsuke"); assertThat("Usernames match", "kohsuke".equals(kohsuke.getLogin())); @@ -58,7 +58,7 @@ public void testNewWhenOldOneExpires() throws IOException { public void testNotNewWhenOldOneIsStillValid() throws IOException { gitHub = getGitHubBuilder().withAuthorizationProvider(() -> "original token") .withEndpoint(mockGitHub.apiServer().baseUrl()) - .withRateLimitHandler(RateLimitHandler.WAIT) + .withRateLimitHandler(GitHubRateLimitHandler.WAIT) .build(); final GHUser kohsuke = gitHub.getUser("kohsuke"); assertThat("Usernames match", "kohsuke".equals(kohsuke.getLogin())); diff --git a/src/test/java/org/kohsuke/github/extras/okhttp3/OkHttpConnectorTest.java b/src/test/java/org/kohsuke/github/extras/okhttp3/OkHttpConnectorTest.java deleted file mode 100644 index 470147f2e1..0000000000 --- a/src/test/java/org/kohsuke/github/extras/okhttp3/OkHttpConnectorTest.java +++ /dev/null @@ -1,348 +0,0 @@ -package org.kohsuke.github.extras.okhttp3; - -import com.github.tomakehurst.wiremock.core.WireMockConfiguration; -import com.github.tomakehurst.wiremock.matching.RequestPatternBuilder; -import okhttp3.Cache; -import okhttp3.OkHttpClient; -import org.apache.commons.io.FileUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.kohsuke.github.AbstractGitHubWireMockTest; -import org.kohsuke.github.GHRateLimit; -import org.kohsuke.github.GHRepository; -import org.kohsuke.github.GitHub; - -import java.io.File; -import java.io.IOException; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.lessThanOrEqualTo; -import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.core.Is.is; -import static org.junit.Assume.assumeFalse; -import static org.junit.Assume.assumeTrue; - -// TODO: Auto-generated Javadoc -/** - * Test showing the behavior of OkHttpConnector with and without cache. - *

    - * Key take aways: - * - *

      - *
    • 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.
    • - *
    - * - * @author Liam Newman - */ -public class OkHttpConnectorTest extends AbstractGitHubWireMockTest { - - /** - * Instantiates a new ok http connector test. - */ - public OkHttpConnectorTest() { - useDefaultGitHub = false; - } - - private static int defaultRateLimitUsed = 17; - private static int okhttpRateLimitUsed = 17; - private static int maxAgeZeroRateLimitUsed = 7; - private static int maxAgeThreeRateLimitUsed = 7; - private static int maxAgeNoneRateLimitUsed = 4; - - private static int userRequestCount = 0; - - private static int defaultNetworkRequestCount = 16; - private static int okhttpNetworkRequestCount = 16; - private static int maxAgeZeroNetworkRequestCount = 16; - private static int maxAgeThreeNetworkRequestCount = 9; - private static int maxAgeNoneNetworkRequestCount = 5; - - private static int maxAgeZeroHitCount = 10; - private static int maxAgeThreeHitCount = 10; - private static int maxAgeNoneHitCount = 11; - - private GHRateLimit rateLimitBefore; - private Cache cache = null; - - /** - * Gets the wire mock options. - * - * @return the wire mock options - */ - @Override - protected WireMockConfiguration getWireMockOptions() { - return super.getWireMockOptions() - // Use the same data files as the 2.x test - .usingFilesUnderDirectory(baseRecordPath.replace("/okhttp3/", "/")) - .extensions(templating.newResponseTransformer()); - } - - /** - * Setup repo. - * - * @throws Exception - * the exception - */ - @Before - public void setupRepo() throws Exception { - if (mockGitHub.isUseProxy()) { - GHRepository repo = getRepository(getNonRecordingGitHub()); - repo.setDescription("Resetting"); - - // Let things settle a bit between tests when working against the live site - Thread.sleep(5000); - userRequestCount = 1; - } - } - - /** - * Delete cache. - * - * @throws IOException - * Signals that an I/O exception has occurred. - */ - @After - public void deleteCache() throws IOException { - if (cache != null) { - cache.delete(); - } - } - - /** - * Default connector. - * - * @throws Exception - * the exception - */ - @Test - public void DefaultConnector() throws Exception { - - this.gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()).build(); - - doTestActions(); - - // Testing behavior after change - // Uncached connection gets updated correctly but at cost of rate limit - assertThat(getRepository(gitHub).getDescription(), is("Tricky")); - - checkRequestAndLimit(defaultNetworkRequestCount, defaultRateLimitUsed); - } - - /** - * Ok http connector no cache. - * - * @throws Exception - * the exception - */ - @Test - 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(); - - doTestActions(); - - // Testing behavior after change - // Uncached okhttp connection gets updated correctly but at cost of rate limit - assertThat(getRepository(gitHub).getDescription(), is("Tricky")); - - checkRequestAndLimit(okhttpNetworkRequestCount, okhttpRateLimitUsed); - - assertThat("Cache", cache, is(nullValue())); - } - - /** - * Ok http connector cache max age none. - * - * @throws Exception - * the exception - */ - @Test - public void OkHttpConnector_Cache_MaxAgeNone() throws Exception { - // The responses were recorded from github, but the Date headers - // have been templated to make caching behavior work as expected. - // This is reasonable as long as the number of network requests matches up. - snapshotNotAllowed(); - - OkHttpClient client = createClient(true); - OkHttpConnector connector = new OkHttpConnector(client, -1); - - this.gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()) - .withConnector(connector) - .build(); - - doTestActions(); - - // Testing behavior after change - // 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())); - - checkRequestAndLimit(maxAgeNoneNetworkRequestCount, maxAgeNoneRateLimitUsed); - - // NOTE: this is actually bad. - // This elevated hit count is the stale requests returning bad data took longer to detect a change. - assertThat("getHitCount", cache.hitCount(), is(maxAgeNoneHitCount)); - } - - /** - * Ok http connector cache max age three. - * - * @throws Exception - * the exception - */ - @Test - public void OkHttpConnector_Cache_MaxAge_Three() throws Exception { - - // NOTE: This test is very timing sensitive. - // It can be run locally to verify behavior but snapshot data is to touchy - 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(); - - doTestActions(); - - // Due to max-age=3 this eventually checks the site and gets updated information. Yay? - assertThat(getRepository(gitHub).getDescription(), is("Tricky")); - - checkRequestAndLimit(maxAgeThreeNetworkRequestCount, maxAgeThreeRateLimitUsed); - - assertThat("getHitCount", cache.hitCount(), is(maxAgeThreeHitCount)); - } - - /** - * Ok http connector cache max age default zero. - * - * @throws Exception - * the exception - */ - @Test - public void OkHttpConnector_Cache_MaxAgeDefault_Zero() throws Exception { - // The responses were recorded from github, but the Date headers - // have been templated to make caching behavior work as expected. - // This is reasonable as long as the number of network requests matches up. - snapshotNotAllowed(); - - OkHttpClient client = createClient(true); - OkHttpConnector connector = new OkHttpConnector(client); - - this.gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()) - .withConnector(connector) - .build(); - - doTestActions(); - - // Testing behavior after change - // NOTE: max-age=0 produces the same result at uncached without added rate-limit use. - assertThat(getRepository(gitHub).getDescription(), is("Tricky")); - - checkRequestAndLimit(maxAgeZeroNetworkRequestCount, maxAgeZeroRateLimitUsed); - - assertThat("getHitCount", cache.hitCount(), is(maxAgeZeroHitCount)); - } - - private void checkRequestAndLimit(int networkRequestCount, int rateLimitUsed) throws IOException { - GHRateLimit rateLimitAfter = gitHub.rateLimit(); - 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))); - - } - - private int getRequestCount() { - return mockGitHub.apiServer().countRequestsMatching(RequestPatternBuilder.allRequests().build()).getCount(); - } - - private OkHttpClient createClient(boolean useCache) throws IOException { - OkHttpClient.Builder builder = new OkHttpClient().newBuilder(); - - if (useCache) { - File cacheDir = new File("target/cache/" + baseFilesClassPath + "/" + mockGitHub.getMethodName()); - cacheDir.mkdirs(); - FileUtils.cleanDirectory(cacheDir); - cache = new Cache(cacheDir, 100 * 1024L * 1024L); - - builder.cache(cache); - } - - return builder.build(); - } - - /** - * This is a standard set of actions to be performed with each connector - * - * @throws Exception - */ - private void doTestActions() throws Exception { - rateLimitBefore = gitHub.getRateLimit(); - - String name = mockGitHub.getMethodName(); - - GHRepository repo = getRepository(gitHub); - - // Testing behavior when nothing has changed. - pollForChange("Resetting"); - assertThat(getRepository(gitHub).getDescription(), is("Resetting")); - - repo.setDescription(name); - - pollForChange(name); - - // 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(getNonRecordingGitHub()); - altRepo.setDescription("Tricky"); - } - - // Testing behavior after change - pollForChange("Tricky"); - } - - 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 - 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 - if (mockGitHub.isUseProxy()) { - Thread.sleep(4000); - } - } - - private static GHRepository getRepository(GitHub gitHub) throws IOException { - return gitHub.getOrganization("hub4j-test-org").getRepository("github-api"); - } - -} diff --git a/src/test/java/org/kohsuke/github/internal/DefaultGitHubConnectorTest.java b/src/test/java/org/kohsuke/github/internal/DefaultGitHubConnectorTest.java index 997298debb..c908d46034 100644 --- a/src/test/java/org/kohsuke/github/internal/DefaultGitHubConnectorTest.java +++ b/src/test/java/org/kohsuke/github/internal/DefaultGitHubConnectorTest.java @@ -9,7 +9,6 @@ import org.kohsuke.github.connector.GitHubConnectorRequest; import org.kohsuke.github.connector.GitHubConnectorResponse; import org.kohsuke.github.extras.HttpClientGitHubConnector; -import org.kohsuke.github.extras.okhttp3.OkHttpConnector; import java.io.IOException; @@ -58,16 +57,6 @@ public void testCreate() throws Exception { assertThat(adapter.httpConnector, equalTo(HttpConnector.DEFAULT)); } - connector = DefaultGitHubConnector.create("urlconnection"); - assertThat(connector, instanceOf(GitHubConnectorHttpConnectorAdapter.class)); - adapter = (GitHubConnectorHttpConnectorAdapter) connector; - assertThat(adapter.httpConnector, equalTo(HttpConnector.DEFAULT)); - - connector = DefaultGitHubConnector.create("okhttpconnector"); - assertThat(connector, instanceOf(GitHubConnectorHttpConnectorAdapter.class)); - adapter = (GitHubConnectorHttpConnectorAdapter) connector; - assertThat(adapter.httpConnector, instanceOf(OkHttpConnector.class)); - connector = DefaultGitHubConnector.create("okhttp"); Assert.assertThrows(IllegalStateException.class, () -> DefaultGitHubConnector.create("")); @@ -83,9 +72,5 @@ public GitHubConnectorResponse send(GitHubConnectorRequest connectorRequest) thr throw new IOException(); } }).build(); - Assert.assertThrows(UnsupportedOperationException.class, () -> gitHub.getConnector()); - gitHub.setConnector((HttpConnector) GitHubConnector.OFFLINE); - // Doesn't throw when HttpConnect is implemented - gitHub.getConnector(); } } diff --git a/src/test/resources/org/kohsuke/github/AppTest/wiremock/testGetDeploymentStatuses/mappings/4-r_h_g_deployments_315601644_statuses.json b/src/test/resources/org/kohsuke/github/AppTest/wiremock/testGetDeploymentStatuses/mappings/4-r_h_g_deployments_315601644_statuses.json index 6618ee85ed..95ff9c2aac 100644 --- a/src/test/resources/org/kohsuke/github/AppTest/wiremock/testGetDeploymentStatuses/mappings/4-r_h_g_deployments_315601644_statuses.json +++ b/src/test/resources/org/kohsuke/github/AppTest/wiremock/testGetDeploymentStatuses/mappings/4-r_h_g_deployments_315601644_statuses.json @@ -11,7 +11,7 @@ }, "bodyPatterns": [ { - "equalToJson": "{\"environment\":\"new-ci-env\",\"environment_url\":\"http://www.github.com/envurl\",\"target_url\":\"http://www.github.com\",\"log_url\":\"http://www.github.com/logurl\",\"description\":\"success\",\"state\":\"queued\"}", + "equalToJson": "{\"environment\":\"new-ci-env\",\"environment_url\":\"http://www.github.com/envurl\",\"log_url\":\"http://www.github.com/logurl\",\"description\":\"success\",\"state\":\"queued\"}", "ignoreArrayOrder": true, "ignoreExtraElements": false }