From f15fdae8a56e1f71fef09f05d031436dc7a7b0b3 Mon Sep 17 00:00:00 2001 From: Madawa Soysa Date: Fri, 21 Jun 2019 17:16:26 +1000 Subject: [PATCH] Refactor ui request interceptor Related to: entgra/product-iots#103 --- .../request/interceptor/InvokerHandler.java | 16 +++++----- .../ui/request/interceptor/LoginHandler.java | 30 +++++++++---------- .../request/interceptor/util/HandlerUtil.java | 14 +++++---- 3 files changed, 29 insertions(+), 31 deletions(-) diff --git a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/InvokerHandler.java b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/InvokerHandler.java index 864f5d6801..8acf32b2f6 100644 --- a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/InvokerHandler.java +++ b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/InvokerHandler.java @@ -58,8 +58,6 @@ import java.io.IOException; import java.util.Enumeration; import java.util.List; -import static io.entgra.ui.request.interceptor.util.HandlerUtil.execute; - @MultipartConfig @WebServlet( name = "RequestHandlerServlet", @@ -84,7 +82,7 @@ public class InvokerHandler extends HttpServlet { HttpPost postRequest = new HttpPost(generateBackendRequestURL(req)); generateRequestEntity(req, postRequest); postRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken()); - ProxyResponse proxyResponse = execute(postRequest); + ProxyResponse proxyResponse = HandlerUtil.execute(postRequest); if (HandlerConstants.TOKEN_IS_EXPIRED.equals(proxyResponse.getExecutorResponse())) { proxyResponse = retryRequestWithRefreshedToken(req, resp, postRequest); @@ -113,7 +111,7 @@ public class InvokerHandler extends HttpServlet { HttpGet getRequest = new HttpGet(generateBackendRequestURL(req)); copyRequestHeaders(req, getRequest, false); getRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken()); - ProxyResponse proxyResponse = execute(getRequest); + ProxyResponse proxyResponse = HandlerUtil.execute(getRequest); if (HandlerConstants.TOKEN_IS_EXPIRED.equals(proxyResponse.getExecutorResponse())) { proxyResponse = retryRequestWithRefreshedToken(req, resp, getRequest); if (proxyResponse == null) { @@ -139,7 +137,7 @@ public class InvokerHandler extends HttpServlet { HttpPut putRequest = new HttpPut(generateBackendRequestURL(req)); generateRequestEntity(req, putRequest); putRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken()); - ProxyResponse proxyResponse = execute(putRequest); + ProxyResponse proxyResponse = HandlerUtil.execute(putRequest); if (HandlerConstants.TOKEN_IS_EXPIRED.equals(proxyResponse.getExecutorResponse())) { proxyResponse = retryRequestWithRefreshedToken(req, resp, putRequest); @@ -168,7 +166,7 @@ public class InvokerHandler extends HttpServlet { HttpDelete deleteRequest = new HttpDelete(generateBackendRequestURL(req)); copyRequestHeaders(req, deleteRequest, false); deleteRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken()); - ProxyResponse proxyResponse = execute(deleteRequest); + ProxyResponse proxyResponse = HandlerUtil.execute(deleteRequest); if (HandlerConstants.TOKEN_IS_EXPIRED.equals(proxyResponse.getExecutorResponse())) { proxyResponse = retryRequestWithRefreshedToken(req, resp, deleteRequest); if (proxyResponse == null) { @@ -202,7 +200,7 @@ public class InvokerHandler extends HttpServlet { List fileItemList = servletFileUpload.parseRequest(req); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); - for (FileItem item : fileItemList) { + for (FileItem item: fileItemList) { if (!item.isFormField()) { entityBuilder.addPart(item.getFieldName(), new InputStreamBody(item.getInputStream(), ContentType.create(item.getContentType()), item.getName())); @@ -321,7 +319,7 @@ public class InvokerHandler extends HttpServlet { HttpRequestBase httpRequest) throws IOException { if (refreshToken(req, resp)) { httpRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken()); - ProxyResponse proxyResponse = execute(httpRequest); + ProxyResponse proxyResponse = HandlerUtil.execute(httpRequest); if (proxyResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { log.error("Error occurred while invoking the API after refreshing the token."); HandlerUtil.handleError(req, resp, serverUrl, platform, proxyResponse); @@ -363,7 +361,7 @@ public class InvokerHandler extends HttpServlet { encodedClientApp); tokenEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()); - ProxyResponse tokenResultResponse = execute(tokenEndpoint); + ProxyResponse tokenResultResponse = HandlerUtil.execute(tokenEndpoint); if (tokenResultResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { log.error("Error occurred while refreshing access token."); HandlerUtil.handleError(req, resp, serverUrl, platform, tokenResultResponse); diff --git a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/LoginHandler.java b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/LoginHandler.java index 25516268c6..f35f0151e1 100644 --- a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/LoginHandler.java +++ b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/LoginHandler.java @@ -50,8 +50,6 @@ import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.Base64; -import static io.entgra.ui.request.interceptor.util.HandlerUtil.execute; - @MultipartConfig @WebServlet("/login") public class LoginHandler extends HttpServlet { @@ -78,12 +76,12 @@ public class LoginHandler extends HttpServlet { httpSession.invalidate(); } httpSession = req.getSession(true); - //setting session to expiry in 5 mins + //setting session to expiry in 5 minutes httpSession.setMaxInactiveInterval(Math.toIntExact(HandlerConstants.TIMEOUT)); HttpGet uiConfigEndpoint = new HttpGet(uiConfigUrl); JsonParser jsonParser = new JsonParser(); - ProxyResponse uiConfigResponse = execute(uiConfigEndpoint); + ProxyResponse uiConfigResponse = HandlerUtil.execute(uiConfigEndpoint); String executorResponse = uiConfigResponse.getExecutorResponse(); if (!StringUtils.isEmpty(executorResponse) && executorResponse .contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { @@ -126,7 +124,7 @@ public class LoginHandler extends HttpServlet { apiRegEndpoint.setHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); apiRegEndpoint.setEntity(constructAppRegPayload(tags)); - ProxyResponse clientAppResponse = execute(apiRegEndpoint); + ProxyResponse clientAppResponse = HandlerUtil.execute(apiRegEndpoint); String clientAppResult = clientAppResponse.getData(); if (!StringUtils.isEmpty(clientAppResult) && getTokenAndPersistInSession(req, resp, @@ -141,11 +139,11 @@ public class LoginHandler extends HttpServlet { HandlerUtil.handleError(req, resp, serverUrl, platform, null); } } catch (IOException e) { - log.error("Error occured while sending the response into the socket. ", e); + log.error("Error occurred while sending the response into the socket. ", e); } catch (JsonSyntaxException e) { - log.error("Error occured while parsing the response. ", e); + log.error("Error occurred while parsing the response. ", e); } catch (LoginException e) { - log.error("Error occured while getting token data. ", e); + log.error("Error occurred while getting token data. ", e); } } @@ -203,7 +201,7 @@ public class LoginHandler extends HttpServlet { } return false; } catch (IOException e) { - throw new LoginException("Error occured while sending the response into the socket", e); + throw new LoginException("Error occurred while sending the response into the socket", e); } } @@ -216,8 +214,8 @@ public class LoginHandler extends HttpServlet { if (scopes != null && scopes.size() > 0) { StringBuilder builder = new StringBuilder(); for (JsonElement scope : scopes) { - String tmpscope = scope.getAsString() + " "; - builder.append(tmpscope); + String tmpScope = scope.getAsString() + " "; + builder.append(tmpScope); } return builder.toString(); } else { @@ -248,7 +246,7 @@ public class LoginHandler extends HttpServlet { " Invalid login request. Username or Password is not received for login request."); } } catch (IOException e) { - throw new LoginException("Error Occured while redirecting to default error page.", e); + throw new LoginException("Error occurred while redirecting to default error page.", e); } } @@ -271,13 +269,13 @@ public class LoginHandler extends HttpServlet { * @param encodedClientApp - Base64 encoded clientId:clientSecret. * @param scopes - Scopes which are retrieved by reading application-mgt configuration * @return Invoke token endpoint and return the response as string. - * @throws IOException IO exception throws if an error occured when invoking token endpoint + * @throws IOException IO exception throws if an error occurred when invoking token endpoint */ private ProxyResponse getTokenResult(String encodedClientApp, JsonArray scopes) throws IOException { HttpPost tokenEndpoint = new HttpPost(serverUrl + HandlerConstants.TOKEN_ENDPOINT); - tokenEndpoint.setHeader("Authorization", "Basic " + encodedClientApp); - tokenEndpoint.setHeader("Content-Type", ContentType.APPLICATION_FORM_URLENCODED.toString()); + tokenEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + encodedClientApp); + tokenEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()); String scopeString = getScopeString(scopes); if (scopeString != null) { @@ -290,6 +288,6 @@ public class LoginHandler extends HttpServlet { "grant_type=password&username=" + username + "&password=" + password + "&scope=" + scopeString, ContentType.APPLICATION_FORM_URLENCODED); tokenEndpoint.setEntity(tokenEPPayload); - return execute(tokenEndpoint); + return HandlerUtil.execute(tokenEndpoint); } } diff --git a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/util/HandlerUtil.java b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/util/HandlerUtil.java index f3baea315f..399655ae0a 100644 --- a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/util/HandlerUtil.java +++ b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/util/HandlerUtil.java @@ -23,9 +23,11 @@ import com.google.gson.JsonObject; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.apache.http.Consts; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.methods.HttpRequestBase; +import org.apache.http.entity.ContentType; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.json.JSONException; @@ -79,7 +81,7 @@ public class HandlerUtil { if (jsonString.contains("Access token expired") || jsonString .contains("Invalid input. Access token validation failed")) { proxyResponse.setCode(statusCode); - proxyResponse.setExecutorResponse("ACCESS_TOKEN_IS_EXPIRED"); + proxyResponse.setExecutorResponse(HandlerConstants.TOKEN_IS_EXPIRED); return proxyResponse; } else { proxyResponse.setCode(statusCode); @@ -161,8 +163,8 @@ public class HandlerUtil { } resp.setStatus(proxyResponse.getCode()); - resp.setContentType("application/json"); - resp.setCharacterEncoding("UTF-8"); + resp.setContentType(ContentType.APPLICATION_JSON.getMimeType()); + resp.setCharacterEncoding(Consts.UTF_8.name()); if (httpSession != null) { JsonObject uiConfig = (JsonObject) httpSession.getAttribute(HandlerConstants.UI_CONFIG_KEY); @@ -192,13 +194,13 @@ public class HandlerUtil { public static void handleSuccess(HttpServletRequest req, HttpServletResponse resp, String serverUrl, String platform, ProxyResponse proxyResponse) throws IOException { if (proxyResponse == null){ - handleError(req,resp,serverUrl,platform,proxyResponse); + handleError(req, resp, serverUrl, platform, null); return; } resp.setStatus(proxyResponse.getCode()); - resp.setContentType("application/json"); - resp.setCharacterEncoding("UTF-8"); + resp.setContentType(ContentType.APPLICATION_JSON.getMimeType()); + resp.setCharacterEncoding(Consts.UTF_8.name()); JSONObject response = new JSONObject(); String redirectUrl = proxyResponse.getUrl();