blob: 6a63946c77e94146e0da79f43312a5204c9a0d93 [file] [log] [blame]
/*
*******************************************************************************
* Copyright (c) 2018 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*******************************************************************************
*/
package org.eclipse.openk.core.communication;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.eclipse.openk.auth2.util.JwtHelper;
import org.eclipse.openk.common.Globals;
import org.eclipse.openk.core.exceptions.HttpStatusException;
import org.eclipse.openk.core.exceptions.PgmNestedException;
import org.eclipse.openk.core.viewmodel.ErrorReturn;
public class RestServiceWrapper {
private static final Logger LOGGER = Logger.getLogger(RestServiceWrapper.class.getName());
private String baseURL;
private boolean useHttps;
public RestServiceWrapper(String baseURL, boolean https) {
this.baseURL = baseURL;
this.useHttps = https;
}
public String performGetRequest(String restFunctionWithParams, String token) throws HttpStatusException {
LOGGER.debug("BaseUrl: " + baseURL);
String completeRequest = baseURL + "/" + restFunctionWithParams;
LOGGER.debug("CompleteUrl: " + completeRequest);
// create HTTP Client
CloseableHttpClient httpClient = createHttpsClient();
// create new Request with given URL
HttpGet getRequest = new HttpGet(completeRequest);
getRequest.addHeader("accept", Globals.HEADER_JSON_UTF8);
if (token != null && !token.isEmpty())
{
String accesstoken = JwtHelper.formatToken(token);
getRequest.addHeader(Globals.KEYCLOAK_AUTH_TAG, "Bearer " + accesstoken);
} else {
throw new HttpStatusException(HttpStatus.SC_UNAUTHORIZED);
}
HttpResponse response;
// Execute request an catch response
try {
response = httpClient.execute(getRequest);
} catch (IOException e) {
String errtext = "Communication to <" + completeRequest + "> failed!";
LOGGER.warn(errtext, e);
throw new HttpStatusException(HttpStatus.SC_SERVICE_UNAVAILABLE);
}
return createJson(response);
}
public String performPostRequest(String restFunctionWithParams, String token, String data) throws HttpStatusException {
String completeRequest = baseURL + "/" + restFunctionWithParams;
// create HTTP Client
CloseableHttpClient httpClient = createHttpsClient();
// create new Post Request with given URL
HttpPost postRequest = new HttpPost(completeRequest);
// add additional header to getRequest which accepts application/JSON data
postRequest.addHeader("accept", Globals.HEADER_JSON_UTF8);
postRequest.addHeader("Content-Type", Globals.HEADER_JSON_UTF8);
if (token != null && !token.isEmpty()) {
String accesstoken = JwtHelper.formatToken(token);
postRequest.addHeader(Globals.KEYCLOAK_AUTH_TAG, "Bearer " + accesstoken);
} else {
throw new HttpStatusException(HttpStatus.SC_UNAUTHORIZED);
}
postRequest.setEntity(new StringEntity(data, StandardCharsets.UTF_8));
HttpResponse response;
// Execute request an catch response
try {
response = httpClient.execute(postRequest);
} catch (IOException e) {
String errtext = "Communication to <" + completeRequest + "> failed!";
LOGGER.warn(errtext, e);
throw new HttpStatusException(HttpStatus.SC_SERVICE_UNAVAILABLE);
}
return createJson(response);
}
private CloseableHttpClient createHttpsClient() throws HttpStatusException {
if (useHttps) {
try {
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (Exception e) {
LOGGER.error(e + "SSLContextBuilderException");
throw new HttpStatusException(HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
} else {
return HttpClientBuilder.create().build();
}
}
private String createJson(HttpResponse response) throws HttpStatusException {
String retJson;
try {
retJson = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
} catch (IOException e) {
LOGGER.error(e);
throw new HttpStatusException(HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
ErrorReturn errorReturn = new ErrorReturn();
errorReturn.setErrorCode(response.getStatusLine().getStatusCode());
errorReturn.setErrorText(response.getStatusLine().getReasonPhrase());
throw new PgmNestedException(errorReturn);
}
return retJson;
}
}