diff options
Diffstat (limited to 'ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding')
19 files changed, 3238 insertions, 0 deletions
diff --git a/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/crossapi/IPortalRestAPIService.java b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/crossapi/IPortalRestAPIService.java new file mode 100644 index 00000000..182d2675 --- /dev/null +++ b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/crossapi/IPortalRestAPIService.java @@ -0,0 +1,194 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal SDK + * =================================================================== + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the “License”); + * you may not use this software 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. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * 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. + * + * ============LICENSE_END============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalsdk.core.onboarding.crossapi; + +import java.util.List; + +import javax.servlet.http.HttpServletRequest; + +import org.onap.portalsdk.core.onboarding.exception.PortalAPIException; +import org.onap.portalsdk.core.restful.domain.EcompRole; +import org.onap.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. + * + * @param requestedLoginId + * requested userloginId to fetch available roles + * @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(String requestedLoginId) 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 + * Organization user ID + * @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 + * HttpServletRequest + * @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 + * HttpServletRequest + * @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/onap/portalsdk/core/onboarding/crossapi/IPortalUebAPIService.java b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/crossapi/IPortalUebAPIService.java new file mode 100644 index 00000000..aa11aafe --- /dev/null +++ b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/crossapi/IPortalUebAPIService.java @@ -0,0 +1,67 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal SDK + * =================================================================== + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the “License”); + * you may not use this software 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. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * 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. + * + * ============LICENSE_END============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalsdk.core.onboarding.crossapi; + +import org.onap.portalsdk.core.onboarding.exception.PortalAPIException; + +/** + * 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/onap/portalsdk/core/onboarding/crossapi/PortalAPIResponse.java b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/crossapi/PortalAPIResponse.java new file mode 100644 index 00000000..6ae2cdd8 --- /dev/null +++ b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/crossapi/PortalAPIResponse.java @@ -0,0 +1,76 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal SDK + * =================================================================== + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the “License”); + * you may not use this software 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. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * 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. + * + * ============LICENSE_END============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.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/onap/portalsdk/core/onboarding/crossapi/PortalRestAPIProxy.java b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/crossapi/PortalRestAPIProxy.java new file mode 100644 index 00000000..869500f2 --- /dev/null +++ b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/crossapi/PortalRestAPIProxy.java @@ -0,0 +1,636 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal SDK + * =================================================================== + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the “License”); + * you may not use this software 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. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * 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. + * + * ============LICENSE_END============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.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.onap.portalsdk.core.onboarding.exception.PortalAPIException; +import org.onap.portalsdk.core.onboarding.listener.PortalTimeoutHandler; +import org.onap.portalsdk.core.onboarding.rest.RestWebServiceClient; +import org.onap.portalsdk.core.onboarding.util.PortalApiConstants; +import org.onap.portalsdk.core.onboarding.util.PortalApiProperties; +import org.onap.portalsdk.core.restful.domain.EcompRole; +import org.onap.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, true); + 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, true); + 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(getUserId(request)); + 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() { + return PortalTimeoutHandler.gatherSessionExtensions(); + } + + public boolean timeoutSession(String portalJSessionId) { + return PortalTimeoutHandler.invalidateSession(portalJSessionId); + } + + public boolean updateSessionTimeOuts(String sessionMap) { + 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(String requestedLoginId) throws PortalAPIException { + return portalRestApiServiceImpl.getAvailableRoles(requestedLoginId); + } + + @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/onap/portalsdk/core/onboarding/crossapi/SessionCommunicationService.java b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/crossapi/SessionCommunicationService.java new file mode 100644 index 00000000..1f9bfd07 --- /dev/null +++ b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/crossapi/SessionCommunicationService.java @@ -0,0 +1,173 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal SDK + * =================================================================== + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the “License”); + * you may not use this software 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. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * 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. + * + * ============LICENSE_END============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.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 + * Remote system URL + * @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(); + try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"))) { + String inputLine; + while ((inputLine = in.readLine()) != null) + response.append(inputLine); + } + catch (Exception ex) { + logger.error("getSessionSlotCheckInterval failed to read stream", ex); + } + 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 + * Remote system URL + * @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 + * Session timeout map + * @return Content read from the remote REST endpoint + */ + public static String requestPortalSessionTimeoutExtension(String ecompRestURL, String userName, String password, + String uebKey, String sessionTimeoutMap) { + + try { + + String url = ecompRestURL + "/extendSessionTimeOuts"; + 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(); + try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) { + String inputLine; + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + } catch (Exception ex) { + logger.error("requestPortalSessionTimeoutExtension failed", ex); + } + return response.toString(); + } catch (Exception e) { + logger.error("requestPortalSessionTimeoutExtension: failed to request Portal to extend time out ", e); + return null; + } + + } + +} diff --git a/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/exception/CipherUtilException.java b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/exception/CipherUtilException.java new file mode 100644 index 00000000..a1109abe --- /dev/null +++ b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/exception/CipherUtilException.java @@ -0,0 +1,64 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal SDK + * =================================================================== + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the “License”); + * you may not use this software 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. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * 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. + * + * ============LICENSE_END============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalsdk.core.onboarding.exception; + +public class CipherUtilException extends Exception { + + private static final long serialVersionUID = -4163367786939629691L; + + public CipherUtilException() { + super(); + } + + public CipherUtilException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } + + public CipherUtilException(String message, Throwable cause) { + super(message, cause); + } + + public CipherUtilException(String message) { + super(message); + } + + public CipherUtilException(Throwable cause) { + super(cause); + } + +} diff --git a/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/exception/PortalAPIException.java b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/exception/PortalAPIException.java new file mode 100644 index 00000000..ccfb95b2 --- /dev/null +++ b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/exception/PortalAPIException.java @@ -0,0 +1,64 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal SDK + * =================================================================== + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the “License”); + * you may not use this software 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. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * 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. + * + * ============LICENSE_END============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalsdk.core.onboarding.exception; + +public class PortalAPIException extends Exception{ + + private static final long serialVersionUID = 4854048794984375707L; + + public PortalAPIException() { + super(); + } + + public PortalAPIException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } + + public PortalAPIException(String message, Throwable cause) { + super(message, cause); + } + + public PortalAPIException(String message) { + super(message); + } + + public PortalAPIException(Throwable cause) { + super(cause); + } + +} diff --git a/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/listener/PortalTimeoutBindingListener.java b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/listener/PortalTimeoutBindingListener.java new file mode 100644 index 00000000..f700f261 --- /dev/null +++ b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/listener/PortalTimeoutBindingListener.java @@ -0,0 +1,71 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal SDK + * =================================================================== + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the “License”); + * you may not use this software 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. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * 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. + * + * ============LICENSE_END============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalsdk.core.onboarding.listener; + +import java.io.Serializable; + +import javax.servlet.http.HttpSession; +import javax.servlet.http.HttpSessionBindingEvent; +import javax.servlet.http.HttpSessionBindingListener; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.onap.portalsdk.core.onboarding.util.PortalApiConstants; + +public class PortalTimeoutBindingListener implements HttpSessionBindingListener, Serializable { + + private static final long serialVersionUID = -8036365986695276137L; + + private final Log logger = LogFactory.getLog(getClass()); + + @Override + public void valueBound(HttpSessionBindingEvent event) { + final HttpSession session = event.getSession(); + PortalTimeoutHandler.sessionMap.put((String) session.getAttribute(PortalApiConstants.PORTAL_JSESSION_ID), + session); + } + + @Override + public void valueUnbound(HttpSessionBindingEvent event) { + final HttpSession session = event.getSession(); + String portalJSessionId = (String) session.getAttribute(PortalApiConstants.PORTAL_JSESSION_ID); + logger.debug(portalJSessionId + " getting removed"); + PortalTimeoutHandler.sessionMap.remove(portalJSessionId); + } + +} diff --git a/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/listener/PortalTimeoutHandler.java b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/listener/PortalTimeoutHandler.java new file mode 100644 index 00000000..649fb747 --- /dev/null +++ b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/listener/PortalTimeoutHandler.java @@ -0,0 +1,457 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal SDK + * =================================================================== + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the “License”); + * you may not use this software 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. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * 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. + * + * ============LICENSE_END============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalsdk.core.onboarding.listener; + +import java.util.Calendar; +import java.util.Hashtable; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.onap.portalsdk.core.onboarding.crossapi.SessionCommunicationService; +import org.onap.portalsdk.core.onboarding.util.PortalApiConstants; +import org.onap.portalsdk.core.restful.domain.PortalTimeoutVO; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * Invoked by listeners (UserContextListener and UserSessionListener) to track + * user sessions. + */ +public class PortalTimeoutHandler { + + protected static final SessionCommInf sessionComm = new SessionComm(); + + public interface SessionCommInf { + public Integer fetchSessionSlotCheckInterval(String... params); + + public void extendSessionTimeOuts(String... sessionMap); + } + + public static class SessionComm implements SessionCommInf { + public Integer fetchSessionSlotCheckInterval(String... params) { + + String ecompRestURL = params[0]; + String userName = params[1]; + String pwd = params[2]; + String uebKey = params[3]; + + String sessionSlot = SessionCommunicationService.getSessionSlotCheckInterval(ecompRestURL, userName, pwd, + uebKey); + if (sessionSlot == null) + return null; + return Integer.parseInt(sessionSlot); + } + + public void extendSessionTimeOuts(String... params) { + + String ecompRestURL = params[0]; + String userName = params[1]; + String pwd = params[2]; + String uebKey = params[3]; + String sessionTimeoutMap = params[4]; + + SessionCommunicationService.requestPortalSessionTimeoutExtension(ecompRestURL, userName, pwd, uebKey, + sessionTimeoutMap); + } + } + + public static final Map<String, HttpSession> sessionMap = new Hashtable<String, HttpSession>(); + public static final Integer repeatInterval = 15 * 60; // 15 minutes + protected static final Log logger = LogFactory.getLog(PortalTimeoutHandler.class); + static ObjectMapper mapper = new ObjectMapper(); + private static PortalTimeoutHandler timeoutHandler; + + public static PortalTimeoutHandler getInstance() { + if (timeoutHandler == null) + timeoutHandler = new PortalTimeoutHandler(); + + return timeoutHandler; + } + + /** + * TODO: remove static + * + * @param portalJSessionId + * Portal (remote) session ID + * @param jSessionId + * Local session ID + * @param session + * HttpSession + */ + public static void sessionCreated(String portalJSessionId, String jSessionId, HttpSession session) { + + storeMaxInactiveTime(session); + + // this key is a combination of portal jsession id and app session id + String jSessionKey = jSessionKey(jSessionId, portalJSessionId); + Object jSessionKeySessionVal = session.getAttribute(PortalApiConstants.PORTAL_JSESSION_ID); + + // do not reset the attributes if the same values have already been set + // because that will cause PortalTimeoutBindingListener to unbound the + // value from map + if (jSessionKeySessionVal != null && jSessionKeySessionVal.equals(jSessionKey)) { + logger.debug(" Session Values already exist in te map for sessionKey " + jSessionKey); + return; + } + + session.setAttribute(PortalApiConstants.PORTAL_JSESSION_ID, jSessionKey); + + // session binding listener will add this value to the static map + // and with session replication the listener will fire in all tomcat + // instances + session.setAttribute(PortalApiConstants.PORTAL_JSESSION_BIND, new PortalTimeoutBindingListener()); + // sessionMap.put((String)session.getAttribute(PortalApiConstants.PORTAL_JSESSION_ID), + // session); + + } + + /** + * TODO: remove static + * + * @param session + */ + protected static void storeMaxInactiveTime(HttpSession session) { + if (session.getAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME) == null) + session.setAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME, session.getMaxInactiveInterval()); + } + + /** + * TODO: remove static + * + * @param session + * HttpSession + */ + public static void sessionDestroyed(HttpSession session) { + try { + logger.info(" Session getting destroyed - id: " + session.getId()); + session.removeAttribute(PortalApiConstants.PORTAL_JSESSION_BIND); + // sessionMap.remove((String)session.getAttribute(PortalApiConstants.PORTAL_JSESSION_ID)); + } catch (Exception e) { + logger.error("sessionDestroyed failed", e); + } + } + + /*** + * TODO: remove static + * + * @param portalJSessionId + * Portal session ID + * @return true on success, false if the session cannot be found, etc. + */ + public static boolean invalidateSession(String portalJSessionId) { + boolean result = false; + logger.debug("Session Management: request from Portal to invalidate the session: " + portalJSessionId); + for (String jSessionKey : sessionMap.keySet()) { + try { + HttpSession session = sessionMap.get(jSessionKey); + if (portalJSessionId(jSessionKey).equals(portalJSessionId)) { + session.invalidate(); + result = true; + } + } catch (Exception e) { + logger.error("invalidateSession failed", e); + } + } + return result; + } + + /** + * TODO: remove static + * + * @return json version of the timeout map: session ID -> timeout object + */ + public static String gatherSessionExtensions() { + logger.debug("Session Management: gatherSessionExtensions"); + + Map<String, PortalTimeoutVO> sessionTimeoutMap = new Hashtable<String, PortalTimeoutVO>(); + String jsonMap = ""; + + for (String jSessionKey : sessionMap.keySet()) { + + try { + // get the expirytime in seconds + HttpSession session = sessionMap.get(jSessionKey); + + Long lastAccessedTimeMilliSec = session.getLastAccessedTime(); + Long maxIntervalMilliSec = session.getMaxInactiveInterval() * 1000L; + // Long currentTimeMilliSec = + // Calendar.getInstance().getTimeInMillis() ; + // (maxIntervalMilliSec - (currentTimeMilliSec - + // lastAccessedTimeMilliSec) + ; + Calendar instance = Calendar.getInstance(); + instance.setTimeInMillis(session.getLastAccessedTime()); + logger.debug("Session Management: Last Accessed time for " + jSessionKey + ": " + instance.getTime()); + + Long sessionTimOutMilliSec = maxIntervalMilliSec + lastAccessedTimeMilliSec; + + sessionTimeoutMap.put(portalJSessionId(jSessionKey), + getSingleSessionTimeoutObj(jSessionKey, sessionTimOutMilliSec)); + logger.debug("Session Management: putting session in map " + jSessionKey + " sessionTimoutSec" + + (int) (sessionTimOutMilliSec / 1000)); + + jsonMap = mapper.writeValueAsString(sessionTimeoutMap); + + } catch (Exception e) { + logger.error("gatherSessionExtensions failed", e); + } + + } + + return jsonMap; + + } + + /** + * TODO: remove static + * + * @param sessionTimeoutMapStr + * Session timeout map as string + * @return true on success, false otherwise + */ + public static boolean updateSessionExtensions(String sessionTimeoutMapStr) { + logger.debug("Session Management: updateSessionExtensions"); + // Map<String,Object> sessionTimeoutMap = + // mapper.readValue(sessionTimeoutMapStr, Map.class); + Map<String, PortalTimeoutVO> sessionTimeoutMap = null; + + try { + TypeReference<Hashtable<String, PortalTimeoutVO>> typeRef = new TypeReference<Hashtable<String, PortalTimeoutVO>>() { + }; + sessionTimeoutMap = mapper.readValue(sessionTimeoutMapStr, typeRef); + } catch (Exception e) { + logger.error("updateSessionExtensions failed to parse the sessionTimeoutMap from portal", e); + return false; + } + + boolean result = true; + for (String jPortalSessionId : sessionTimeoutMap.keySet()) { + try { + PortalTimeoutVO extendedTimeoutVO = mapper.readValue( + mapper.writeValueAsString(sessionTimeoutMap.get(jPortalSessionId)), PortalTimeoutVO.class); + HttpSession session = sessionMap.get(jSessionKey(extendedTimeoutVO.getjSessionId(), jPortalSessionId)); + + if (session == null) { + continue; + } + + Long lastAccessedTimeMilliSec = session.getLastAccessedTime(); + Long maxIntervalMilliSec = session.getMaxInactiveInterval() * 1000L; + Long sessionTimOutMilliSec = maxIntervalMilliSec + lastAccessedTimeMilliSec; + + Long maxTimeoutTimeMilliSec = extendedTimeoutVO.getSessionTimOutMilliSec(); + if (maxTimeoutTimeMilliSec > sessionTimOutMilliSec) { + session.setMaxInactiveInterval((int) (maxTimeoutTimeMilliSec - lastAccessedTimeMilliSec) / 1000); + logger.debug("Session Management: extended session for :" + session.getId() + " to :" + + (int) (maxTimeoutTimeMilliSec / 1000)); + // System.out.println("!!!!!!!!!extended session for :" + + // session.getId() + " to :" + + // (int)(maxTimeoutTimeMilliSec/1000)); + } + } catch (Exception e) { + logger.error("updateSessionExtensions failed to update session timeouts", e); + // Signal a problem if any one of them fails + result = false; + } + + } + return result; + } + + /** + * TODO: Remove static + * + * @param request + * HttpServletRequest + * @param userName + * User name + * @param pwd + * Password + * @param uebKey + * UEB key (application ID) + * @param ecompRestURL + * Remote system URL + * @param _sessionComm + * Session communication information + */ + public static void handleSessionUpdatesNative(HttpServletRequest request, String userName, String pwd, + String uebKey, String ecompRestURL, SessionCommInf _sessionComm) { + + if (_sessionComm == null) { + _sessionComm = sessionComm; + } + try { + synchronizeSessionForLastMinuteRequests(request, ecompRestURL, userName, pwd, uebKey, _sessionComm); + } catch (Exception e) { + logger.error("handleSesionUpdatesNative failed", e); + } + resetSessionMaxIdleTimeOut(request); + } + + /** + * TODO: remove Static + * + * @param request + * HttpServletRequest + * @param ecompRestURL + * Remote URL + * @param userName + * user name + * @param pwd + * password + * @param uebKey + * UEB key + * @param _sessionComm + * session information + * @throws JsonProcessingException + * On failure to serialize + */ + public static void synchronizeSessionForLastMinuteRequests(HttpServletRequest request, String ecompRestURL, + String userName, String pwd, String uebKey, SessionCommInf _sessionComm) throws JsonProcessingException { + + HttpSession session = request.getSession(false); + if (session == null) + return; + + Object portalSessionSlotCheckObj = session.getServletContext() + .getAttribute(PortalApiConstants.PORTAL_SESSION_SLOT_CHECK); + Integer portalSessionSlotCheckinMilliSec = 5 * 60 * 1000; // (5 minutes) + if (portalSessionSlotCheckObj != null) { + portalSessionSlotCheckinMilliSec = Integer.valueOf(portalSessionSlotCheckObj.toString()); + } else { + portalSessionSlotCheckObj = _sessionComm + .fetchSessionSlotCheckInterval(new String[] { ecompRestURL, userName, pwd, uebKey }); + logger.debug("Fetching Portal Session Slot Object: " + portalSessionSlotCheckObj); + if (portalSessionSlotCheckObj != null) { + portalSessionSlotCheckinMilliSec = Integer.valueOf(portalSessionSlotCheckObj.toString()); + session.getServletContext().setAttribute(PortalApiConstants.PORTAL_SESSION_SLOT_CHECK, + portalSessionSlotCheckinMilliSec); + } + } + + Object previousToLastAccessTimeObj = session.getAttribute(PortalApiConstants.SESSION_PREVIOUS_ACCESS_TIME); + final long lastAccessedTimeMilliSec = session.getLastAccessedTime(); + if (previousToLastAccessTimeObj == null) { + previousToLastAccessTimeObj = lastAccessedTimeMilliSec; + session.setAttribute(PortalApiConstants.SESSION_PREVIOUS_ACCESS_TIME, previousToLastAccessTimeObj); + } else { + Long previousToLastAccessTime = (Long) previousToLastAccessTimeObj; + final int maxIntervalMilliSec = session.getMaxInactiveInterval() * 1000; + if (maxIntervalMilliSec + - (lastAccessedTimeMilliSec - previousToLastAccessTime) <= portalSessionSlotCheckinMilliSec) { + + String jSessionKey = (String) session.getAttribute(PortalApiConstants.PORTAL_JSESSION_ID); + Map<String, PortalTimeoutVO> sessionTimeoutMap = new Hashtable<String, PortalTimeoutVO>(); + Long sessionTimOutMilliSec = maxIntervalMilliSec + lastAccessedTimeMilliSec; + + sessionTimeoutMap.put(PortalTimeoutHandler.portalJSessionId(jSessionKey), + PortalTimeoutHandler.getSingleSessionTimeoutObj(jSessionKey, sessionTimOutMilliSec)); + String jsonMap = mapper.writeValueAsString(sessionTimeoutMap); + logger.debug("Extension requested for all the Apps and Portal; JessionKey: " + jSessionKey + + "; SessionMap: " + sessionTimeoutMap); + _sessionComm.extendSessionTimeOuts(new String[] { ecompRestURL, userName, pwd, uebKey, jsonMap }); + } + + } + } + + /** + * TODO: remove static + * + * @param request + * HttpServletRequest + */ + public static void resetSessionMaxIdleTimeOut(HttpServletRequest request) { + try { + HttpSession session = request.getSession(false); + if (session == null) + return; + final Object maxIdleAttribute = session.getAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME); + if (maxIdleAttribute != null) { + session.setMaxInactiveInterval(Integer.parseInt(maxIdleAttribute.toString())); + } + } catch (Exception e) { + logger.error("resetSessionMaxIdleTimeout failed", e); + } + + } + + /** + * + * @param jSessionKey + * @param sessionTimOutMilliSec + * @return + */ + private static PortalTimeoutVO getSingleSessionTimeoutObj(String jSessionKey, Long sessionTimOutMilliSec) { + return new PortalTimeoutVO(jSessionId(jSessionKey), sessionTimOutMilliSec); + } + + /** + * + * @param jSessionId + * @param portalJSessionId + * @return + */ + private static String jSessionKey(String jSessionId, String portalJSessionId) { + return portalJSessionId + "-" + jSessionId; + } + + /** + * + * @param jSessionKey + * @return + */ + private static String portalJSessionId(String jSessionKey) { + return jSessionKey.split("-")[0]; + } + + /** + * + * @param jSessionKey + * @return + */ + private static String jSessionId(String jSessionKey) { + return jSessionKey.split("-")[1]; + } + +}
\ No newline at end of file diff --git a/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/listener/UserContextListener.java b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/listener/UserContextListener.java new file mode 100644 index 00000000..8599a67c --- /dev/null +++ b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/listener/UserContextListener.java @@ -0,0 +1,72 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal SDK + * =================================================================== + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the “License”); + * you may not use this software 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. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * 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. + * + * ============LICENSE_END============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalsdk.core.onboarding.listener; + +import java.util.HashMap; + +import javax.servlet.ServletContext; +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; +import javax.servlet.annotation.WebListener; +import javax.servlet.http.HttpSession; + +import org.onap.portalsdk.core.onboarding.util.PortalApiConstants; + +@WebListener +public class UserContextListener implements ServletContextListener { + + public void contextInitialized(ServletContextEvent event) { + ServletContext context = event.getServletContext(); + // + // create a map to store references to all the active + // sessions and bind it to context scope. + // + HashMap<String, HttpSession> activeUsers = new HashMap<String, HttpSession>(); + context.setAttribute(PortalApiConstants.ACTIVE_USERS_NAME, activeUsers); + } + + /** + * Needed for the ServletContextListener interface. + */ + public void contextDestroyed(ServletContextEvent event) { + // To overcome the problem with losing the session references + // during server restarts, put code here to serialize the + // activeUsers HashMap. Then put code in the contextInitialized + // method that reads and reloads it if it exists... + } +}
\ No newline at end of file diff --git a/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/listener/UserSessionListener.java b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/listener/UserSessionListener.java new file mode 100644 index 00000000..95b2d44e --- /dev/null +++ b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/listener/UserSessionListener.java @@ -0,0 +1,103 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal SDK + * =================================================================== + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the “License”); + * you may not use this software 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. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * 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. + * + * ============LICENSE_END============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalsdk.core.onboarding.listener; + +import java.util.HashMap; +import java.util.Hashtable; +import java.util.Map; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletContext; +import javax.servlet.annotation.WebListener; +import javax.servlet.http.HttpSession; +import javax.servlet.http.HttpSessionEvent; +import javax.servlet.http.HttpSessionListener; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.onap.portalsdk.core.onboarding.util.PortalApiConstants; + +/** + * Listens to session-create and session-destroy events. + */ +@WebListener +public class UserSessionListener implements HttpSessionListener { + + private Log logger = LogFactory.getLog(getClass()); + + public static Map<String, HttpSession> activeSessions = new Hashtable<String, HttpSession>(); + + public void init(ServletConfig config) { + } + + /** + * Adds sessions to the context-scoped HashMap when they begin. + */ + public void sessionCreated(HttpSessionEvent event) { + HttpSession session = event.getSession(); + ServletContext context = session.getServletContext(); + @SuppressWarnings("unchecked") + HashMap<String, HttpSession> activeUsers = (HashMap<String, HttpSession>) context + .getAttribute(PortalApiConstants.ACTIVE_USERS_NAME); + if (activeUsers != null) + activeUsers.put(session.getId(), session); + context.setAttribute(PortalApiConstants.ACTIVE_USERS_NAME, activeUsers); + activeSessions.put(session.getId(), session); + session.getServletContext().setAttribute(PortalApiConstants.MAX_IDLE_TIME, session.getMaxInactiveInterval()); + } + + /** + * Removes sessions from the context-scoped HashMap when they expire or are + * invalidated. + */ + public void sessionDestroyed(HttpSessionEvent event) { + try { + HttpSession session = event.getSession(); + ServletContext context = session.getServletContext(); + @SuppressWarnings("unchecked") + HashMap<String, HttpSession> activeUsers = (HashMap<String, HttpSession>) context + .getAttribute(PortalApiConstants.ACTIVE_USERS_NAME); + if (activeUsers != null) + activeUsers.remove(session.getId()); + activeSessions.remove(session.getId()); + PortalTimeoutHandler.sessionDestroyed(session); + } catch (Exception e) { + logger.warn(e.getMessage(), e); + } + } +} diff --git a/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/rest/FavoritesClient.java b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/rest/FavoritesClient.java new file mode 100644 index 00000000..92ea75a8 --- /dev/null +++ b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/rest/FavoritesClient.java @@ -0,0 +1,71 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal SDK + * =================================================================== + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the “License”); + * you may not use this software 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. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * 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. + * + * ============LICENSE_END============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalsdk.core.onboarding.rest; + +import java.io.IOException; + +/** + * Provides a convenience method for fetching the favorites for a user from the + * ECOMP Portal. + */ +public class FavoritesClient { + + /** + * Fetches the favorites data from portal + * + * @param userId + * userId value that it should be using to fetch the + * data + * @param appName + * Application name for logging etc. + * @param requestId + * 128-bit UUID value to uniquely identify the transaction; if null, a new one is generated. + * @param appUserName + * REST API user-name + * @param appPassword + * REST API decrypted password + * @return JSON with favorites + * @throws IOException + * on any failure + */ + public static String getFavorites(String userId, String appName, String requestId, String appUserName, + String appPassword) throws IOException { + return RestWebServiceClient.getInstance().getPortalContent("/getFavorites", userId, appName, requestId, appUserName, + appPassword,true); + } +}
\ No newline at end of file diff --git a/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/rest/FunctionalMenuClient.java b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/rest/FunctionalMenuClient.java new file mode 100644 index 00000000..7fc98c67 --- /dev/null +++ b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/rest/FunctionalMenuClient.java @@ -0,0 +1,74 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal SDK + * =================================================================== + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the “License”); + * you may not use this software 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. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * 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. + * + * ============LICENSE_END============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalsdk.core.onboarding.rest; + +import java.io.IOException; + +/** + * Provides a convenience method for fetching the functional menu for a user + * from the ECOMP Portal via UEB. + */ +public class FunctionalMenuClient { + + /** + * Fetches the functional menu data from the configured ECOMP Portal + * instance. + * + * @param userId + * userId for the user to whom the menu will be shown + * @param appName + * Application name for logging etc. + * @param requestId + * 128-bit UUID value to uniquely identify the transaction; if + * null, a new one is generated. + * @param appUserName + * REST API user name, used by Portal to authenticate the request + * @param appPassword + * REST API password (in the clear, not encrypted), used by + * Portal to authenticate the request + * @return JSON with functional menu + * @throws IOException + * on any failure + */ + public static String getFunctionalMenu(String userId, String appName, String requestId, String appUserName, + String appPassword) throws IOException { + return RestWebServiceClient.getInstance().getPortalContent("/functionalMenuItemsForUser", userId, appName, + requestId, appUserName, appPassword,true); + } + +}
\ No newline at end of file diff --git a/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/rest/RestWebServiceClient.java b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/rest/RestWebServiceClient.java new file mode 100644 index 00000000..7c9f72a1 --- /dev/null +++ b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/rest/RestWebServiceClient.java @@ -0,0 +1,558 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal SDK + * =================================================================== + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the “License”); + * you may not use this software 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. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * 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. + * + * ============LICENSE_END============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalsdk.core.onboarding.rest; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.Base64; +import java.util.UUID; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.onap.portalsdk.core.onboarding.util.PortalApiConstants; +import org.onap.portalsdk.core.onboarding.util.PortalApiProperties; + +/** + * Simple REST client for GET, POST and DELETE operations against the Portal + * application. + */ +public class RestWebServiceClient { + + private final Log logger = LogFactory.getLog(RestWebServiceClient.class); + + /** + * Singleton instance + */ + private static RestWebServiceClient instance = null; + + /** + * Constructor is private. Clients should obtain an instance via getInstance(). + */ + private RestWebServiceClient() { + } + + /** + * Gets the static instance of RestWebServiceClient; creates it if necessary. + * Synchronized to be thread safe. + * + * @return Static instance of RestWebServiceClient. + */ + public static synchronized RestWebServiceClient getInstance() { + if (instance == null) + instance = new RestWebServiceClient(); + return instance; + } + + /** + * Convenience method that fetches the URL for the Portal REST API endpoint and + * the application UEB key, then calls + * {@link #get(String, String, String, String, String, String, String)} to + * access the Portal's REST endpoint. + * + * @param restPath + * Partial path of the endpoint; e.g., "/specialRestService" + * @param userId + * userId for the user originating the request + * @param appName + * Application Name for logging. + * @param requestId + * 128-bit UUID value to uniquely identify the transaction. + * @param appUserName + * REST API user name for Portal to authenticate the request + * @param appPassword + * REST API password (in the clear, not encrypted) for Portal to + * authenticate the request + * @param isBasicAuth + * If true, send credentials as HTTP Basic Authentication + * @return Content from REST endpoint + * @throws IOException + * on any failure + */ + public String getPortalContent(String restPath, String userId, String appName, String requestId, String appUserName, + String appPassword, boolean isBasicAuth) throws IOException { + String restURL = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL); + if (restURL == null) { + String msg = "getPortalContent: failed to get property " + PortalApiConstants.ECOMP_REST_URL; + logger.error(msg); + throw new IOException(msg); + } + String appUebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY); + if (appUebKey == null) { + String msg = "getPortalContent: failed to get property " + PortalApiConstants.UEB_APP_KEY; + logger.error(msg); + throw new IOException(msg); + } + final String restEndpointUrl = restURL + restPath; + if (isBasicAuth) { + return get(restEndpointUrl, userId, appName, requestId, appUebKey, appUserName, appPassword, isBasicAuth); + } + return get(restEndpointUrl, userId, appName, requestId, appUebKey, appUserName, appPassword); + } + + /** + * Makes a call to a Portal REST API using the specified URL and parameters. + * + * @param url + * Complete URL of the REST endpoint. + * @param loginId + * User that it should be fetching the data + * @param appName + * Application name for logging; if null or empty, defaulted to + * Unknown. + * @param requestId + * 128-bit UUID value to uniquely identify the transaction; if null + * or empty, one is generated. + * @param appUebKey + * Unique key for the application, used by Portal to authenticate the + * request + * @param appUserName + * REST API user name, used by Portal to authenticate the request + * @param appPassword + * REST API password, used by Portal to authenticate the request + * @return Content from REST endpoint + * @throws IOException + * On any failure; e.g., unknown host. + */ + public String get(String url, String loginId, String appName, String requestId, String appUebKey, + String appUserName, String appPassword) throws IOException { + return get(url, loginId, appName, requestId, appUebKey, appUserName, appPassword, false); + } + + /** + * Makes a call to a Portal REST API using the specified URL and parameters. + * + * @param url + * Complete URL of the REST endpoint. + * @param loginId + * User that it should be fetching the data + * @param appName + * Application name for logging; if null or empty, defaulted to + * Unknown. + * @param requestId + * 128-bit UUID value to uniquely identify the transaction; if null + * or empty, one is generated. + * @param appUebKey + * Unique key for the application, used by Portal to authenticate the + * request + * @param appUserName + * REST API user name, used by Portal to authenticate the request + * @param appPassword + * REST API password, used by Portal to authenticate the request + * @param useBasicAuth + * If true, send credentials as HTTP Basic Authentication + * @return Content from REST endpoint + * @throws IOException + * On any failure; e.g., unknown host. + */ + public String get(String url, String loginId, String appName, String requestId, String appUebKey, + String appUserName, String appPassword, Boolean useBasicAuth) throws IOException { + + logger.debug("RestWebServiceClient.get (" + url + ") operation is started."); + + if (appName == null || appName.trim().length() == 0) + appName = "Unknown"; + if (requestId == null || requestId.trim().length() == 0) + requestId = UUID.randomUUID().toString(); + + URL obj = new URL(url); + // Create the connection object + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + con.setRequestMethod("GET"); + // if the portal property is set then gets the timeout value from portal + // properties + con.setConnectTimeout(3000); + if (PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_CONNECTION_TIMEOUT) != null) + con.setConnectTimeout(Integer + .parseInt(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_CONNECTION_TIMEOUT))); + con.setReadTimeout(8000); + if (PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_READ_TIMEOUT) != null) + con.setReadTimeout( + Integer.parseInt(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_READ_TIMEOUT))); + + // add request header + con.setRequestProperty("uebkey", appUebKey); + con.setRequestProperty("LoginId", loginId); + con.setRequestProperty("user-agent", appName); + con.setRequestProperty("X-ECOMP-RequestID", requestId); + con.setRequestProperty("username", appUserName); + con.setRequestProperty("password", appPassword); + if (useBasicAuth) { + String encoding = Base64.getEncoder().encodeToString((appUserName + ":" + appPassword).getBytes()); + con.setRequestProperty("Authorization", "Basic " + encoding); + } + + int responseCode = con.getResponseCode(); + logger.debug("get: received response code '" + responseCode + "' while getting the '" + url + "' for user: " + + loginId); + + final String response = readAndCloseStream(con.getInputStream()); + if (logger.isDebugEnabled()) + logger.debug("get: url " + url + " yielded " + response); + return response; + } + + /** + * Convenience method that fetches the URL for the Portal REST API endpoint and + * the application UEB key, then calls + * {@link #post(String, String, String, String, String, String, String, String, String, boolean)} + * to access the Portal's REST endpoint. + * + * @param restPath + * Partial path of the endpoint; e.g., "/specialRestService" + * @param userId + * ID for the user originating the request + * @param appName + * Application Name for logging. + * @param requestId + * 128-bit UUID value to uniquely identify the transaction. + * @param appUserName + * REST API user name for Portal to authenticate the request; ignored + * if null + * @param appPassword + * REST API password (in the clear, not encrypted) for Portal to + * authenticate the request; ignored if null + * @param contentType + * content type for header + * @param content + * String to post + * @param isBasicAuth + * If true, use HTTP Basic Authentication + * @return Content from REST endpoint + * @throws IOException + * on any failure + */ + public String postPortalContent(String restPath, String userId, String appName, String requestId, + String appUserName, String appPassword, String contentType, String content, boolean isBasicAuth) + throws IOException { + String restURL = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL); + + if (restURL == null) { + String msg = "getPortalContent: failed to get property " + PortalApiConstants.ECOMP_REST_URL; + logger.error(msg); + throw new IOException(msg); + } + String appUebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY); + if (appUebKey == null) { + String msg = "getPortalContent: failed to get property " + PortalApiConstants.UEB_APP_KEY; + logger.error(msg); + throw new IOException(msg); + } + final String separator = restURL.endsWith("/") || restPath.startsWith("/") ? "" : "/"; + final String restEndpointUrl = restURL + separator + restPath; + return post(restEndpointUrl, userId, appName, requestId, appUebKey, appUserName, appPassword, contentType, + content, isBasicAuth); + } + + /** + * Makes a POST call to a Portal REST API using the specified URL and + * parameters. + * + * @param url + * Complete URL of the REST endpoint. + * @param loginId + * User who is fetching the data + * @param appName + * Application name for logging; if null or empty, defaulted to + * Unknown. + * @param requestId + * 128-bit UUID value to uniquely identify the transaction; if null + * or empty, one is generated. + * @param appUebKey + * Unique key for the application, used by Portal to authenticate the + * request + * @param appUserName + * REST API user name used by Portal to authenticate the request; + * ignored if null + * @param appPassword + * REST API password used by Portal to authenticate the request; + * ignored if null + * @param contentType + * MIME header + * @param content + * Content to POST + * @param isBasicAuth + * If true, use HTTP Basic Authentication + * @return Any content read from the endpoint + * @throws IOException + * On any error + */ + public String post(String url, String loginId, String appName, String requestId, String appUebKey, + String appUserName, String appPassword, String contentType, String content, boolean isBasicAuth) + throws IOException { + + if (logger.isDebugEnabled()) + logger.debug("RestWebServiceClient.post to URL " + url); + if (appName == null || appName.trim().length() == 0) + appName = "Unknown"; + if (requestId == null || requestId.trim().length() == 0) + requestId = UUID.randomUUID().toString(); + + URL obj = new URL(url); + // Create the connection object + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + con.setRequestMethod("POST"); + + con.setConnectTimeout(3000); + // if the portal property is set then gets the timeout value from portal + // properties + if (PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_CONNECTION_TIMEOUT) != null) + con.setConnectTimeout(Integer + .parseInt(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_CONNECTION_TIMEOUT))); + con.setReadTimeout(15000); + if (PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_READ_TIMEOUT) != null) + con.setReadTimeout( + Integer.parseInt(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_READ_TIMEOUT))); + + // add request header + con.setRequestProperty("uebkey", appUebKey); + if (appUserName != null) + con.setRequestProperty("username", appUserName); + if (appPassword != null) + con.setRequestProperty("password", appPassword); + con.setRequestProperty("LoginId", loginId); + con.setRequestProperty("user-agent", appName); + con.setRequestProperty("X-ECOMP-RequestID", requestId); + con.setRequestProperty("Content-Type", contentType); + if (isBasicAuth) { + String encoding = Base64.getEncoder().encodeToString((appUserName + ":" + appPassword).getBytes()); + con.setRequestProperty("Authorization", "Basic " + encoding); + } + + con.setDoInput(true); + con.setDoOutput(true); + if (content != null) { + con.getOutputStream().write(content.getBytes()); + } + con.getOutputStream().flush(); + con.getOutputStream().close(); + + int responseCode = con.getResponseCode(); + logger.debug("Response Code : " + responseCode); + final String response = readAndCloseStream(con.getInputStream()); + return response; + } + + /** + * Convenience method that fetches the URL for the Portal REST API endpoint and + * the application UEB key, then calls + * {@link #delete(String, String, String, String, String, String, String, String, String, boolean)} + * to access the Portal's REST endpoint. + * + * @param restPath + * Complete URL of the REST endpoint. + * @param userId + * User who is fetching the data + * @param appName + * Application name for logging; if null or empty, defaulted to + * Unknown. + * @param requestId + * 128-bit UUID value to uniquely identify the transaction; if null + * or empty, one is generated. + * @param appUserName + * REST API user name used by Portal to authenticate the request; + * ignored if null + * @param appPassword + * REST API password used by Portal to authenticate the request; + * ignored if null + * @param contentType + * MIME header + * @param content + * Content + * @param isBasicAuth + * If true, use HTTP Basic Authentication + * @return Any content read from the endpoint + * @throws IOException + * On any error + */ + public String deletePortalContent(String restPath, String userId, String appName, String requestId, + String appUserName, String appPassword, String contentType, String content, boolean isBasicAuth) + throws IOException { + String restURL = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL); + if (restURL == null) { + String msg = "deletePortalContent: failed to get property " + PortalApiConstants.ECOMP_REST_URL; + logger.error(msg); + throw new IOException(msg); + } + String appUebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY); + if (appUebKey == null) { + String msg = "deletePortalContent: failed to get property " + PortalApiConstants.UEB_APP_KEY; + logger.error(msg); + throw new IOException(msg); + } + final String separator = restURL.endsWith("/") || restPath.startsWith("/") ? "" : "/"; + final String restEndpointUrl = restURL + separator + restPath; + return delete(restEndpointUrl, userId, appName, requestId, appUebKey, appUserName, appPassword, contentType, + content, isBasicAuth); + } + + /** + * Makes a DELETE call to a Portal REST API using the specified URL and + * parameters. + * + * @param url + * Complete URL of the REST endpoint. + * @param loginId + * User who is fetching the data + * @param appName + * Application name for logging; if null or empty, defaulted to + * Unknown. + * @param requestId + * 128-bit UUID value to uniquely identify the transaction; if null + * or empty, one is generated. + * @param appUebKey + * Unique key for the application, used by Portal to authenticate the + * request + * @param appUserName + * REST API user name used by Portal to authenticate the request; + * ignored if null + * @param appPassword + * REST API password used by Portal to authenticate the request; + * ignored if null + * @param contentType + * MIME header + * @param content + * Content + * @param isBasicAuth + * If true, use HTTP Basic Authentication + * @return Any content read from the endpoint + * @throws IOException + * On any error + */ + public String delete(String url, String loginId, String appName, String requestId, String appUebKey, + String appUserName, String appPassword, String contentType, String content, boolean isBasicAuth) + throws IOException { + + if (logger.isDebugEnabled()) + logger.debug("RestWebServiceClient.post to URL " + url); + if (appName == null || appName.trim().length() == 0) + appName = "Unknown"; + if (requestId == null || requestId.trim().length() == 0) + requestId = UUID.randomUUID().toString(); + + URL obj = new URL(url); + // Create the connection object + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + con.setRequestMethod("DELETE"); + con.setConnectTimeout(3000); + // if the portal property is set then gets the timeout value from portal + // properties + if (PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_CONNECTION_TIMEOUT) != null) + con.setConnectTimeout(Integer + .parseInt(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_CONNECTION_TIMEOUT))); + con.setReadTimeout(15000); + if (PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_READ_TIMEOUT) != null) + con.setReadTimeout( + Integer.parseInt(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_READ_TIMEOUT))); + + // add request header + con.setRequestProperty("uebkey", appUebKey); + if (appUserName != null) + con.setRequestProperty("username", appUserName); + if (appPassword != null) + con.setRequestProperty("password", appPassword); + con.setRequestProperty("LoginId", loginId); + con.setRequestProperty("user-agent", appName); + con.setRequestProperty("X-ECOMP-RequestID", requestId); + con.setRequestProperty("Content-Type", contentType); + if (isBasicAuth) { + String encoding = Base64.getEncoder().encodeToString((appUserName + ":" + appPassword).getBytes()); + con.setRequestProperty("Authorization", "Basic " + encoding); + } + + con.setDoInput(true); + con.setDoOutput(true); + if (content != null) + con.getOutputStream().write(content.getBytes()); + con.getOutputStream().flush(); + con.getOutputStream().close(); + + int responseCode = con.getResponseCode(); + logger.debug("Response Code : " + responseCode); + final String response = readAndCloseStream(con.getInputStream()); + return response; + } + + /** + * Reads content of string to a StringBuffer, decoded as UTF-8, and returns as + * string. + * + * @param inputStream + * Stream to read + * @return String read + * @throws IOException + */ + private String readAndCloseStream(InputStream inputStream) throws IOException { + StringBuffer sb = new StringBuffer(); + InputStreamReader in = null; + char[] buf = new char[8196]; + int bytes; + try { + in = new InputStreamReader(inputStream, "UTF-8"); + while ((bytes = in.read(buf)) > 0) + sb.append(new String(buf, 0, bytes)); + } finally { + if (in != null) + in.close(); + } + return sb.toString(); + } + + /** + * Basic unit test for the client to call Portal app on localhost. + * + * @param args + * Ignored + * @throws IOException + * On failure + */ + public static void main(String[] args) throws IOException { + RestWebServiceClient client = RestWebServiceClient.getInstance(); + final String getUrl = "http://www.ecomp.openecomp.org:8080/ecompportal/auxapi/analytics"; + String get = client.get(getUrl, "userId", "appName", null, "appUebKey", "appUserName", "appPassword", null); + System.out.println("Get result:\n" + get); + final String postUrl = "http://www.ecomp.openecomp.org:8080/ecompportal/auxapi/storeAnalytics"; + final String content = " { " + " \"action\" : \"test1\", " + " \"page\" : \"test2\", " + + " \"function\" : \"test3\", " + " \"userid\" : \"ab1234\" " + "}"; + String post = client.post(postUrl, "userId", "appName", null, "appUebKey", "appUserName", "appPassword", + "application/json", content, true); + System.out.println("Post result:\n" + post); + } +} diff --git a/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/util/CipherUtil.java b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/util/CipherUtil.java new file mode 100644 index 00000000..f3125f03 --- /dev/null +++ b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/util/CipherUtil.java @@ -0,0 +1,174 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal SDK + * =================================================================== + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the “License”); + * you may not use this software 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. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * 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. + * + * ============LICENSE_END============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalsdk.core.onboarding.util; + +import java.io.UnsupportedEncodingException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.spec.SecretKeySpec; + +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.onap.portalsdk.core.onboarding.exception.CipherUtilException; + +public class CipherUtil { + + private static final Log logger = LogFactory.getLog(CipherUtil.class); + + /** + * Default key. + */ + private final static String key = "AGLDdG4D04BKm2IxIWEr8o==!"; + + /** + * Encrypts the text using the specified secret key. + * + * @param plainText + * Text to encrypt + * @param secretKey + * Key to use for encryption + * @return encrypted version of plain text. + * @throws CipherUtilException + * if any encryption step fails + */ + public static String encrypt(String plainText, String secretKey) throws CipherUtilException { + String encryptedString = null; + try { + byte[] encryptText = plainText.getBytes("UTF-8"); + byte[] rawKey = Base64.decodeBase64(secretKey); + SecretKeySpec sKeySpec = new SecretKeySpec(rawKey, "AES"); + Cipher cipher = Cipher.getInstance("AES"); + cipher.init(Cipher.ENCRYPT_MODE, sKeySpec); + encryptedString = Base64.encodeBase64String(cipher.doFinal(encryptText)); + } catch (BadPaddingException | IllegalBlockSizeException | InvalidKeyException | NoSuchAlgorithmException + | NoSuchPaddingException | UnsupportedEncodingException ex) { + logger.error("encrypt failed", ex); + throw new CipherUtilException(ex); + } + return encryptedString; + } + + /** + * Encrypts the text using a default secret key. + * + * @param plainText + * Text to encrypt + * @return Encrypted Text + * @throws CipherUtilException + * if any decryption step fails + */ + public static String encrypt(String plainText) throws CipherUtilException { + return CipherUtil.encrypt(plainText, key); + } + + /** + * Decrypts the text using the specified secret key. + * + * @param encryptedText + * Text to decrypt + * @param secretKey + * Key to use for decryption + * @return plain text version of encrypted text + * @throws CipherUtilException + * if any decryption step fails + */ + public static String decrypt(String encryptedText, String secretKey) throws CipherUtilException { + String encryptedString = null; + try { + byte[] rawKey = Base64.decodeBase64(secretKey); + SecretKeySpec sKeySpec = new SecretKeySpec(rawKey, "AES"); + byte[] encryptText = Base64.decodeBase64(encryptedText.getBytes("UTF-8")); + Cipher cipher = Cipher.getInstance("AES"); + cipher.init(Cipher.DECRYPT_MODE, sKeySpec); + encryptedString = new String(cipher.doFinal(encryptText)); + } catch (BadPaddingException | IllegalBlockSizeException | InvalidKeyException | NoSuchAlgorithmException + | NoSuchPaddingException | UnsupportedEncodingException ex) { + logger.error("decrypt failed", ex); + throw new CipherUtilException(ex); + } + return encryptedString; + } + + /** + * Decrypts the text using a default secret key. + * + * @param encryptedText + * Text to decrypt + * @return Decrypted text + * @throws CipherUtilException + * if any decryption step fails + */ + public static String decrypt(String encryptedText) throws CipherUtilException { + return CipherUtil.decrypt(encryptedText, key); + } + + public static void main(String[] args) throws CipherUtilException { + + String password = "Welcome123"; + String encrypted; + String decrypted; + + if (args.length != 2) { + System.out.println("Default password testing... "); + System.out.println("Plain password: " + password); + encrypted = encrypt(password); + System.out.println("Encrypted password: " + encrypted); + decrypted = decrypt(encrypted); + System.out.println("Decrypted password: " + decrypted); + } else { + String whatToDo = args[0]; + if (whatToDo.equalsIgnoreCase("d")) { + encrypted = args[1]; + System.out.println("Encrypted Text: " + encrypted); + decrypted = decrypt(encrypted); + System.out.println("Decrypted Text: " + decrypted); + } else { + decrypted = args[1]; + System.out.println("Plain Text: " + decrypted); + encrypted = encrypt(decrypted); + System.out.println("Encrypted Text" + encrypted); + } + } + } +} diff --git a/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/util/PortalApiConstants.java b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/util/PortalApiConstants.java new file mode 100644 index 00000000..1419851a --- /dev/null +++ b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/util/PortalApiConstants.java @@ -0,0 +1,83 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal SDK + * =================================================================== + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the “License”); + * you may not use this software 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. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * 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. + * + * ============LICENSE_END============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalsdk.core.onboarding.util; + +public interface PortalApiConstants { + public static final String API_PREFIX = "/api/v2"; + public static final String PORTAL_JSESSION_ID = "PORTAL_JSESSION_ID"; + public static final String PORTAL_JSESSION_BIND = "PORTAL_JSESSION_BIND"; + public static final String ACTIVE_USERS_NAME = "activeUsers"; + + /** Portal service cookie name */ + public static final String EP_SERVICE = "EPService"; + + public static final String GLOBAL_SESSION_MAX_IDLE_TIME = "global_session_max_idle_time"; + public static final String PORTAL_SESSION_SLOT_CHECK = "portal_session_slot_check"; + public static final String SESSION_PREVIOUS_ACCESS_TIME = "session_previous_access_time"; + public static final String MAX_IDLE_TIME = "max.idle.time"; + + // Names of keys in the portal.properties file + public static final String PORTAL_API_IMPL_CLASS = "portal.api.impl.class"; + public static final String ECOMP_REDIRECT_URL = "ecomp_redirect_url"; + public static final String ECOMP_REST_URL = "ecomp_rest_url"; + public static final String ROLE_ACCESS_CENTRALIZED = "role_access_centralized"; + public static final String CSP_COOKIE_NAME = "csp_cookie_name"; + public static final String CSP_GATE_KEEPER_PROD_KEY = "csp_gate_keeper_prod_key"; + + // UEB related + public static final String UEB_URL_LIST = "ueb_url_list"; // In properties file + public static final String ECOMP_PORTAL_INBOX_NAME = "ecomp_portal_inbox_name"; + public static final String ECOMP_DEFAULT_MSG_ID = "0"; + public static final String ECOMP_GENERAL_UEB_PARTITION = "EPGeneralPartition"; + public static final String UEB_LISTENERS_ENABLE = "ueb_listeners_enable"; + public static final String UEB_APP_INBOUND_MAILBOX_NAME = "ueb_app_mailbox_name"; + public static final String UEB_APP_CONSUMER_GROUP_NAME = "ueb_app_consumer_group_name"; + + // UebManager generates a consumer group name for special token {UUID} + public static final String UEB_APP_CONSUMER_GROUP_NAME_GENERATOR = "{UUID}"; + public static final String UEB_APP_KEY = "ueb_app_key"; + public static final String UEB_APP_SECRET = "ueb_app_secret"; + public static final String ECOMP_UEB_INVALID_MSG = "100: Invalid Message format."; + public static final String ECOMP_UEB_TIMEOUT_ERROR = "101: Timeout"; + public static final String ECOMP_UEB_UNKNOWN_PUBLISH_ERROR = "102: Unknown error during publish"; + public static final String ECOMP_UEB_UNKNOWN_CONSUME_ERROR = "103: Unknown error during consume"; + public static final String USE_REST_FOR_FUNCTIONAL_MENU = "use_rest_for_functional_menu"; + + public static final String EXT_REQUEST_CONNECTION_TIMEOUT = "ext_req_connection_timeout"; + public static final String EXT_REQUEST_READ_TIMEOUT = "ext_req_read_timeout"; +} diff --git a/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/util/PortalApiProperties.java b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/util/PortalApiProperties.java new file mode 100644 index 00000000..3d5ddae8 --- /dev/null +++ b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/util/PortalApiProperties.java @@ -0,0 +1,124 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal SDK + * =================================================================== + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the “License”); + * you may not use this software 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. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * 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. + * + * ============LICENSE_END============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalsdk.core.onboarding.util; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * Singleton Class representing portal properties. Searches the classpath for + * the file "portal.properties". + * + * To put the file "portal.properties" on the classpath, it can be in the same + * directory where the first package folder is - 'myClasses' folder in the + * following case as an example: + * + */ +public class PortalApiProperties { + + private static final Log logger = LogFactory.getLog(PortalApiProperties.class); + + private static Properties properties; + private static String propertyFileName = "portal.properties"; + + private static final Object lockObject = new Object(); + + /** + * Constructor is private. + */ + private PortalApiProperties() { + } + + /** + * Gets the property value for the specified key. If a value is found, leading + * and trailing space is trimmed. + * + * @param property + * Property key + * @return Value for the named property; null if the property file was not + * loaded or the key was not found. + */ + public static String getProperty(String property) { + if (properties == null) { + synchronized (lockObject) { + try { + if (!initialize()) { + logger.error("Failed to read property file " + propertyFileName); + return null; + } + } catch (IOException e) { + logger.error("Failed to read property file " + propertyFileName, e); + return null; + } + } + } + String value = properties.getProperty(property); + if (value != null) + value = value.trim(); + return value; + } + + /** + * Reads properties from a portal.properties file on the classpath. + * + * Clients do NOT need to call this method. Clients MAY call this method to test + * whether the properties file can be loaded successfully. + * + * @return True if properties were successfully loaded, else false. + * @throws IOException + * On failure + */ + public static boolean initialize() throws IOException { + if (properties != null) + return true; + InputStream in = PortalApiProperties.class.getClassLoader().getResourceAsStream(propertyFileName); + if (in == null) + return false; + properties = new Properties(); + try { + properties.load(in); + } finally { + in.close(); + } + return true; + } +} diff --git a/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/util/SSOFilter.java b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/util/SSOFilter.java new file mode 100644 index 00000000..00afecaf --- /dev/null +++ b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/util/SSOFilter.java @@ -0,0 +1,94 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal SDK + * =================================================================== + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the “License”); + * you may not use this software 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. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * 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. + * + * ============LICENSE_END============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ + +package org.onap.portalsdk.core.onboarding.util; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.onap.portalsdk.core.onboarding.crossapi.PortalRestAPIProxy; +import org.onap.portalsdk.core.onboarding.exception.PortalAPIException; + +public class SSOFilter implements Filter { + + private final Log logger = LogFactory.getLog(getClass()); + + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws java.io.IOException, ServletException { + + try { + if (PortalRestAPIProxy.getPortalRestApiServiceImpl().getUserId((HttpServletRequest) request) == null) { + String redirectURL = SSOUtil.getECOMPSSORedirectURL(((HttpServletRequest) request), + ((HttpServletResponse) response), + (((HttpServletRequest) request).getRequestURI() + .substring(((HttpServletRequest) request).getContextPath().length() + 1) + + (((HttpServletRequest) request).getQueryString() != null + ? ("?" + ((HttpServletRequest) request).getQueryString()) + : ""))); + + ((HttpServletResponse) response).sendRedirect(redirectURL); + + } else { + // Pass request back down the filter chain + chain.doFilter(request, response); + + } + } catch (PortalAPIException e) { + logger.error("Issue calling getUserId method "); + throw new ServletException(e); + } + + } + + public void destroy() { + + } + + public void init(FilterConfig arg0) throws ServletException { + // TODO Auto-generated method stub + + } +} diff --git a/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/util/SSOUtil.java b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/util/SSOUtil.java new file mode 100644 index 00000000..9a5428f4 --- /dev/null +++ b/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/util/SSOUtil.java @@ -0,0 +1,83 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal SDK + * =================================================================== + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the “License”); + * you may not use this software 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. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * 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. + * + * ============LICENSE_END============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalsdk.core.onboarding.util; + +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +public class SSOUtil { + + private static final Log logger = LogFactory.getLog(SSOUtil.class); + + /** + * Constructs a path for this server, this app's context, etc. + * + * @param request + * HttpServletRequest + * @param response + * HttpServletResponse + * @param forwardPath + * Path to forward user + * @return Redirect URL + */ + public static String getECOMPSSORedirectURL(HttpServletRequest request, HttpServletResponse response, + String forwardPath) { + String appURL = (request.isSecure() ? "https://" : "http://") + request.getServerName() + ":" + + request.getServerPort() + request.getContextPath() + "/" + forwardPath; + String encodedAppURL = null; + try { + encodedAppURL = URLEncoder.encode(appURL, "UTF-8"); + } catch (UnsupportedEncodingException ex) { + logger.error("getECOMPSSORedirectURL: Failed to encode app URL " + appURL); + } + String portalURL = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL); + if (portalURL == null || portalURL.length() == 0) { + logger.error("getECOMPSSORedirectURL: Failed to get property " + PortalApiConstants.ECOMP_REDIRECT_URL); + return null; + } + String redirectURL = portalURL + "?redirectUrl=" + encodedAppURL; + return redirectURL; + } + +} |