All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.sealights.agents.plugin.services.BuildSessionIdProxy Maven / Gradle / Ivy

package io.sealights.agents.plugin.services;

import io.sealights.agents.plugin.Utils.JsonSerializer;
import io.sealights.agents.plugin.Utils.StreamUtils;
import io.sealights.agents.plugin.Utils.UrlBuilder;
import io.sealights.agents.plugin.entities.BuildSessionData;
import io.sealights.agents.plugin.upgrade.utils.UserMessageHelper;
import org.apache.maven.plugin.logging.Log;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;

/**
 * Created by shahar on 12/21/2016.
 */
public class BuildSessionIdProxy {

    private UserMessageHelper userMessageHelper;
    private ApacheHttpClient apacheHttpClient;
    private Log logger;

    public BuildSessionIdProxy(ApacheHttpClient apacheHttpClient, UserMessageHelper userMessageHelper, Log logger) {
        this.apacheHttpClient = apacheHttpClient;
        this.userMessageHelper = userMessageHelper;
        this.logger = logger;
    }

    public JsonResponse sendBuildSessionRequest(
            BuildSessionData buildSessionData, String token, String server, String proxy){
        String resolvedUrl;
        try {
            UrlBuilder urlBuilder = new UrlBuilder();
            resolvedUrl = urlBuilder.withHost(server).withPath("v2","agents","buildsession").toString();
        } catch (MalformedURLException e) {
            userMessageHelper.printError("Unable to create url to post configuration. Error:", e);
            return null;
        }

        HttpResponse httpResponse = null;
        try {
            return doPost(resolvedUrl, proxy, token, buildSessionData);
        } catch (IOException e) {
            userMessageHelper.printError("Failed to post configuration to server. Error:", e);
        }
        return null;
    }

    private JsonResponse doPost(
            String resolvedUrl, String proxy, String token, BuildSessionData configurationData) throws IOException {

        int currentAttempt = 1;
        int maxAttempts = getMaxAttempts();
        int delay = getDelay();
        Exception lastError = null;
        do {
            try {
                if (currentAttempt > 1)
                    sleep(delay);

                logger.info("[To BSS] - attempt '#" + currentAttempt + "' out of '" + maxAttempts
                        + "'. Request: " + configurationData.toString());

                ApacheJsonClient apacheJsonClient = new ApacheJsonClient(apacheHttpClient, logger);
                JsonResponse jsonResponse = apacheJsonClient.postObjectAsJson(resolvedUrl, proxy, token, configurationData, String.class);

                logger.info("[From BSS] - " + jsonResponse.getResponseObject());

                return jsonResponse;
            } catch (Exception e) {
                logger.error("[From BSS] - Failed to send request. Error: ", e);
                lastError = e;
                currentAttempt++;
            }

        } while (currentAttempt <= maxAttempts);

        throw new RuntimeException("Failed to post build session configuration data to server. Last error:", lastError);
    }

    public BuildSessionData getConfigurationByBuildSessionId(
            String buildSessionId, String token, String server, String proxy) {
        BuildSessionData configurationData = null;
        try {
            UrlBuilder urlBuilder = new UrlBuilder();
            String resolvedUrl = urlBuilder.withHost(server).withPath("v2", "agents", "buildsession", buildSessionId).toString();
            HttpResponse httpResponse = doGet(resolvedUrl, proxy, token);

            String jsonOrServerError = StreamUtils.toString(httpResponse.getByteArrayInputStream());

            if (httpResponse.getStatusCode() == 200) {
                userMessageHelper.println("Request to get configuration data returned: " + jsonOrServerError);
                configurationData = JsonSerializer.deserialize(jsonOrServerError, BuildSessionData.class);
            } else {
                userMessageHelper.printError("Unable to get configuration for build session id '" + buildSessionId
                        + "'. Request returned with status code '" + httpResponse.getStatusCode()
                        + "' and message '" + jsonOrServerError + "'");
            }

        } catch (Exception e) {
            userMessageHelper.printError("Failed to get configuration from server. Error:", e);
        }

        return configurationData;
    }

    private HttpResponse doGet(String resolvedUrl, String proxy, String token) {

        int currentAttempt = 1;
        int maxAttempts = getMaxAttempts();
        int delay = getDelay();
        Exception lastError = null;
        do {
            try {
                if (currentAttempt > 1)
                    sleep(delay);

                logger.info("[To BSS] - attempt '#" + currentAttempt + "' out of '" + maxAttempts + "'. Request: " + resolvedUrl);
                HttpResponse httpResponse = apacheHttpClient.getJson(resolvedUrl, proxy, token);

                httpResponse = updateResponseByteArray(httpResponse);
                String jsonOrServerError = StreamUtils.toString(httpResponse.getByteArrayInputStream());
                httpResponse.getByteArrayInputStream().reset();

                logger.info("[From BSS] - " + jsonOrServerError);
                return httpResponse;
            } catch (Exception e) {
                logger.error("[From BSS] - Failed to send request. Error: ", e);
                lastError = e;
                currentAttempt++;
            }

        } while (currentAttempt <= maxAttempts);

        throw new RuntimeException("Failed to get build session configuration from server. Last error:", lastError);
    }

    private HttpResponse updateResponseByteArray(HttpResponse httpResponse) throws IOException {
        InputStream responseStream = httpResponse.getResponseStream();
        ByteArrayInputStream bis = StreamUtils.toByteArrayInputStream(responseStream);
        httpResponse.setByteArrayInputStream(bis);
        return httpResponse;
    }

    private final int MAX_ATTEMPTS = 5;
    private final int DELAY = 5 * 1000;

    private int getMaxAttempts() {
        String maxAttempts = System.getProperty("sl.buildMapping.maxAttempts");
        try {
            Integer value = Integer.valueOf(maxAttempts);
            return value;
        } catch (Exception e) {
            return MAX_ATTEMPTS;
        }
    }

    private int getDelay() {
        String delay = System.getProperty("sl.buildMapping.delay");
        try {
            Integer value = Integer.valueOf(delay);
            return value;
        } catch (Exception e) {
            return DELAY;
        }
    }

    private void sleep(int duration) {
        try {
            logger.info("Sleeping for " + duration + " milliseconds.");
            Thread.sleep(duration);
        } catch (InterruptedException e) {
            logger.error("Failed to sleep due to an error. Error:", e);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy