Search in sources :

Example 61 with HttpResponseException

use of org.apache.http.client.HttpResponseException in project stashbot by palantir.

the class JenkinsManager method synchronousTriggerBuild.

public void synchronousTriggerBuild(Repository repo, JobType jobType, String hashToBuild, String buildRef) {
    try {
        RepositoryConfiguration rc = cpm.getRepositoryConfigurationForRepository(repo);
        JenkinsServerConfiguration jsc = cpm.getJenkinsServerConfiguration(rc.getJenkinsServerName());
        JobTemplate jt = jtm.getJobTemplate(jobType, rc);
        String jenkinsBuildId = jt.getBuildNameFor(repo);
        String url = jsc.getUrl();
        String user = jsc.getUsername();
        String password = jsc.getPassword();
        log.info("Triggering jenkins build id " + jenkinsBuildId + " on hash " + hashToBuild + " (" + user + "@" + url + " pw: " + password.replaceAll(".", "*") + ")");
        final JenkinsServer js = jenkinsClientManager.getJenkinsServer(jsc, rc);
        Map<String, Job> jobMap = js.getJobs();
        String key = jt.getBuildNameFor(repo);
        if (!jobMap.containsKey(key)) {
            throw new RuntimeException("Build doesn't exist: " + key);
        }
        Builder<String, String> builder = ImmutableMap.builder();
        builder.put("buildHead", hashToBuild);
        builder.put("repoId", repo.getId().toString());
        if (buildRef != null) {
            builder.put("buildRef", buildRef);
        }
        jobMap.get(key).build(builder.build());
    } catch (SQLException e) {
        throw new RuntimeException(e);
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    } catch (HttpResponseException e) {
        // client
        if (e.getStatusCode() == 302) {
            // to some URL after the fact.
            return;
        }
        // For other HTTP errors, log it for easier debugging
        log.error("HTTP Error (resp code " + Integer.toString(e.getStatusCode()) + ")", e);
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Also used : SQLException(java.sql.SQLException) JenkinsServer(com.offbytwo.jenkins.JenkinsServer) HttpResponseException(org.apache.http.client.HttpResponseException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) JobTemplate(com.palantir.stash.stashbot.persistence.JobTemplate) RepositoryConfiguration(com.palantir.stash.stashbot.persistence.RepositoryConfiguration) JenkinsServerConfiguration(com.palantir.stash.stashbot.persistence.JenkinsServerConfiguration) Job(com.offbytwo.jenkins.model.Job)

Example 62 with HttpResponseException

use of org.apache.http.client.HttpResponseException in project carbon-apimgt by wso2.

the class SolaceNotifierUtils method checkApiProductAlreadyDeployedIntoSolaceEnvironments.

/**
 * Check whether the given API product is already deployed in the Solace environment
 *
 * @param api          Name of the API
 * @param environments List of the environments
 * @return returns true if the given API product is already deployed in one of environments
 * @throws IOException            If an error occurs when checking API product availability
 * @throws APIManagementException if an error occurs when getting Solace config
 */
public static boolean checkApiProductAlreadyDeployedIntoSolaceEnvironments(API api, List<Environment> environments) throws IOException, APIManagementException {
    int numberOfDeployedEnvironmentsInSolace = 0;
    for (Environment environment : environments) {
        String apiNameWithContext = generateApiProductNameForSolaceBroker(api, environment.getName());
        SolaceAdminApis solaceAdminApis = SolaceNotifierUtils.getSolaceAdminApis();
        CloseableHttpResponse response = solaceAdminApis.apiProductGet(environment.getAdditionalProperties().get(SolaceConstants.SOLACE_ENVIRONMENT_ORGANIZATION), apiNameWithContext);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            if (log.isDebugEnabled()) {
                log.info("API product found in Solace Broker");
            }
            numberOfDeployedEnvironmentsInSolace++;
        } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            if (log.isDebugEnabled()) {
                log.error("API product not found in Solace broker");
                log.error(EntityUtils.toString(response.getEntity()));
            }
            throw new HttpResponseException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase());
        } else {
            if (log.isDebugEnabled()) {
                log.error("Cannot find API product in Solace Broker");
                log.error(EntityUtils.toString(response.getEntity()));
            }
            throw new HttpResponseException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase());
        }
    }
    return numberOfDeployedEnvironmentsInSolace == environments.size();
}
Also used : SolaceAdminApis(org.wso2.carbon.apimgt.solace.SolaceAdminApis) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) Environment(org.wso2.carbon.apimgt.api.model.Environment) HttpResponseException(org.apache.http.client.HttpResponseException)

Example 63 with HttpResponseException

use of org.apache.http.client.HttpResponseException in project carbon-apimgt by wso2.

the class SolaceNotifierUtils method checkApiProductAlreadyDeployedInSolace.

/**
 * Check whether the given API product is already deployed in the Solace broker
 *
 * @param api          Name of the API
 * @param organization Name of the organization
 * @return returns true if the given API product is already deployed in the Solace
 * @throws APIManagementException If an error occurs when checking API product availability
 */
private boolean checkApiProductAlreadyDeployedInSolace(API api, String organization) throws IOException, APIManagementException {
    Map<String, Environment> environmentMap = APIUtil.getReadOnlyGatewayEnvironments();
    Environment solaceEnvironment = environmentMap.get(SolaceConstants.SOLACE_ENVIRONMENT);
    if (solaceEnvironment != null) {
        SolaceAdminApis solaceAdminApis = new SolaceAdminApis(solaceEnvironment.getServerURL(), solaceEnvironment.getUserName(), solaceEnvironment.getPassword(), solaceEnvironment.getAdditionalProperties().get(SolaceConstants.SOLACE_ENVIRONMENT_DEV_NAME));
        String apiNameWithContext = generateApiProductNameForSolaceBroker(api, getThirdPartySolaceBrokerEnvironmentNameOfAPIDeployment(api));
        CloseableHttpResponse response = solaceAdminApis.apiProductGet(organization, apiNameWithContext);
        if (response != null) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                log.info("API product found in Solace Broker");
                return true;
            } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
                log.error("API product not found in Solace broker");
                log.error(EntityUtils.toString(response.getEntity()));
                throw new HttpResponseException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase());
            } else {
                log.error("Cannot find API product in Solace Broker");
                log.error(EntityUtils.toString(response.getEntity()));
                throw new HttpResponseException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase());
            }
        }
        return false;
    } else {
        throw new APIManagementException("Solace Environment configurations are not provided properly");
    }
}
Also used : SolaceAdminApis(org.wso2.carbon.apimgt.solace.SolaceAdminApis) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) Environment(org.wso2.carbon.apimgt.api.model.Environment) HttpResponseException(org.apache.http.client.HttpResponseException)

Example 64 with HttpResponseException

use of org.apache.http.client.HttpResponseException in project uavstack by uavorg.

the class PackageDownloadAction method downloadFile.

/**
 * Download file from HTTP server(host:port)
 *
 * @param fileName:
 *            the target file name
 * @param target:
 *            The destination where new file will be placed
 * @return
 * @throws Exception
 */
private boolean downloadFile(String fileName, Path destination) throws Exception {
    final Path path = destination;
    if (log.isTraceEnable()) {
        log.info(this, "Downloading file: " + fileName);
    }
    if (path == null || StringHelper.isEmpty(fileName)) {
        throw new IllegalArgumentException("Illegal argument for downloading");
    }
    URI uri = new URIBuilder().setScheme("http").setHost(this.host).setPort(this.port).setPath("/uav/upgrade").addParameter("softwareId", this.getSoftwareId()).addParameter("target", fileName).build();
    Files.deleteIfExists(path);
    if (Files.notExists(path.getParent())) {
        Files.createDirectories(path.getParent());
    }
    boolean result = false;
    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        HttpGet httpGet = new HttpGet(uri);
        result = httpClient.execute(httpGet, new ResponseHandler<Boolean>() {

            @Override
            public Boolean handleResponse(HttpResponse response) throws IOException {
                HttpEntity entity = response.getEntity();
                StatusLine statusLine = response.getStatusLine();
                if (statusLine.getStatusCode() >= 300) {
                    throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
                }
                if (entity == null) {
                    throw new ClientProtocolException("Response contains no content");
                }
                if (entity != null) {
                    try (InputStream instream = entity.getContent();
                        FileChannel fileChannel = FileChannel.open(path, StandardOpenOption.CREATE, StandardOpenOption.APPEND)) {
                        byte[] byteArr = new byte[8192];
                        ByteBuffer byteBuf = ByteBuffer.wrap(byteArr);
                        int len = -1;
                        while ((len = instream.read(byteArr)) != -1) {
                            byteBuf.position(len);
                            byteBuf.flip();
                            fileChannel.write(byteBuf);
                            byteBuf.clear();
                        }
                    }
                }
                return true;
            }
        });
    }
    return result;
}
Also used : Path(java.nio.file.Path) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) ResponseHandler(org.apache.http.client.ResponseHandler) HttpEntity(org.apache.http.HttpEntity) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) FileChannel(java.nio.channels.FileChannel) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) HttpResponseException(org.apache.http.client.HttpResponseException) URI(java.net.URI) ByteBuffer(java.nio.ByteBuffer) URIBuilder(org.apache.http.client.utils.URIBuilder) ClientProtocolException(org.apache.http.client.ClientProtocolException) StatusLine(org.apache.http.StatusLine)

Example 65 with HttpResponseException

use of org.apache.http.client.HttpResponseException in project docker-maven-plugin by fabric8io.

the class DockerAccessWithHcClientTest method givenThePushWillFail.

private void givenThePushWillFail(final int retries) throws IOException {
    new Expectations() {

        {
            int fail = retries + 1;
            mockDelegate.post(anyString, null, (Map<String, String>) any, (ResponseHandler) any, 200);
            minTimes = fail;
            maxTimes = fail;
            result = new HttpResponseException(HTTP_INTERNAL_ERROR, "error");
        }
    };
}
Also used : Expectations(mockit.Expectations) HttpResponseException(org.apache.http.client.HttpResponseException)

Aggregations

HttpResponseException (org.apache.http.client.HttpResponseException)82 IOException (java.io.IOException)32 StatusLine (org.apache.http.StatusLine)30 HttpEntity (org.apache.http.HttpEntity)25 HttpGet (org.apache.http.client.methods.HttpGet)14 HttpResponse (org.apache.http.HttpResponse)13 BasicResponseHandler (org.apache.http.impl.client.BasicResponseHandler)11 Header (org.apache.http.Header)9 ClientProtocolException (org.apache.http.client.ClientProtocolException)9 URISyntaxException (java.net.URISyntaxException)8 ArrayList (java.util.ArrayList)8 URI (java.net.URI)7 Document (org.jsoup.nodes.Document)7 Test (org.junit.Test)7 InputStream (java.io.InputStream)6 Expectations (mockit.Expectations)5 HttpClient (org.apache.http.client.HttpClient)5 Element (org.jsoup.nodes.Element)5 SubstitutionSchedule (me.vertretungsplan.objects.SubstitutionSchedule)4 HttpPost (org.apache.http.client.methods.HttpPost)4