diff options
Diffstat (limited to 'ecomp-sdk/epsdk-fw/src/main/java/org/openecomp/portalsdk/core/onboarding/crossapi')
5 files changed, 1059 insertions, 0 deletions
diff --git a/ecomp-sdk/epsdk-fw/src/main/java/org/openecomp/portalsdk/core/onboarding/crossapi/IPortalRestAPIService.java b/ecomp-sdk/epsdk-fw/src/main/java/org/openecomp/portalsdk/core/onboarding/crossapi/IPortalRestAPIService.java new file mode 100644 index 00000000..0efd1ce4 --- /dev/null +++ b/ecomp-sdk/epsdk-fw/src/main/java/org/openecomp/portalsdk/core/onboarding/crossapi/IPortalRestAPIService.java @@ -0,0 +1,175 @@ +/*- + * ================================================================================ + * ECOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.onboarding.crossapi; + +import java.util.List; + +import javax.servlet.http.HttpServletRequest; + +import org.openecomp.portalsdk.core.onboarding.exception.PortalAPIException; +import org.openecomp.portalsdk.core.restful.domain.EcompRole; +import org.openecomp.portalsdk.core.restful.domain.EcompUser; + +/** + * Defines the REST API Interface that an on-boarding application must implement + * to answer queries and accept updates from the ECOMP Portal about the + * application's users, roles and user-role assignments. + */ +public interface IPortalRestAPIService { + + // EcompUser Interface + + /** + * Creates a user with the specified details. If any error occurs, for + * example the user exists, the method should throw PortalApiException with + * an appropriate message. The FW library will catch the exception and send + * an appropriate response to Portal. + * + * @param user + * Model object with attributes of user to be created. + * @throws PortalAPIException + * If any error occurs while processing the request; for + * example, user exists. + */ + public void pushUser(EcompUser user) throws PortalAPIException; + + /** + * Updates details about the user with the specified loginId. For example, + * mark user as inactive. If any error occurs, the method should throw + * PortalApiException with an appropriate message. The FW library will catch + * the exception and send an appropriate response to Portal. + * + * @param loginId + * EcompUser ID to be updated. + * @param user + * Model object with attributes of user to be updated. + * @throws PortalAPIException + * If any error occurs while processing the request; for + * example, unknown user. + */ + public void editUser(String loginId, EcompUser user) throws PortalAPIException; + + /** + * Gets and returns the user object with the specified loginId. If any error + * occurs, the method should throw PortalApiException with an appropriate + * message. The FW library will catch the exception and send an appropriate + * response to Portal + * + * @param loginId + * EcompUser ID to be fetched + * @return Model object with user attributes. + * @throws PortalAPIException + * If any error occurs while processing the request; for + * example, unknown user. + */ + public EcompUser getUser(String loginId) throws PortalAPIException; + + /** + * Gets and returns a list of active users. If any error occurs, the method + * should throw PortalApiException with an appropriate message. The FW + * library will catch the exception and send an appropriate response to + * Portal. + * + * @return List of user attribute model objects; empty list if none are + * found. + * @throws PortalAPIException + * If any error occurs while processing the request. + */ + public List<EcompUser> getUsers() throws PortalAPIException; + + // Roles Interface + + /** + * Gets and returns a list of active roles. If any error occurs, the method + * should throw PortalApiException with an appropriate message. The FW + * library will catch the exception and send an appropriate response to + * Portal. + * + * @return List of role attribute objects; empty list if none are found. + * @throws PortalAPIException + * If an unexpected error occurs while processing the request. + */ + public List<EcompRole> getAvailableRoles() throws PortalAPIException; + + /** + * Updates roles for the user with the specified loginId to the list of + * roles provided as the second argument. After this operation, the should + * have ONLY the roles provided in the list above. For example, if user had + * roles r1, r2 and r3; and a call was made to pushUserRole with a list + * containing only roles r3 and r4, this method should leave the user with + * roles r3 and r4 since those were the ONLY roles provided in second + * argument. If any error occurs, the method should throw PortalApiException + * with an appropriate message. The FW library will catch the exception and + * send an appropriate response to Portal. + * + * @param loginId + * EcompUser ID to be updated. + * @param roles + * List of role attribute objects + * @throws PortalAPIException + * If any error occurs while processing the request. + */ + public void pushUserRole(String loginId, List<EcompRole> roles) throws PortalAPIException; + + /** + * Gets and returns a list of roles for the user with the specified loginId. + * If any error occurs, the method should throw PortalApiException with an + * appropriate message. The FW library will catch the exception and send an + * appropriate response to Portal. + * + * @param loginId + * @return List of model objects; empty if no roles are found. + * @throws PortalAPIException + * If any error occurs while processing the request; e.g., user + * not found. + */ + public List<EcompRole> getUserRoles(String loginId) throws PortalAPIException; + + // Security Interface + + /** + * Should return true if the call should be allowed and false if not. + * Currently Portal sends two headers of username and password in each + * request which the app should check. If match, return true; else return + * false. If any error occurs, the method should throw PortalApiException + * with an appropriate message. The FW library will catch the exception and + * send an appropriate response to Portal. + * + * @param request + * @return true if the request contains appropriate credentials, else false. + * @throws PortalAPIException + * If an unexpected error occurs while processing the request. + */ + public boolean isAppAuthenticated(HttpServletRequest request) throws PortalAPIException; + + /** + * Gets and returns the userId for the logged-in user based on the request. + * If any error occurs, the method should throw PortalApiException with an + * appropriate message. The FW library will catch the exception and send an + * appropriate response to Portal. + * + * @param request + * @return true if the request contains appropriate credentials, else false. + * @throws PortalAPIException + * If an unexpected error occurs while processing the request. + */ + public String getUserId(HttpServletRequest request) throws PortalAPIException; + +} diff --git a/ecomp-sdk/epsdk-fw/src/main/java/org/openecomp/portalsdk/core/onboarding/crossapi/IPortalUebAPIService.java b/ecomp-sdk/epsdk-fw/src/main/java/org/openecomp/portalsdk/core/onboarding/crossapi/IPortalUebAPIService.java new file mode 100644 index 00000000..b6e0150e --- /dev/null +++ b/ecomp-sdk/epsdk-fw/src/main/java/org/openecomp/portalsdk/core/onboarding/crossapi/IPortalUebAPIService.java @@ -0,0 +1,47 @@ +/*- + * ================================================================================ + * ECOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.onboarding.crossapi; + +import org.openecomp.portalsdk.core.onboarding.exception.PortalAPIException; + +/** + * + * @author Ikram Ikramullah + * + * UEB API Interface for all the onboarding third party applications. + * + */ + +public interface IPortalUebAPIService { + //User Interface + public String pushUser(String userJson) throws PortalAPIException; + public String editUser(String loginId, String userJson) throws PortalAPIException; + public String getUser(String loginId) throws PortalAPIException; + public String getUsers() throws PortalAPIException; + + //Roles Interface + public String getAvailableRoles() throws PortalAPIException; + public String getAvailableFullRoles() throws PortalAPIException; + public String pushUserRole(String loginId, String rolesJson) throws PortalAPIException; + public String getUserRoles(String loginId) throws PortalAPIException; + + //Security Interface + public boolean isAppAuthenticated(String appUserName, String appPassword) throws PortalAPIException; +} diff --git a/ecomp-sdk/epsdk-fw/src/main/java/org/openecomp/portalsdk/core/onboarding/crossapi/PortalAPIResponse.java b/ecomp-sdk/epsdk-fw/src/main/java/org/openecomp/portalsdk/core/onboarding/crossapi/PortalAPIResponse.java new file mode 100644 index 00000000..ad1eae8d --- /dev/null +++ b/ecomp-sdk/epsdk-fw/src/main/java/org/openecomp/portalsdk/core/onboarding/crossapi/PortalAPIResponse.java @@ -0,0 +1,58 @@ +/*- + * ================================================================================ + * ECOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.onboarding.crossapi; + +/** + * This bean holds a response that is returned by the role and user-management + * REST API. + */ +public class PortalAPIResponse { + + /** + * Either "ok" or "error" + */ + private String status; + /** + * Optional if status is ok + */ + private String message; + + public PortalAPIResponse(boolean isOk, String msg) { + status = (isOk? "ok" : "error"); + message = msg; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + +} diff --git a/ecomp-sdk/epsdk-fw/src/main/java/org/openecomp/portalsdk/core/onboarding/crossapi/PortalRestAPIProxy.java b/ecomp-sdk/epsdk-fw/src/main/java/org/openecomp/portalsdk/core/onboarding/crossapi/PortalRestAPIProxy.java new file mode 100644 index 00000000..02d35ae9 --- /dev/null +++ b/ecomp-sdk/epsdk-fw/src/main/java/org/openecomp/portalsdk/core/onboarding/crossapi/PortalRestAPIProxy.java @@ -0,0 +1,618 @@ +/*- + * ================================================================================ + * ECOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.onboarding.crossapi; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.List; +import java.util.Map; + +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.openecomp.portalsdk.core.onboarding.exception.PortalAPIException; +import org.openecomp.portalsdk.core.onboarding.listener.PortalTimeoutHandler; +import org.openecomp.portalsdk.core.onboarding.rest.RestWebServiceClient; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties; +import org.openecomp.portalsdk.core.restful.domain.EcompRole; +import org.openecomp.portalsdk.core.restful.domain.EcompUser; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * This servlet performs the functions described below. It listens on a path + * like "/api" (see {@link PortalApiConstants#API_PREFIX}). The servlet checks + * for authorized access and rejects unauthorized requests. + * <OL> + * <LI>Proxies user (i.e., browser) requests for web analytics. The GET method + * fetches javascript from the Portal and returns it. The POST method forwards + * data sent by the browser on to Portal. These requests are checked for a valid + * User UID in a header; these requests do NOT use the application + * username-password header.</LI> + * <LI>Responds to ECOMP Portal API requests to query and update user, role and + * user-role information. The servlet proxies all requests on to a local Java + * class that implements {@link IPortalRestAPIService}. These requests must have + * the application username-password header.</LI> + * </OL> + * This servlet will not start if the required portal.properties file is not + * found on the classpath. + */ + +@WebServlet(urlPatterns = { PortalApiConstants.API_PREFIX + "/*" }) +public class PortalRestAPIProxy extends HttpServlet implements IPortalRestAPIService { + private static final long serialVersionUID = 1L; + + private static final String contentTypeAppJson = "application/json"; + + private final Log logger = LogFactory.getLog(getClass()); + + /** + * Mapper for JSON to object etc. + */ + private final ObjectMapper mapper = new ObjectMapper(); + + /** + * Client-supplied class that implements our interface. + */ + private static IPortalRestAPIService portalRestApiServiceImpl; + + public PortalRestAPIProxy() { + // Ensure that any additional fields sent by the Portal + // will be ignored when creating objects. + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + } + + @Override + public void init() throws ServletException { + String className = PortalApiProperties.getProperty(PortalApiConstants.PORTAL_API_IMPL_CLASS); + if (className == null) + throw new ServletException( + "init: Failed to find class name property " + PortalApiConstants.PORTAL_API_IMPL_CLASS); + try { + logger.debug("init: creating instance of class " + className); + Class<?> implClass = Class.forName(className); + portalRestApiServiceImpl = (IPortalRestAPIService) (implClass.getConstructor().newInstance()); + } catch (Exception ex) { + throw new ServletException("init: Failed to find or instantiate class " + className, ex); + } + } + + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws IOException, ServletException { + + if (portalRestApiServiceImpl == null) { + // Should never happen due to checks in init() + logger.error("doPost: no service class instance"); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + response.getWriter().write(buildJsonResponse(false, "Misconfigured - no instance of service class")); + return; + } + String requestUri = request.getRequestURI(); + String responseJson = ""; + String storeAnalyticsContextPath = "/storeAnalytics"; + if (requestUri.endsWith(PortalApiConstants.API_PREFIX + storeAnalyticsContextPath)) { + String userId; + try { + userId = getUserId(request); + } catch (PortalAPIException e) { + logger.error("Issue with invoking getUserId implemenation !!! ", e); + throw new ServletException(e); + } + if (userId == null || userId.length() == 0) { + logger.debug("doPost: userId is null or empty"); + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + responseJson = buildJsonResponse(false, "Not authorized for " + storeAnalyticsContextPath); + } else { + // User ID obtained from request + try { + String credential = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY); + // for now lets also pass uebkey as user name and password + String requestBody = readRequestBody(request); + @SuppressWarnings("unchecked") + Map<String, String> bodyMap = mapper.readValue(requestBody, Map.class); + // add user ID + bodyMap.put("userid", userId); + requestBody = mapper.writeValueAsString(bodyMap); + responseJson = RestWebServiceClient.getInstance().postPortalContent(storeAnalyticsContextPath, + userId, credential, null, credential, credential, "application/json", requestBody); + if (logger.isDebugEnabled()) + logger.debug("doPost: postPortalContent returns " + responseJson); + response.setStatus(HttpServletResponse.SC_OK); + } catch (Exception ex) { + logger.error("doPost: " + storeAnalyticsContextPath + " caught exception", ex); + responseJson = buildJsonResponse(ex); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + } + writeAndFlush(response, contentTypeAppJson, responseJson); + return; + } // post analytics + + boolean secure = false; + try { + secure = isAppAuthenticated(request); + } catch (PortalAPIException ex) { + logger.error("doPost: isAppAuthenticated threw exception", ex); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + response.getWriter().write(buildJsonResponse(false, "Failed to authenticate request")); + return; + } + if (!secure) { + if (logger.isDebugEnabled()) + logger.debug("doPost: isAppAuthenticated answered false"); + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + writeAndFlush(response, contentTypeAppJson, buildJsonResponse(false, "Not authorized")); + return; + } + + try { + String requestBody = readRequestBody(request); + if (logger.isDebugEnabled()) + logger.debug("doPost: URI = " + requestUri + ", payload = " + requestBody); + + /* + * All APIs: + * + * 1. /user <-- save user + * + * 2. /user/{loginId} <-- edit user + * + * 3. /user/{loginId}/roles <-- save roles for user + */ + + // On success return the empty string. + + if (requestUri.endsWith("/updateSessionTimeOuts")) { + if (updateSessionTimeOuts(requestBody)) { + if (logger.isDebugEnabled()) + logger.debug("doPost: updated session timeouts"); + response.setStatus(HttpServletResponse.SC_OK); + } else { + String msg = "Failed to update session time outs"; + logger.error("doPost: " + msg); + responseJson = buildJsonResponse(false, msg); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + } else if (requestUri.endsWith("/timeoutSession")) { + String portalJSessionId = request.getParameter("portalJSessionId"); + if (portalJSessionId == null) { + portalJSessionId = ""; + } + if (timeoutSession(portalJSessionId)) { + if (logger.isDebugEnabled()) + logger.debug("doPost: timed out session"); + response.setStatus(HttpServletResponse.SC_OK); + } else { + String msg = "Failed to timeout session"; + logger.error("doPost: " + msg); + responseJson = buildJsonResponse(false, msg); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + } else + // Example: /user <-- create user + if (requestUri.endsWith(PortalApiConstants.API_PREFIX + "/user")) { + try { + EcompUser user = mapper.readValue(requestBody, EcompUser.class); + pushUser(user); + if (logger.isDebugEnabled()) + logger.debug("doPost: pushUser: success"); + responseJson = buildJsonResponse(true, null); + response.setStatus(HttpServletResponse.SC_OK); + } catch (Exception ex) { + responseJson = buildJsonResponse(ex); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + logger.error("doPost: pushUser: caught exception", ex); + } + } else + // Example: /user/fi241c <-- edit user fi241c + if (requestUri.contains(PortalApiConstants.API_PREFIX + "/user/") && !(requestUri.endsWith("/roles"))) { + String loginId = requestUri.substring(requestUri.lastIndexOf('/') + 1); + try { + EcompUser user = mapper.readValue(requestBody, EcompUser.class); + editUser(loginId, user); + if (logger.isDebugEnabled()) + logger.debug("doPost: editUser: success"); + responseJson = buildJsonResponse(true, null); + response.setStatus(HttpServletResponse.SC_OK); + } catch (Exception ex) { + responseJson = buildJsonResponse(ex); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + logger.error("doPost: editUser: caught exception", ex); + } + } else + // Example: /user/{loginId}/roles <-- save roles for user + if (requestUri.contains(PortalApiConstants.API_PREFIX + "/user/") && requestUri.endsWith("/roles")) { + String loginId = requestUri.substring(requestUri.indexOf("/user/") + ("/user").length() + 1, + requestUri.lastIndexOf('/')); + try { + TypeReference<List<EcompRole>> typeRef = new TypeReference<List<EcompRole>>() { + }; + List<EcompRole> roles = mapper.readValue(requestBody, typeRef); + pushUserRole(loginId, roles); + if (logger.isDebugEnabled()) + logger.debug("doPost: pushUserRole: success"); + responseJson = buildJsonResponse(true, null); + response.setStatus(HttpServletResponse.SC_OK); + } catch (Exception ex) { + responseJson = buildJsonResponse(ex); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + logger.error("doPost: pushUserRole: caught exception", ex); + } + } else { + String msg = "doPost: no match for request " + requestUri; + logger.warn(msg); + responseJson = buildJsonResponse(false, msg); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + } + } catch (Exception ex) { + logger.error("doPost: Failed to process request " + requestUri, ex); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + responseJson = buildJsonResponse(ex); + } + + writeAndFlush(response, contentTypeAppJson, responseJson); + + } + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws IOException, ServletException { + + if (portalRestApiServiceImpl == null) { + // Should never happen due to checks in init() + logger.error("doGet: no service class instance"); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + writeAndFlush(response, contentTypeAppJson, + buildJsonResponse(false, "Misconfigured - no instance of service class")); + return; + } + + String requestUri = request.getRequestURI(); + String responseString = ""; + String contentType = contentTypeAppJson; + + String webAnalyticsContextPath = "/analytics"; + if (requestUri.endsWith(PortalApiConstants.API_PREFIX + webAnalyticsContextPath)) { + String userId; + try { + userId = getUserId(request); + } catch (PortalAPIException e) { + logger.error("Issue with invoking getUserId implemenation !!! ", e); + throw new ServletException(e); + } + if (userId == null || userId.length() == 0) { + logger.debug("doGet: userId is null or empty"); + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + responseString = buildJsonResponse(false, "Not authorized for " + webAnalyticsContextPath); + } else { + // User ID obtained from request + try { + String credential = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY); + // for now lets also pass uebkey as user name and password + contentType = "text/javascript"; + responseString = RestWebServiceClient.getInstance().getPortalContent(webAnalyticsContextPath, + userId, credential, null, credential, credential); + if (logger.isDebugEnabled()) + logger.debug("doGet: " + webAnalyticsContextPath + ": " + responseString); + response.setStatus(HttpServletResponse.SC_OK); + } catch (Exception ex) { + responseString = buildJsonResponse(ex); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + logger.error("doGet: " + webAnalyticsContextPath + " caught exception", ex); + } + } + writeAndFlush(response, contentType, responseString); + return; + } + + boolean secure = false; + try { + secure = isAppAuthenticated(request); + } catch (PortalAPIException ex) { + logger.error("doGet: isAppAuthenticated threw exception", ex); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + writeAndFlush(response, contentTypeAppJson, buildJsonResponse(false, "Failed to authenticate request")); + return; + } + + if (!secure) { + if (logger.isDebugEnabled()) + logger.debug("doGet: isAppAuthenticated answered false"); + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + writeAndFlush(response, contentTypeAppJson, buildJsonResponse(false, "Not authorized")); + return; + } + + String responseJson = null; + try { + // Ignore any request body in a GET. + // String requestBody = readRequestBody(request); + if (logger.isDebugEnabled()) + logger.debug("doGet: URI = " + requestUri); + + /* + * 1. /roles <-- get roles + * + * 2. /user/{loginId} <-- get user + * + * 3. /users <-- get all users + * + * 4. /user/{loginId}/roles <-- get roles for user + */ + + if (requestUri.endsWith("/sessionTimeOuts")) { + responseJson = getSessionTimeOuts(); + if (responseJson != null && responseJson.length() > 0) { + if (logger.isDebugEnabled()) + logger.debug("doGet: got session timeouts"); + response.setStatus(HttpServletResponse.SC_OK); + } else { + String msg = "Failed to get session time outs"; + logger.error("doGet: " + msg); + responseJson = buildJsonResponse(false, msg); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + } else + // Example: /users <-- get all users + if (requestUri.endsWith(PortalApiConstants.API_PREFIX + "/users")) { + try { + List<EcompUser> users = getUsers(); + responseJson = mapper.writeValueAsString(users); + if (logger.isDebugEnabled()) + logger.debug("doGet: getUsers: " + responseJson); + } catch (Exception ex) { + responseJson = buildJsonResponse(ex); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + logger.error("doGet: getUsers: caught exception", ex); + } + } else + // Example: /roles <-- get all roles + if (requestUri.endsWith(PortalApiConstants.API_PREFIX + "/roles")) { + try { + List<EcompRole> roles = getAvailableRoles(); + responseJson = mapper.writeValueAsString(roles); + if (logger.isDebugEnabled()) + logger.debug("doGet: getAvailableRoles: " + responseJson); + } catch (Exception ex) { + responseJson = buildJsonResponse(ex); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + logger.error("doGet: getAvailableRoles: caught exception", ex); + } + } else + // Example: /user/fi241c <-- get user fi241c + if (requestUri.contains(PortalApiConstants.API_PREFIX + "/user/") && !requestUri.endsWith("/roles")) { + String loginId = requestUri.substring(requestUri.lastIndexOf('/') + 1); + try { + EcompUser user = getUser(loginId); + responseJson = mapper.writeValueAsString(user); + if (logger.isDebugEnabled()) + logger.debug("doGet: getUser: " + responseJson); + } catch (Exception ex) { + responseJson = buildJsonResponse(ex); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + logger.error("doGet: getUser: caught exception", ex); + } + } + // Example: /user/fi241c/roles <-- get roles for user fi241c + else if (requestUri.contains(PortalApiConstants.API_PREFIX + "/user/") && requestUri.endsWith("/roles")) { + String loginId = requestUri.substring(requestUri.indexOf("/user/") + ("/user").length() + 1, + requestUri.lastIndexOf('/')); + try { + List<EcompRole> roles = getUserRoles(loginId); + responseJson = mapper.writeValueAsString(roles); + if (logger.isDebugEnabled()) + logger.debug("doGet: getUserRoles: " + responseJson); + } catch (Exception ex) { + responseJson = buildJsonResponse(ex); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + logger.error("doGet: getUserRoles: caught exception", ex); + } + } else { + logger.warn("doGet: no match found for request"); + responseJson = buildJsonResponse(false, "No match for request"); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + } + } catch (Exception ex) { + logger.error("doGet: Failed to process request", ex); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + responseJson = buildJsonResponse(ex); + } + writeAndFlush(response, contentTypeAppJson, responseJson); + } + + public String getSessionTimeOuts() throws Exception { + return PortalTimeoutHandler.gatherSessionExtensions(); + } + + public boolean timeoutSession(String portalJSessionId) throws Exception { + return PortalTimeoutHandler.invalidateSession(portalJSessionId); + } + + public boolean updateSessionTimeOuts(String sessionMap) throws Exception { + return PortalTimeoutHandler.updateSessionExtensions(sessionMap); + } + + @Override + public void pushUser(EcompUser user) throws PortalAPIException { + portalRestApiServiceImpl.pushUser(user); + } + + @Override + public void editUser(String loginId, EcompUser user) throws PortalAPIException { + portalRestApiServiceImpl.editUser(loginId, user); + } + + @Override + public EcompUser getUser(String loginId) throws PortalAPIException { + return portalRestApiServiceImpl.getUser(loginId); + } + + @Override + public List<EcompUser> getUsers() throws PortalAPIException { + return portalRestApiServiceImpl.getUsers(); + } + + @Override + public List<EcompRole> getAvailableRoles() throws PortalAPIException { + return portalRestApiServiceImpl.getAvailableRoles(); + } + + @Override + public void pushUserRole(String loginId, List<EcompRole> roles) throws PortalAPIException { + portalRestApiServiceImpl.pushUserRole(loginId, roles); + } + + @Override + public List<EcompRole> getUserRoles(String loginId) throws PortalAPIException { + return portalRestApiServiceImpl.getUserRoles(loginId); + } + + @Override + public boolean isAppAuthenticated(HttpServletRequest request) throws PortalAPIException { + return portalRestApiServiceImpl.isAppAuthenticated(request); + } + + /** + * Sets the content type and writes the response. + * + * @param response + * @param contentType + * @param responseBody + * @throws IOException + */ + private void writeAndFlush(HttpServletResponse response, String contentType, String responseBody) + throws IOException { + response.setContentType(contentType); + PrintWriter out = response.getWriter(); + out.print(responseBody); + out.flush(); + } + + /** + * Reads the request body and closes the input stream. + * + * @param request + * @return String read from the request, the empty string if nothing is + * read. + * @throws IOException + */ + private static String readRequestBody(HttpServletRequest request) throws IOException { + + String body = null; + StringBuilder stringBuilder = new StringBuilder(); + BufferedReader bufferedReader = null; + try { + InputStream inputStream = request.getInputStream(); + if (inputStream != null) { + bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); + char[] charBuffer = new char[1024]; + int bytesRead = -1; + while ((bytesRead = bufferedReader.read(charBuffer)) > 0) { + stringBuilder.append(charBuffer, 0, bytesRead); + } + } else { + stringBuilder.append(""); + } + } finally { + if (bufferedReader != null) { + try { + bufferedReader.close(); + } catch (IOException ex) { + throw ex; + } + } + } + body = stringBuilder.toString(); + return body; + } + + /** + * Builds JSON object with status + message response body. + * + * @param success + * True to indicate success, false to signal failure. + * @param msg + * Message to include in the response object; ignored if null. + * @return + * + * <pre> + * { "status" : "ok" (or "error"), "message": "some explanation" } + * </pre> + */ + private String buildJsonResponse(boolean success, String msg) { + PortalAPIResponse response = new PortalAPIResponse(success, msg); + String json = null; + try { + json = mapper.writeValueAsString(response); + } catch (JsonProcessingException ex) { + // Truly should never, ever happen + json = "{ \"status\": \"error\",\"message\":\"" + ex.toString() + "\" }"; + } + return json; + } + + /** + * Builds JSON object with status of error and message containing stack + * trace for the specified throwable. + * + * @param t + * Throwable with stack trace to use as message + * + * @return + * + * <pre> + * { "status" : "error", "message": "some-big-stacktrace" } + * </pre> + */ + private String buildJsonResponse(Throwable t) { + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + t.printStackTrace(pw); + return buildJsonResponse(false, sw.toString()); + } + + @Override + public String getUserId(HttpServletRequest request) throws PortalAPIException { + return portalRestApiServiceImpl.getUserId(request); + } + + public static IPortalRestAPIService getPortalRestApiServiceImpl() { + return portalRestApiServiceImpl; + } + + public static void setPortalRestApiServiceImpl(IPortalRestAPIService portalRestApiServiceImpl) { + PortalRestAPIProxy.portalRestApiServiceImpl = portalRestApiServiceImpl; + } + +} diff --git a/ecomp-sdk/epsdk-fw/src/main/java/org/openecomp/portalsdk/core/onboarding/crossapi/SessionCommunicationService.java b/ecomp-sdk/epsdk-fw/src/main/java/org/openecomp/portalsdk/core/onboarding/crossapi/SessionCommunicationService.java new file mode 100644 index 00000000..be3a7d54 --- /dev/null +++ b/ecomp-sdk/epsdk-fw/src/main/java/org/openecomp/portalsdk/core/onboarding/crossapi/SessionCommunicationService.java @@ -0,0 +1,161 @@ +/*- + * ================================================================================ + * ECOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.onboarding.crossapi; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +public class SessionCommunicationService { + + protected static final Log logger = LogFactory.getLog(SessionCommunicationService.class); + + /** + * Calls the ECOMP Portal to retrieve the session slot check interval. + * + * @param ecompRestURL + * @param userName + * application user name used for authentication at Portal + * @param password + * application password used for authentication at Portal + * @param uebKey + * application UEB key (basically application ID) used for + * authentication at Portal + * @return Content read from the remote REST endpoint + */ + public static String getSessionSlotCheckInterval(String ecompRestURL, String userName, String password, + String uebKey) { + try { + String url = ecompRestURL + "/getSessionSlotCheckInterval"; + + URL obj = new URL(url); + + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + + // optional default is GET + con.setRequestMethod("GET"); + con.setConnectTimeout(3000); + con.setReadTimeout(8000); + // add request header + con.setRequestProperty("username", userName); + con.setRequestProperty("password", password); + con.setRequestProperty("uebkey", uebKey); + + int responseCode = con.getResponseCode(); + if (logger.isDebugEnabled()) { + logger.debug("getSessionSlotCheckInterval: Sending 'GET' request to URL : " + url); + logger.debug("getSessionSlotCheckInterval: Response Code : " + responseCode); + } + + StringBuffer response = new StringBuffer(); + + BufferedReader in = null; + try { + in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); + String inputLine; + while ((inputLine = in.readLine()) != null) + response.append(inputLine); + } finally { + in.close(); + } + return response.toString(); + } catch (Exception e) { + logger.error("getSessionSlotCheckInterval: failed to fetch the session slot check", e); + return null; + } + + } + + /** + * Calls the ECOMP Portal to request an extension of the current session. + * + * @param ecompRestURL + * @param userName + * application user name used for authentication at Portal + * @param password + * application password used for authentication at Portal + * @param uebKey + * application UEB key (basically application ID) used for + * authentication at Portal + * @param sessionTimeoutMap + * @return Content read from the remote REST endpoint + * @throws Exception + */ + public static String requestPortalSessionTimeoutExtension(String ecompRestURL, String userName, String password, + String uebKey, String sessionTimeoutMap) throws Exception { + + try { + + String url = ecompRestURL + "/extendSessionTimeOuts"; + // String decreptedPwd = + // app.appPassword;//CipherUtil.decrypt(encriptedPwdDB, + // SystemProperties.getProperty(SystemProperties.SECRET_KEY)); + + URL obj = new URL(url); + + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + + con.setRequestMethod("POST"); + con.setConnectTimeout(3000); + con.setReadTimeout(15000); + + // add request header + con.setRequestProperty("username", userName); + con.setRequestProperty("password", password); + con.setRequestProperty("uebkey", uebKey); + con.setRequestProperty("sessionMap", sessionTimeoutMap); + con.setDoInput(true); + con.setDoOutput(true); + con.getOutputStream().write(sessionTimeoutMap.getBytes()); + con.getOutputStream().flush(); + con.getOutputStream().close(); + + // con.set + + int responseCode = con.getResponseCode(); + if (logger.isDebugEnabled()) { + logger.debug("requestPortalSessionTimeoutExtension: Sending 'GET' request to URL : " + url); + logger.debug("requestPortalSessionTimeoutExtension: Response Code : " + responseCode); + } + + StringBuffer response = new StringBuffer(); + BufferedReader in = null; + try { + in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String inputLine; + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + } finally { + in.close(); + } + return response.toString(); + } catch (Exception e) { + logger.error("requestPortalSessionTimeoutExtension: failed to request Portal to extend time out ", e); + return null; + } + + } + +} |