Upgrade with latest http client

master
tcdlpds 1 year ago
parent d4f9472e48
commit 2d9352a788

@ -18,6 +18,10 @@
package io.entgra.device.mgt.core.ui.request.interceptor;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
@ -31,11 +35,11 @@ import io.entgra.device.mgt.core.ui.request.interceptor.beans.AuthData;
import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse;
import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants;
import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.core5.http.*;
import org.apache.hc.core5.http.io.entity.HttpEntities;
import org.apache.hc.core5.http.io.support.ClassicRequestBuilder;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
@ -44,7 +48,10 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
@MultipartConfig
@WebServlet("/user")
@ -85,7 +92,22 @@ public class UserHandler extends HttpServlet {
StringEntity tokenEPPayload = new StringEntity("token=" + accessToken,
ContentType.APPLICATION_FORM_URLENCODED);
tokenEndpoint.setEntity(tokenEPPayload);
ProxyResponse tokenStatus = HandlerUtil.execute(tokenEndpoint);
JsonFactory jsonFactory = new JsonFactory();
ObjectMapper objectMapper = new ObjectMapper(jsonFactory);
List<NameValuePair> nvps = new ArrayList<>();
nvps.add(new BasicNameValuePair("token", accessToken));
// nvps.add(new BasicNameValuePair("password", "secret"));
ClassicHttpRequest httpPost = ClassicRequestBuilder.post(keymanagerUrl + HandlerConstants.INTROSPECT_ENDPOINT)
.setEntity(new UrlEncodedFormEntity(nvps))
.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString())
.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + Base64.getEncoder().encodeToString((adminUsername + HandlerConstants.COLON + adminPassword).getBytes()))
.build();
ProxyResponse tokenStatus = HandlerUtil.execute(httpPost);
if (tokenStatus.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) {
if (tokenStatus.getCode() == HttpStatus.SC_UNAUTHORIZED) {
@ -100,29 +122,52 @@ public class UserHandler extends HttpServlet {
return;
}
}
String tokenData = tokenStatus.getData();
JsonNode tokenData = tokenStatus.getData();
if (tokenData == null) {
log.error("Invalid token data is received.");
HandlerUtil.handleError(resp, tokenStatus);
return;
}
JsonParser jsonParser = new JsonParser();
JsonElement jTokenResult = jsonParser.parse(tokenData);
if (jTokenResult.isJsonObject()) {
JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject();
if (!jTokenResultAsJsonObject.get("active").getAsBoolean()) {
if (!tokenData.get("active").asBoolean()) {
HandlerUtil.sendUnAuthorizeResponse(resp);
return;
}
ProxyResponse proxyResponse = new ProxyResponse();
proxyResponse.setStatus(ProxyResponse.Status.SUCCESS);
proxyResponse.setCode(HttpStatus.SC_OK);
proxyResponse.setData(
jTokenResultAsJsonObject.get("username").getAsString().replaceAll("@carbon.super", ""));
// proxyResponse.setData(
// tokenData.get("username").textValue().replaceAll("@carbon.super", ""));
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> nodeMap = mapper.convertValue(tokenData, new TypeReference<Map<String, Object>>(){});
nodeMap.put("username", tokenData.get("username").textValue().replaceAll("@carbon.super", ""));
proxyResponse.setData(mapper.convertValue(nodeMap, JsonNode.class));
// tokenData = ;
HandlerUtil.handleSuccess(resp, proxyResponse);
httpSession.setAttribute(HandlerConstants.USERNAME_WITH_DOMAIN, jTokenResultAsJsonObject.get("username").getAsString());
log.info("Customer login", userLogContextBuilder.setUserName(proxyResponse.getData()).setUserRegistered(true).build());
}
// JsonParser jsonParser = new JsonParser();
// JsonElement jTokenResult = jsonParser.parse(tokenData);
// if (jTokenResult.isJsonObject()) {
// JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject();
// if (!jTokenResultAsJsonObject.get("active").getAsBoolean()) {
// HandlerUtil.sendUnAuthorizeResponse(resp);
// return;
// }
// ProxyResponse proxyResponse = new ProxyResponse();
// proxyResponse.setStatus(ProxyResponse.Status.SUCCESS);
// proxyResponse.setCode(HttpStatus.SC_OK);
// proxyResponse.setData(
// jTokenResultAsJsonObject.get("username").getAsString().replaceAll("@carbon.super", ""));
// HandlerUtil.handleSuccess(resp, proxyResponse);
// httpSession.setAttribute(HandlerConstants.USERNAME_WITH_DOMAIN, jTokenResultAsJsonObject.get("username").getAsString());
// log.info("Customer login", userLogContextBuilder.setUserName(proxyResponse.getData()).setUserRegistered(true).build());
// }
} catch (IOException e) {
log.error("Error occurred while sending the response into the socket. ", e);
} catch (JsonSyntaxException e) {

@ -17,7 +17,8 @@
*/
package io.entgra.device.mgt.core.ui.request.interceptor.beans;
import org.apache.http.Header;
import com.fasterxml.jackson.databind.JsonNode;
import org.apache.hc.core5.http.Header;
public class ProxyResponse {
@ -27,7 +28,7 @@ public class ProxyResponse {
}
private int code;
private String data;
private JsonNode data;
private String executorResponse;
private int status;
private Header[] headers;
@ -36,9 +37,9 @@ public class ProxyResponse {
public void setCode(int code) { this.code = code; }
public String getData() { return data; }
public JsonNode getData() { return data; }
public void setData(String data) { this.data = data; }
public void setData(JsonNode data) { this.data = data; }
public String getExecutorResponse() { return executorResponse; }

@ -18,6 +18,9 @@
package io.entgra.device.mgt.core.ui.request.interceptor.util;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
@ -32,27 +35,25 @@ import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.entity.mime.InputStreamBody;
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.client5.http.ssl.NoopHostnameVerifier;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactoryBuilder;
import org.apache.hc.client5.http.ssl.TrustAllStrategy;
import org.apache.hc.core5.http.*;
import org.apache.hc.core5.http.io.entity.BufferedHttpEntity;
import org.apache.hc.core5.http.io.entity.InputStreamEntity;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.ssl.SSLContextBuilder;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.cookie.SM;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.json.JSONArray;
@ -70,13 +71,11 @@ import javax.servlet.http.HttpSession;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.*;
import java.math.BigInteger;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Enumeration;
import java.util.List;
@ -96,71 +95,75 @@ public class HandlerUtil {
* @return response as string
* @throws IOException IO exception returns if error occurs when executing the httpMethod
*/
public static ProxyResponse execute(HttpRequestBase httpRequest) throws IOException {
public static ProxyResponse execute(ClassicHttpRequest httpRequest) throws IOException {
try (CloseableHttpClient client = getHttpClient()) {
HttpResponse response = client.execute(httpRequest);
ProxyResponse proxyResponse = new ProxyResponse();
if (response == null) {
log.error("Received null response for http request : " + httpRequest.getMethod() + " " + httpRequest
.getURI().toString());
proxyResponse.setCode(HandlerConstants.INTERNAL_ERROR_CODE);
proxyResponse.setStatus(ProxyResponse.Status.ERROR);
proxyResponse.setExecutorResponse(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + getStatusKey(
JsonFactory jsonFactory = new JsonFactory();
ObjectMapper objectMapper = new ObjectMapper(jsonFactory);
return client.execute(httpRequest, response -> {
final HttpEntity responseEntity = response.getEntity();
ProxyResponse handlerResponse = new ProxyResponse();
int statusCode = response.getCode();
if (responseEntity == null) {
log.error("Received null response for http request : " + httpRequest.getMethod() + " " + httpRequest.getRequestUri());
handlerResponse.setCode(HandlerConstants.INTERNAL_ERROR_CODE);
handlerResponse.setStatus(ProxyResponse.Status.ERROR);
handlerResponse.setExecutorResponse(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + getStatusKey(
HandlerConstants.INTERNAL_ERROR_CODE));
return proxyResponse;
} else {
int statusCode = response.getStatusLine().getStatusCode();
String jsonString = getResponseString(response);
return handlerResponse;
}
try (InputStream inputStream = responseEntity.getContent()) {
JsonNode responseData = objectMapper.readTree(inputStream);
if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
proxyResponse.setCode(statusCode);
proxyResponse.setData(jsonString);
proxyResponse.setStatus(ProxyResponse.Status.SUCCESS);
proxyResponse.setExecutorResponse("SUCCESS");
proxyResponse.setHeaders(response.getAllHeaders());
return proxyResponse;
handlerResponse.setCode(statusCode);
handlerResponse.setData(responseData);
handlerResponse.setStatus(ProxyResponse.Status.SUCCESS);
handlerResponse.setExecutorResponse("SUCCESS");
handlerResponse.setHeaders(response.getHeaders());
return handlerResponse;
} else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
if (isTokenExpired(jsonString)) {
proxyResponse.setCode(statusCode);
proxyResponse.setStatus(ProxyResponse.Status.ERROR);
proxyResponse.setExecutorResponse(HandlerConstants.TOKEN_IS_EXPIRED);
if (isTokenExpired(responseData)) {
handlerResponse.setCode(statusCode);
handlerResponse.setStatus(ProxyResponse.Status.ERROR);
handlerResponse.setExecutorResponse(HandlerConstants.TOKEN_IS_EXPIRED);
} else {
log.error(
"Received " + statusCode + " response for http request : " + httpRequest.getMethod()
+ " " + httpRequest.getURI().toString() + ". Error message: " + jsonString);
proxyResponse.setCode(statusCode);
proxyResponse.setData(jsonString);
proxyResponse.setStatus(ProxyResponse.Status.ERROR);
proxyResponse.setExecutorResponse(
+ " " + httpRequest.getRequestUri() + ". Error message: " + responseData.textValue());
handlerResponse.setCode(statusCode);
handlerResponse.setData(responseData);
handlerResponse.setStatus(ProxyResponse.Status.ERROR);
handlerResponse.setExecutorResponse(
HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + getStatusKey(statusCode));
}
return proxyResponse;
return handlerResponse;
}
log.error("Received " + statusCode +
" response for http request : " + httpRequest.getMethod() + " " + httpRequest.getURI()
.toString() + ". Error message: " + jsonString);
proxyResponse.setCode(statusCode);
proxyResponse.setData(jsonString);
proxyResponse.setStatus(ProxyResponse.Status.ERROR);
proxyResponse
log.error("Received " + statusCode + " response for http request : " + httpRequest.getMethod()
+ " " + httpRequest.getRequestUri() + ". Error message: " + responseData.textValue());
handlerResponse.setCode(statusCode);
handlerResponse.setData(responseData);
handlerResponse.setStatus(ProxyResponse.Status.ERROR);
handlerResponse
.setExecutorResponse(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + getStatusKey(statusCode));
return proxyResponse;
return handlerResponse;
}
});
}
}
public static boolean isTokenExpired(String jsonBody) {
return jsonBody.contains("Access token expired") || jsonBody
public static boolean isTokenExpired(JsonNode jsonBody) {
return jsonBody.textValue().contains("Access token expired") || jsonBody.textValue()
.contains("Invalid input. Access token validation failed");
}
public static String getMemeType(HttpResponse response) {
String memeType = "";
Header contentType = response.getEntity().getContentType();
if (contentType != null) {
memeType = contentType.getValue().split(";")[0].trim();
return contentType.getValue().split(";")[0].trim();
}
return memeType;
return "";
}
/***
@ -367,7 +370,21 @@ public class HandlerUtil {
boolean isIgnoreHostnameVerification = Boolean.parseBoolean(System.
getProperty("org.wso2.ignoreHostnameVerification"));
if (isIgnoreHostnameVerification) {
return HttpClients.custom().setHostnameVerifier((X509HostnameVerifier) NoopHostnameVerifier.INSTANCE).build();
try {
return HttpClients.custom()
.setConnectionManager(PoolingHttpClientConnectionManagerBuilder.create()
.setSSLSocketFactory(SSLConnectionSocketFactoryBuilder.create()
.setSslContext(SSLContextBuilder.create()
.loadTrustMaterial(TrustAllStrategy.INSTANCE)
.build())
.setHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.build())
.build())
.build();
} catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
log.error("Error Occurred while creating the custom http client", e);
throw new RuntimeException(e);
}
} else {
return HttpClients.createDefault();
}

Loading…
Cancel
Save