Skip to content

Commit

Permalink
[#60feature/#60-restlib] lib used
Browse files Browse the repository at this point in the history
Signed-off-by: huluvu424242 <huluvu424242@gmail.com>
  • Loading branch information
Huluvu424242 committed Jan 29, 2023
1 parent 7015b80 commit abe6067
Show file tree
Hide file tree
Showing 5 changed files with 112 additions and 35 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,12 @@
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.Callable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import com.cdancy.jenkins.rest.JenkinsClient;
import com.cdancy.jenkins.rest.domain.job.BuildInfo;
import com.cdancy.jenkins.rest.features.JobsApi;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
Expand Down Expand Up @@ -81,9 +86,9 @@ public JobStatusBeschreibung call() throws Exception {
protected JobStatusBeschreibung getJobStatus() {

try {
final JSONObject resultJSON = sendGetRequest();
final String jobName = resultJSON.getString(JSONKEY_FULL_DISPLAY_NAME);
final String jobStatus = resultJSON.getString(JSONKEY_RESULT);
final BuildInfo resultJSON = sendGetRequest();
final String jobName = resultJSON.fullDisplayName();// getString(JSONKEY_FULL_DISPLAY_NAME);
final String jobStatus = resultJSON.result(); //getString(JSONKEY_RESULT);
return new JobStatusBeschreibung(jobName, JobStatus.valueOf(jobStatus), jobAbfragedaten.getJenkinsJobUrl(), jobOrderId);
} catch (JobNotFoundException e) {
return new JobStatusBeschreibung("Job Not Found ERROR: " + jobAbfragedaten.getJenkinsJobUrl(), JobStatus.OTHER, jobAbfragedaten.getJenkinsJobUrl(), jobOrderId);
Expand All @@ -96,35 +101,61 @@ protected JobStatusBeschreibung getJobStatus() {
}
}

protected JSONObject sendGetRequest() throws JobNotFoundException, ConnectionFailedException, ConnectionErrorException {
protected BuildInfo sendGetRequest() throws JobNotFoundException, ConnectionFailedException, ConnectionErrorException {
final URL statusAbfrageUrl = jobAbfragedaten.getStatusAbfrageUrl();
int statusCode = -1;
int timeout = 1;
final RequestConfig config = RequestConfig.custom()
.setConnectTimeout(timeout * 1000)
.setConnectionRequestTimeout(timeout * 1000)
.setSocketTimeout(timeout * 1000).build();
try (final CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build()) {
final HttpHost target = new HttpHost(statusAbfrageUrl.getHost(), statusAbfrageUrl.getPort(), statusAbfrageUrl.getProtocol());
final HttpGet httpGetRequest = new HttpGet(statusAbfrageUrl.getPath());
final String basicAuthToken = jobAbfragedaten.getBasicAuthToken();
if (basicAuthToken != null && basicAuthToken.length() > 1) {
httpGetRequest.setHeader("Authorization", "Basic " + basicAuthToken); // NOSONAR java:S2647
}
final HttpResponse httpResponse;
httpResponse = getHttpResponse(httpClient, target, httpGetRequest);
LOGGER.debug("Abfrage: {}{}",target,httpGetRequest);
statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == 404) {
throw new JobNotFoundException(new HttpResponseException(statusCode, httpResponse.getStatusLine().getReasonPhrase()));
} else if (statusCode != 200) {
throw new ConnectionErrorException(new HttpResponseException(statusCode, httpResponse.getStatusLine().getReasonPhrase()));
}
return getJsonObjectFromResponse(httpResponse);
} catch (JSONException | IOException ex) {
LOGGER.warn(String.format("Could not retrieve data from jenkins: %s", ex));
// final RequestConfig config = RequestConfig.custom()
// .setConnectTimeout(timeout * 1000)
// .setConnectionRequestTimeout(timeout * 1000)
// .setSocketTimeout(timeout * 1000).build();
// try (final CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build()) {

final JenkinsClient.Builder clientBuilder = JenkinsClient.builder()
.endPoint(String.format("%s://%s:%d/", statusAbfrageUrl.getProtocol(), statusAbfrageUrl.getHost(), statusAbfrageUrl.getPort()));
// Basic Auth
final String basicAuthToken = jobAbfragedaten.getBasicAuthToken();
if (basicAuthToken != null && basicAuthToken.length() > 1) {
clientBuilder.credentials(jobAbfragedaten.getBasicAuthToken());
}
return null;
final JenkinsClient client = clientBuilder.build();

final String abfrageURL = statusAbfrageUrl.getPath();
Pattern pattern = Pattern.compile(".*/job/(.*)/job/(.*)");
Matcher matcher = pattern.matcher(statusAbfrageUrl.getPath());
final String folderName;
final String jobName;
final boolean matched= matcher.matches();
if(matched){
folderName = matcher.group(1);
jobName = matcher.group(2);
}else{
folderName=null;
jobName=null;
}


final JobsApi api = client.api().jobsApi();

// final int lastBuildNumber = api.lastBuildNumber(null, statusAbfrageUrl.getPath());
final int lastBuildNumber = api.lastBuildNumber(folderName, jobName);
LOGGER.debug("Letzte Buildnummer von {} ist {}", statusAbfrageUrl.getPath(), lastBuildNumber);

final BuildInfo buildInfo = client.api().jobsApi().buildInfo(folderName,jobName, lastBuildNumber);
LOGGER.debug("RESPONSE: URL: {}\n STATUS: {} \n", buildInfo.url(), buildInfo.result());


// statusCode = httpResponse.getStatusLine().getStatusCode();
// if (statusCode == 404) {
// throw new JobNotFoundException(new HttpResponseException(statusCode, httpResponse.getStatusLine().getReasonPhrase()));
// } else if (statusCode != 200) {
// throw new ConnectionErrorException(new HttpResponseException(statusCode, httpResponse.getStatusLine().getReasonPhrase()));
// }
// return getJsonObjectFromResponse(httpResponse);
// } catch (JSONException | IOException ex) {
// LOGGER.warn(String.format("Could not retrieve data from jenkins: %s", ex));
// }
return buildInfo;
}

protected HttpResponse getHttpResponse(CloseableHttpClient httpClient, HttpHost target, HttpGet httpGetRequest) throws ConnectionFailedException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ public String getBasicAuthToken() {

public URL getStatusAbfrageUrl() {
try {
return new URL(jenkinsJobUrl.toExternalForm() + JenkinsAPI.STATUS_PATH);
// return new URL(jenkinsJobUrl.toExternalForm() + JenkinsAPI.STATUS_PATH);
return new URL(jenkinsJobUrl.toExternalForm());
} catch (MalformedURLException e) {
LOGGER.warn("Generierter Statusabfrage URL ist ungültig", e);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,27 @@
package com.github.funthomas424242.jenkinsmonitor.logstash;

/*-
* #%L
* Jenkins Monitor
* %%
* Copyright (C) 2019 - 2023 PIUG
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/

import java.util.Arrays;

public enum LogAppender {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,27 @@
package com.github.funthomas424242.jenkinsmonitor.logstash;

/*-
* #%L
* Jenkins Monitor
* %%
* Copyright (C) 2019 - 2023 PIUG
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/

import java.util.Arrays;

public enum Loglevel {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
* #L%
*/

import com.cdancy.jenkins.rest.domain.job.BuildInfo;
import com.github.funthomas424242.jenkinsmonitor.gui.JobStatusBeschreibungen;
import com.github.tomakehurst.wiremock.WireMockServer;
import java.net.MalformedURLException;
Expand Down Expand Up @@ -156,23 +157,23 @@ void getValidJsonRed() {
void getValidJsonGreen() {
final JobAbfragedaten jobAbfragedaten = new JobAbfragedaten(JOB_URL_MULTIBRANCH_JOB1_GREEN, null);
final JobAbfrage requester = new JobAbfrage(jobAbfragedaten, "#1");
final JSONObject json = assertDoesNotThrow(() -> requester.sendGetRequest());
final BuildInfo json = assertDoesNotThrow(() -> requester.sendGetRequest());
assertNotNull(json);
assertEquals("mypocketmod \u00bb master #2", json.get("fullDisplayName"));
assertEquals("SUCCESS", json.get("result"));
assertEquals("mypocketmod \u00bb master #2", json.fullDisplayName()); //get("fullDisplayName"));
assertEquals("SUCCESS", json.result()); //get("result"));
}

@Test
@DisplayName("Die Statusabfrage eines gelben Build Jobs gibt ein valides JSON zurück")
void getValidJsonYellow() {
final JSONObject json = assertDoesNotThrow(() -> {
final BuildInfo json = assertDoesNotThrow(() -> {
final JobAbfragedaten jobAbfragedaten = new JobAbfragedaten(JOB_URL_MULTIBRANCH_JOB1_YELLOW, null);
final JobAbfrage requester = new JobAbfrage(jobAbfragedaten, "#1");
return requester.sendGetRequest();
});
assertNotNull(json);
assertEquals("mypocketmod » master #2", json.get("fullDisplayName"));
assertEquals("UNSTABLE", json.get("result"));
assertEquals("mypocketmod » master #2", json.fullDisplayName()); //get("fullDisplayName"));
assertEquals("UNSTABLE", json.result()); //get("result"));
}

@Test
Expand Down

0 comments on commit abe6067

Please sign in to comment.