Search in sources :

Example 1 with GitHubConfiguration

use of org.jenkinsci.plugins.github_branch_source.GitHubConfiguration in project blueocean-plugin by jenkinsci.

the class GithubPipelineCreateRequest method updateEndpoints.

private void updateEndpoints(String apiUrl) {
    GitHubConfiguration config = GitHubConfiguration.get();
    synchronized (config) {
        final String finalApiUrl = apiUrl;
        Optional<Endpoint> optionalEndpoint = config.getEndpoints().stream().filter(input -> input != null && input.getApiUri().equals(finalApiUrl)).findFirst();
        Endpoint endpoint = optionalEndpoint.orElse(null);
        if (endpoint == null) {
            config.setEndpoints(Collections.singletonList(new Endpoint(apiUrl, apiUrl)));
            config.save();
        }
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) GitHubSCMSource(org.jenkinsci.plugins.github_branch_source.GitHubSCMSource) BlueOceanDomainRequirement(io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainRequirement) DataBoundConstructor(org.kohsuke.stapler.DataBoundConstructor) MultiBranchProject(jenkins.branch.MultiBranchProject) GitHubSCMSourceBuilder(org.jenkinsci.plugins.github_branch_source.GitHubSCMSourceBuilder) StringUtils(org.apache.commons.lang3.StringUtils) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) SCMSource(jenkins.scm.api.SCMSource) AbstractScmSourceEvent(io.jenkins.blueocean.scm.api.AbstractScmSourceEvent) NonNull(edu.umd.cs.findbugs.annotations.NonNull) ChangeRequestCheckoutStrategy(jenkins.scm.api.mixin.ChangeRequestCheckoutStrategy) CredentialsUtils(io.jenkins.blueocean.credential.CredentialsUtils) AbstractMultiBranchCreateRequest(io.jenkins.blueocean.scm.api.AbstractMultiBranchCreateRequest) CleanBeforeCheckoutTrait(jenkins.plugins.git.traits.CleanBeforeCheckoutTrait) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) OriginPullRequestDiscoveryTrait(org.jenkinsci.plugins.github_branch_source.OriginPullRequestDiscoveryTrait) CleanAfterCheckoutTrait(jenkins.plugins.git.traits.CleanAfterCheckoutTrait) SCMSourceOwner(jenkins.scm.api.SCMSourceOwner) Set(java.util.Set) IOException(java.io.IOException) LocalBranchTrait(jenkins.plugins.git.traits.LocalBranchTrait) ServiceException(io.jenkins.blueocean.commons.ServiceException) BlueScmConfig(io.jenkins.blueocean.rest.model.BlueScmConfig) ForkPullRequestDiscoveryTrait(org.jenkinsci.plugins.github_branch_source.ForkPullRequestDiscoveryTrait) StandardUsernamePasswordCredentials(com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials) GitHubConfiguration(org.jenkinsci.plugins.github_branch_source.GitHubConfiguration) List(java.util.List) Endpoint(org.jenkinsci.plugins.github_branch_source.Endpoint) BranchDiscoveryTrait(org.jenkinsci.plugins.github_branch_source.BranchDiscoveryTrait) Optional(java.util.Optional) ErrorMessage(io.jenkins.blueocean.commons.ErrorMessage) Collections(java.util.Collections) GitHubConfiguration(org.jenkinsci.plugins.github_branch_source.GitHubConfiguration) Endpoint(org.jenkinsci.plugins.github_branch_source.Endpoint)

Example 2 with GitHubConfiguration

use of org.jenkinsci.plugins.github_branch_source.GitHubConfiguration in project blueocean-plugin by jenkinsci.

the class GithubServerContainer method create.

@CheckForNull
public ScmServerEndpoint create(@JsonBody JSONObject request) {
    try {
        Jenkins.get().checkPermission(Item.CREATE);
    } catch (Exception e) {
        throw new ServiceException.ForbiddenException("User does not have permission to create repository.", e);
    }
    List<ErrorMessage.Error> errors = new LinkedList<>();
    // Validate name
    final String name = (String) request.get(GithubServer.NAME);
    if (StringUtils.isEmpty(name)) {
        errors.add(new ErrorMessage.Error(GithubServer.NAME, ErrorMessage.Error.ErrorCodes.MISSING.toString(), GithubServer.NAME + " is required"));
    } else {
        GithubServer byName = findByName(name);
        if (byName != null) {
            errors.add(new ErrorMessage.Error(GithubServer.NAME, ErrorMessage.Error.ErrorCodes.ALREADY_EXISTS.toString(), GithubServer.NAME + " already exists for server at '" + byName.getApiUrl() + "'"));
        }
    }
    // Validate url
    final String url = (String) request.get(GithubServer.API_URL);
    if (StringUtils.isEmpty(url)) {
        errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.MISSING.toString(), GithubServer.API_URL + " is required"));
    } else {
        Endpoint byUrl = GitHubConfiguration.get().findEndpoint(url);
        if (byUrl != null) {
            errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.ALREADY_EXISTS.toString(), GithubServer.API_URL + " is already registered as '" + byUrl.getName() + "'"));
        }
    }
    if (StringUtils.isNotEmpty(url)) {
        // Validate that the URL represents a GitHub API endpoint
        try {
            HttpURLConnection connection = HttpRequest.get(url).connect();
            if (connection.getHeaderField("X-GitHub-Request-Id") == null) {
                errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.INVALID.toString(), ERROR_MESSAGE_INVALID_SERVER));
            } else {
                boolean isGithubCloud = false;
                boolean isGithubEnterprise = false;
                try {
                    InputStream inputStream;
                    int code = connection.getResponseCode();
                    if (200 <= code && code < 300) {
                        inputStream = HttpRequest.getInputStream(connection);
                    } else {
                        inputStream = HttpRequest.getErrorStream(connection);
                    }
                    TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {
                    };
                    Map<String, String> responseBody = GithubScm.getMappingObjectReader().forType(typeRef).readValue(inputStream);
                    isGithubCloud = code == 200 && responseBody.containsKey("current_user_url");
                    isGithubEnterprise = code == 401 && responseBody.containsKey("message");
                } catch (IllegalArgumentException | IOException ioe) {
                    LOGGER.log(Level.INFO, "Could not parse response body from Github");
                }
                if (!isGithubCloud && !isGithubEnterprise) {
                    errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.INVALID.toString(), ERROR_MESSAGE_INVALID_APIURL));
                }
            }
        } catch (Throwable e) {
            errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.INVALID.toString(), e.toString()));
            LOGGER.log(Level.INFO, "Could not connect to Github", e);
        }
    }
    if (errors.isEmpty()) {
        try (ACLContext ctx = ACL.as(ACL.SYSTEM)) {
            // We need to escalate privilege to add user defined endpoint to
            GitHubConfiguration config = GitHubConfiguration.get();
            String sanitizedUrl = discardQueryString(url);
            Endpoint endpoint = new Endpoint(sanitizedUrl, name);
            if (!config.addEndpoint(endpoint)) {
                errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.ALREADY_EXISTS.toString(), GithubServer.API_URL + " is already registered as '" + endpoint.getName() + "'"));
            } else {
                return new GithubServer(endpoint, getLink());
            }
        }
    }
    ErrorMessage message = new ErrorMessage(400, "Failed to create GitHub server");
    message.addAll(errors);
    throw new ServiceException.BadRequestException(message);
}
Also used : GitHubConfiguration(org.jenkinsci.plugins.github_branch_source.GitHubConfiguration) HashMap(java.util.HashMap) HttpURLConnection(java.net.HttpURLConnection) Endpoint(org.jenkinsci.plugins.github_branch_source.Endpoint) ScmServerEndpoint(io.jenkins.blueocean.rest.impl.pipeline.scm.ScmServerEndpoint) TypeReference(com.fasterxml.jackson.core.type.TypeReference) InputStream(java.io.InputStream) IOException(java.io.IOException) IOException(java.io.IOException) ServiceException(io.jenkins.blueocean.commons.ServiceException) LinkedList(java.util.LinkedList) Endpoint(org.jenkinsci.plugins.github_branch_source.Endpoint) ScmServerEndpoint(io.jenkins.blueocean.rest.impl.pipeline.scm.ScmServerEndpoint) ACLContext(hudson.security.ACLContext) ServiceException(io.jenkins.blueocean.commons.ServiceException) JSONObject(net.sf.json.JSONObject) ErrorMessage(io.jenkins.blueocean.commons.ErrorMessage) CheckForNull(javax.annotation.CheckForNull)

Aggregations

ErrorMessage (io.jenkins.blueocean.commons.ErrorMessage)2 ServiceException (io.jenkins.blueocean.commons.ServiceException)2 IOException (java.io.IOException)2 HttpURLConnection (java.net.HttpURLConnection)2 Endpoint (org.jenkinsci.plugins.github_branch_source.Endpoint)2 GitHubConfiguration (org.jenkinsci.plugins.github_branch_source.GitHubConfiguration)2 StandardUsernamePasswordCredentials (com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials)1 TypeReference (com.fasterxml.jackson.core.type.TypeReference)1 NonNull (edu.umd.cs.findbugs.annotations.NonNull)1 ACLContext (hudson.security.ACLContext)1 CredentialsUtils (io.jenkins.blueocean.credential.CredentialsUtils)1 BlueOceanDomainRequirement (io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainRequirement)1 ScmServerEndpoint (io.jenkins.blueocean.rest.impl.pipeline.scm.ScmServerEndpoint)1 BlueScmConfig (io.jenkins.blueocean.rest.model.BlueScmConfig)1 AbstractMultiBranchCreateRequest (io.jenkins.blueocean.scm.api.AbstractMultiBranchCreateRequest)1 AbstractScmSourceEvent (io.jenkins.blueocean.scm.api.AbstractScmSourceEvent)1 InputStream (java.io.InputStream)1 ArrayList (java.util.ArrayList)1 Collections (java.util.Collections)1 HashMap (java.util.HashMap)1