From ae85cf4b6c02ba9c330d436bbee39d211428755d Mon Sep 17 00:00:00 2001 From: Manuel Recena Date: Sat, 5 Mar 2016 17:42:25 +0100 Subject: [PATCH] Improve checkApiUrlValidity() method to support the private mode in GitHub Enterprise servers --- src/main/java/org/kohsuke/github/GitHub.java | 30 ++++++++++++++++++- .../java/org/kohsuke/github/GitHubTest.java | 7 ++++- 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/kohsuke/github/GitHub.java b/src/main/java/org/kohsuke/github/GitHub.java index 77d178800c..14e7b13368 100644 --- a/src/main/java/org/kohsuke/github/GitHub.java +++ b/src/main/java/org/kohsuke/github/GitHub.java @@ -31,6 +31,7 @@ import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; +import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.text.ParseException; @@ -482,7 +483,34 @@ void check(String apiUrl) throws IOException { * Otherwise this method throws {@link IOException} to indicate the problem. */ public void checkApiUrlValidity() throws IOException { - retrieve().to("/", GHApiInfo.class).check(apiUrl); + try { + retrieve().to("/", GHApiInfo.class).check(apiUrl); + } catch (IOException ioe) { + if (isPrivateModeEnabled()) { + throw new IOException("GitHub Enterprise server (" + apiUrl + ") with private mode enabled"); + } + throw ioe; + } + } + + /** + * Ensures if a GitHub Enterprise server is configured in private mode. + * + * @return {@code true} if private mode is enabled. If it tries to use this method with GitHub, returns {@code + * false}. + */ + private boolean isPrivateModeEnabled() { + try { + HttpURLConnection connect = getConnector().connect(getApiURL("/")); + if (connect.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED + && connect.getHeaderField("Server") != null + && connect.getHeaderField("Server").equals("GitHub.com")) { + return true; + } + return false; + } catch (IOException e) { + return false; + } } /** diff --git a/src/test/java/org/kohsuke/github/GitHubTest.java b/src/test/java/org/kohsuke/github/GitHubTest.java index 1663d24144..b8ae4ff0df 100644 --- a/src/test/java/org/kohsuke/github/GitHubTest.java +++ b/src/test/java/org/kohsuke/github/GitHubTest.java @@ -124,6 +124,11 @@ public void testGitHubEnterpriseDoesNotHaveRateLimit() throws IOException { @Test public void testGitHubIsApiUrlValid() throws IOException { GitHub github = GitHub.connectAnonymously(); - github.checkApiUrlValidity(); + //GitHub github = GitHub.connectToEnterpriseAnonymously("https://github.mycompany.com/api/v3/"); + try { + github.checkApiUrlValidity(); + } catch (IOException ioe) { + assertTrue(ioe.getMessage().contains("private mode enabled")); + } } }