package com.cloudbees.jenkins;

import hudson.Extension;
import hudson.Util;
import hudson.model.AbstractDescribableImpl;
import hudson.model.Descriptor;
import hudson.util.FormValidation;
import hudson.util.Secret;
import org.kohsuke.github.GitHub;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;

import java.io.IOException;

/**
 * Credential to access GitHub.
 *
 * @author Kohsuke Kawaguchi
 */
public class Credential extends AbstractDescribableImpl<Credential> {
    public final String username;
    public final String apiUrl;
    public final String oauthAccessToken;

    @DataBoundConstructor
    public Credential(String username, String apiUrl, String oauthAccessToken) {
        this.username = username;
        this.apiUrl = apiUrl;
        this.oauthAccessToken = oauthAccessToken;
    }

    public GitHub login() throws IOException {
        if (Util.fixEmpty(apiUrl) != null) {
            return GitHub.connectToEnterprise(apiUrl,oauthAccessToken);
        }
        return GitHub.connect(username,oauthAccessToken);
    }

    @Extension
    public static class DescriptorImpl extends Descriptor<Credential> {
        @Override
        public String getDisplayName() {
            return ""; // unused
        }

        public FormValidation doValidate(@QueryParameter String apiUrl, @QueryParameter String username, @QueryParameter String oauthAccessToken) throws IOException {
            GitHub gitHub;
            if (Util.fixEmpty(apiUrl) != null) {
                gitHub = GitHub.connectToEnterprise(apiUrl,oauthAccessToken);
            } else {
                gitHub = GitHub.connect(username,oauthAccessToken);
            }

            if (gitHub.isCredentialValid())
                return FormValidation.ok("Verified");
            else
                return FormValidation.error("Failed to validate the account");
        }
    }
}

@@ -1432,32 +1432,54 @@
 s IOException %7B%0A
+            try %7B%0A    
             GitH
@@ -1493,32 +1493,36 @@
 ub;%0A            
+  
+  
 if (Util.fixEmpt
@@ -1534,32 +1534,36 @@
 Url) != null) %7B%0A
+    
                 
@@ -1636,16 +1636,20 @@
         
+    
 %7D else %7B
@@ -1657,32 +1657,36 @@
                 
+  
+  
 gitHub = GitHub.
@@ -1725,35 +1725,43 @@
 n);%0A            
-%7D%0A%0A
+    %7D%0A%0A    
             if (
@@ -1796,32 +1796,36 @@
                 
+  
+  
 return FormValid
@@ -1862,13 +1862,21 @@
     
+    
 else%0A
+    
     
@@ -1946,24 +1946,157 @@
  account%22);%0A
+            %7D catch (IOException e) %7B%0A                return FormValidation.error(e,%22Failed to validate the account%22);%0A            %7D%0A
         %7D%0A  

Handle errors gracefully, such as a failure to resolve a host name in case it is invalid.