com.zaubersoftware.mule.module.jenkins.api.impl.HttpJenkinsService.java Source code

Java tutorial

Introduction

Here is the source code for com.zaubersoftware.mule.module.jenkins.api.impl.HttpJenkinsService.java

Source

/**
 * Copyright (c) 2011 Zauber S.A. <http://www.zaubersoftware.com>
 *
 * 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.
 */
package com.zaubersoftware.mule.module.jenkins.api.impl;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.ws.rs.core.MediaType;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.NotImplementedException;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientRequest;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
import com.sun.jersey.core.header.MediaTypes;
import com.zaubersoftware.mule.module.jenkins.api.JenkinsService;

public class HttpJenkinsService implements JenkinsService {
    private final Logger logger = LoggerFactory.getLogger(HttpJenkinsService.class);
    private final WebResource webResource;

    public HttpJenkinsService(final URI jenkinsBaseURL) throws KeyManagementException, NoSuchAlgorithmException {
        this(jenkinsBaseURL, null, null);
    }

    public HttpJenkinsService(final URI jenkinsBaseURL, final String jenkinsUsername, final String jenkinsPassword)
            throws KeyManagementException, NoSuchAlgorithmException {
        Validate.notNull(jenkinsBaseURL);

        final DefaultClientConfig config = new DefaultClientConfig();
        addSslConfiguration();
        config.getClasses().add(ClientRequest.class);
        config.getClasses().add(ClientResponse.class);

        final Client client = Client.create(config);
        if (jenkinsUsername != null && jenkinsPassword != null) {
            client.addFilter(new HTTPBasicAuthFilter(jenkinsUsername, jenkinsPassword));
        }
        webResource = client.resource(jenkinsBaseURL);
    }

    protected void addSslConfiguration() throws NoSuchAlgorithmException, KeyManagementException {
        final SSLContext ctx = SSLContext.getInstance("SSL");

        ctx.init(null, null, null);
    }

    @Override
    public boolean exists(final String projectName) {
        validateProjectName(projectName);
        final ClientResponse response = webResource.path("/job/" + encode(projectName) + "/")
                .get(ClientResponse.class);
        return response.getStatus() == 200;
    }

    @Override
    public void create(final String projectName, final InputStream template) {
        try {
            final ClientResponse response = webResource.path("/createItem/").queryParam("name", projectName)
                    .entity(template, MediaType.APPLICATION_XML).post(ClientResponse.class);
            if (response.getStatus() != 200) {
                throw new IllegalArgumentException("response status " + response.getStatus() + " "
                        + response.getClientResponseStatus().getReasonPhrase());
            }
        } finally {
            IOUtils.closeQuietly(template);
        }
    }

    @Override
    public void build(final String projectName) {
        validateProjectName(projectName);
        final ClientResponse response = webResource.path("/job/" + encode(projectName) + "/build")
                .get(ClientResponse.class);
        if (response.getStatus() != 200) {
            logger.warn("The project '{}' could not be built, response status: {}", projectName,
                    response.getStatus());
            throw new RuntimeException("response status: " + response.getStatus());
        }
    }

    private void validateProjectName(final String projectName) {
        Validate.isTrue(StringUtils.isNotBlank(projectName));
    }

    private String encode(final String url) {
        try {
            return URLEncoder.encode(url, "utf-8");
        } catch (final UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}