httputils.RavelloHttpClient.java Source code

Java tutorial

Introduction

Here is the source code for httputils.RavelloHttpClient.java

Source

/**
 * Copyright 2012-2014 Ravello Systems, 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.
 */

package httputils;

import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jenkinsci.plugins.RavelloException;

import javax.json.*;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

public class RavelloHttpClient {
    private static String HOMEADD = "https://cloud.ravellosystems.com/api/v1";
    private HttpClientContext context;
    private CloseableHttpClient client;

    public RavelloHttpClient(String username, String password) {
        this.client = HttpClients.createDefault();

        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(username + ":" + password));
        this.context = HttpClientContext.create();
        this.context.setCredentialsProvider(credentialsProvider);
    }

    public HttpResponse execute(HttpUriRequest request) throws ClientProtocolException, IOException {
        return this.client.execute(request, context);
    }

    public JsonObject publishBlueprint(String applicationName, int blueprintId, int stopTime, int startupDelay,
            String preferredCloud, String preferredRegion, boolean startAllVms, boolean costOptimized)
            throws RavelloException, InterruptedException {
        JsonObject value = null;
        HttpResponse response = null;

        try {
            response = this.getBlueprint(blueprintId);
            if (!HttpUtil.verifyResponseWithoutConsuming(response)) {
                EntityUtils.consumeQuietly(response.getEntity());
                throw new RavelloException("Failed to get blueprint number " + blueprintId + " error: "
                        + response.getStatusLine().toString());
            }
            JsonObject vmTemp = HttpUtil.convertResponseToJson(response);
            EntityUtils.consume(response.getEntity());

            JsonBuilderFactory factory = Json.createBuilderFactory(null);
            Iterator<Map.Entry<String, JsonValue>> it = vmTemp.entrySet().iterator();
            JsonObjectBuilder builder = factory.createObjectBuilder();
            Map.Entry<String, JsonValue> ent;
            while (it.hasNext()) {
                ent = it.next();
                if (!ent.getKey().equals("id") && !ent.getKey().equals("owner")) {
                    builder.add(ent.getKey(), ent.getValue());
                }
            }
            builder.add("name", applicationName);
            value = builder.build();
            vmTemp = null;

            response = this.createApplication(value);
            this.verifyResponseAndConsume(response, "Failed to create application - error: ");

            value = HttpUtil.convertResponseToJson(response);
            EntityUtils.consumeQuietly(response.getEntity());

            int appId = value.getInt("id");

            if (costOptimized) {
                value = factory.createObjectBuilder().add("startAllVms", startAllVms).build();
            } else {
                value = factory.createObjectBuilder().add("startAllVms", startAllVms)
                        .add("preferredCloud", preferredCloud).add("preferredRegion", preferredRegion)
                        .add("optimizationLevel", "PERFORMANCE_OPTIMIZED").build();
            }
            response = this.post("/applications/" + appId + "/publish", value);
            this.verifyResponseAndConsume(response, "Failed to publish application - error: ");

            value = factory.createObjectBuilder().add("expirationFromNowSeconds", stopTime).build();
            response = this.post("/applications/" + appId + "/setExpiration", value);
            if (!HttpUtil.verifyResponseAndConsume(response)) {
                throw new RavelloException("Failed to set expiration time for application - error: "
                        + response.getStatusLine().toString() + "\n"
                        + "THIS ERROR MAY CAUSE APPLICATION TO RUN INDEFINITELY - MAKE SURE TO CHECK IT STOPPED");
            }

            if (!startAllVms) {
                response = this.getApplication(appId);
                if (!HttpUtil.verifyResponseWithoutConsuming(response)) {
                    EntityUtils.consumeQuietly(response.getEntity());
                    throw new RavelloException(
                            "Failed to get application status - error: " + response.getStatusLine().toString());
                }
                value = HttpUtil.convertResponseToJson(response);

                return value;
            }

            String state;
            JsonArray jArr;
            boolean allStarted;
            while (true) {
                allStarted = true;
                response = this.getApplication(appId);
                if (!HttpUtil.verifyResponseWithoutConsuming(response)) {
                    EntityUtils.consumeQuietly(response.getEntity());
                    throw new RavelloException(
                            "Failed to get application status - error: " + response.getStatusLine().toString());
                }
                value = HttpUtil.convertResponseToJson(response);

                jArr = value.getJsonObject("deployment").getJsonArray("vms");
                for (int jt = 0; jt < jArr.size(); jt++) {
                    state = jArr.getJsonObject(jt).getString("state");
                    allStarted = state.equals("STARTED");
                    if (state.equals("ERROR")) {
                        throw new RavelloException(
                                "vm" + jArr.getJsonObject(jt).getString("name") + " failed to start");
                    }
                    if (!allStarted) {
                        break;
                    }
                }

                if (allStarted) {
                    break;
                } else {
                    EntityUtils.consumeQuietly(response.getEntity());
                    Thread.sleep(20000);
                }
            }

        } catch (ClientProtocolException e) {
            throw new RavelloException("ClientProtocolException - " + e.getMessage());
        } catch (IOException e) {
            throw new RavelloException("IOException - " + e.getMessage());
        } catch (NullPointerException e) {
            throw new RavelloException("NullPointerException - " + e.getMessage());
        }

        Thread.sleep(startupDelay * 1000);

        return value;
    }

    public HttpResponse createApplication(JsonObject app) throws IOException {
        return this.post("/applications/", app);
    }

    public HttpResponse stopApplication(int appId) throws IOException {
        return this.post("/applications/" + appId + "/stop");
    }

    public HttpResponse getBlueprint(int bpId) throws IOException {
        return this.get("/blueprints/" + bpId);
    }

    public HttpResponse getApplication(int appId) throws IOException {
        return this.get("/applications/" + appId);
    }

    public HttpResponse post(String path) throws IOException {
        HttpPost req = new HttpPost(HOMEADD + path);
        HttpUtil.setJsonHeaders(req);
        return this.execute(req);
    }

    public HttpResponse post(String path, JsonObject body) throws IOException {
        HttpPost req = new HttpPost(HOMEADD + path);
        HttpUtil.setJsonHeaders(req);
        req.setEntity(new StringEntity(body.toString()));
        return this.execute(req);
    }

    public HttpResponse get(String path) throws IOException {
        HttpGet get = new HttpGet(HOMEADD + path);
        get.addHeader("Accept", "application/json");

        return this.execute(get);
    }

    private void verifyResponseAndConsume(HttpResponse response, String errorPrefix) throws RavelloException {
        if (!HttpUtil.verifyResponseWithoutConsuming(response)) {
            throw new RavelloException(errorPrefix + response.getStatusLine().toString());
        }
    }

    public void close() throws IOException {
        client.close();
    }

}