Search in sources :

Example 16 with PermanentException

use of com.hp.octane.integrations.exceptions.PermanentException in project octane-ci-java-sdk by MicroFocus.

the class CoverageServiceImpl method isSonarReportRelevant.

@Override
public boolean isSonarReportRelevant(String jobId) {
    if (jobId == null || jobId.isEmpty()) {
        throw new IllegalArgumentException("job ID MUST NOT be null nor empty");
    }
    boolean result = false;
    OctaneResponse response;
    boolean base64 = isEncodeBase64();
    String encodedJobId = base64 ? CIPluginSDKUtils.urlEncodeBase64(jobId) : CIPluginSDKUtils.urlEncodePathParam(jobId);
    // get result
    try {
        String url = getAnalyticsContextPath(configurer.octaneConfiguration.getUrl(), configurer.octaneConfiguration.getSharedSpace()) + "servers/" + CIPluginSDKUtils.urlEncodePathParam(configurer.octaneConfiguration.getInstanceId()) + "/jobs/" + encodedJobId + "/workspaceId";
        if (base64) {
            url = CIPluginSDKUtils.addParameterEncode64ToUrl(url);
        }
        OctaneRequest preflightRequest = dtoFactory.newDTO(OctaneRequest.class).setMethod(HttpMethod.GET).setUrl(url);
        response = restService.obtainOctaneRestClient().execute(preflightRequest);
        if (response.getStatus() == HttpStatus.SC_SERVICE_UNAVAILABLE || response.getStatus() == HttpStatus.SC_BAD_GATEWAY) {
            throw new TemporaryException("preflight request failed with status " + response.getStatus());
        } else if (response.getStatus() != HttpStatus.SC_OK && response.getStatus() != HttpStatus.SC_NO_CONTENT) {
            throw new PermanentException("preflight request failed with status " + response.getStatus());
        }
    } catch (IOException ioe) {
        throw new TemporaryException("failed to perform preflight request", ioe);
    }
    // parse result
    if (response.getStatus() == HttpStatus.SC_OK && response.getBody() != null && !response.getBody().isEmpty()) {
        try {
            String[] wss = CIPluginSDKUtils.getObjectMapper().readValue(response.getBody(), String[].class);
            if (wss.length > 0) {
                logger.info(configurer.octaneConfiguration.getLocationForLog() + "coverage of " + jobId + " found " + wss.length + " interested workspace/s in Octane, dispatching the coverage");
                result = true;
            } else {
                logger.info(configurer.octaneConfiguration.getLocationForLog() + "coverage of " + jobId + ", found no interested workspace in Octane");
            }
        } catch (IOException ioe) {
            throw new PermanentException("failed to parse preflight response '" + response.getBody() + "' for '" + jobId + "'");
        }
    }
    return result;
}
Also used : TemporaryException(com.hp.octane.integrations.exceptions.TemporaryException) PermanentException(com.hp.octane.integrations.exceptions.PermanentException) OctaneResponse(com.hp.octane.integrations.dto.connectivity.OctaneResponse) OctaneRequest(com.hp.octane.integrations.dto.connectivity.OctaneRequest) IOException(java.io.IOException)

Example 17 with PermanentException

use of com.hp.octane.integrations.exceptions.PermanentException in project octane-ci-java-sdk by MicroFocus.

the class CoverageServiceImpl method pushCoverage.

@Override
public OctaneResponse pushCoverage(String jobId, String buildId, CoverageReportType reportType, InputStream coverageReport) {
    if (jobId == null || jobId.isEmpty()) {
        throw new IllegalArgumentException("job ID MUST NOT be null nor empty");
    }
    if (buildId == null || buildId.isEmpty()) {
        throw new IllegalArgumentException("build ID MUST NOT be null nor empty");
    }
    if (reportType == null) {
        throw new IllegalArgumentException("report type MUST NOT be null");
    }
    if (coverageReport == null) {
        throw new IllegalArgumentException("coverage report data MUST NOT be null");
    }
    boolean base64 = isEncodeBase64();
    String tempJobId = jobId;
    if (base64) {
        tempJobId = CIPluginSDKUtils.urlEncodeBase64(jobId);
    }
    String url;
    try {
        url = new URIBuilder(getAnalyticsContextPath(configurer.octaneConfiguration.getUrl(), configurer.octaneConfiguration.getSharedSpace()) + "coverage").setParameter("ci-server-identity", configurer.octaneConfiguration.getInstanceId()).setParameter("ci-job-id", tempJobId).setParameter("ci-build-id", buildId).setParameter("file-type", reportType.name()).toString();
        if (base64) {
            url = CIPluginSDKUtils.addParameterEncode64ToUrl(url);
        }
    } catch (URISyntaxException urise) {
        throw new PermanentException("failed to build URL to push coverage report", urise);
    }
    String correlationId = CIPluginSDKUtils.getNextCorrelationId();
    Map<String, String> headers = new HashMap<>();
    headers.put(CORRELATION_ID_HEADER, correlationId);
    OctaneRequest pushCoverageRequest = dtoFactory.newDTO(OctaneRequest.class).setMethod(HttpMethod.PUT).setUrl(url).setHeaders(headers).setBody(coverageReport);
    try {
        return restService.obtainOctaneRestClient().execute(pushCoverageRequest);
    } catch (IOException ioe) {
        throw new TemporaryException("failed to push coverage report", ioe);
    }
}
Also used : TemporaryException(com.hp.octane.integrations.exceptions.TemporaryException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) PermanentException(com.hp.octane.integrations.exceptions.PermanentException) URISyntaxException(java.net.URISyntaxException) OctaneRequest(com.hp.octane.integrations.dto.connectivity.OctaneRequest) IOException(java.io.IOException) URIBuilder(org.apache.http.client.utils.URIBuilder)

Example 18 with PermanentException

use of com.hp.octane.integrations.exceptions.PermanentException in project octane-ci-java-sdk by MicroFocus.

the class EventsServiceImpl method worker.

// infallible everlasting worker function
private void worker() {
    while (!eventsPushExecutor.isShutdown()) {
        if (!workerPreflight.preflight()) {
            continue;
        }
        // build events list to be sent
        List<CIEvent> eventsChunk = null;
        CIEventsList eventsSnapshot;
        try {
            eventsChunk = getEventsChunk();
            CIServerInfo serverInfo = configurer.pluginServices.getServerInfo();
            serverInfo.setInstanceId(configurer.octaneConfiguration.getInstanceId());
            eventsSnapshot = dtoFactory.newDTO(CIEventsList.class).setServer(serverInfo).setEvents(eventsChunk);
        } catch (Throwable t) {
            logger.error(configurer.octaneConfiguration.getLocationForLog() + "failed to serialize chunk of " + (eventsChunk != null ? eventsChunk.size() : "[NULL]") + " events, dropping them off (if any) and continue");
            removeEvents(eventsChunk);
            continue;
        }
        // send the data to Octane
        try {
            String correlationId = CIPluginSDKUtils.getNextCorrelationId();
            logEventsToBeSent(eventsSnapshot, correlationId);
            sendEventsData(eventsSnapshot, correlationId);
            removeEvents(eventsChunk);
            if (events.size() > 0) {
                logger.info(configurer.octaneConfiguration.getLocationForLog() + "left to send " + events.size() + " events");
            }
        } catch (RequestTimeoutException rte) {
            requestTimeoutCount++;
            lastRequestTimeoutTime = System.currentTimeMillis();
            logger.info(configurer.octaneConfiguration.getLocationForLog() + rte.getMessage());
            CIPluginSDKUtils.doWait(TEMPORARY_FAILURE_PAUSE);
        } catch (TemporaryException tqie) {
            logger.error(configurer.octaneConfiguration.getLocationForLog() + "failed to send events with temporary error, breathing " + TEMPORARY_FAILURE_PAUSE + "ms and continue", tqie);
            CIPluginSDKUtils.doWait(TEMPORARY_FAILURE_PAUSE);
        } catch (PermanentException pqie) {
            logger.error(configurer.octaneConfiguration.getLocationForLog() + "failed to send events with permanent error, dropping this chunk and continue", pqie);
            removeEvents(eventsChunk);
        } catch (Throwable t) {
            logger.error(configurer.octaneConfiguration.getLocationForLog() + "failed to send events with unexpected error, dropping this chunk and continue", t);
            removeEvents(eventsChunk);
        }
    }
}
Also used : RequestTimeoutException(com.hp.octane.integrations.exceptions.RequestTimeoutException) TemporaryException(com.hp.octane.integrations.exceptions.TemporaryException) CIEvent(com.hp.octane.integrations.dto.events.CIEvent) CIEventsList(com.hp.octane.integrations.dto.events.CIEventsList) PermanentException(com.hp.octane.integrations.exceptions.PermanentException) CIServerInfo(com.hp.octane.integrations.dto.general.CIServerInfo)

Example 19 with PermanentException

use of com.hp.octane.integrations.exceptions.PermanentException in project octane-ci-java-sdk by MicroFocus.

the class CoverageServiceImpl method pushCoverageWithPreflight.

private void pushCoverageWithPreflight(CoverageQueueItem queueItem) {
    // preflight
    if (!isSonarReportRelevant(queueItem.jobId)) {
        return;
    }
    // get coverage report content
    InputStream coverageReport = configurer.pluginServices.getCoverageReport(queueItem.jobId, queueItem.buildId, queueItem.reportFileName);
    if (coverageReport == null) {
        logger.info(configurer.octaneConfiguration.getLocationForLog() + "no log for " + queueItem + " found, abandoning");
        return;
    }
    // push coverage
    OctaneResponse response = pushCoverage(queueItem.jobId, queueItem.buildId, queueItem.reportType, coverageReport);
    if (response.getStatus() == HttpStatus.SC_OK) {
        logger.info(configurer.octaneConfiguration.getLocationForLog() + "successfully pushed coverage of " + queueItem + ", CorrelationId - " + response.getCorrelationId());
    } else if (response.getStatus() == HttpStatus.SC_SERVICE_UNAVAILABLE || response.getStatus() == HttpStatus.SC_BAD_GATEWAY) {
        throw new TemporaryException("temporary failed to push coverage of " + queueItem + ", status: " + HttpStatus.SC_SERVICE_UNAVAILABLE);
    } else {
        throw new PermanentException("permanently failed to push coverage of " + queueItem + ", status: " + response.getStatus());
    }
}
Also used : TemporaryException(com.hp.octane.integrations.exceptions.TemporaryException) InputStream(java.io.InputStream) PermanentException(com.hp.octane.integrations.exceptions.PermanentException) OctaneResponse(com.hp.octane.integrations.dto.connectivity.OctaneResponse)

Example 20 with PermanentException

use of com.hp.octane.integrations.exceptions.PermanentException in project octane-ci-java-sdk by MicroFocus.

the class SSCRestClientImpl method sendReqAuth.

private AuthToken.AuthTokenData sendReqAuth(SSCProjectConfiguration sscProjectConfiguration) {
    // "/{SSC Server Context}/api/v1"
    // String url = "http://" + serverURL + "/ssc/api/v1/projects?q=id:2743&fulltextsearch=true";
    String url = sscProjectConfiguration.getSSCUrl() + "/api/v1/tokens";
    HttpPost request = new HttpPost(url);
    request.addHeader("Authorization", sscProjectConfiguration.getSSCBaseAuthToken());
    request.addHeader("Accept", "application/json");
    request.addHeader("Host", getNetHost(sscProjectConfiguration.getSSCUrl()));
    request.addHeader("Content-Type", "application/json;charset=UTF-8");
    String body = "{\"type\": \"UnifiedLoginToken\"}";
    CloseableHttpResponse response = null;
    try {
        HttpEntity entity = new ByteArrayEntity(body.getBytes(StandardCharsets.UTF_8));
        request.setEntity(entity);
        response = httpClient.execute(request);
        if (succeeded(response.getStatusLine().getStatusCode())) {
            String toString = CIPluginSDKUtils.inputStreamToUTF8String(response.getEntity().getContent());
            AuthToken authToken = new ObjectMapper().readValue(toString, TypeFactory.defaultInstance().constructType(AuthToken.class));
            return authToken.getData();
        } else {
            throw new PermanentException("Couldn't Authenticate SSC user, need to check SSC configuration in Octane plugin");
        }
    } catch (Throwable t) {
        throw new PermanentException(t);
    } finally {
        if (response != null) {
            EntityUtils.consumeQuietly(response.getEntity());
            HttpClientUtils.closeQuietly(response);
        }
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpEntity(org.apache.http.HttpEntity) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) PermanentException(com.hp.octane.integrations.exceptions.PermanentException) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) AuthToken(com.hp.octane.integrations.services.vulnerabilities.ssc.dto.AuthToken) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Aggregations

PermanentException (com.hp.octane.integrations.exceptions.PermanentException)31 TemporaryException (com.hp.octane.integrations.exceptions.TemporaryException)19 IOException (java.io.IOException)15 OctaneResponse (com.hp.octane.integrations.dto.connectivity.OctaneResponse)10 OctaneRequest (com.hp.octane.integrations.dto.connectivity.OctaneRequest)8 InputStream (java.io.InputStream)6 URISyntaxException (java.net.URISyntaxException)6 URIBuilder (org.apache.http.client.utils.URIBuilder)6 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)5 RequestTimeoutException (com.hp.octane.integrations.exceptions.RequestTimeoutException)5 HashMap (java.util.HashMap)5 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)5 InterruptedIOException (java.io.InterruptedIOException)4 HttpGet (org.apache.http.client.methods.HttpGet)4 OctaneRestClient (com.hp.octane.integrations.services.rest.OctaneRestClient)3 LinkedHashMap (java.util.LinkedHashMap)3 JsonNode (com.fasterxml.jackson.databind.JsonNode)2 OctaneSDKGeneralException (com.hp.octane.integrations.exceptions.OctaneSDKGeneralException)2 List (java.util.List)2 HttpEntity (org.apache.http.HttpEntity)2