diff options
author | TATTAVARADA <statta@research.att.com> | 2017-04-27 07:53:18 -0400 |
---|---|---|
committer | st782s <statta@research.att.com> | 2017-04-27 08:31:27 -0400 |
commit | 6beb446925c967aca92f5513adf36c5db77c00d6 (patch) | |
tree | 9392057ed0739de2445c5b2a2a8bee6dcdacbcf7 /ecomp-sdk/epsdk-core/src | |
parent | 246b225194e3e8dc1926294de591a94fd9787fa7 (diff) |
[PORTAL-7] Rebase
This rebasing includes common libraries and common overlays projects
abstraction of components
Change-Id: Ia1efa4deacdc5701e6205104ac021a6c80ed60ba
Signed-off-by: st782s <statta@research.att.com>
Diffstat (limited to 'ecomp-sdk/epsdk-core/src')
161 files changed, 20544 insertions, 0 deletions
diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/FusionObject.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/FusionObject.java new file mode 100644 index 00000000..8258913f --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/FusionObject.java @@ -0,0 +1,111 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core; + +/** + * <p> + * Title: FusionObject + * </p> + * + * <p> + * Description: This interface is implemented by all top-level support classes + * of each package in FUSION. This allows all top-level support classes to have + * some commonality for easier maintenance. + * </p> + * + * <p> + * Copyright: Copyright (c) 2007 + * </p> + * + * @version 1.1 + */ +public interface FusionObject { + + public class Parameters { + // HashMap parameters passed to the Service and Dao tiers + public static final String PARAM_USERID = "userId"; + public static final String PARAM_HTTP_REQUEST = "request"; + public static final String PARAM_FILTERS = "filters"; + public static final String PARAM_CLIENT_DEVICE = "client_device"; + // Request parameters passed in the Web tier + public static final String REQUEST_PARAM_DISPLAY_SUCCESS_MESSAGE = "display_success_message"; + } + + /** + * <p> + * Title: FusionObject.Utilities + * </p> + * + * <p> + * Description: Inner class that has some utility functions available for + * any class that implements it. + * </p> + * + * <p> + * Copyright: Copyright (c) 2007 + * </p> + * + * @version 1.1 + */ + public class Utilities { + /** + * nvl - replaces a string value with an empty string if null. + * + * @param s + * String - the string value that needs to be checked + * @return String - returns the original string value if not null. + * Otherwise an empty string ("") is returned. + */ + public static String nvl(String s) { + return (s == null) ? "" : s; + } + + /** + * nvl - replaces a string value with a default value if null. + * + * @param s + * String - the string value that needs to be checked + * @param sDefault + * String - the default value + * @return String - returns the original string value if not null. + * Otherwise the default value is returned. + */ + public static String nvl(String s, String sDefault) { + return nvl(s).equals("") ? sDefault : s; + } + + /** + * Tests the specified string for nullity. + * + * @param a + * String to test for nullity. + * @return True if the specified string is null, empty or the 4-character + * sequence "null" (ignoring case); otherwise false. + */ + public static boolean isNull(String a) { + if ((a == null) || (a.length() == 0) || a.equalsIgnoreCase("null")) + return true; + else + return false; + } + + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/auth/LoginStrategy.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/auth/LoginStrategy.java new file mode 100644 index 00000000..0378101a --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/auth/LoginStrategy.java @@ -0,0 +1,131 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.auth; + +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.openecomp.portalsdk.core.command.LoginBean; +import org.openecomp.portalsdk.core.menu.MenuProperties; +import org.openecomp.portalsdk.core.onboarding.exception.PortalAPIException; +import org.openecomp.portalsdk.core.onboarding.listener.PortalTimeoutHandler; +import org.openecomp.portalsdk.core.service.LoginService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.portalsdk.core.web.support.AppUtils; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.util.WebUtils; + +public abstract class LoginStrategy { + + public static final String DEFAULT_SUCCESS_VIEW = "welcome"; + public static final String DEFAULT_FAILURE_VIEW = "login"; + private static final String JSESSIONID = "JSESSIONID"; + + public static final String EP_SERVICE = "EPService"; + public static final String USER_ID = "UserId"; + public static final String ERROR_MESSAGE_KEY = "error"; + + @Autowired + private LoginService loginService; + + public abstract ModelAndView doLogin(HttpServletRequest request, HttpServletResponse response) throws Exception; + + public abstract String getUserId(HttpServletRequest request) throws PortalAPIException; + + public ModelAndView doExternalLogin(HttpServletRequest request, HttpServletResponse response) throws Exception { + + invalidateExistingSession(request); + + Map<String, String> model = new HashMap<String, String>(); + LoginBean commandBean = new LoginBean(); + String loginId = request.getParameter("loginId"); + String password = request.getParameter("password"); + commandBean.setLoginId(loginId); + commandBean.setLoginPwd(password); + HashMap additionalParamsMap = new HashMap(); + + // Get the client device type and pass it into LoginService for audit + // logging. + /** + * ClientDeviceType clientDevice = (ClientDeviceType)request.getAttribut + * (SystemProperties.getProperty(SystemProperties.CLIENT_DEVICE_ATTRIBUTE_NAME)); + * additionalParamsMap.put(Parameters.PARAM_CLIENT_DEVICE, + * clientDevice); + **/ + commandBean = loginService.findUser(commandBean, + (String) request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY), additionalParamsMap); + + if (commandBean.getUser() == null) { + String loginErrorMessage = (commandBean.getLoginErrorMessage() != null) ? commandBean.getLoginErrorMessage() + : "login.error.external.invalid"; + model.put("error", loginErrorMessage); + + String[] errorCodes = new String[1]; + errorCodes[0] = loginErrorMessage; + + return new ModelAndView("login_external", "model", model); + + } else { + // store the currently logged in user's information in the session + UserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(), + commandBean.getBusinessDirectMenu(), + SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_BACKDOOR)); + initateSessionMgtHandler(request); + + // user has been authenticated, now take them to the welcome page + // return new ModelAndView("redirect:/profile_search"); + return new ModelAndView("redirect:welcome.htm"); + + } + } + + protected void invalidateExistingSession(HttpServletRequest request){ + request.getSession().invalidate(); + } + + protected String getJessionId(HttpServletRequest request) { + Cookie ep = WebUtils.getCookie(request, JSESSIONID); + if (ep == null) { + return request.getSession().getId(); + } + return ep.getValue(); + + } + + protected void initateSessionMgtHandler(HttpServletRequest request) { + String jSessionId = getJessionId(request); + PortalTimeoutHandler.sessionCreated(jSessionId, jSessionId, AppUtils.getSession(request)); + } + + public LoginService getLoginService() { + return loginService; + } + + public void setLoginService(LoginService loginService) { + this.loginService = loginService; + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/command/LoginBean.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/command/LoginBean.java new file mode 100644 index 00000000..37df8db1 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/command/LoginBean.java @@ -0,0 +1,193 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.command; + +import java.util.Set; + +import org.openecomp.portalsdk.core.domain.User; +import org.openecomp.portalsdk.core.domain.support.FusionCommand; + +public class LoginBean extends FusionCommand { + + private String loginId; + private String loginPwd; + private String hrid; + private String userid; + private String siteAccess; + private String loginErrorMessage; + + private User user; + @SuppressWarnings("rawtypes") + private Set menu; + @SuppressWarnings("rawtypes") + private Set businessDirectMenu; + + /** + * getLoginId + * + * @return String + */ + public String getLoginId() { + return loginId; + } + + /** + * getLoginPwd + * + * @return String + */ + public String getLoginPwd() { + return loginPwd; + } + + /** + * getMenu + * + * @return Set + */ + @SuppressWarnings("rawtypes") + public Set getMenu() { + return menu; + } + + /** + * getUser + * + * @return User + */ + public User getUser() { + return user; + } + + /** + * getHrid + * + * @return String + */ + public String getHrid() { + return hrid; + } + + /** + * getSiteAccess + * + * @return String + */ + public String getSiteAccess() { + return siteAccess; + } + + /** + * getBusinessDirectMenu + * + * @return Set + */ + @SuppressWarnings("rawtypes") + public Set getBusinessDirectMenu() { + return businessDirectMenu; + } + + /** + * getLoginErrorMessage + * + * @return String + */ + public String getLoginErrorMessage() { + return loginErrorMessage; + } + + /** + * setLoginId + * + * @param loginId String + */ + public void setLoginId(String loginId) { + this.loginId = loginId; + } + + /** + * setLoginPwd + * + * @param loginPwd String + */ + public void setLoginPwd(String loginPwd) { + this.loginPwd = loginPwd; + } + + @SuppressWarnings("rawtypes") + public void setMenu(Set menu) { + this.menu = menu; + } + + /** + * setUser + * + * @param user User + */ + public void setUser(User user) { + this.user = user; + } + + /** + * setHrid + * + * @param hrid String + */ + public void setHrid(String hrid) { + this.hrid = hrid; + } + + /** + * setSiteAccess + * + * @param siteAccess String + */ + public void setSiteAccess(String siteAccess) { + this.siteAccess = siteAccess; + } + + /** + * setBusinessDirectMenu + * + * @param businessDirectMenu Set + */ + @SuppressWarnings("rawtypes") + public void setBusinessDirectMenu(Set businessDirectMenu) { + this.businessDirectMenu = businessDirectMenu; + } + + /** + * setLoginErrorMessage + * + * @param loginErrorMessage String + */ + public void setLoginErrorMessage(String loginErrorMessage) { + this.loginErrorMessage = loginErrorMessage; + } + + public String getUserid() { + return userid; + } + + public void setUserid(String userid) { + this.userid = userid; + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/command/PostDroolsBean.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/command/PostDroolsBean.java new file mode 100644 index 00000000..541d9f71 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/command/PostDroolsBean.java @@ -0,0 +1,51 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.command; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; + +@JsonSerialize +public class PostDroolsBean { + + private String droolsFile; + private String className; + private String selectedRules; + + public String getDroolsFile() { + return droolsFile; + } + public void setDroolsFile(String droolsFile) { + this.droolsFile = droolsFile; + } + public String getSelectedRules() { + return selectedRules; + } + public void setSelectedRules(String selectedRules) { + this.selectedRules = selectedRules; + } + public String getClassName() { + return className; + } + public void setClassName(String className) { + this.className = className; + } + + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/command/PostSearchBean.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/command/PostSearchBean.java new file mode 100644 index 00000000..68806b39 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/command/PostSearchBean.java @@ -0,0 +1,375 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.command; + +import java.util.List; + +import org.openecomp.portalsdk.core.command.support.SearchBase; +import org.openecomp.portalsdk.core.domain.User; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; + +@JsonSerialize +public class PostSearchBean extends SearchBase { + + private User user = null; + private User userOrig = null; + private String[] selected; + private String[] postHrid; + private String[] postOrgUserId; + private String[] postFirstName; + private String[] postLastName; + private String[] postOrgCode; + private String[] postPhone; + private String[] postEmail; + private String[] postAddress1; + private String[] postAddress2; + private String[] postCity; + private String[] postState; + private String[] postZipCode; + private String[] postLocationClli; + private String[] postBusinessCountryCode; + private String[] postBusinessCountryName; + private String[] postDepartment; + private String[] postDepartmentName; + private String[] postBusinessUnit; + private String[] postBusinessUnitName; + private String[] postJobTitle; + private String[] postOrgManagerUserId; + private String[] postCommandChain; + private String[] postCompanyCode; + private String[] postCompany; + private String[] postCostCenter; + private String[] postSiloStatus; + private String[] postFinancialLocCode; + + + @SuppressWarnings("rawtypes") + public PostSearchBean() { + this(null); + } // PostSearchBean + + @SuppressWarnings("rawtypes") + public PostSearchBean(List items) { + super(items); + + user = new User(); + userOrig = new User(); + + setSortBy1(""); + setSortBy1Orig(""); + + //setSortByList(...); + } // PostSearchBean + + + public String getFirstName() { return user.getFirstName(); } + public String getLastName() { return user.getLastName(); } + public String getHrid() { return user.getHrid(); } + public String getOrgUserId() { return user.getOrgUserId(); } + public String getOrgCode() { return user.getOrgCode(); } + public String getEmail() { return user.getEmail(); } + public String getOrgManagerUserId() { return user.getOrgManagerUserId(); } + + public String getFirstNameOrig() { return user.getFirstName(); } + public String getLastNameOrig() { return user.getLastName(); } + public String getHridOrig() { return user.getHrid(); } + public String getOrgUserIdOrig() { return user.getOrgUserId(); } + public String getOrgCodeOrig() { return user.getOrgCode(); } + public String getEmailOrig() { return user.getEmail(); } + public String getOrgManagerUserIdOrig() { return user.getOrgManagerUserId(); } + + + public User getUser() { return user; } + + public String[] getPostEmail() { + return postEmail; + } + + public String[] getPostFirstName() { + return postFirstName; + } + + public String[] getPostHrid() { + return postHrid; + } + + public String[] getPostLastName() { + return postLastName; + } + + public String[] getPostOrgCode() { + return postOrgCode; + } + + public String[] getPostPhone() { + return postPhone; + } + + public String[] getPostOrgUserId() { + return postOrgUserId; + } + + public String[] getSelected() { + return selected; + } + + public String[] getPostAddress1() { + return postAddress1; + } + + public String[] getPostBusinessCountryCode() { + return postBusinessCountryCode; + } + + public String[] getPostCity() { + return postCity; + } + + public String[] getPostCommandChain() { + return postCommandChain; + } + + public String[] getPostCompany() { + return postCompany; + } + + public String[] getPostCompanyCode() { + return postCompanyCode; + } + + public String[] getPostDepartment() { + return postDepartment; + } + + public String[] getPostDepartmentName() { + return postDepartmentName; + } + + public String[] getPostBusinessCountryName() { + return postBusinessCountryName; + } + + public String[] getPostJobTitle() { + return postJobTitle; + } + + public String[] getPostLocationClli() { + return postLocationClli; + } + + public String[] getPostOrgManagerUserId() { + return postOrgManagerUserId; + } + + public String[] getPostState() { + return postState; + } + + public String[] getPostZipCode() { + return postZipCode; + } + + public void setFirstName(String value) { user.setFirstName(value); } + public void setLastName(String value) { user.setLastName(value); } + public void setHrid(String value) { user.setHrid(value); } + public void setOrgUserId(String value) { user.setOrgUserId(value); } + public void setOrgCode(String value) { user.setOrgCode(value); } + public void setEmail(String value) { user.setEmail(value); } + public void setOrgManagerUserId(String value) { user.setOrgManagerUserId(value); } + + public void setFirstNameOrig(String value) { userOrig.setFirstName(value); } + public void setLastNameOrig(String value) { userOrig.setLastName(value); } + public void setHridOrig(String value) { userOrig.setHrid(value); } + public void setOrgUserIdOrig(String value) { userOrig.setOrgUserId(value); } + public void setOrgCodeOrig(String value) { userOrig.setOrgCode(value); } + public void setEmailOrig(String value) { userOrig.setEmail(value); } + public void setOrgManagerUserIdOrig(String value) { userOrig.setOrgManagerUserId(value); } + + public void setUser(User value) { this.user = value; } + + public void setPostEmail(String[] postEmail) { + this.postEmail = postEmail; + } + + public void setPostFirstName(String[] postFirstName) { + this.postFirstName = postFirstName; + } + + public void setPostHrid(String[] postHrid) { + this.postHrid = postHrid; + } + + public void setPostLastName(String[] postLastName) { + this.postLastName = postLastName; + } + + public void setPostOrgCode(String[] postOrgCode) { + this.postOrgCode = postOrgCode; + } + + public void setPostPhone(String[] postPhone) { + this.postPhone = postPhone; + } + + public void setPostOrgUserId(String[] postOrgUserId) { + this.postOrgUserId = postOrgUserId; + } + + public void setSelected(String[] selected) { + this.selected = selected; + } + + public void setPostAddress1(String[] postAddress1) { + this.postAddress1 = postAddress1; + } + + public void setPostBusinessCountryCode(String[] postBusinessCountryCode) { + this.postBusinessCountryCode = postBusinessCountryCode; + } + + public void setPostCity(String[] postCity) { + this.postCity = postCity; + } + + public void setPostCommandChain(String[] postCommandChain) { + this.postCommandChain = postCommandChain; + } + + public void setPostCompany(String[] postCompany) { + this.postCompany = postCompany; + } + + public void setPostCompanyCode(String[] postCompanyCode) { + this.postCompanyCode = postCompanyCode; + } + + public void setPostDepartment(String[] postDepartment) { + this.postDepartment = postDepartment; + } + + public void setPostDepartmentName(String[] postDepartmentName) { + this.postDepartmentName = postDepartmentName; + } + + public void setPostBusinessCountryName(String[] postBusinessCountryName) { + this.postBusinessCountryName = postBusinessCountryName; + } + + public void setPostJobTitle(String[] postJobTitle) { + this.postJobTitle = postJobTitle; + } + + public void setPostLocationClli(String[] postLocationClli) { + this.postLocationClli = postLocationClli; + } + + public void setPostOrgManagerUserId(String[] postOrgManagerUserId) { + this.postOrgManagerUserId = postOrgManagerUserId; + } + + public void setPostState(String[] postState) { + this.postState = postState; + } + + public void setPostZipCode(String[] postZipCode) { + this.postZipCode = postZipCode; + } + + public String[] getPostAddress2() { + return postAddress2; + } + + public void setPostAddress2(String[] postAddress2) { + this.postAddress2 = postAddress2; + } + + public User getUserOrig() { + return userOrig; + } + + public void setUserOrig(User userOrig) { + this.userOrig = userOrig; + } + + public String[] getPostBusinessUnit() { + return postBusinessUnit; + } + + public void setPostBusinessUnit(String[] postBusinessUnit) { + this.postBusinessUnit = postBusinessUnit; + } + + public String[] getPostBusinessUnitName() { + return postBusinessUnitName; + } + + public void setPostBusinessUnitName(String[] postBusinessUnitName) { + this.postBusinessUnitName = postBusinessUnitName; + } + + public String[] getPostCostCenter() { + return postCostCenter; + } + + public void setPostCostCenter(String[] postCostCenter) { + this.postCostCenter = postCostCenter; + } + + public String[] getPostSiloStatus() { + return postSiloStatus; + } + + public void setPostSiloStatus(String[] postSiloStatus) { + this.postSiloStatus = postSiloStatus; + } + + public String[] getPostFinancialLocCode() { + return postFinancialLocCode; + } + + public void setPostFinancialLocCode(String[] postFinancialLocCode) { + this.postFinancialLocCode = postFinancialLocCode; + } + + public void resetSearch() { + super.resetSearch(); + setUser(new User()); + } // resetSearch + + + public boolean isCriteriaUpdated() { + if(user==null&&userOrig==null) + return false; + else if(user==null||userOrig==null) + return true; + else + return (! ( + Utilities.nvl(user.getFirstName()).equals(Utilities.nvl(userOrig.getFirstName()))&& + Utilities.nvl(user.getLastName()).equals(Utilities.nvl(userOrig.getLastName()))&& + //Utilities.nvl(user.getHrid()).equals(Utilities.nvl(userOrig.getHrid()))&& + Utilities.nvl(user.getOrgUserId()).equals(Utilities.nvl(userOrig.getOrgUserId()))&& + Utilities.nvl(user.getOrgCode()).equals(Utilities.nvl(userOrig.getOrgCode()))&& + Utilities.nvl(user.getEmail()).equals(Utilities.nvl(userOrig.getEmail()))&& + Utilities.nvl(user.getOrgManagerUserId()).equals(Utilities.nvl(userOrig.getOrgManagerUserId()))&& + true)); + } // isCriteriaUpdated + +} // PostSearchBean diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/command/UserRowBean.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/command/UserRowBean.java new file mode 100644 index 00000000..fb6c2eab --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/command/UserRowBean.java @@ -0,0 +1,85 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.command; + +import org.openecomp.portalsdk.core.domain.User; + +public class UserRowBean extends User { + + /** + * + */ + private static final long serialVersionUID = -2724597119083972190L; + private String sessionId; + private String lastAccess; + private String remaining; + private String loginTime; + private String LastLoginTime; + + + public String getLastAccess(){ + return this.lastAccess; + } + + + public void setLastAccess(String lastAccess){ + this.lastAccess = lastAccess; + } + + + public String getRemaining(){ + return this.remaining; + } + + + public void setRemaining(String remaining){ + this.remaining = remaining; + } + + + public String getSessionId() { + return sessionId; + } + + + public void setSessionId(String sessionId) { + this.sessionId = sessionId; + } + + + public String getLoginTime() { + return loginTime; + } + + + public void setLoginTime(String loginTime) { + this.loginTime = loginTime; + } + + + public String getLastLoginTime() { + return LastLoginTime; + } + + + public void setLastLoginTime(String lastLoginTime) { + LastLoginTime = lastLoginTime; + } +}
\ No newline at end of file diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/command/support/SearchBase.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/command/support/SearchBase.java new file mode 100644 index 00000000..f2f5408b --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/command/support/SearchBase.java @@ -0,0 +1,270 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.command.support; + +import java.util.*; + +import org.openecomp.portalsdk.core.domain.support.FusionCommand; + +public abstract class SearchBase extends FusionCommand { + + public static String SORT_BY_MODIFIER_DESC = "D"; + public static String SORT_BY_MODIFIER_ASC = "A"; + public static String SORT_BY_MODIFIER_DESC_IMAGE_NAME = "sort_desc.gif"; + public static String SORT_BY_MODIFIER_ASC_IMAGE_NAME = "sort_asc.gif"; + + + private String sortBy1 = null; + private String sortBy2 = null; + private String sortBy3 = null; + + private String sortBy1Orig = null; + private String sortBy2Orig = null; + private String sortBy3Orig = null; + + private String sortByModifier1 = null; + private String sortByModifier2 = null; + private String sortByModifier3 = null; + + private String sortByModifier1Orig = null; + private String sortByModifier2Orig = null; + private String sortByModifier3Orig = null; + + private String accessType = "WRITE"; //null; + + private String submitAction = ""; + private String masterId = ""; + private String detailId = ""; + + private String showResult = "Y"; + + private SearchResult searchResult = null; + private boolean sortingUpdated; + + @SuppressWarnings("rawtypes") + public SearchBase(List items) { + searchResult = (items == null) ? (new SearchResult()) : (new SearchResult(items)); + } // SearchBase + + + public String getSortBy1() { + return sortBy1; + } + + public String getSortBy2() { + return sortBy2; + } + + public String getSortBy3() { + return sortBy3; + } + + public String getSortBy1Orig() { + return sortBy1; + } + + public String getSortBy2Orig() { + return sortBy2; + } + + public String getSortBy3Orig() { + return sortBy3; + } + + public String getAccessType() { + return accessType; + } + + public String getSubmitAction() { + return submitAction; + } + + public String getMasterId() { + return masterId; + } + + public String getDetailId() { + return detailId; + } + + public String getShowResult() { + return showResult; + } + + //public ArrayList getSortByList() { return sortByList; } + + public SearchResult getSearchResult() { + return searchResult; + } + + public String getSortByModifier1() { + return sortByModifier1; + } + + public String getSortByModifier1Orig() { + return sortByModifier1; + } + + public String getSortByModifier2() { + return sortByModifier2; + } + + public String getSortByModifier2Orig() { + return sortByModifier2; + } + + public String getSortByModifier3() { + return sortByModifier3; + } + + public String getSortByModifier3Orig() { + return sortByModifier3; + } + + public int getPageNo() { + return (isCriteriaUpdated() || isSortingUpdated()) ? 0 : getSearchResult().getPageNo(); + } + + public int getPageSize() { + return getSearchResult().getPageSize(); + } + + public int getDataSize() { + return getSearchResult().getDataSize(); + } + + public int getNewDataSize() { + return isCriteriaUpdated() ? -1 : getDataSize(); + } + + + public void setSortBy1(String sortBy1) { + this.sortBy1 = sortBy1; + } + + public void setSortBy2(String sortBy2) { + this.sortBy2 = sortBy2; + } + + public void setSortBy3(String sortBy3) { + this.sortBy3 = sortBy3; + } + + public void setSortBy1Orig(String sortBy1Orig) { + this.sortBy1Orig = sortBy1Orig; + } + + public void setSortBy2Orig(String sortBy2Orig) { + this.sortBy2Orig = sortBy2Orig; + } + + public void setSortBy3Orig(String sortBy3Orig) { + this.sortBy3Orig = sortBy3Orig; + } + + public void setAccessType(String accessType) { + this.accessType = accessType; + } + + public void setSubmitAction(String submitAction) { + this.submitAction = submitAction; + } + + public void setMasterId(String masterId) { + this.masterId = masterId; + } + + public void setDetailId(String detailId) { + this.detailId = detailId; + } + + public void setShowResult(String showResult) { + this.showResult = showResult; + } + + public void setSearchResult(SearchResult searchResult) { + this.searchResult = searchResult; + } + + public void setSortByModifier1(String sortByModifier1) { + this.sortByModifier1 = sortByModifier1; + } + + public void setSortByModifier1Orig(String sortByModifier1Orig) { + this.sortByModifier1Orig = sortByModifier1Orig; + } + + public void setSortByModifier2(String sortByModifier2) { + this.sortByModifier2 = sortByModifier2; + } + + public void setSortByModifier2Orig(String sortByModifier2Orig) { + this.sortByModifier2Orig = sortByModifier2Orig; + } + + public void setSortByModifier3(String sortByModifier3) { + this.sortByModifier3 = sortByModifier3; + } + + public void setSortByModifier3Orig(String sortByModifier3Orig) { + this.sortByModifier3Orig = sortByModifier3Orig; + } + + public void setSortingUpdated(boolean sortingUpdated) { + this.sortingUpdated = sortingUpdated; + } + + public void setPageNo(int pageNo) { + getSearchResult().setPageNo(pageNo); + } + + public void setPageSize(int pageSize) { + getSearchResult().setPageSize(pageSize); + } + + public void setDataSize(int dataSize) { + getSearchResult().setDataSize(dataSize); + } + + + public void resetSearch() { + setSortBy1(null); + setSortBy2(null); + setSortBy3(null); + setSortByModifier1(SearchBase.SORT_BY_MODIFIER_ASC); + setSortByModifier2(SearchBase.SORT_BY_MODIFIER_ASC); + setSortByModifier3(SearchBase.SORT_BY_MODIFIER_ASC); + setPageNo(0); + setDataSize( -1); + } // resetSearch + + + public abstract boolean isCriteriaUpdated(); + + public boolean isSortingUpdated() { + return (!(Utilities.nvl(sortBy1).equals(Utilities.nvl(sortBy1Orig)) && + Utilities.nvl(sortBy2).equals(Utilities.nvl(sortBy2Orig)) && + Utilities.nvl(sortBy3).equals(Utilities.nvl(sortBy3Orig)) && + Utilities.nvl(sortByModifier1).equals(Utilities.nvl(sortByModifier1Orig)) && + Utilities.nvl(sortByModifier2).equals(Utilities.nvl(sortByModifier2Orig)) && + Utilities.nvl(sortByModifier3).equals(Utilities.nvl(sortByModifier3Orig)))); + } // isSortingUpdated + +} // SearchBase diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/command/support/SearchResult.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/command/support/SearchResult.java new file mode 100644 index 00000000..286b39cb --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/command/support/SearchResult.java @@ -0,0 +1,67 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.command.support; + +import java.util.*; + +@SuppressWarnings("rawtypes") +public class SearchResult extends ArrayList implements java.io.Serializable { + /** + * + */ + private static final long serialVersionUID = -451947878984459011L; + private int pageNo = 0; + private int pageSize = 50; + private int dataSize = -1; + + private String accessType = null; + + //private boolean empty = true; // Overrides collections [isEmpty] with searchResult present/not present logic + + + public SearchResult() {} + + @SuppressWarnings("unchecked") + public SearchResult(List items) { + super(items); + } // SearchResult + + /*public SearchResult(boolean empty) { + this(); + this.empty = empty; + } // SearchResult*/ + + + public int getPageNo() { return pageNo; } + public int getPageSize() { return pageSize; } + public int getDataSize() { return dataSize; } + + public int getSize() { return size(); } // for Struts bean property access + //public boolean isEmpty() { return empty; } + + public String getAccessType() { return accessType; } + + public void setPageNo(int pageNo) { this.pageNo=pageNo; } + public void setPageSize(int pageSize) { this.dataSize=pageSize; } + public void setDataSize(int dataSize) { this.dataSize=dataSize; } + + public void setAccessType(String accessType) { this.accessType = accessType; } + +} // SearchResult diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/conf/AppConfig.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/conf/AppConfig.java new file mode 100644 index 00000000..118b0e56 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/conf/AppConfig.java @@ -0,0 +1,313 @@ +/*- + * ================================================================================ + * ECOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.conf; + +import java.util.ArrayList; +import java.util.List; + +import javax.sql.DataSource; + +import org.openecomp.portalsdk.core.interceptor.ResourceInterceptor; +import org.openecomp.portalsdk.core.interceptor.SessionTimeoutInterceptor; +import org.openecomp.portalsdk.core.lm.FusionLicenseManager; +import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum; +import org.openecomp.portalsdk.core.logging.format.AppMessagesEnum; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.menu.MenuBuilder; +import org.openecomp.portalsdk.core.onboarding.util.CipherUtil; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.service.DataAccessServiceImpl; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.portalsdk.core.web.support.AppUtils; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.context.annotation.Bean; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.view.InternalResourceViewResolver; +import org.springframework.web.servlet.view.JstlView; +import org.springframework.web.servlet.view.UrlBasedViewResolver; +import org.springframework.web.servlet.view.tiles3.TilesConfigurer; +import org.springframework.web.servlet.view.tiles3.TilesView; + +import com.mchange.v2.c3p0.ComboPooledDataSource; + +/** + * Configures Spring features in the ECOMP Portal SDK including request + * interceptors and view resolvers. Application should subclass and override + * methods as needed. + */ +public class AppConfig extends WebMvcConfigurerAdapter implements Configurable, ApplicationContextAware { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppConfig.class); + + private final List<String> tileDefinitions = new ArrayList<String>(); + protected ApplicationContext appApplicationContext = null; + + public AppConfig() { + //loads all default fields and marks logging + //has been started for each log file type. + initGlobalLocalContext(); + } + + /** + * Creates and returns a new instance of a secondary (order=2) + * {@link ViewResolver} that finds files by adding prefix "/WEB-INF/jsp/" + * and suffix ".jsp" to the base view name. + * + * @return New instance of {@link ViewResolver}. + */ + @Bean + public ViewResolver viewResolver() { + InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); + viewResolver.setViewClass(JstlView.class); + viewResolver.setPrefix("/WEB-INF/jsp/"); + viewResolver.setSuffix(".jsp"); + viewResolver.setOrder(2); + return viewResolver; + } + + /** + * Loads all the default logging fields into the + * global MDC context and marks each log file type + * that logging has been started. + */ + private void initGlobalLocalContext() { + logger.init(); + } + + /* + * Any requests from the url pattern /static/**, Spring will look for the + * resources from the /static/ Same as <mvc:resources mapping="/static/**" + * location="/static/"/> in xml + */ + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + // registry.addResourceHandler("/static/**").addResourceLocations("/static/"); + registry.addResourceHandler("/**").addResourceLocations("/"); + } + + /** + * Creates and returns a new instance of a {@link DataAccessService} class. + * + * @return New instance of {@link DataAccessService}. + */ + @Bean + public DataAccessService dataAccessService() { + return new DataAccessServiceImpl(); + } + + /** + * Creates and returns a new instance of a {@link SystemProperties} class. + * + * @return New instance of {@link SystemProperties}. + */ + @Bean + public SystemProperties systemProperties() { + return new SystemProperties(); + } + + /** + * Creates and returns a new instance of a {@link MenuBuilder} class. + * + * @return New instance of {@link MenuBuilder}. + */ + @Bean + public MenuBuilder menuBuilder() { + return new MenuBuilder(); + } + + /** + * Creates and returns a new instance of a {@link UserUtils} class. + * + * @return New instance of {@link UserUtils}. + */ + @Bean + public UserUtils userUtil() { + return new UserUtils(); + } + + /** + * Creates and returns a new instance of an {@link AppUtils} class. + * + * @return New instance of {@link AppUtils}. + */ + @Bean + public AppUtils appUtils() { + return new AppUtils(); + } + + /** + * Creates and returns a new instance of a {@link TilesConfigurer} class. + * + * @return New instance of {@link TilesConfigurer}. + */ + @Bean + public TilesConfigurer tilesConfigurer() { + TilesConfigurer tilesConfigurer = new TilesConfigurer(); + tilesConfigurer.setDefinitions(tileDefinitions()); + tilesConfigurer.setCheckRefresh(true); + return tilesConfigurer; + } + + /** + * + * Application Data Source + * + * @return DataSource Object + */ + + @Bean + public DataSource dataSource() throws Exception { + systemProperties(); + ComboPooledDataSource dataSource = new ComboPooledDataSource(); + try { + dataSource.setDriverClass(SystemProperties.getProperty(SystemProperties.DB_DRIVER)); + dataSource.setJdbcUrl(SystemProperties.getProperty(SystemProperties.DB_CONNECTIONURL)); + dataSource.setUser(SystemProperties.getProperty(SystemProperties.DB_USERNAME)); + // dataSource.setPassword(SystemProperties.getProperty(SystemProperties.DB_PASSWOR)); + String password = SystemProperties.getProperty(SystemProperties.DB_PASSWOR); + if (SystemProperties.containsProperty(SystemProperties.DB_ENCRYPT_FLAG)) { + String encryptFlag = SystemProperties.getProperty(SystemProperties.DB_ENCRYPT_FLAG); + if (encryptFlag != null && encryptFlag.equalsIgnoreCase("true")) { + password = CipherUtil.decrypt(password); + } + } + dataSource.setPassword(password); + dataSource + .setMinPoolSize(Integer.parseInt(SystemProperties.getProperty(SystemProperties.DB_MIN_POOL_SIZE))); + dataSource + .setMaxPoolSize(Integer.parseInt(SystemProperties.getProperty(SystemProperties.DB_MAX_POOL_SIZE))); + dataSource.setIdleConnectionTestPeriod( + Integer.parseInt(SystemProperties.getProperty(SystemProperties.IDLE_CONNECTION_TEST_PERIOD))); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Error initializing database, verify database settings in properties file: " + + UserUtils.getStackTrace(e),AlarmSeverityEnum.CRITICAL); + logger.error(EELFLoggerDelegate.debugLogger, "Error initializing database, verify database settings in properties file: " + + UserUtils.getStackTrace(e),AlarmSeverityEnum.CRITICAL); + // Raise an alarm that opening a connection to the database is + // failed. + logger.logEcompError(AppMessagesEnum.BeDaoSystemError); + throw e; + } + return dataSource; + } + + /* + * TODO: Check whether it is appropriate to extend the list of tile + * definitions at every invocation. + */ + protected String[] tileDefinitions() { + tileDefinitions.add("/WEB-INF/fusion/defs/definitions.xml"); + tileDefinitions.addAll(addTileDefinitions()); + + return tileDefinitions.toArray(new String[0]); + } + + /** + * Creates and returns a new empty list. This method should be overridden by + * child classes. + * + * @return An empty list. + */ + public List<String> addTileDefinitions() { + return new ArrayList<String>(); + } + + /** + * Creates and returns a new instance of a primary (order=1) + * {@link UrlBasedViewResolver} that finds files using the contents of + * definitions.xml files. + * + * @return New instance of {@link UrlBasedViewResolver} + */ + @Bean + public UrlBasedViewResolver tileViewResolver() { + UrlBasedViewResolver viewResolver = new UrlBasedViewResolver(); + viewResolver.setViewClass(TilesView.class); + viewResolver.setOrder(1); + return viewResolver; + } + + /** + * Adds new instances of the following interceptors to the specified + * interceptor registry: {@link SessionTimeoutInterceptor}, + * {@link ResourceInterceptor} + */ + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(new SessionTimeoutInterceptor()) + .excludePathPatterns(getExcludeUrlPathsForSessionTimeout()); + registry.addInterceptor(resourceInterceptor()); + } + + /** + * Creates and returns a new instance of a {@link ResourceInterceptor}. + * + * @return New instance of {@link ResourceInterceptor} + */ + @Bean + public ResourceInterceptor resourceInterceptor() { + return new ResourceInterceptor(); + } + + private String[] excludeUrlPathsForSessionTimeout = {}; + + /** + * Gets the array of Strings that are paths excluded for session timeout. + * + * @return Array of String + */ + public String[] getExcludeUrlPathsForSessionTimeout() { + return excludeUrlPathsForSessionTimeout; + } + + /** + * Sets the array of Strings that are paths excluded for session timeout. + */ + public void setExcludeUrlPathsForSessionTimeout(final String... excludeUrlPathsForSessionTimeout) { + this.excludeUrlPathsForSessionTimeout = excludeUrlPathsForSessionTimeout; + } + + /** + * Creates and returns a new instance of a {@link FusionLicenseManager}. + * + * @return New instance of {@link FusionLicenseManager}. +// @Bean + public FusionLicenseManager fusionLicenseManager() { + return new FusionLicenseManager(new LicenseableClassImpl()); + } + */ + + /* + * (non-Javadoc) + * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext) + */ + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + appApplicationContext = applicationContext; + + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/conf/AppInitializer.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/conf/AppInitializer.java new file mode 100644 index 00000000..82e449f1 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/conf/AppInitializer.java @@ -0,0 +1,69 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.conf; + +import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; + +public abstract class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppInitializer.class); + private final String activeProfile = "src"; + + @Override + protected WebApplicationContext createServletApplicationContext() { + WebApplicationContext context = super.createServletApplicationContext(); + + try { + + ((ConfigurableEnvironment) context.getEnvironment()).setActiveProfiles(activeProfile); + } catch (Exception e) { + + logger.error(EELFLoggerDelegate.errorLogger, "Unable to set the active profile" + e.getMessage(),AlarmSeverityEnum.MAJOR); + throw e; + + } + + return context; + } + + @Override + protected Class<?>[] getRootConfigClasses() { + return null; + } + + @Override + protected Class<?>[] getServletConfigClasses() { + + return new Class[] { AppConfig.class }; + } + + /* + * URL request will direct to the Spring dispatcher for processing + */ + @Override + protected String[] getServletMappings() { + return new String[] { "/" }; + } + +}
\ No newline at end of file diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/conf/Configurable.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/conf/Configurable.java new file mode 100644 index 00000000..9585e45d --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/conf/Configurable.java @@ -0,0 +1,38 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.conf; + +import java.util.List; + +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; + +public interface Configurable { + + public ViewResolver viewResolver(); + + public void addResourceHandlers(ResourceHandlerRegistry registry) ; + + public DataAccessService dataAccessService(); + + public List<String> addTileDefinitions(); + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/conf/HibernateConfiguration.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/conf/HibernateConfiguration.java new file mode 100644 index 00000000..8a3459d1 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/conf/HibernateConfiguration.java @@ -0,0 +1,139 @@ +/*- + * ================================================================================ + * ECOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.conf; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import javax.sql.DataSource; + +import org.hibernate.SessionFactory; +import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.orm.hibernate4.HibernateTransactionManager; +import org.springframework.orm.hibernate4.LocalSessionFactoryBean; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import com.mchange.v2.c3p0.ComboPooledDataSource; + +@Configuration +@EnableTransactionManagement +public class HibernateConfiguration { + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HibernateConfiguration.class); + + @Autowired + private HibernateMappingLocatable hbMappingLocatable; + + @Autowired + private DataSource dataSource; + + @Bean + public LocalSessionFactoryBean sessionFactory() { + LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); + sessionFactory.setDataSource(dataSource); + sessionFactory.setPackagesToScan(hbMappingLocatable.getPackagesToScan()); + sessionFactory.setHibernateProperties(getHibernateProperties()); + sessionFactory.setMappingLocations(hbMappingLocatable.getMappingLocations()); + return sessionFactory; + } + + /** + * Builds a properties object with Hibernate properties in te system.properties file. + * + * @return Properties object + */ + private Properties getHibernateProperties() { + Properties properties = new Properties(); + properties.put("hibernate.dialect", SystemProperties.getProperty(SystemProperties.HB_DIALECT)); + properties.put("hibernate.show_sql", SystemProperties.getProperty(SystemProperties.HB_SHOW_SQL)); + return properties; + } + + @SuppressWarnings("rawtypes") + @Bean + public Map dataSourceMap() throws Exception { + Connection conn = null; + Statement stmt = null; + Map<String, ComboPooledDataSource> dataSourceMap = new HashMap<String, ComboPooledDataSource>(); + + try { + conn = dataSource.getConnection(); + stmt = conn.createStatement(); + String sql; + sql = "SELECT schema_id,datasource_type,connection_url,user_name,password,driver_class,min_pool_size,max_pool_size,idle_connection_test_period FROM schema_info"; + ResultSet rs = stmt.executeQuery(sql); + + while (rs.next()) { + ComboPooledDataSource dataSource = new ComboPooledDataSource(); + dataSource.setDriverClass(rs.getString("driver_class")); + dataSource.setJdbcUrl(rs.getString("connection_url")); + dataSource.setUser(rs.getString("user_name")); + dataSource.setPassword(rs.getString("password")); + dataSource.setMinPoolSize(rs.getInt("min_pool_size")); + dataSource.setMaxPoolSize(rs.getInt("max_pool_size")); + dataSource.setIdleConnectionTestPeriod(rs.getInt("idle_connection_test_period")); + dataSourceMap.put(rs.getString("schema_id"), dataSource); + } + rs.close(); + stmt.close(); + conn.close(); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "Error initializing database, verify database settings in properties file: " + e.getMessage(), + AlarmSeverityEnum.CRITICAL); + e.printStackTrace(); + dataSourceMap = null; + throw e; + } finally { + try { + if (stmt != null) + stmt.close(); + } catch (SQLException se2) { + } + try { + if (conn != null) + conn.close(); + } catch (SQLException se) { + se.printStackTrace(); + } + } + + return dataSourceMap; + } + + @Bean + @Autowired + public HibernateTransactionManager transactionManager(SessionFactory s) { + HibernateTransactionManager txManager = new HibernateTransactionManager(); + txManager.setSessionFactory(s); + return txManager; + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/conf/HibernateMappingLocatable.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/conf/HibernateMappingLocatable.java new file mode 100644 index 00000000..94aed111 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/conf/HibernateMappingLocatable.java @@ -0,0 +1,43 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.conf; + +import org.springframework.core.io.Resource; + +/** + * Defines methods used by developers to supply Hibernate configuration. + */ +public interface HibernateMappingLocatable { + + /** + * Gets Hibernate mapping locations. + * + * @return Array of Resource objects (usually ClassPathResource that's a + * file) which contain Hibernate mapping information. + */ + public Resource [] getMappingLocations(); + + /** + * Gets package names. + * + * @return Array of Java package names to scan for classes with Hibernate annotations. + */ + public String [] getPackagesToScan(); +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/controller/FusionBaseController.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/controller/FusionBaseController.java new file mode 100644 index 00000000..c7820115 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/controller/FusionBaseController.java @@ -0,0 +1,135 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.controller; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import org.openecomp.portalsdk.core.domain.MenuData; +import org.openecomp.portalsdk.core.domain.User; +import org.openecomp.portalsdk.core.interfaces.SecurityInterface; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.menu.MenuBuilder; +import org.openecomp.portalsdk.core.service.AppService; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.service.FnMenuService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.ModelAttribute; + +import com.fasterxml.jackson.databind.ObjectMapper; + +@Controller +public abstract class FusionBaseController implements SecurityInterface{ + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FusionBaseController.class); + + @Override + public boolean isAccessible() { + return true; + } + + public boolean isRESTfulCall(){ + return true; + } + @Autowired + private FnMenuService fnMenuService; + + @Autowired + private MenuBuilder menuBuilder; + + @Autowired + private DataAccessService dataAccessService; + + @Autowired + AppService appService; + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @ModelAttribute("menu") + public Map<String, Object> getMenu(HttpServletRequest request) { + HttpSession session = null; + Map<String, Object> model = new HashMap<String, Object>(); + try { + try { + String appName = appService.getDefaultAppName(); + if (appName==null || appName=="") { + appName = SystemProperties.SDK_NAME; + } + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, appName); + } catch (Exception e) { + } + + session = request.getSession(); + User user = UserUtils.getUserSession(request); + if(session!=null && user!=null){ + Set<MenuData> menuResult = (Set<MenuData>) session.getAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME)); + if(menuResult==null){ + Set appMenu = getMenuBuilder().getMenu(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_SET_NAME),dataAccessService); + session.setAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME), MenuBuilder.filterMenu(appMenu, request)); + menuResult = (Set<MenuData>) session.getAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME)); + } + model = setMenu(menuResult); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); + } + return model; + } + + public Map<String, Object> setMenu(Set<MenuData> menuResult) throws Exception{ + ObjectMapper mapper = new ObjectMapper(); + List<List<MenuData>> childItemList = new ArrayList<List<MenuData>>();; + List<MenuData> parentList = new ArrayList<MenuData>();; + Map<String, Object> model = new HashMap<String, Object>(); + try{ + fnMenuService.setMenuDataStructure(childItemList, parentList, menuResult); + }catch(Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); + } + model.put("childItemList",childItemList!=null?mapper.writeValueAsString(childItemList):""); + model.put("parentList",parentList!=null?mapper.writeValueAsString(parentList):""); + return model; + } + + public MenuBuilder getMenuBuilder() { + return menuBuilder; + } + + public void setMenuBuilder(MenuBuilder menuBuilder) { + this.menuBuilder = menuBuilder; + } + + public DataAccessService getDataAccessService() { + return dataAccessService; + } + + public void setDataAccessService(DataAccessService dataAccessService) { + this.dataAccessService = dataAccessService; + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/controller/RestrictedBaseController.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/controller/RestrictedBaseController.java new file mode 100644 index 00000000..2b2e3426 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/controller/RestrictedBaseController.java @@ -0,0 +1,50 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.controller; + +public class RestrictedBaseController extends FusionBaseController{ + + protected String viewName; + private String exceptionView; + @Override + public boolean isAccessible() { + return false; + } + @Override + public boolean isRESTfulCall(){ + return false; + } + protected String getViewName() { + return viewName; + } + protected void setViewName(String viewName) { + this.viewName = viewName; + } + + public String getExceptionView() { + return (exceptionView == null) ? "runtime_error_handler" : exceptionView; + } + + public void setExceptionView(String exceptionView) { + this.exceptionView = exceptionView; + } + + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/controller/RestrictedRESTfulBaseController.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/controller/RestrictedRESTfulBaseController.java new file mode 100644 index 00000000..d11c7d76 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/controller/RestrictedRESTfulBaseController.java @@ -0,0 +1,50 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.controller; + +public class RestrictedRESTfulBaseController extends FusionBaseController{ + + protected String viewName; + private String exceptionView; + @Override + public boolean isAccessible() { + return false; + } + @Override + public boolean isRESTfulCall(){ + return true; + } + protected String getViewName() { + return viewName; + } + protected void setViewName(String viewName) { + this.viewName = viewName; + } + + public String getExceptionView() { + return (exceptionView == null) ? "runtime_error_handler" : exceptionView; + } + + public void setExceptionView(String exceptionView) { + this.exceptionView = exceptionView; + } + + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/controller/UnRestrictedBaseController.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/controller/UnRestrictedBaseController.java new file mode 100644 index 00000000..78bf4c51 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/controller/UnRestrictedBaseController.java @@ -0,0 +1,40 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.controller; + +public class UnRestrictedBaseController extends FusionBaseController{ + protected String viewName; + + @Override + public boolean isAccessible() { + return true; + } + @Override + public boolean isRESTfulCall(){ + return false; + } + protected String getViewName() { + return viewName; + } + + protected void setViewName(String viewName) { + this.viewName = viewName; + } +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/dao/AbstractDao.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/dao/AbstractDao.java new file mode 100644 index 00000000..0b274068 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/dao/AbstractDao.java @@ -0,0 +1,62 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.dao; +import java.io.Serializable; +import java.lang.reflect.ParameterizedType; + +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.springframework.beans.factory.annotation.Autowired; + +public abstract class AbstractDao<PK extends Serializable, T> { + + private final Class<T> persistentClass; + + @SuppressWarnings("unchecked") + public AbstractDao(){ + this.persistentClass =(Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1]; + } + + @Autowired + private SessionFactory sessionFactory; + + protected Session getSession(){ + return sessionFactory.getCurrentSession(); + } + + @SuppressWarnings("unchecked") + public T getByKey(PK key) { + return (T) getSession().get(persistentClass, key); + } + + public void persist(T entity) { + getSession().persist(entity); + } + + public void delete(T entity) { + getSession().delete(entity); + } + + protected Criteria createEntityCriteria(){ + return getSession().createCriteria(persistentClass); + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/dao/ProfileDao.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/dao/ProfileDao.java new file mode 100644 index 00000000..0094072c --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/dao/ProfileDao.java @@ -0,0 +1,29 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.dao; + +import java.util.List; + +import org.openecomp.portalsdk.core.domain.Profile; + +public interface ProfileDao { + List<Profile> findAll(); + Profile getProfile(int id); +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/dao/ProfileDaoImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/dao/ProfileDaoImpl.java new file mode 100644 index 00000000..4dd2711e --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/dao/ProfileDaoImpl.java @@ -0,0 +1,51 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.dao; + +import java.util.List; + +import org.hibernate.Criteria; +import org.hibernate.criterion.Restrictions; +import org.openecomp.portalsdk.core.dao.AbstractDao; +import org.openecomp.portalsdk.core.domain.Profile; +import org.springframework.stereotype.Repository; + +@Repository("profileDao") +public class ProfileDaoImpl extends AbstractDao<Integer, Profile> implements ProfileDao{ + + + public List<Profile> findAll() { + Criteria crit = getSession().createCriteria(Profile.class); + @SuppressWarnings("unchecked") + List<Profile> p = crit.list(); + + return p; + } + + + public Profile getProfile(int id) { + Criteria crit = getSession().createCriteria(Profile.class); + crit.add(Restrictions.eq("id", id)); + Profile profile = (Profile) crit.uniqueResult(); + + return profile; + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/dao/hibernate/ModelOperationsCommon.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/dao/hibernate/ModelOperationsCommon.java new file mode 100644 index 00000000..cd9e644b --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/dao/hibernate/ModelOperationsCommon.java @@ -0,0 +1,453 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.dao.hibernate; + +import java.io.Serializable; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.hibernate.Criteria; +import org.hibernate.FetchMode; +import org.hibernate.Query; +import org.hibernate.SQLQuery; +import org.hibernate.Session; +import org.hibernate.criterion.Criterion; +import org.hibernate.criterion.Order; +import org.hibernate.criterion.ProjectionList; +import org.hibernate.type.LongType; +import org.openecomp.portalsdk.core.dao.support.FusionDao; +import org.openecomp.portalsdk.core.domain.Lookup; +import org.openecomp.portalsdk.core.domain.support.DomainVo; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.util.SystemProperties; + +public abstract class ModelOperationsCommon extends FusionDao { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ModelOperationsCommon.class); + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public List _getList(Class domainClass, String filterClause, Integer fromIndex, Integer toIndex, String orderBy) { + List list = null; + String className = domainClass.getName(); + + Session session = getSessionFactory().getCurrentSession(); + + logger.info(EELFLoggerDelegate.debugLogger, "Getting " + className.toLowerCase() + " records" + + ((fromIndex != null) ? " from rows " + fromIndex.toString() + " to " + toIndex.toString() : "") + + "..."); + + + if (filterClause != null && filterClause.length() > 0) { + logger.info(EELFLoggerDelegate.debugLogger, "Filtering " + className + " by: " + filterClause); + + } + + list = session.createQuery("from " + className + Utilities.nvl(filterClause, "") + + ((orderBy != null) ? " order by " + orderBy : "")).list(); + list = (fromIndex != null) ? list.subList(fromIndex.intValue() - 1, toIndex.intValue()) : list; + + if (orderBy == null && list != null) { + Collections.sort(list); + } + + return list; + } + + public List<?> _getList(Class<?> domainClass, ProjectionList projectionsList, List<Criterion> restrictionsList, + List<Order> orderByList) { + return _getList(domainClass, projectionsList, restrictionsList, orderByList, null); + } + + public List<?> _getList(Class<?> domainClass, ProjectionList projectionsList, List<Criterion> restrictionsList, + List<Order> orderByList, HashMap<String, FetchMode> fetchModeMap) { + + Session session = getSessionFactory().getCurrentSession(); + + Criteria criteria = session.createCriteria(domainClass); + + if (projectionsList != null) { + criteria.setProjection(projectionsList); + } + + if (restrictionsList != null && !restrictionsList.isEmpty()) { + for (Criterion criterion : restrictionsList) + criteria.add(criterion); + } + + if (orderByList != null && !orderByList.isEmpty()) { + for (Order order : orderByList) + criteria.addOrder(order); + } + + if (fetchModeMap != null) { + Iterator<String> itr = fetchModeMap.keySet().iterator(); + String key = null; + while (itr.hasNext()) { + key = itr.next(); + criteria.setFetchMode(key, fetchModeMap.get(key)); + } + + } + return criteria.list(); + } + + @SuppressWarnings("rawtypes") + public DomainVo _get(Class domainClass, Serializable id) { + DomainVo vo = null; + + Session session = getSessionFactory().getCurrentSession(); + + logger.info(EELFLoggerDelegate.debugLogger, "Getting " + domainClass.getName() + " record for id - " + id.toString()); + + + vo = (DomainVo) session.get(domainClass, id); + + if (vo == null) { + try { + vo = (DomainVo) domainClass.newInstance(); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed while instantiating a class of " + domainClass.getName() + e.getMessage()); + + } + } + + return vo; + } + + @SuppressWarnings("rawtypes") + public List _getLookupList(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy, + HashMap additionalParams) { + logger.info(EELFLoggerDelegate.debugLogger, "Retrieving " + dbTable + " lookup list..."); + + List list = null; + String dbOrderByCol = dbOrderBy; + + Session session = getSessionFactory().getCurrentSession(); + + // default the orderBy if null; + if (Utilities.nvl(dbOrderBy).length() == 0) { + dbOrderByCol = dbLabelCol; + dbOrderBy = dbLabelCol; + } else { + if (dbOrderBy.lastIndexOf(" ") > -1) { + dbOrderByCol = dbOrderBy.substring(0, dbOrderBy.lastIndexOf(" ")); + } + } + + StringBuffer sql = new StringBuffer(); + + sql.append("select distinct ").append(dbLabelCol).append(" as lab, ").append(dbValueCol).append(" as val, ") + .append(dbOrderByCol).append(" as sortOrder ").append("from ").append(dbTable).append(" ") + .append((Utilities.nvl(dbFilter).length() == 0) ? "" : (" where " + dbFilter)).append(" order by ") + .append(dbOrderBy); + + try { + list = session.createSQLQuery(sql.toString()).addEntity(Lookup.class).list(); + } catch (Exception e) { + list = null; + logger.info(EELFLoggerDelegate.debugLogger, "The results for the lookup list query [" + sql + "] were empty."); + } + + return list; + } // getLookupList + + /* This method is used to execute SQL queries */ + @SuppressWarnings("rawtypes") + protected final List _executeSQLQuery(String sql, Class domainClass) { + return _executeSQLQuery(sql, domainClass, null, null); + } + + /* This method is used to execute SQL queries with paging */ + @SuppressWarnings("rawtypes") + protected final List _executeSQLQuery(String sql, Class domainClass, Integer fromIndex, Integer toIndex) { + Session session = getSessionFactory().getCurrentSession(); + + SQLQuery query = session.createSQLQuery(sql).addEntity(domainClass.getName().toLowerCase(), domainClass); + + if (fromIndex != null && toIndex != null) { + query.setFirstResult(fromIndex.intValue()); + int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1; + query.setMaxResults(pageSize); + } + + return query.list(); + } + + /* This method is used to execute HQL queries */ + @SuppressWarnings("rawtypes") + protected final List _executeQuery(String sql) { + return _executeQuery(sql, null, null); + } + + /* This method is used to execute HQL queries with paging */ + @SuppressWarnings("rawtypes") + protected final List _executeQuery(String sql, Integer fromIndex, Integer toIndex) { + Session session = getSessionFactory().getCurrentSession(); + + Query query = session.createQuery(sql); + + if (fromIndex != null && toIndex != null) { + query.setFirstResult(fromIndex.intValue()); + int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1; + query.setMaxResults(pageSize); + } + + return query.list(); + } + + /* + * This method can be used to execute both HQL or SQL named queries. The + * distinction will come in the hbm.xml mapping file defining the named + * query. Named HQL queries use the <query> tag while named SQL queries use + * the <sql-query> tag. + */ + @SuppressWarnings("rawtypes") + protected final List _executeNamedQuery(String queryName, Map params) { + return _executeNamedQuery(queryName, params, null, null); + } + + /* + * This method can be used to execute both HQL or SQL named queries with + * paging. The distinction will come in the hbm.xml mapping file defining + * the named query. Named HQL queries use the <query> tag while named SQL + * queries use the <sql-query> tag. + */ + @SuppressWarnings("rawtypes") + protected final List _executeNamedQuery(String queryName, Map params, Integer fromIndex, Integer toIndex) { + Session session = getSessionFactory().getCurrentSession(); + Query query = session.getNamedQuery(queryName); + bindQueryParameters(query, params); + if (fromIndex != null && toIndex != null) { + query.setFirstResult(fromIndex.intValue()); + int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1; + query.setMaxResults(pageSize); + } + return query.list(); + } + + // RAPTOR ZK + /* + * This method can be used to execute both HQL or SQL named queries with + * paging. The distinction will come in the hbm.xml mapping file defining + * the named query. Named HQL queries use the <query> tag while named SQL + * queries use the <sql-query> tag. + */ + @SuppressWarnings("rawtypes") + protected final List _executeNamedCountQuery(Class entity, String queryName, String whereClause, Map params) { + Session session = getSessionFactory().getCurrentSession(); + Query query = session.getNamedQuery(queryName); + String queryStr = query.getQueryString(); + StringBuffer modifiedSql = new StringBuffer(" select count(*) as countRows from (" + queryStr + " ) al "); + if (whereClause != null && whereClause.length() > 0) + modifiedSql.append("where " + whereClause); + // SQLQuery sqlQuery = session.createSQLQuery(" select count(*) as + // {reportSearch.countRows} from ("+ modifiedSql.toString()+")"); + SQLQuery sqlQuery = session.createSQLQuery(modifiedSql.toString()); + bindQueryParameters(sqlQuery, params); + sqlQuery.addScalar("countRows", LongType.INSTANCE); + // sqlQuery.addEntity("reportSearch", entity); + // sqlQuery.setResultTransformer(new + // AliasToBeanResultTransformer(SearchCount.class)); + return sqlQuery.list(); + + } + + /* + * This method can be used to execute both HQL or SQL named queries with + * paging. The distinction will come in the hbm.xml mapping file defining + * the named query. Named HQL queries use the <query> tag while named SQL + * queries use the <sql-query> tag. It is modified to test ZK filter. + */ + @SuppressWarnings("rawtypes") + protected final List _executeNamedQuery(Class entity, String queryName, String whereClause, Map params, + Integer fromIndex, Integer toIndex) { + Session session = getSessionFactory().getCurrentSession(); + Query query = session.getNamedQuery(queryName); + bindQueryParameters(query, params); + String queryStr = query.getQueryString(); + StringBuffer modifiedSql = new StringBuffer(" select * from (" + queryStr + " ) al "); + if (whereClause != null && whereClause.length() > 0) + modifiedSql.append("where " + whereClause); + + SQLQuery sqlQuery = session.createSQLQuery(modifiedSql.toString()); + bindQueryParameters(sqlQuery, params); + sqlQuery.addEntity("reportSearch", entity); + + if (fromIndex != null && toIndex != null) { + sqlQuery.setFirstResult(fromIndex.intValue()); + int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1; + sqlQuery.setMaxResults(pageSize); + } + return sqlQuery.list(); + } + + /* + * This method can be used to execute both HQL or SQL named queries with + * paging. The distinction will come in the hbm.xml mapping file defining + * the named query. Named HQL queries use the <query> tag while named SQL + * queries use the <sql-query> tag. + */ + @SuppressWarnings("rawtypes") + protected final List _executeNamedQueryWithOrderBy(Class entity, String queryName, Map params, String _orderBy, + boolean asc, Integer fromIndex, Integer toIndex) { + Session session = getSessionFactory().getCurrentSession(); + Query query = session.getNamedQuery(queryName); + bindQueryParameters(query, params); + String queryStr = query.getQueryString(); + queryStr = String.format(queryStr, _orderBy, asc ? "ASC" : "DESC"); + SQLQuery sqlQuery = session.createSQLQuery(queryStr); + bindQueryParameters(sqlQuery, params); + sqlQuery.addEntity("reportSearch", entity); + if (fromIndex != null && toIndex != null) { + sqlQuery.setFirstResult(fromIndex.intValue()); + int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1; + sqlQuery.setMaxResults(pageSize); + } + return sqlQuery.list(); + } + + // Where Clause + @SuppressWarnings("rawtypes") + protected final List _executeNamedQueryWithOrderBy(Class entity, String queryName, String whereClause, Map params, + String _orderBy, boolean asc, Integer fromIndex, Integer toIndex) { + Session session = getSessionFactory().getCurrentSession(); + Query query = session.getNamedQuery(queryName); + bindQueryParameters(query, params); + String queryStr = query.getQueryString(); + queryStr = String.format(queryStr, _orderBy, asc ? "ASC" : "DESC"); + // StringBuffer modifiedSql = new StringBuffer(queryStr ); + StringBuffer modifiedSql = new StringBuffer(" select * from (" + queryStr + " ) al "); + // modifiedSql.insert(queryStr.lastIndexOf("order by"), " " + + // whereClause + " "); + if (whereClause != null && whereClause.length() > 0) + modifiedSql.append("where " + whereClause); + SQLQuery sqlQuery = session.createSQLQuery(modifiedSql.toString()); + bindQueryParameters(sqlQuery, params); + sqlQuery.addEntity("reportSearch", entity); + if (fromIndex != null && toIndex != null) { + sqlQuery.setFirstResult(fromIndex.intValue()); + int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1; + sqlQuery.setMaxResults(pageSize); + } + return sqlQuery.list(); + } + + // RAPTOR ZK END + + /* Processes custom Insert/Update/Delete SQL statements */ + protected final int _executeUpdateQuery(String sql) throws Exception { + Session session = getSessionFactory().getCurrentSession(); + Query query = session.createSQLQuery(sql); + return query.executeUpdate(); + } + + /* Processes Insert/Update/Delete Named SQL statements */ + @SuppressWarnings("rawtypes") + protected final int _executeNamedUpdateQuery(String queryName, Map params) throws Exception { + Session session = getSessionFactory().getCurrentSession(); + Query query = session.getNamedQuery(queryName); + bindQueryParameters(query, params); + return query.executeUpdate(); + } + + protected final void _update(DomainVo vo, Integer userId) { + _update(vo, ((userId != null) ? userId.intValue() : 0)); + } + + protected final void _update(DomainVo vo, int userId) { + Date timestamp = new Date(); + + Session session = getSessionFactory().getCurrentSession(); + + if (vo.getId() == null || vo.getId().intValue() == 0) { // add new + vo.setCreated(timestamp); + vo.setModified(timestamp); + + if (userId != 0 + && userId != Integer.parseInt(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID))) { + vo.setCreatedId(new Long(userId)); + vo.setModifiedId(new Long(userId)); + } + } else { // update existing + vo.setModified(timestamp); + + if (userId != 0 + && userId != Integer.parseInt(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID))) { + vo.setModifiedId(new Long(userId)); + } + } + + session.saveOrUpdate(vo); + } + + protected final void _remove(DomainVo vo) { + Session session = getSessionFactory().getCurrentSession(); + session.delete(vo); + } + + @SuppressWarnings("rawtypes") + protected final int _remove(Class domainClass, String whereClause) { + int rowsAffected = 0; + + Session session = getSessionFactory().getCurrentSession(); + + StringBuffer sql = new StringBuffer("delete from "); + + sql.append(domainClass.getName()).append(" where ").append(whereClause); + + rowsAffected = session.createQuery(sql.toString()).executeUpdate(); + + return rowsAffected; + } + + protected final void _flush() { + Session session = getSessionFactory().getCurrentSession(); + session.flush(); + } + + @SuppressWarnings("rawtypes") + private void bindQueryParameters(Query query, Map params) { + if (params != null) { + for (Iterator i = params.entrySet().iterator(); i.hasNext();) { + Map.Entry entry = (Map.Entry) i.next(); + + Object parameterValue = entry.getValue(); + + if (!(parameterValue instanceof Collection) && !(parameterValue instanceof Object[])) { + query.setParameter((String) entry.getKey(), parameterValue); + } else { + if (parameterValue instanceof Collection) { + query.setParameterList((String) entry.getKey(), (Collection) parameterValue); + } else { + if (parameterValue instanceof Object[]) { + query.setParameterList((String) entry.getKey(), (Object[]) parameterValue); + } + } + } + } + } + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/dao/support/FusionDao.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/dao/support/FusionDao.java new file mode 100644 index 00000000..086a8da0 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/dao/support/FusionDao.java @@ -0,0 +1,36 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.dao.support; + +import org.hibernate.SessionFactory; + +import org.openecomp.portalsdk.core.FusionObject; + +public class FusionDao implements FusionObject { + private SessionFactory sessionFactory; + + public void setSessionFactory(SessionFactory sessionFactory) { + this.sessionFactory = sessionFactory; + } + + public SessionFactory getSessionFactory() { + return this.sessionFactory; + } +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/App.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/App.java new file mode 100644 index 00000000..6e8e6c80 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/App.java @@ -0,0 +1,206 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.domain; + +import org.openecomp.portalsdk.core.domain.support.DomainVo; + +/** + * Represents a row in the FN_APP table in the EP_SDK database. (A nearly + * identical table is defined in Portal database.) + * + * @version 1.0 + */ +public class App extends DomainVo { + + private static final long serialVersionUID = 3465979916929796990L; + + // superclass defines Id + private String name; // app_name + private String imageUrl; // app_image_url + private String description; // app_description + private String notes; // app_notes + private String url; // app_url + private String alternateUrl; // app_alternate_url + private String restEndpoint; // app_rest_endpoint + private String mlAppName; // ml_app_name + private String mlAppAdminId; // ml_app_admin_id; + private String motsId; // mots_id + private String appPassword; // app_password + private String open; + private String enabled; + private byte[] thumbnail; + private String username; // app_username + private String uebKey; // ueb_key + private String uebSecret; // ueb_secret + private String uebTopicName; // ueb_topic_name + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAppPassword() { + return appPassword; + } + + public void setAppPassword(String appPassword) { + this.appPassword = appPassword; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getImageUrl() { + return imageUrl; + } + + public void setImageUrl(String imageUrl) { + this.imageUrl = imageUrl; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getNotes() { + return notes; + } + + public void setNotes(String notes) { + this.notes = notes; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getAlternateUrl() { + return alternateUrl; + } + + public void setAlternateUrl(String alternateUrl) { + this.alternateUrl = alternateUrl; + } + + public String getRestEndpoint() { + return restEndpoint; + } + + public void setRestEndpoint(String restEndpoint) { + this.restEndpoint = restEndpoint; + } + + public String getMlAppName() { + return mlAppName; + } + + public void setMlAppName(String mlAppName) { + this.mlAppName = mlAppName; + } + + public String getMlAppAdminId() { + return mlAppAdminId; + } + + public void setMlAppAdminId(String mlAppAdminId) { + this.mlAppAdminId = mlAppAdminId; + } + + public String getMotsId() { + return motsId; + } + + public void setMotsId(String motsId) { + this.motsId = motsId; + } + + public String getOpen() { + return open; + } + + public void setOpen(String open) { + this.open = open; + } + + public String getEnabled() { + return enabled; + } + + public void setEnabled(String enabled) { + this.enabled = enabled; + } + + public byte[] getThumbnail() { + return this.thumbnail; + } + + public void setThumbnail(byte[] thumbnail) { + this.thumbnail = thumbnail; + } + + public String getUebKey() { + return uebKey; + } + + public void setUebKey(String uebKey) { + this.uebKey = uebKey; + } + + public String getUebSecret() { + return uebSecret; + } + + public void setUebSecret(String uebSecret) { + this.uebSecret = uebSecret; + } + + public String getUebTopicName() { + return uebTopicName; + } + + public void setUebTopicName(String uebTopicName) { + this.uebTopicName = uebTopicName; + } + + /** + * Answers true if the objects have the same ID. + */ + public int compareTo(Object obj) { + Long c1 = getId(); + Long c2 = ((App) obj).getId(); + return c1.compareTo(c2); + } +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/AuditLog.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/AuditLog.java new file mode 100644 index 00000000..1b1326b6 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/AuditLog.java @@ -0,0 +1,106 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.domain; + +import java.util.Date; + +import org.openecomp.portalsdk.core.domain.support.DomainVo; + +public class AuditLog extends DomainVo { + + /** + * + */ + private static final long serialVersionUID = 1L; + public static final String CD_ACTIVITY_LOGIN = "login"; + public static final String CD_ACTIVITY_LOGOUT = "logout"; + public static final String CD_ACTIVITY_MOBILE_LOGIN = "mobile_login"; + public static final String CD_ACTIVITY_MOBILE_LOGOUT = "mobile_logout"; + + /*-------Profile activities -----------*/ + public static final String CD_ACTIVITY_ROLE_ADD = "add_role"; + public static final String CD_ACTIVITY_ROLE_REMOVE = "remove_role"; + public static final String CD_ACTIVITY_CHILD_ROLE_ADD = "add_child_role"; + public static final String CD_ACTIVITY_CHILD_ROLE_REMOVE = "remove_child_role"; + public static final String CD_ACTIVITY_ROLE_ADD_FUNCTION = "add_role_function"; + public static final String CD_ACTIVITY_ROLE_REMOVE_FUNCTION = "remove_role_function"; + public static final String CD_ACTIVITY_USER_ROLE_ADD = "add_user_role"; + public static final String CD_ACTIVITY_USER_ROLE_REMOVE = "remove_user_role"; + + /*Audit activities*/ + public static final String CD_ACTIVITY_FUNCTIONAL_ACCESS = "functional_access"; + public static final String CD_ACTIVITY_TAB_ACCESS = "tab_access"; + public static final String CD_ACTIVITY_APP_ACCESS = "app_access"; + public static final String CD_ACTIVITY_LEFT_MENU_ACCESS = "left_menu_access"; + + + private String activityCode; + private String affectedRecordId; + private String comments; + private Date auditDate; + private Long userId; + + public AuditLog() { + setCreated(new Date()); + } + + public String getActivityCode() { + return activityCode; + } + + public String getComments() { + return comments; + } + + public String getAffectedRecordId() { + return affectedRecordId; + } + + public void setActivityCode(String activityCode) { + this.activityCode = activityCode; + } + + public void setComments(String comments) { + this.comments = comments; + } + + public void setAffectedRecordId(String affectedRecordId) { + this.affectedRecordId = affectedRecordId; + } + + public Date getAuditDate() { + return auditDate; + } + + public void setAuditDate(Date auditDate) { + this.auditDate = auditDate; + } + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/BroadcastMessage.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/BroadcastMessage.java new file mode 100644 index 00000000..42122dbd --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/BroadcastMessage.java @@ -0,0 +1,124 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.domain; + +import java.util.*; + +import org.openecomp.portalsdk.core.domain.support.DomainVo; + +public class BroadcastMessage extends DomainVo { + + /** + * + */ + + private static final long serialVersionUID = 1L; + public BroadcastMessage() { + } + + public static final String ID_MESSAGE_LOCATION_LOGIN = "10"; + public static final String ID_MESSAGE_LOCATION_WELCOME = "20"; + + private String messageText; + private Integer locationId; + private Date startDate; + private Date endDate; + private Integer sortOrder; + private Boolean active; + private String siteCd; + + public Boolean getActive() { + return active; + } + + public Date getEndDate() { + return endDate; + } + + public Integer getLocationId() { + return locationId; + } + + public String getMessageText() { + return messageText; + } + + public Integer getSortOrder() { + return sortOrder; + } + + public Date getStartDate() { + return startDate; + } + + public String getSiteCd() { + return siteCd; + } + + + public void setActive(Boolean active) { + this.active = active; + } + + public void setEndDate(Date endDate) { + this.endDate = endDate; + } + + public void setLocationId(Integer locationId) { + this.locationId = locationId; + } + + public void setMessageText(String messageText) { + this.messageText = messageText; + } + + public void setSortOrder(Integer sortOrder) { + this.sortOrder = sortOrder; + } + + public void setStartDate(Date startDate) { + this.startDate = startDate; + } + + public void setSiteCd(String siteCd) { + this.siteCd = siteCd; + } + + + public int compareTo(Object obj){ + Integer c1 = getLocationId(); + Integer c2 = ((BroadcastMessage)obj).getLocationId(); + + if (c1.compareTo(c2) == 0) { + c1 = getSortOrder(); + c2 = ((BroadcastMessage)obj).getSortOrder(); + + if (c1.compareTo(c2) == 0) { + Long c3 = getId(); + Long c4 = ((BroadcastMessage)obj).getId(); + + return c3.compareTo(c4); + } + } + + return c1.compareTo(c2); + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/DomainVo.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/DomainVo.java new file mode 100644 index 00000000..9d173996 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/DomainVo.java @@ -0,0 +1,177 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.domain; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.util.Date; +import java.util.HashSet; +import java.util.Set; + +/* Super class from which all data objects descend + * + * Per Sunder T on 3 June 2016: + * + * Yes, we need to get rid of domain.DomainVO and fold all the references to the support.DomainVO. + */ +@SuppressWarnings("rawtypes") +@Deprecated +public class DomainVo extends FusionVo implements Serializable, Cloneable, Comparable { + + /** + * + */ + private static final long serialVersionUID = 1L; + protected Long id; + protected Date created; + protected Date modified; + protected Long createdId; + protected Long modifiedId; + protected Long rowNum; + + protected Serializable auditUserId; + + Set auditTrail = null; + + public DomainVo() { + } + + public void setId(Long i) { + id = i; + } + + public void setCreated(Date created) { + this.created = created; + } + + public void setModified(Date modified) { + this.modified = modified; + } + + public void setCreatedId(Long createdId) { + this.createdId = createdId; + } + + public void setModifiedId(Long modifiedId) { + this.modifiedId = modifiedId; + } + + public void setAuditUserId(Serializable auditUserId) { + this.auditUserId = auditUserId; + } + + public void setRowNum(Long rowNum) { + this.rowNum = rowNum; + } + + public void setAuditTrail(Set auditTrail) { + this.auditTrail = auditTrail; + } + + public Long getId() { + return id; + } + + public Date getCreated() { + return created; + } + + public Date getModified() { + return modified; + } + + public Long getCreatedId() { + return createdId; + } + + public Long getModifiedId() { + return modifiedId; + } + + public Serializable getAuditUserId() { + return auditUserId; + } + + public Long getRowNum() { + return rowNum; + } + + public Set getAuditTrail() { + return auditTrail; + } + + @SuppressWarnings("unchecked") + public void addAuditTrailLog(AuditLog auditLog) { + if (getAuditTrail() == null) { + setAuditTrail(new HashSet()); + } + + getAuditTrail().add(auditLog); + } + + public Object clone() throws CloneNotSupportedException { + return super.clone(); + } + + public Object copy() { + return copy(false); + } + + public Object copy(boolean isIdNull) { + // let's create a "copy" of the object using serialization + ByteArrayOutputStream baos = null; + ByteArrayInputStream bais = null; + ObjectOutputStream oos = null; + ObjectInputStream ois = null; + + DomainVo newVo = null; + + try { + + baos = new ByteArrayOutputStream(); + oos = new ObjectOutputStream(baos); + oos.writeObject(this); + + bais = new ByteArrayInputStream(baos.toByteArray()); + ois = new ObjectInputStream(bais); + newVo = (DomainVo) ois.readObject(); + + if (isIdNull) { + newVo.setId(null); + } + + } catch (Exception e) { + e.printStackTrace(); + } + + return newVo; + } + + public int compareTo(Object obj) { + Long c1 = getId(); + Long c2 = ((DomainVo) obj).getId(); + + return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2); + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/FnMenu.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/FnMenu.java new file mode 100644 index 00000000..d9aaf43d --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/FnMenu.java @@ -0,0 +1,141 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.domain; + + +import org.openecomp.portalsdk.core.domain.support.DomainVo; + +/** + * <p>RoleFunction.java</p> + * + * <p>Represents a role function data object.</p> + * + * @version 1.0 + */ +public class FnMenu extends DomainVo { + /** + * + */ + private static final long serialVersionUID = 1L; + public FnMenu() {} + + private Integer menuId; + private String label; + private Integer parentId; + private String action; + private String functionCd; + private Integer sortOrder; + private String servlet; + private String queryString; + private String externalUrl; + private String target; + private String active; + private String separator; + private String imageSrc; + private String menuSetCode; + + public Integer getMenuId() { + return menuId; + } + public void setMenuId(Integer menuId) { + this.menuId = menuId; + } + public String getLabel() { + return label; + } + public void setLabel(String label) { + this.label = label; + } + public Integer getParentId() { + return parentId; + } + public void setParentId(Integer parentId) { + this.parentId = parentId; + } + public String getAction() { + return action; + } + public void setAction(String action) { + this.action = action; + } + public String getFunctionCd() { + return functionCd; + } + public void setFunctionCd(String functionCd) { + this.functionCd = functionCd; + } + public Integer getSortOrder() { + return sortOrder; + } + public void setSortOrder(Integer sortOrder) { + this.sortOrder = sortOrder; + } + public String getServlet() { + return servlet; + } + public void setServlet(String servlet) { + this.servlet = servlet; + } + public String getQueryString() { + return queryString; + } + public void setQueryString(String queryString) { + this.queryString = queryString; + } + public String getExternalUrl() { + return externalUrl; + } + public void setExternalUrl(String externalUrl) { + this.externalUrl = externalUrl; + } + public String getTarget() { + return target; + } + public void setTarget(String target) { + this.target = target; + } + public String getActive() { + return active; + } + public void setActive(String active) { + this.active = active; + } + public String getSeparator() { + return separator; + } + public void setSeparator(String separator) { + this.separator = separator; + } + public String getImageSrc() { + return imageSrc; + } + public void setImageSrc(String imageSrc) { + this.imageSrc = imageSrc; + } + public String getMenuSetCode() { + return menuSetCode; + } + public void setMenuSetCode(String menuSetCode) { + this.menuSetCode = menuSetCode; + } + + + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/FusionVo.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/FusionVo.java new file mode 100644 index 00000000..dc1b8d4c --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/FusionVo.java @@ -0,0 +1,27 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.domain; + +import org.openecomp.portalsdk.core.FusionObject; + +public class FusionVo implements FusionObject { + public FusionVo() { + } +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/LoginBean.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/LoginBean.java new file mode 100644 index 00000000..f20eb4a8 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/LoginBean.java @@ -0,0 +1,187 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.domain; + +import java.util.Set; + +import org.openecomp.portalsdk.core.domain.support.FusionCommand; + +@SuppressWarnings("rawtypes") +public class LoginBean extends FusionCommand { + + private String loginId; + private String loginPwd; + private String hrid; + private String orgUserId; + private String siteAccess; + private String loginErrorMessage; + + private User user; + private Set menu; + private Set businessDirectMenu; + + /** + * getLoginId + * + * @return String + */ + public String getLoginId() { + return loginId; + } + + /** + * getLoginPwd + * + * @return String + */ + public String getLoginPwd() { + return loginPwd; + } + + /** + * getMenu + * + * @return Set + */ + public Set getMenu() { + return menu; + } + + /** + * getUser + * + * @return User + */ + public User getUser() { + return user; + } + + /** + * getHrid + * + * @return String + */ + public String getHrid() { + return hrid; + } + + /** + * getSiteAccess + * + * @return String + */ + public String getSiteAccess() { + return siteAccess; + } + + /** + * getBusinessDirectMenu + * + * @return Set + */ + public Set getBusinessDirectMenu() { + return businessDirectMenu; + } + + /** + * getLoginErrorMessage + * + * @return String + */ + public String getLoginErrorMessage() { + return loginErrorMessage; + } + + public String getOrgUserId() { + return orgUserId; + } + + /** + * setLoginId + * + * @param loginId String + */ + public void setLoginId(String loginId) { + this.loginId = loginId; + } + + /** + * setLoginPwd + * + * @param loginPwd String + */ + public void setLoginPwd(String loginPwd) { + this.loginPwd = loginPwd; + } + + public void setMenu(Set menu) { + this.menu = menu; + } + + /** + * setUser + * + * @param user User + */ + public void setUser(User user) { + this.user = user; + } + + /** + * setHrid + * + * @param hrid String + */ + public void setHrid(String hrid) { + this.hrid = hrid; + } + + /** + * setSiteAccess + * + * @param siteAccess String + */ + public void setSiteAccess(String siteAccess) { + this.siteAccess = siteAccess; + } + + /** + * setBusinessDirectMenu + * + * @param businessDirectMenu Set + */ + public void setBusinessDirectMenu(Set businessDirectMenu) { + this.businessDirectMenu = businessDirectMenu; + } + + /** + * setLoginErrorMessage + * + * @param loginErrorMessage String + */ + public void setLoginErrorMessage(String loginErrorMessage) { + this.loginErrorMessage = loginErrorMessage; + } + + public void setOrgUserId(String orgUserId) { + this.orgUserId = orgUserId; + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/Lookup.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/Lookup.java new file mode 100644 index 00000000..aa7d036c --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/Lookup.java @@ -0,0 +1,85 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.domain; + +import java.io.Serializable; + +import org.openecomp.portalsdk.core.domain.support.NameValueId; + +public class Lookup extends FusionVo implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 1L; + private NameValueId nameValueId = new NameValueId(); + + public Lookup() {} + + public Lookup(String label, String value) { + this(); + setLabel(label); + setValue(value); + } + + public String getValue() { + return getNameValueId().getVal(); + } + + public String getLabel() { + return getNameValueId().getLab(); + } + + public void setValue(String value) { + getNameValueId().setVal(value); + } + + public void setLabel(String label) { + getNameValueId().setLab(label); + } + + public NameValueId getNameValueId() { + return nameValueId; + } + + public void setNameValueId(NameValueId nameValueId) { + this.nameValueId = nameValueId; + } + + // required by ZK for to set the selectedItems of Listboxes (used heavily for <select>-style drop-downs) + public int hashCode() { + int hash = getValue().hashCode(); + hash = hash + getLabel().hashCode(); + + return hash; + } + + public boolean equals( Object obj ) { + boolean equivalent = false; + + Lookup lookup = (Lookup)obj; + if( lookup.getValue().equals(getValue()) && lookup.getLabel().equals(getLabel())) { + equivalent = true; + } + + return equivalent; + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/LuCountry.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/LuCountry.java new file mode 100644 index 00000000..f0237892 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/LuCountry.java @@ -0,0 +1,87 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.domain; + + +import org.openecomp.portalsdk.core.domain.support.*; + + +/** + * <p>luCountry.java</p> + * + * <p>Represents a country data object.</p> + * + * @version 1.0 + */ +public class LuCountry extends DomainVo { + + /** + * + */ + private static final long serialVersionUID = 1L; + LuCountry() {} + + public String getCountry() { + return country; + } + + public String getAbbr() { + return abbr; + } + + public void setCountry(String country) { + this.country = country; + } + + public void setAbbr(String abbr) { + this.abbr = abbr; + } + + + public String getFullName() { + return fullName; + } + + public void setFullName(String fullName) { + this.fullName = fullName; + } + + public String getWebphoneCountryLabel() { + return webphoneCountryLabel; + } + + public void setWebphoneCountryLabel(String webphoneCountryLabel) { + this.webphoneCountryLabel = webphoneCountryLabel; + } + + public int compareTo(Object obj){ + String c1 = getCountry(); + String c2 = ((LuCountry)obj).getCountry(); + + return c1.compareTo(c2); + } + + + private String abbr; + private String country; + private String fullName; + private String webphoneCountryLabel; + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/LuState.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/LuState.java new file mode 100644 index 00000000..09d25b28 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/LuState.java @@ -0,0 +1,70 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.domain; + + +import org.openecomp.portalsdk.core.domain.support.*; + + +/** + * <p>State.java</p> + * + * <p>Represents a state data object.</p> + * + * @version 1.0 + */ +public class LuState extends DomainVo { + + /** + * + */ + private static final long serialVersionUID = 1L; + + LuState() {} + + public String getState() { + return state; + } + + public String getAbbr() { + return abbr; + } + + public void setState(String state) { + this.state = state; + } + + public void setAbbr(String abbr) { + this.abbr = abbr; + } + + + public int compareTo(Object obj){ + String c1 = getState(); + String c2 = ((LuState)obj).getState(); + + return c1.compareTo(c2); + } + + + private String abbr; + private String state; + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/LuTimeZone.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/LuTimeZone.java new file mode 100644 index 00000000..bc0d9326 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/LuTimeZone.java @@ -0,0 +1,79 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.domain; + + +import org.openecomp.portalsdk.core.domain.support.*; + + +/** + * <p>LuTimeZone.java</p> + * + * <p>Represents a LuTimeZone data object.</p> + * + * @version 1.0 + */ +public class LuTimeZone extends DomainVo { + + /** + * + */ + private static final long serialVersionUID = 1L; + + LuTimeZone() {} + + public String getName() { + return name; + } + + public String getValue() { + return value; + } + + public void setName(String name) { + this.name = name; + } + + public void setValue(String value) { + this.value = value; + } + + + public Long getTimezoneId() { + return timezoneId; + } + + public void setTimezoneId(Long timezoneId) { + this.timezoneId = timezoneId; + } + + public int compareTo(Object obj){ + Long c1 = getId(); + Long c2 = ((LuTimeZone)obj).getId(); + + return c1.compareTo(c2); + } + + + private String name; + private Long timezoneId; + private String value; + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/Menu.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/Menu.java new file mode 100644 index 00000000..471edf86 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/Menu.java @@ -0,0 +1,160 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.domain; + + +import org.openecomp.portalsdk.core.domain.support.DomainVo; + +public class Menu extends DomainVo { + + /** + * + */ + private static final long serialVersionUID = 1L; + public Menu() {} + + public String getAction() { + return action; + } + + public boolean isActive() { + return active; + } + + public String getExternalUrl() { + return externalUrl; + } + + public String getFunctionCd() { + return functionCd; + } + + public String getLabel() { + return label; + } + + public String getMenuLevel() { + return menuLevel; + } + + public Long getParentId() { + return parentId; + } + + public String getQueryString() { + return queryString; + } + + public String getServlet() { + return servlet; + } + + public Short getSortOrder() { + return sortOrder; + } + + public String getTarget() { + return target; + } + + public String getMenuSetCode() { + return menuSetCode; + } + + public void setAction(String action) { + this.action = action; + } + + public void setActive(boolean active) { + this.active = active; + } + + public void setExternalUrl(String externalUrl) { + this.externalUrl = externalUrl; + } + + public void setFunctionCd(String functionCd) { + this.functionCd = functionCd; + } + + public void setLabel(String label) { + this.label = label; + } + + public void setMenuLevel(String menuLevel) { + this.menuLevel = menuLevel; + } + + public void setParentId(Long parentId) { + this.parentId = parentId; + } + + public void setQueryString(String queryString) { + this.queryString = queryString; + } + + public void setServlet(String servlet) { + this.servlet = servlet; + } + + public void setSortOrder(Short sortOrder) { + this.sortOrder = sortOrder; + } + + public void setTarget(String target) { + this.target = target; + } + + public void setMenuSetCode(String menuSetCode) { + this.menuSetCode = menuSetCode; + } + + public boolean isSeparator() { + return separator; + } + + public void setSeparator(boolean separator) { + this.separator = separator; + } + + public String getImageSrc() { + return imageSrc; + } + + public void setImageSrc(String imageSrc) { + this.imageSrc = imageSrc; + } + + private String menuLevel; + private String label; + private Long parentId; + private String action; + private String functionCd; + private Short sortOrder; + private String servlet; + private String queryString; + private String externalUrl; + private String target; + private boolean active; + private String menuSetCode; + private boolean separator; + private String imageSrc; + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/MenuData.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/MenuData.java new file mode 100644 index 00000000..c1cefb0b --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/MenuData.java @@ -0,0 +1,72 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.domain; + +import java.util.*; + +public class MenuData extends Menu { + + /** + * + */ + private static final long serialVersionUID = 1L; + private MenuData parentMenu; + private Set childMenus = new TreeSet(); + + public MenuData() {} + + public Set getChildMenus() { + return childMenus; + } + + public MenuData getParentMenu() { + return parentMenu; + } + + public void setChildMenus(Set childMenus) { + this.childMenus = childMenus; + } + + public void setParentMenu(MenuData parentMenu) { + this.parentMenu = parentMenu; + } + + public int compareTo(Object obj){ + + Short c1 = getSortOrder(); + Short c2 = ((MenuData)obj).getSortOrder(); + + return (c1 == null || c2 == null) ? 1 : ((c1.compareTo(c2) == 0) ? 1 : c1.compareTo(c2)); + } + + public String getActiveAsString(){ + return String.valueOf(isActive()); + } + + public String getParentIdAsString(){ + return String.valueOf(getParentId()); + } + + public String getSeparatorAsString(){ + return String.valueOf(isSeparator()); + } + + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/Profile.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/Profile.java new file mode 100644 index 00000000..b5592021 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/Profile.java @@ -0,0 +1,96 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.domain; +import org.openecomp.portalsdk.core.domain.support.DomainVo; + +public class Profile extends DomainVo{ + + private static final long serialVersionUID = 3409056457412656883L; + + private Long id; + private String first_name; + private String last_name; + private String email; + private String orgManagerUserId; + private String active_yn; + private String orgUserId; + public Profile() {} + + + public Long getId() { + return id; + } + + + public void setId(Long id) { + this.id = id; + } + + + public String getFirst_name() { + return first_name; + } + + public void setFirst_name(String first_name) { + this.first_name = first_name; + } + + public String getLast_name() { + return last_name; + } + + public void setLast_name(String last_name) { + this.last_name = last_name; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getOrgManagerUserId() { + return orgManagerUserId; + } + + public void setOrgManagerUserId(String orgManagerUserId) { + this.orgManagerUserId = orgManagerUserId; + } + + public String getActive_yn() { + return active_yn; + } + + public void setActive_yn(String active_yn) { + this.active_yn = active_yn; + } + + public String getOrgUserId() { + return orgUserId; + } + + public void setOrgUserId(String orgUserId) { + this.orgUserId = orgUserId; + } + + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/Role.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/Role.java new file mode 100644 index 00000000..a56fe672 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/Role.java @@ -0,0 +1,174 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.domain; + + +import java.util.Iterator; +import java.util.Set; +import java.util.TreeSet; + +import org.openecomp.portalsdk.core.domain.support.DomainVo; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +/** + * <p>Role.java</p> + * <p>Represents a role data object.</p> + * + * @version 1.0 + */ +public class Role extends DomainVo { + + /** + * + */ + private static final long serialVersionUID = 1L; + private String name; + private boolean active; + private Integer priority; + + private Set roleFunctions = new TreeSet(); + + private Set childRoles = new TreeSet(); + @JsonIgnore + private Set parentRoles = new TreeSet(); + + public Role() {} + + public String getName() { + return name; + } + + public boolean getActive() { + return active; + } + + public Set getRoleFunctions() { + return roleFunctions; + } + + public Integer getPriority() { + return priority; + } + + public Set getChildRoles() { + return childRoles; + } + + public Set getParentRoles() { + return parentRoles; + } + + public void setName(String name) { + this.name = name; + } + + public void setActive(boolean active) { + this.active = active; + } + + public void setRoleFunctions(Set roleFunctions) { + this.roleFunctions = roleFunctions; + } + + public void setPriority(Integer priority) { + this.priority = priority; + } + + + public void setChildRoles(Set childRoles) { + this.childRoles = childRoles; + } + + public void setParentRoles(Set parentRoles) { + this.parentRoles = parentRoles; + } + + @SuppressWarnings("unchecked") + public void addRoleFunction(RoleFunction roleFunction) { + this.roleFunctions.add(roleFunction); + } + + @SuppressWarnings("unchecked") + public void addChildRole(Role role) { + this.childRoles.add(role); + } + + @SuppressWarnings("unchecked") + public void addParentRole(Role role) { + this.parentRoles.add(role); + } + + public String getEditUrl() { + return "/role.htm?role_id=" + getId(); + } + + public String getToggleActiveImage() { + return "/static/fusion/images/" + (getActive() ? "active.png" : "inactive.png" ); + } + + public String getToggleActiveAltText() { + return getActive() ? "Click to Deactivate Role" : "Click to Activate Role"; + } + + public void removeChildRole(Long roleId) { + Iterator i = this.childRoles.iterator(); + + while (i.hasNext()) { + Role childRole = (Role)i.next(); + if (childRole.getId().equals(roleId)) { + this.childRoles.remove(childRole); + break; + } + } + } + + public void removeParentRole(Long roleId) { + Iterator i = this.parentRoles.iterator(); + + while (i.hasNext()) { + Role parentRole = (Role)i.next(); + if (parentRole.getId().equals(roleId)) { + this.parentRoles.remove(parentRole); + break; + } + } + } + + public void removeRoleFunction(String roleFunctionCd) { + Iterator i = this.roleFunctions.iterator(); + + while (i.hasNext()) { + RoleFunction roleFunction = (RoleFunction)i.next(); + if (roleFunction.getCode().equals(roleFunctionCd)) { + this.roleFunctions.remove(roleFunction); + break; + } + } + } + + public int compareTo(Object obj){ + String c1 = getName(); + String c2 = ((Role)obj).getName(); + + return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2); + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/RoleFunction.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/RoleFunction.java new file mode 100644 index 00000000..e6735763 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/RoleFunction.java @@ -0,0 +1,71 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.domain; + + +import org.openecomp.portalsdk.core.domain.support.DomainVo; + +/** + * <p>RoleFunction.java</p> + * + * <p>Represents a role function data object.</p> + * + * @version 1.0 + */ +public class RoleFunction extends DomainVo { + + /** + * + */ + private static final long serialVersionUID = 1L; + public RoleFunction() {} + + public String getName() { + return name; + } + + public String getCode() { + return code; + } + + public void setName(String name) { + this.name = name; + } + + public void setCode(String code) { + this.code = code; + } + + public String getEditUrl() { + return "/role_function.htm?role_function_id=" + getCode(); + } + + public int compareTo(Object obj){ + String c1 = getName(); + String c2 = ((RoleFunction)obj).getName(); + + return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2); + } + + private String code; + private String name; + private String editUrl; + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/UrlsAccessible.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/UrlsAccessible.java new file mode 100644 index 00000000..e0f35db0 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/UrlsAccessible.java @@ -0,0 +1,83 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.domain; + +import java.io.Serializable; + +public class UrlsAccessible extends FusionVo implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 1L; + private UrlsAccessibleKey urlsAccessibleKey = new UrlsAccessibleKey(); + + public UrlsAccessible() {} + + public UrlsAccessible(String url, String functionCd) { + this(); + setUrl(url); + setFunctionCd(functionCd); + } + + public String getUrl() { + return getUrlsAccessibleKey().getUrl(); + } + + public String getFunctionCd() { + return getUrlsAccessibleKey().getFunctionCd(); + } + + public void setUrl(String url) { + getUrlsAccessibleKey().setUrl(url); + } + + public void setFunctionCd(String functionCd) { + getUrlsAccessibleKey().setFunctionCd(functionCd); + } + + public UrlsAccessibleKey getUrlsAccessibleKey() { + return urlsAccessibleKey; + } + + public void setUrlsAccessibleKey(UrlsAccessibleKey urlsAccessibleKey) { + this.urlsAccessibleKey = urlsAccessibleKey; + } + + // required by ZK for to set the selectedItems of Listboxes (used heavily for <select>-style drop-downs) + public int hashCode() { + int hash = getUrl().hashCode(); + hash = hash + getFunctionCd().hashCode(); + + return hash; + } + + public boolean equals( Object obj ) { + boolean equivalent = false; + + UrlsAccessible lookup = (UrlsAccessible)obj; + if( lookup.getUrl().equals(getUrl()) && lookup.getFunctionCd().equals(getFunctionCd())) { + equivalent = true; + } + + return equivalent; + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/UrlsAccessibleKey.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/UrlsAccessibleKey.java new file mode 100644 index 00000000..fc0b36ce --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/UrlsAccessibleKey.java @@ -0,0 +1,90 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.domain; + +import java.io.*; + + +public class UrlsAccessibleKey implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 1L; + private String url; + private String functionCd; + + public UrlsAccessibleKey() { + } + + public UrlsAccessibleKey(String url, String functionCd) { + setUrl(url); + setFunctionCd(functionCd); + } + + + public String getUrl() { + return url; + } + + + public String getFunctionCd() { + return functionCd; + } + + + public void setUrl(String url) { + this.url = url; + } + + + public void setFunctionCd(String functionCd) { + this.functionCd = functionCd; + } + + + public boolean equals(Object o) { + if (this == o) { + return true; + } + + if (o == null) { + return false; + } + + if (!(o instanceof UrlsAccessibleKey)) { + return false; + } + + final UrlsAccessibleKey key = (UrlsAccessibleKey)o; + + if (getFunctionCd().equals(key.getFunctionCd()) & getUrl().equals(key.getUrl())) { + return true; + } + + return false; + } + + + public int hashCode() { + return getUrl().hashCode() + getFunctionCd().hashCode(); + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/User.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/User.java new file mode 100644 index 00000000..06c4d59e --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/User.java @@ -0,0 +1,584 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.domain; + + +import java.util.Date; +import java.util.Iterator; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; + +import org.openecomp.portalsdk.core.domain.support.DomainVo; + +/** + * <p>User.java</p> + * + * <p>Represents a user data object.</p> + * + * @version 1.0 + */ +public class User extends DomainVo { + + /** + * + */ + private static final long serialVersionUID = 1L; + private Long orgId; + private Long managerId; + private String firstName; + private String middleInitial; + private String lastName; + private String phone; + private String fax; + private String cellular; + private String email; + private Long addressId; + private String alertMethodCd; + private String hrid; + private String orgUserId; + private String orgCode; + private String address1; + private String address2; + private String city; + private String state; + private String zipCode; + private String country; + private String orgManagerUserId; + private String locationClli; + private String businessCountryCode; + private String businessCountryName; + private String businessUnit; + private String businessUnitName; + private String department; + private String departmentName; + private String companyCode; + private String company; + private String zipCodeSuffix; + private String jobTitle; + private String commandChain; + private String siloStatus; + private String costCenter; + private String financialLocCode; + + + + private String loginId; + private String loginPwd; + private Date lastLoginDate; + private boolean active; + private boolean internal; + private Long selectedProfileId; + private Long timeZoneId; + private boolean online; + private String chatId; + + private Set userApps = new TreeSet(); + + private Set pseudoRoles = new TreeSet(); + + + public User() {} + + public Long getAddressId() { + return addressId; + } + + public String getAlertMethodCd() { + return alertMethodCd; + } + + public String getCellular() { + return cellular; + } + + public String getEmail() { + return email; + } + + public String getFax() { + return fax; + } + + public String getFirstName() { + return firstName; + } + + public String getHrid() { + return hrid; + } + + public Date getLastLoginDate() { + return lastLoginDate; + } + + public String getLastName() { + return lastName; + } + + public String getFullName() { + return getFirstName() + " " + getLastName(); + } + + public String getLoginId() { + return loginId; + } + + public String getLoginPwd() { + return loginPwd; + } + + public Long getManagerId() { + return managerId; + } + + public String getMiddleInitial() { + return middleInitial; + } + + public String getOrgCode() { + return orgCode; + } + + public Long getOrgId() { + return orgId; + } + + public String getPhone() { + return phone; + } + + public String getOrgUserId() { + return orgUserId; + } + + public boolean getActive() { + return active; + } + + public boolean getInternal() { + return internal; + } + + public String getAddress1() { + return address1; + } + + public String getAddress2() { + return address2; + } + + public String getCity() { + return city; + } + + public String getCountry() { + return country; + } + + public String getState() { + return state; + } + + public String getZipCode() { + return zipCode; + } + + public String getBusinessCountryCode() { + return businessCountryCode; + } + + public String getCommandChain() { + return commandChain; + } + + public String getCompany() { + return company; + } + + public String getCompanyCode() { + return companyCode; + } + + public String getDepartment() { + return department; + } + + public String getJobTitle() { + return jobTitle; + } + + public String getLocationClli() { + return locationClli; + } + + public String getOrgManagerUserId() { + return orgManagerUserId; + } + + public String getZipCodeSuffix() { + return zipCodeSuffix; + } + + public String getBusinessCountryName() { + return businessCountryName; + } + + public Set getPseudoRoles() { + return pseudoRoles; + } + + public Long getSelectedProfileId() { + return selectedProfileId; + } + + public void setAddressId(Long addressId) { + this.addressId = addressId; + } + + public void setAlertMethodCd(String alertMethodCd) { + this.alertMethodCd = alertMethodCd; + } + + public void setCellular(String cellular) { + this.cellular = cellular; + } + + public void setEmail(String email) { + this.email = email; + } + + public void setFax(String fax) { + this.fax = fax; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public void setHrid(String hrid) { + this.hrid = hrid; + } + + public void setLastLoginDate(Date lastLoginDate) { + this.lastLoginDate = lastLoginDate; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public void setLoginId(String loginId) { + this.loginId = loginId; + } + + public void setLoginPwd(String loginPwd) { + this.loginPwd = loginPwd; + } + + public void setManagerId(Long managerId) { + this.managerId = managerId; + } + + public void setMiddleInitial(String middleInitial) { + this.middleInitial = middleInitial; + } + + public void setOrgCode(String orgCode) { + this.orgCode = orgCode; + } + + public void setOrgId(Long orgId) { + this.orgId = orgId; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + public void setOrgUserId(String orgUserId) { + this.orgUserId = orgUserId; + } + + public void setActive(boolean active) { + this.active = active; + } + + public void setInternal(boolean internal) { + this.internal = internal; + } + + public void setAddress1(String address1) { + this.address1 = address1; + } + + public void setAddress2(String address2) { + this.address2 = address2; + } + + public void setCity(String city) { + this.city = city; + } + + public void setCountry(String country) { + this.country = country; + } + + public void setState(String state) { + this.state = state; + } + + public void setZipCode(String zipCode) { + this.zipCode = zipCode; + } + + public void setBusinessCountryCode(String businessCountryCode) { + this.businessCountryCode = businessCountryCode; + } + + public void setCommandChain(String commandChain) { + this.commandChain = commandChain; + } + + public void setCompany(String company) { + this.company = company; + } + + public void setCompanyCode(String companyCode) { + this.companyCode = companyCode; + } + + public void setDepartment(String department) { + this.department = department; + } + + public void setJobTitle(String jobTitle) { + this.jobTitle = jobTitle; + } + + public void setLocationClli(String locationClli) { + this.locationClli = locationClli; + } + + public void setOrgManagerUserId(String orgManagerUserId) { + this.orgManagerUserId = orgManagerUserId; + } + + public void setZipCodeSuffix(String zipCodeSuffix) { + this.zipCodeSuffix = zipCodeSuffix; + } + + public void setBusinessCountryName(String businessCountryName) { + this.businessCountryName = businessCountryName; + } + + public void setPseudoRoles(Set pseudoRoles) { + this.pseudoRoles = pseudoRoles; + } + + public void setSelectedProfileId(Long selectedProfileId) { + this.selectedProfileId = selectedProfileId; + } + + public Long getTimeZoneId() { + return timeZoneId; + } + + public void setTimeZoneId(Long timeZoneId) { + this.timeZoneId = timeZoneId; + } + + public String getBusinessUnit() { + return businessUnit; + } + + public void setBusinessUnit(String businessUnit) { + this.businessUnit = businessUnit; + } + + public String getSiloStatus() { + return siloStatus; + } + + public void setSiloStatus(String siloStatus) { + this.siloStatus = siloStatus; + } + + public String getCostCenter() { + return costCenter; + } + + public void setCostCenter(String costCenter) { + this.costCenter = costCenter; + } + + public String getFinancialLocCode() { + return financialLocCode; + } + + public void setFinancialLocCode(String financialLocCode) { + this.financialLocCode = financialLocCode; + } + + public String getBusinessUnitName() { + return businessUnitName; + } + + public void setBusinessUnitName(String businessUnitName) { + this.businessUnitName = businessUnitName; + } + + public String getDepartmentName() { + return departmentName; + } + + public void setDepartmentName(String departmentName) { + this.departmentName = departmentName; + } + + public int compareTo(Object obj){ + User user = (User)obj; + + String c1 = getLastName() + getFirstName() + getMiddleInitial(); + String c2 = user.getLastName() + user.getFirstName() + user.getMiddleInitial(); + + return c1.compareTo(c2); + } + + public boolean isOnline() { + return online; + } + + public void setOnline(boolean online) { + this.online = online; + } + + public String getChatId() { + return chatId; + } + + public void setChatId(String chatId) { + this.chatId = chatId; + } + + public Set getUserApps() { + return userApps; + } + + public void setUserApps(Set userApps) { + this.userApps = userApps; + } + + @SuppressWarnings("unchecked") + public void addAppRoles(App app, SortedSet<Role> roles) { + if(roles!=null){ + //add all + Set userApps = new TreeSet(); + Iterator itr = roles.iterator(); + while(itr.hasNext()){ + Role role = (Role) itr.next(); + UserApp userApp = new UserApp(); + userApp.setUserId(this.id); + userApp.setApp(app); + userApp.setRole(role); + userApps.add(userApp); + } + setUserApps(userApps); + } else { + //remove all + this.userApps.clear(); + } + + + } + + @SuppressWarnings("unchecked") + public SortedSet<Role> getAppRoles(App app) { + SortedSet<Role> roles = new TreeSet(); + Set apps = getUserApps(); + Iterator appsItr = apps.iterator(); + UserApp userApp = null; + //getting default app + while(appsItr.hasNext()){ + UserApp tempUserApp = (UserApp)appsItr.next(); + if(tempUserApp.getApp().getId().equals(app.getId())){ + userApp = tempUserApp; + roles.add(userApp.getRole()); + } + } + return roles; + } + + public SortedSet<Role> getRoles() { + App app = new App(); + app.setId(new Long(1)); + app.setName("Default"); + return getAppRoles(app); + } + + public UserApp getDefaultUserApp(){ + Set apps = getUserApps(); + Iterator appsItr = apps.iterator(); + UserApp userApp = null; + //getting default app + while(appsItr.hasNext()){ + UserApp tempApp = (UserApp)appsItr.next(); + if(tempApp.equals(new Long(1))){ + userApp = tempApp; + break; + } + } + return userApp; + } + + public void setRoles(SortedSet<Role> roles) { + App app = new App(); + app.setId(new Long(1)); + app.setName("Default"); + addAppRoles(app,roles); + } + + public void removeRole(Long roleId) { + Set apps = getUserApps(); + Iterator appsItr = apps.iterator(); + //getting default app + while(appsItr.hasNext()){ + UserApp tempUserApp = (UserApp)appsItr.next(); + if(tempUserApp.getRole().getId().equals(roleId)){ + appsItr.remove(); + } + } + + } + + @SuppressWarnings("unchecked") + public void addRole(Role role){ + if(role!=null){ + SortedSet<Role> roles = getRoles(); + if(roles==null){ + roles = new TreeSet(); + } + roles.add(role); + setRoles(roles); + } + + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/UserApp.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/UserApp.java new file mode 100644 index 00000000..cfadd995 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/UserApp.java @@ -0,0 +1,111 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.domain; + +import java.util.Set; +import java.util.TreeSet; + +// Generated Aug 27, 2014 5:51:36 PM by Hibernate Tools 3.4.0.CR1 + +/** + * FnUserRole generated by hbm2java + */ +@SuppressWarnings("rawtypes") +public class UserApp implements java.io.Serializable, Comparable { + + /** + * + */ + private static final long serialVersionUID = 1L; + private Long userId; + private App app; + private Role role; + private Short priority; + + public UserApp() { + } + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public App getApp() { + return app; + } + + public void setApp(App app) { + this.app = app; + } + + public Role getRole() { + return role; + } + + public void setRole(Role role) { + this.role = role; + } + + public Short getPriority() { + return this.priority; + } + + public void setPriority(Short priority) { + this.priority = priority; + } + + public boolean equals(Object other) { + if ((this == other)) + return true; + if ((other == null)) + return false; + if (!(other instanceof UserApp)) + return false; + UserApp castOther = (UserApp) other; + + return (this.getUserId().equals(castOther.getUserId())) + && (this.getApp().getId().equals(castOther.getApp().getId())) + && (this.getRole().getId().equals(castOther.getRole().getId())) + && ((this.priority==null && castOther.getPriority()==null) || this.getPriority().equals(castOther.getPriority())); + } + + public int hashCode() { + int result = 17; + + result = 37 * result + (int) (this.getUserId()==null ? 0 : this.getUserId().intValue()); + result = 37 * result + (int) (this.getApp().getId()==null ? 0 : this.getApp().getId().intValue()); + result = 37 * result + (int) (this.getRole().getId()==null ? 0 : this.getRole().getId().intValue()); + result = 37 * result + (int) (this.priority==null ? 0 : this.priority); + return result; + } + + public int compareTo(Object other){ + UserApp castOther = (UserApp) other; + + Long c1 = (this.getUserId()==null ? 0 : this.getUserId()) + (this.getApp()==null||this.getApp().getId()==null ? 0 : this.getApp().getId()) + (this.getRole()==null||this.getRole().getId()==null ? 0 : this.getRole().getId()) + (this.priority==null ? 0 : this.priority); + Long c2 = (castOther.getUserId()==null ? 0 : castOther.getUserId()) + (castOther.getApp()==null||castOther.getApp().getId()==null ? 0 : castOther.getApp().getId()) + (castOther.getRole()==null||castOther.getRole().getId()==null ? 0 : castOther.getRole().getId()) + (castOther.priority==null ? 0 : castOther.priority); + + return c1.compareTo(c2); + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/UserAppId.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/UserAppId.java new file mode 100644 index 00000000..9458b90a --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/UserAppId.java @@ -0,0 +1,88 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.domain; + +// Generated Aug 27, 2014 5:51:36 PM by Hibernate Tools 3.4.0.CR1 + +/** + * FnUserRoleId generated by hbm2java + */ +public class UserAppId implements java.io.Serializable { + + /** + * + */ + private static final long serialVersionUID = 1L; + private Long userId; + private App app; + private Role role; + + public UserAppId() { + super(); + } + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public App getApp() { + return app; + } + + public void setApp(App app) { + this.app = app; + } + + public Role getRole() { + return role; + } + + public void setRole(Role role) { + this.role = role; + } + + public boolean equals(Object other) { + if ((this == other)) + return true; + if ((other == null)) + return false; + if (!(other instanceof UserAppId)) + return false; + UserAppId castOther = (UserAppId) other; + + return (this.getUserId() == castOther.getUserId()) + && (this.getApp().getId() == castOther.getApp().getId()) + && (this.getRole().getId() == castOther.getRole().getId()); + } + + public int hashCode() { + int result = 17; + + result = 37 * result + (int) (this.getUserId()==null ? 0 : this.getUserId().intValue()); + result = 37 * result + (int) (this.getApp().getId()==null ? 0 : this.getApp().getId().intValue()); + result = 37 * result + (int) (this.getRole().getId()==null ? 0 : this.getRole().getId().intValue()); + return result; + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/sessionmgt/TimeoutVO.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/sessionmgt/TimeoutVO.java new file mode 100644 index 00000000..0f6c3876 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/sessionmgt/TimeoutVO.java @@ -0,0 +1,63 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.domain.sessionmgt; + +public class TimeoutVO implements Comparable<TimeoutVO>{ + + private String jSessionId; + private Long sessionTimOutMilliSec; + + public TimeoutVO(){ + + } + + public TimeoutVO(String _jSessionId, Long _sessionTimOutMilliSec) { + setjSessionId(_jSessionId); + setSessionTimOutMilliSec(_sessionTimOutMilliSec); + + } + + public String getjSessionId() { + return jSessionId; + } + + public void setjSessionId(String jSessionId) { + this.jSessionId = jSessionId; + } + + public Long getSessionTimOutMilliSec() { + return sessionTimOutMilliSec; + } + + public void setSessionTimOutMilliSec(Long sessionTimOutMilliSec) { + this.sessionTimOutMilliSec = sessionTimOutMilliSec; + } + + @Override + public int compareTo(TimeoutVO o) { + return sessionTimOutMilliSec.compareTo(o.sessionTimOutMilliSec); + } + + + + + + +}
\ No newline at end of file diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/Attribute.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/Attribute.java new file mode 100644 index 00000000..a78d7bfa --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/Attribute.java @@ -0,0 +1,62 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.domain.support; + +public class Attribute { + public double width; + public double top; + public double left; + public String name; + public double height; + + public double getWidth() { + return width; + } + public void setWidth(double width) { + this.width = width; + } + public double getTop() { + return top; + } + public void setTop(double top) { + this.top = top; + } + public double getLeft() { + return left; + } + public void setLeft(double left) { + this.left = left; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public double getHeight() { + return height; + } + public void setHeight(double height) { + this.height = height; + } + + + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/CollaborateList.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/CollaborateList.java new file mode 100644 index 00000000..eaeab84d --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/CollaborateList.java @@ -0,0 +1,56 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.domain.support; + +import java.io.Serializable; +import java.util.HashSet; + +public class CollaborateList implements Serializable { + + private static final long serialVersionUID = -4104440747626736243L; + private HashSet<String> userNameList = new HashSet<String>(); + private static CollaborateList userListData = new CollaborateList(); + private CollaborateList(){} + + public static CollaborateList getInstance(){ + return userListData; + } + + public HashSet<String> getAllUserName(){ + return userNameList; + } + + public static void addUserName(String name){ + final HashSet<String> allUserName = CollaborateList.getInstance().getAllUserName(); + if(allUserName.contains(name)){ + //System.out.println("cannot add this user"); + }else{ + allUserName.add(name); + } + } + + public static void delUserName(String name){ + final HashSet<String> allUserName = CollaborateList.getInstance().getAllUserName(); + allUserName.remove((String) name); + } + + + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/Container.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/Container.java new file mode 100644 index 00000000..88a9fa71 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/Container.java @@ -0,0 +1,331 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.domain.support; + +import java.util.List; +import java.util.Map; + +public class Container { + + String id; + + public String name; + + Size size; + + Position p; + + public Map<String,Container> containerRowCol; + + public Map<String,Element> elementRowCol; + + int numOfRows; + + int numOfCols; + + double sum = 0; + + double interEleWd; + + double interEleH; + + double interEleToContainerWd; + + double interEleToContainerH; + + double interEleToInnerContainerWd; + + double interEleToInnerContainerH; + + public double top; + + public double left; + + public double height; + + public double width; + + public String visibilityType; + + + + + + public Container(String id, String name, int numOfRows, int numOfCols, double interEleWd, double interEleH, + double interEleToContainerWd, double interEleToContainerH, double interEleToInnerContainerWd, + double interEleToInnerContainerH) { + + this.id = id; + this.name = name; + this.numOfRows = numOfRows; + this.numOfCols = numOfCols; + this.interEleWd = interEleWd; + this.interEleH = interEleH; + this.interEleToContainerWd = interEleToContainerWd; + this.interEleToContainerH = interEleToContainerH; + this.interEleToInnerContainerWd = interEleToInnerContainerWd; + this.interEleToInnerContainerH = interEleToInnerContainerH; + + } + + + public List<Container> innerCList; + + public List<Element> elementList; + + public Container() { + + } + + + + public Map<String, Container> getContainerRowCol() { + return containerRowCol; + } + + + + + public Map<String, Element> getElementRowCol() { + return elementRowCol; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + + public void setInnerContainer(Map<String,Container> innerCon) { + containerRowCol = innerCon; + } + + public void setElements(Map<String,Element> innerE) { + elementRowCol = innerE; + } + + + public Position getP() { + return p; + } + + public void setP(Position p) { + this.p = p; + } + + + public void setTop(double top) { + this.top = top; + } + + + public void setLeft(double left) { + this.left = left; + } + + + public void setHeight(double height) { + this.height = height; + } + + + public void setWidth(double width) { + this.width = width; + } + + + public void setInnerCList(List<Container> innerCList) { + this.innerCList = innerCList; + } + + + + public void setElementList(List<Element> elementList) { + this.elementList = elementList; + } + + public void setVisibilityType(String visibilityType) { + this.visibilityType = visibilityType; + } + + public Size computeSize() { + Size size = new Size(); + double width = 0; + double height = 0; + // System.out.println("Inside computesize"); + for (int i = 0; i<numOfRows; i++) { + if ((containerRowCol != null && containerRowCol.containsKey(i+String.valueOf(numOfCols-1))) || + (elementRowCol!=null && elementRowCol.containsKey(i+String.valueOf(numOfCols-1)))) { + for (int j = 0; j < numOfCols; j++) { + if (containerRowCol!=null && containerRowCol.containsKey(i+String.valueOf(j))) { + width+=containerRowCol.get(i+String.valueOf(j)).computeSize().getWidth(); + // System.out.println(containerRowCol.get(i+String.valueOf(j)).getName()+" "+ + // containerRowCol.get(i+String.valueOf(j)).computeSize().getWidth()); + }else if (elementRowCol!=null && elementRowCol.containsKey(i+String.valueOf(j))) + width+=elementRowCol.get(i+String.valueOf(j)).computeSize().getWidth(); + } + break; + } + } + // System.out.println("Object name "+this.getName()); + if (this.getName().equals("Broadworks complex") || this.getName().equals("Application Servers") + || this.getName().equals("Call Session Control") || this.getName().equals("GMLC Provider") || this.getName().equals("Neo") || this.getName().equals("Support")) { + width+=(numOfCols-1)*interEleWd+2*interEleToInnerContainerWd; + } else { + width+=(numOfCols-1)*interEleWd+2*interEleToContainerWd; + } + size.setWidth(width); + for (int j = 0; j<numOfCols; j++) { + // System.out.println("Inside computesize height "+numOfCols); + // System.out.println(containerRowCol.toString()); + if ((containerRowCol != null && containerRowCol.containsKey(String.valueOf(numOfRows-1)+j)) || + (elementRowCol!= null && elementRowCol.containsKey(String.valueOf(numOfRows-1)+j))) { + //System.out.println("Inside if"); + for (int i = 0; i < numOfRows; i++) { + if (containerRowCol!= null && containerRowCol.containsKey(i+String.valueOf(j))) { + height+=containerRowCol.get(i+String.valueOf(j)).computeSize().getHeight(); + //System.out.println("My C name "+this.getName()+":"+containerRowCol.get(i+String.valueOf(j)).computeSize().getHeight()); + } + else if (elementRowCol!=null && elementRowCol.containsKey(i+String.valueOf(j))) + height+=elementRowCol.get(String.valueOf(i)+String.valueOf(j)).computeSize().getHeight(); + } + break; + } + } + if (this.getName().equals("Broadworks complex") || this.getName().equals("Application Servers") + || this.getName().equals("Call Session Control") || this.getName().equals("GMLC Provider") || this.getName().equals("Neo") || this.getName().equals("Support")) { + height+=(numOfRows-1)*interEleH+2*interEleToInnerContainerH+0.1; + } else { + if (this.getName().equals("VoLTE UE") || this.getName().equals("3G UE") || this.getName().equals("HC UE-A") + || this.getName().equals("HC UE-B") || this.getName().equals("VNI UE") || this.getName().equals("PSTN")) { + height+=(numOfRows-1)*interEleH+interEleToContainerH/2; + }else + height+=(numOfRows-1)*interEleH+2*interEleToContainerH; + } + size.setHeight(height); + // System.out.println("C name "+this.getName()+" height "+height); + // System.out.println("test C height "+this.getName()+" height "+height+" (numOfRows-1)*interEleH "+(numOfRows-1)*interEleH+ + // " interEleToContainerH "+interEleToContainerH/2); + return size; + } + + + + public void computeElementPositions() { + double xsum = 0; + double ysum = 0; + for (int i=0; i<numOfRows; i++){ + for (int j=0; j<numOfCols; j++){ + if (containerRowCol != null && containerRowCol.containsKey(String.valueOf(i)+ String.valueOf(j))) { + Container c = containerRowCol.get(String.valueOf(i)+ String.valueOf(j)); + Position p = new Position(); + //System.out.println("within container"); + p.x =j*interEleWd+xsum+this.getP().getX()+ + interEleToContainerWd; + ysum = 0; + for (int k=0; k<i; k++) { + if (containerRowCol.containsKey(String.valueOf(k)+ String.valueOf(j))) + ysum+= containerRowCol.get(String.valueOf(k)+ String.valueOf(j)).computeSize().getHeight(); + else if (elementRowCol.containsKey(String.valueOf(k)+ String.valueOf(j))) + ysum+= elementRowCol.get(String.valueOf(k)+ String.valueOf(j)).computeSize().getHeight(); + } + p.y = i*interEleH+ysum+this.getP().getY() + interEleToContainerH; + // containerCoord.add(c,p); + xsum+= c.computeSize().getWidth(); + c.setP(p); + + } else if (elementRowCol!=null && elementRowCol.containsKey(String.valueOf(i)+ String.valueOf(j))) { + Element e = elementRowCol.get(String.valueOf(i)+ String.valueOf(j)); + Position p = new Position(); + // System.out.println("i "+i+"j "+j); + // System.out.println("element "+e.getName()); + // System.out.println("Is this "+this.getP()); + if (j==numOfCols-1) { + for (int t=0; t<i; t++) { + if (containerRowCol!=null && containerRowCol.containsKey(String.valueOf(t)+ String.valueOf(j-1))) { + if (!elementRowCol.containsKey(String.valueOf(i)+ String.valueOf(j-1)) && + !containerRowCol.containsKey(String.valueOf(i)+ String.valueOf(j-1))) { + xsum+=containerRowCol.get(String.valueOf(t)+ String.valueOf(j-1)).computeSize().getWidth(); + break; + } + } + } + } + if (this.getName().equals("Broadworks complex") || this.getName().equals("Application Servers") + || this.getName().equals("Call Session Control") || this.getName().equals("GMLC Provider") + || this.getName().equals("Neo") || this.getName().equals("Support")) { + p.x = j*interEleWd+xsum+this.getP().getX()+interEleToInnerContainerWd; + } + else if (this.getName().equals("VNI UE") || this.getName().equals("PSTN") || this.getName().equals("3G UE") + || this.getName().equals("HC UE-A") || this.getName().equals("HC UE-B")) { + p.x = j*interEleWd+xsum+this.getP().getX()+interEleToContainerWd-0.8; + }else { + p.x = j*interEleWd+xsum+this.getP().getX()+interEleToContainerWd; + //System.out.println("element name "+e.getName()+" j*interEleWd "+j*interEleWd + // +" xsum " +xsum+"this.getP().getX() "+this.getP().getX()+" interEleToContainerWd " +interEleToContainerWd+" p.x "+p.x); + } + ysum = 0; + for (int k=0; k<i; k++) { + if (containerRowCol!= null && containerRowCol.containsKey(String.valueOf(k)+ String.valueOf(j))) + ysum+= containerRowCol.get(String.valueOf(k)+ String.valueOf(j)).computeSize().getHeight(); + else if (elementRowCol!=null && elementRowCol.containsKey(String.valueOf(k)+ String.valueOf(j))) + ysum+= elementRowCol.get(String.valueOf(k)+ String.valueOf(j)).computeSize().getHeight(); + else if (containerRowCol!= null) { + for (int chk=j; chk>0; chk--) { + if (containerRowCol.containsKey(String.valueOf(k)+ String.valueOf(chk-1))) { + if (containerRowCol.get(String.valueOf(k)+ String.valueOf(chk-1)).computeSize().getWidth() + + containerRowCol.get(String.valueOf(k)+ String.valueOf(chk-1)).getP().getX() > p.x) { + ysum+= containerRowCol.get(String.valueOf(k)+ String.valueOf(chk-1)).computeSize().getHeight(); + break; + } + } + } + } + + } + if (this.getName().equals("Broadworks complex") || this.getName().equals("Application Servers") + || this.getName().equals("Call Session Control") || this.getName().equals("GMLC Provider") || this.getName().equals("Neo") || this.getName().equals("Support")) { + p.y = this.getP().getY()+ysum+i*interEleH+interEleToInnerContainerH+1; + } else { + // System.out.println("element name "+e.getName()+" this.getP().getY() "+this.getP().getY() + // +" ysum " +ysum+" i*interEleH "+i*interEleH+" interEleToContainerH " +interEleToContainerH); + if (e.getName().equals("")) { + p.y = this.getP().getY()+ysum+i*interEleH+(interEleToContainerH); + //System.out.println("test element name "+this.getName()+" Container height "+this.computeSize().getHeight()+" this.getP().getY() "+this.getP().getY() + // +" ysum " +ysum+" i*interEleH "+i*interEleH+" interEleToContainerH-3 " +interEleToContainerH+" p.y "+p.y); + }else + p.y = this.getP().getY()+ysum+i*interEleH+interEleToContainerH; + // System.out.println(e.getName()+"My contain this.getP().getY() "+this.getP().getY() + // +"elements Y "+p.y); + } + xsum+= e.computeSize().getWidth(); + e.setP(p); + //System.out.println("my element name "+e.getName()+" e.getP().getX() "+e.getP().getX()); + //System.out.println(); + } + } + xsum = 0; + } + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/Domain.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/Domain.java new file mode 100644 index 00000000..a21ff395 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/Domain.java @@ -0,0 +1,259 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.domain.support; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class Domain { + // Unique identifier of the domain + String id; + // List<Container> cList; + + public String name; + Size size; + Position p; + + //Attribute1 at; + + public Position getP() { + return p; + } + + public void setP(Position p) { + this.p = p; + } + + //Horizontal space between a pair of containers + double interContWd = 1.0; + //Vertical space between a pair of containers + double interContH; + double domainToLayoutWd; + double domainToContH; + double domainToLayoutH; + int numOfRowsofContainer; + int numOfColsofContainer; + boolean indexChanged; + Map<String,Container> containerRowCol; + public Domain(String id, String name, double interContWd, double interContH, double domainToLayoutWd, + double domainToLayoutH, double domainToContH, int numOfRowsofContainer, int numOfColsofContainer) { + this.id = id; + this.name = name; + this.interContWd = interContWd; + this.interContH = interContH; + this.domainToLayoutWd = domainToLayoutWd; + this.domainToLayoutH = domainToLayoutH; + this.domainToContH = domainToContH; + this.numOfRowsofContainer = numOfRowsofContainer; + this.numOfColsofContainer = numOfColsofContainer; + // at = new Attribute1(); + } + + + + + public double top; + + public double left; + + public double height; + + public double width; + + public List<Container> containerList; + + public double newXafterColl; + + public double YafterColl; + + public void setNewXafterColl(double newXafterColl) { + this.newXafterColl = newXafterColl; + } + + public double getNewXafterColl() { + return newXafterColl; + } + + public double getYafterColl() { + return YafterColl; + } + + public void setYafterColl(double yafterColl) { + YafterColl = yafterColl; + } + + public void setDomainToLayoutWd(double domainToLayoutWd) { + this.domainToLayoutWd = domainToLayoutWd; + } + + public double getDomainToLayoutWd() { + return domainToLayoutWd; + } + + public double getTop() { + return top; + } + + public void setTop(double top) { + this.top = top; + } + + public double getLeft() { + return left; + } + + public void setLeft(double left) { + this.left = left; + } + + public double getHeight() { + return height; + } + + public void setHeight(double height) { + this.height = height; + } + + public double getWidth() { + return width; + } + + public void setWidth(double width) { + this.width = width; + } + + public void setName(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setContainers(Map<String,Container> containerRowCol) { + this.containerRowCol = containerRowCol; + } + + public Map<String, Container> getContainerRowCol() { + return containerRowCol; + } + + + /* public Attribute1 getAt() { + return at; + } + + public void setAt(Attribute1 at) { + this.at = at; + }*/ + + public void setContainerList(List<Container> containerList) { + // new ArrayList<Container>(); + this.containerList = containerList; + } + + + +/* public boolean isCollapsed() { + return collapsed; + } + + public void setCollapsed(boolean collapsed) { + this.collapsed = collapsed; + }*/ + + public boolean isIndexChanged() { + return indexChanged; + } + + public void setIndexChanged(boolean indexChanged) { + this.indexChanged = indexChanged; + } + + //Compute the size of any domain + public Size computeSize() { + size = new Size(); + size.setHeight(5); + double width = 0; + for (int i = 0; i < numOfRowsofContainer; i++) { + if (containerRowCol!=null && containerRowCol.containsKey(String.valueOf(i)+String.valueOf(numOfColsofContainer-1))) { + for (int j = 0; j < numOfColsofContainer; j++) { + width+=containerRowCol.get(String.valueOf(i)+String.valueOf(j)).computeSize().getWidth(); + } + break; + } + + } + width+=(numOfColsofContainer-1)*interContWd; + if (this.getName().equals("VNI")) + size.setWidth(width-4); + else + size.setWidth(width); + return size; + } + + public void computeConatinerPositions() { + + double xsum = 0; + double ysum = 0; + for (int i=0; i< numOfRowsofContainer; i++){ + for (int j=0; j<numOfColsofContainer; j++){ + if (containerRowCol!=null && containerRowCol.containsKey(String.valueOf(i)+ String.valueOf(j))) { + Container c = containerRowCol.get(String.valueOf(i)+ String.valueOf(j)); + // System.out.println("container "+c.toString()); + Position p = new Position(); + if (this.getName().equals("VNI")) { + p.x = j*(interContWd-2)+xsum+domainToLayoutWd; + } else + p.x = j*interContWd+xsum+domainToLayoutWd; + // this.computeSize(); + // p.x = j*interContWd+xsum+this.getP().getX(); + ysum = 0; + for (int k=0; k<i; k++) { + // System.out.println("i value "+i); + if (containerRowCol.containsKey(String.valueOf(k)+ String.valueOf(j))) + ysum+= containerRowCol.get(String.valueOf(k)+ String.valueOf(j)).computeSize().getHeight(); + // System.out.println("Container height "+containerRowCol.get(String.valueOf(k)+ String.valueOf(j)).getName()+ + // ":"+" "+containerRowCol.get(String.valueOf(k)+ String.valueOf(j)).computeSize().getHeight()); + else if (j>0 && containerRowCol.containsKey(String.valueOf(k)+ String.valueOf(j-1)) && + !containerRowCol.get(String.valueOf(i)+ String.valueOf(j)).getName().equals("AIC - Alpharetta")) { + ysum+= containerRowCol.get(String.valueOf(k)+ String.valueOf(j-1)).computeSize().getHeight(); + } + } + //System.out.println("C name "+c.getName()+" ysum "+ysum+" domainToLayoutH "+domainToLayoutH+" this.computeSize().getHeight() "+ + // this.computeSize().getHeight()+" domainToContH "+domainToContH+" interContH "+interContH); + p.y = domainToLayoutH+ysum+this.computeSize().getHeight()+ + domainToContH+i*interContH; + + c.setP(p); + xsum+= c.computeSize().getWidth(); + + } + } + xsum = 0; + + } + + } + +} + + diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/DomainVo.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/DomainVo.java new file mode 100644 index 00000000..369cc4cd --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/DomainVo.java @@ -0,0 +1,166 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.domain.support; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.util.Date; +import java.util.Set; + +import org.openecomp.portalsdk.core.domain.FusionVo; + + +/* Super class from which all data objects descend */ +public class DomainVo extends FusionVo implements Serializable, Cloneable, Comparable { + + protected Long id; + protected Date created; + protected Date modified; + protected Long createdId; + protected Long modifiedId; + protected Long rowNum; + + protected Serializable auditUserId; + + Set auditTrail = null; + + public DomainVo() {} + + + public void setId(Long i) { + id = i; + } + + public void setCreated(Date created) { + this.created = created; + } + + public void setModified(Date modified) { + this.modified = modified; + } + + public void setCreatedId(Long createdId) { + this.createdId = createdId; + } + + public void setModifiedId(Long modifiedId) { + this.modifiedId = modifiedId; + } + + public void setAuditUserId(Serializable auditUserId) { + this.auditUserId = auditUserId; + } + + public void setRowNum(Long rowNum) { + this.rowNum = rowNum; + } + + public void setAuditTrail(Set auditTrail) { + this.auditTrail = auditTrail; + } + + public Long getId() { + return id; + } + + public Date getCreated() { + return created; + } + + public Date getModified() { + return modified; + } + + public Long getCreatedId() { + return createdId; + } + + public Long getModifiedId() { + return modifiedId; + } + + public Serializable getAuditUserId() { + return auditUserId; + } + + public Long getRowNum() { + return rowNum; + } + + public Set getAuditTrail() { + return auditTrail; + } + + + public Object clone() throws CloneNotSupportedException { + return super.clone(); + } + + + public Object copy() { + return copy(false); + } + + + public Object copy(boolean isIdNull) { + // let's create a "copy" of the object using serialization + ByteArrayOutputStream baos = null; + ByteArrayInputStream bais = null; + ObjectOutputStream oos = null; + ObjectInputStream ois = null; + + DomainVo newVo = null; + + try { + + baos = new ByteArrayOutputStream(); + oos = new ObjectOutputStream(baos); + oos.writeObject(this); + + bais = new ByteArrayInputStream(baos.toByteArray()); + ois = new ObjectInputStream(bais); + newVo = (DomainVo)ois.readObject(); + + if (isIdNull) { + newVo.setId(null); + } + + } + catch (Exception e) { + e.printStackTrace(); + } + + return newVo; + } + + + + public int compareTo(Object obj){ + Long c1 = getId(); + Long c2 = ((DomainVo)obj).getId(); + + return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2); + } + + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/Element.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/Element.java new file mode 100644 index 00000000..567487de --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/Element.java @@ -0,0 +1,165 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.domain.support; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Element { + + public String id; + public String name; + + public double top; + + public double left; + + public double height; + + public String imgFileName; + + public String borderType; + + public String bgColor; + + public ElementDetails details; + + //public List<ElementDetails> details; + + + public void setBgColor(String bgColor) { + this.bgColor = bgColor; + } + + public void setId(String id) { + this.id = id; + } + + public void setTop(double top) { + this.top = top; + } + + public void setLeft(double left) { + this.left = left; + } + + public void setHeight(double height) { + this.height = height; + } + + public void setWidth(double width) { + this.width = width; + } + + + public double width; + + + public String getId() { + return id; + } + + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + + Position p; + + public Position getP() { + return p; + } + + public void setP(Position p) { + this.p = p; + } + + + + public Element(String id, String name, String imgPath, String bgColor, String logical_group, String display_longname, + String description, String primary_function, String key_interfaces, String location, String vendor, String vendor_shortname) { + this.id = id; + this.name = name; + this.imgFileName = imgPath; + this.bgColor = bgColor; + + + } + + public Element(String id, String name) { + this.id = id; + this.name = name; + } + + public Element(String id, String name, String imgFilename, String bgColor, String borderType, ElementDetails details) { + this.id = id; + this.name = name; + this.imgFileName = imgFilename; + this.bgColor = bgColor; + this.borderType = borderType; + this.details = details; + + } + + + public void setBorderType(String borderType) { + this.borderType = borderType; + } + + public String getImgFileName() { + return imgFileName; + } + + public void setImgFileName(String imgFileName) { + this.imgFileName = imgFileName; + } + + public String getBorderType() { + return borderType; + } + + + + public ElementDetails getDetails() { + return details; + } + + + + public void setDetails(ElementDetails details) { + this.details = details; + } + + public Size computeSize() { + Size size= new Size(); + size.setWidth(0.5*7.0); + size.setHeight(0.5*3.0); + // size.setWidth(0.5*10.0); + // size.setHeight(0.5*6.0); + return size; + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/ElementDetails.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/ElementDetails.java new file mode 100644 index 00000000..0e22d639 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/ElementDetails.java @@ -0,0 +1,71 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.domain.support; + +import java.util.HashMap; +import java.util.Map; + +public class ElementDetails { + public String logical_group; + public String display_longname; + public String description; + public String primary_function; + public String network_function; + public String key_interfaces; + public String location; + public String vendor; + public String vendor_shortname; + public String enclosingContainer; + + +// public Map<String,String> details1; + +// public ElementDetails(Map<String, String> details) { + + // this.details = new HashMap<String, String>(); + // this.details1 = details; +// } + + + + + + public ElementDetails(String logical_group, String display_longname, String description, String primary_function, String network_function, + String key_interfaces, String location, String vendor, String vendor_shortname, String enclosingContainer) { + + this.logical_group = logical_group; + this.display_longname = display_longname; + this.description = description; + this.primary_function = primary_function; + this.network_function = network_function; + this.key_interfaces = key_interfaces; + this.location = location; + this.vendor = vendor; + this.vendor_shortname = vendor_shortname; + this.enclosingContainer = enclosingContainer; + } + + public void setLogical_group(String logical_group) { + this.logical_group = logical_group; + } + + + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/FusionCommand.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/FusionCommand.java new file mode 100644 index 00000000..6ac85b6f --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/FusionCommand.java @@ -0,0 +1,39 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.domain.support; + +import org.openecomp.portalsdk.core.FusionObject; + +public class FusionCommand implements FusionObject { + + private String task; + + public FusionCommand() { + } + + public String getTask() { + return task; + } + + public void setTask(String task) { + this.task = task; + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/Layout.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/Layout.java new file mode 100644 index 00000000..0d78e5dd --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/Layout.java @@ -0,0 +1,1209 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.domain.support; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; + +public class Layout { + //width of the screen +// double width; + //height of the screen; +// double height; + // Total number of domains present on the screen and assume that + + public Map<String,Domain> domainRowCol; + + Map<String,Domain> originalDomainRowCol; + + //Horizontal space between a pair of domains + double interDomainWd; + //Vertical space between a pair of domains + double interDomainH; + //Computing the co-ordinates of any domain + int numberofRowsofDomains; + + int numberofColsofDomains; + + Map<String, Domain> collapsedDomains; + + List<Domain> collapsedDomainsNewList; + + public List<Domain> getCollapsedDomainsNewList() { + return collapsedDomainsNewList; + } + + public void setCollapsedDomainsNewList(List<Domain> collapsedDomainsNewList) { + this.collapsedDomainsNewList = collapsedDomainsNewList; + } + + public void setCollapsedDomains(Map<String, Domain> collapsedDomains) { + this.collapsedDomains = collapsedDomains; + } + + public Map<String, Domain> getCollapsedDomains() { + return collapsedDomains; + } + + public int getNumberofColsofDomains() { + return numberofColsofDomains; + } + + public void setNumberofColsofDomains(int numberofColsofDomains) { + this.numberofColsofDomains = numberofColsofDomains; + } + + public Layout(Map<String,Domain> domainRowCol, double interDomainWd, double interDomainH, + int numberofRowsofDomains, int numberofColsofDomains) { + + this.domainRowCol = domainRowCol; + this.interDomainWd = interDomainWd; + this.interDomainH = interDomainH; + this.numberofRowsofDomains = numberofRowsofDomains; + this.numberofColsofDomains = numberofColsofDomains; + this.collapsedDomains = new HashMap<String, Domain>(); + this.originalDomainRowCol = new TreeMap<String,Domain>(); + //nline + this.collapsedDomainsNewList = new ArrayList<Domain>(); + } + + public Map<String, Domain> getDomainRowCol() { + return domainRowCol; + } + + public void setDomainRowCol(Map<String, Domain> domainRowCol) { + this.domainRowCol = domainRowCol; + } + + + public void computeDomainPositions() { + double xsum = 0; + double domainTolayout = 10.6; + for (int i=0; i< numberofRowsofDomains; i++){ + for (int j=0; j<numberofColsofDomains; j++){ + if (domainRowCol.containsKey(String.valueOf(i)+ String.valueOf(j))) { + Domain d = domainRowCol.get(String.valueOf(i)+ String.valueOf(j)); + Position p = new Position(); + if (j==0) + //p.x = (j+1)* (interDomainWd+2.6) + xsum; + p.x = domainTolayout; + else + // p.x = (j+1)* interDomainWd + xsum; + p.x = j*interDomainWd + xsum + domainTolayout; + if (getCollapsedDomainsNewList().size() > 0) + p.x+= accountForPlusSpaceBefore(d); + xsum+=d.computeSize().getWidth(); + double ysum=0; + for (int k=0; k<i; k++) { + if (domainRowCol.containsKey(String.valueOf(k)+ String.valueOf(j))) + ysum+= domainRowCol.get(String.valueOf(k)+ String.valueOf(j)).computeSize().getHeight(); + } + // p.y = domainToLayoutH+ysum+this.computeSize().getHeight()+ + // domainToContH+i*interContH; + p.y = (i+1)* interDomainH + ysum; + d.setP(p); + + } + } + xsum = 0; + } + } + + public void computeDomainPositionsModified() { + //double xsum = 0; + // double domainTolayout = 10.6; + for (int i=0; i< numberofRowsofDomains; i++){ + for (int j=0; j<numberofColsofDomains; j++){ + if (domainRowCol.containsKey(String.valueOf(i)+ String.valueOf(j))) { + Domain d = domainRowCol.get(String.valueOf(i)+ String.valueOf(j)); + Position p = new Position(); + Map<String,Container> enclosedContainers = d.getContainerRowCol(); + for (Map.Entry<String, Container> entry : enclosedContainers.entrySet()) { + if (entry.getKey().equals("00")) { + double containerX = entry.getValue().getP().getX(); + p.x = containerX; + double ysum=0; + for (int k=0; k<i; k++) { + if (domainRowCol.containsKey(String.valueOf(k)+ String.valueOf(j))) + ysum+= domainRowCol.get(String.valueOf(k)+ String.valueOf(j)).computeSize().getHeight(); + } + p.y = (i+1)* interDomainH + ysum; + d.setP(p); + break; + } + } + } + } + } + + + } + public Layout collapseDomainModified(String domainsToCollapse) { + + if(domainsToCollapse == null || domainsToCollapse.isEmpty()) + return null; + + Map<String,Domain> updatedRC = new HashMap<String, Domain>(); + + for (Map.Entry<String, Domain> copyEntry : domainRowCol.entrySet()) { + updatedRC.put(copyEntry.getKey(), copyEntry.getValue()); + // System.out.println("copyEntry.getKey() "+copyEntry.getKey()+ " copyEntry.getValue() "+copyEntry.getValue()); + } + + Map<String, Domain> updatedRCSorted = new TreeMap<String, Domain>(updatedRC); + + Map<String, Domain> collapsedDomainMap = getCollapsedDomains(); + + List<Domain> collapsedDomainNewL = getCollapsedDomainsNewList(); + + + if (collapsedDomainNewL.size() == 0) { + for (Map.Entry<String, Domain> copyEntry : domainRowCol.entrySet()) { + originalDomainRowCol.put(copyEntry.getKey(), copyEntry.getValue()); + // System.out.println("copyEntry.getKey() "+copyEntry.getKey()+ " copyEntry.getValue() "+copyEntry.getValue()); + } + } + + + Map<String, Domain> updatedRCSortedTrunc = new TreeMap<String, Domain>(); + + int colToDelete = 0; + for (Map.Entry<String, Domain> entry : updatedRCSorted.entrySet()) { + if (entry.getValue().getName().equals(domainsToCollapse)) { + if (entry.getValue().isIndexChanged()) { + collapsedDomainMap.put("0"+String.valueOf(Integer.parseInt(entry.getKey())+1), entry.getValue()); + + } + //Domain toRemove = entry.getValue(); + else { + collapsedDomainMap.put(entry.getKey(),entry.getValue()); + } + + collapsedDomainNewL.add(entry.getValue()); + setNumberofColsofDomains(getNumberofColsofDomains()-1); + updatedRC.remove(entry.getKey()); + colToDelete = Character.getNumericValue(entry.getKey().toCharArray()[1]); + break; + } + } + + + for (Map.Entry<String, Domain> copyEntry : updatedRCSorted.entrySet()) { + updatedRCSortedTrunc.put(copyEntry.getKey(), copyEntry.getValue()); + //System.out.println("copyEntry.getKey() "+copyEntry.getKey()+ " copyEntry.getValue() "+copyEntry.getValue()); + } + + for (Map.Entry<String, Domain> rmv : updatedRCSorted.entrySet()) { + if (Character.getNumericValue(rmv.getKey().toCharArray()[1]) <= colToDelete) { + updatedRCSortedTrunc.remove(rmv.getKey()); + } + } + + + /* for (Map.Entry<String, Domain> entry : updatedRCSortedTrunc.entrySet()) { + System.out.println("Sorted key: "+entry.getKey()+" Sorted value: "+entry.getValue().getName()); + }*/ + + for (Map.Entry<String, Domain> updateOthers : updatedRCSortedTrunc.entrySet()) { + char update[] = updateOthers.getKey().toCharArray(); + int charToupdate = Character.getNumericValue(update[1]); + --charToupdate; + String resultRowCol = String.valueOf(update[0])+String.valueOf(charToupdate); + updateOthers.getValue().setIndexChanged(true); + updatedRC.put(resultRowCol, updateOthers.getValue()); + updatedRC.remove(updateOthers.getKey()); + + } + setDomainRowCol(updatedRC); + + /* for (Map.Entry<String, Domain> entry : updatedRC.entrySet()) { + System.out.println("Sorted key: "+entry.getKey()+" Sorted value: "+entry.getValue().getName()); + }*/ + + double currDistFromLftM = 11.0; + int orgColofCollapsedd = -1; + int orgColofDisplayedd = -1; + for (Map.Entry<String,Domain> cd : updatedRC.entrySet()) { + /*for (Domain pl : collapsedDomainNewL) { + for (Map.Entry<String, Domain> colCheck : originalDomainRowCol.entrySet()) { + if (colCheck.getValue().getName().equals(pl.getName())) { + orgColofCollapsedd = Character.getNumericValue(colCheck.getKey().toCharArray()[1]); + break; + } + } + + for (Map.Entry<String, Domain> colCheckk : originalDomainRowCol.entrySet()) { + if (colCheckk.getValue().getName().equals(cd.getValue().getName())) { + orgColofDisplayedd = Character.getNumericValue(colCheckk.getKey().toCharArray()[1]); + break; + } + } + + if (orgColofCollapsedd < orgColofDisplayedd) { + currDistFromLftM+= 3; + } + }*/ + Domain d = cd.getValue(); + double accountPlus = accountForPlusSpaceBefore(d); + // currDistFromLftM+= accountForPlusSpaceBefore(d); + d.setDomainToLayoutWd(currDistFromLftM+accountPlus); + d.computeConatinerPositions(); + for (Map.Entry<String, Container> entry1 : d.getContainerRowCol().entrySet()) { + Container c = entry1.getValue(); + c.computeSize(); + c.computeElementPositions(); + if (c.getContainerRowCol() != null) { + for (Map.Entry<String, Container> entryInner : c.getContainerRowCol().entrySet()) { + Container inner = entryInner.getValue(); + inner.computeElementPositions(); + } + } + } + currDistFromLftM += d.computeSize().getWidth()+2; + + } + + + + + //nline + // Insert method invocation + updatePlusPosition(collapsedDomainNewL, updatedRC); + + //order changed + setCollapsedDomains(collapsedDomainMap); + setCollapsedDomainsNewList(collapsedDomainNewL); + + + computeDomainPositionsModified(); + return this; + } + + + + public Layout collapseDomainNew(String domainsToCollapse) { + + if(domainsToCollapse == null || domainsToCollapse.isEmpty()) + return null; + + Map<String,Domain> updatedRC = new HashMap<String, Domain>(); + + for (Map.Entry<String, Domain> copyEntry : domainRowCol.entrySet()) { + updatedRC.put(copyEntry.getKey(), copyEntry.getValue()); + //System.out.println("copyEntry.getKey() "+copyEntry.getKey()+ " copyEntry.getValue() "+copyEntry.getValue()); + } + + Map<String, Domain> updatedRCSorted = new TreeMap<String, Domain>(updatedRC); + + Map<String, Domain> collapsedDomainMap = getCollapsedDomains(); + + List<Domain> collapsedDomainNewL = getCollapsedDomainsNewList(); + + + if (collapsedDomainNewL.size() == 0) { + for (Map.Entry<String, Domain> copyEntry : domainRowCol.entrySet()) { + originalDomainRowCol.put(copyEntry.getKey(), copyEntry.getValue()); + // System.out.println("copyEntry.getKey() "+copyEntry.getKey()+ " copyEntry.getValue() "+copyEntry.getValue()); + } + } + + + Map<String, Domain> updatedRCSortedTrunc = new TreeMap<String, Domain>(); + + int colToDelete = 0; + for (Map.Entry<String, Domain> entry : updatedRCSorted.entrySet()) { + if (entry.getValue().getName().equals(domainsToCollapse)) { + if (entry.getValue().isIndexChanged()) { + collapsedDomainMap.put("0"+String.valueOf(Integer.parseInt(entry.getKey())+1), entry.getValue()); + + } + //Domain toRemove = entry.getValue(); + else { + collapsedDomainMap.put(entry.getKey(),entry.getValue()); + } + + collapsedDomainNewL.add(entry.getValue()); + setNumberofColsofDomains(getNumberofColsofDomains()-1); + updatedRC.remove(entry.getKey()); + colToDelete = Character.getNumericValue(entry.getKey().toCharArray()[1]); + break; + } + } + + + for (Map.Entry<String, Domain> copyEntry : updatedRCSorted.entrySet()) { + updatedRCSortedTrunc.put(copyEntry.getKey(), copyEntry.getValue()); + //System.out.println("copyEntry.getKey() "+copyEntry.getKey()+ " copyEntry.getValue() "+copyEntry.getValue()); + } + + for (Map.Entry<String, Domain> rmv : updatedRCSorted.entrySet()) { + if (Character.getNumericValue(rmv.getKey().toCharArray()[1]) <= colToDelete) { + updatedRCSortedTrunc.remove(rmv.getKey()); + } + } + + + /* for (Map.Entry<String, Domain> entry : updatedRCSortedTrunc.entrySet()) { + System.out.println("Sorted key: "+entry.getKey()+" Sorted value: "+entry.getValue().getName()); + }*/ + + for (Map.Entry<String, Domain> updateOthers : updatedRCSortedTrunc.entrySet()) { + char update[] = updateOthers.getKey().toCharArray(); + int charToupdate = Character.getNumericValue(update[1]); + --charToupdate; + String resultRowCol = String.valueOf(update[0])+String.valueOf(charToupdate); + updateOthers.getValue().setIndexChanged(true); + updatedRC.put(resultRowCol, updateOthers.getValue()); + updatedRC.remove(updateOthers.getKey()); + + } + setDomainRowCol(updatedRC); + + double currDistFromLftM = 11.0; + + boolean isDisplayed; + for (Map.Entry<String,Domain> orgEntry : originalDomainRowCol.entrySet()) { + isDisplayed = false; + for (Map.Entry<String,Domain> cd : updatedRC.entrySet()) { + if (cd.getValue().getName().equals(orgEntry.getValue().getName())) { + Domain d = cd.getValue(); + d.setDomainToLayoutWd(currDistFromLftM); + d.computeConatinerPositions(); + for (Map.Entry<String, Container> entry1 : d.getContainerRowCol().entrySet()) { + Container c = entry1.getValue(); + c.computeSize(); + c.computeElementPositions(); + if (c.getContainerRowCol() != null) { + for (Map.Entry<String, Container> entryInner : c.getContainerRowCol().entrySet()) { + Container inner = entryInner.getValue(); + inner.computeElementPositions(); + } + } + } + currDistFromLftM += d.computeSize().getWidth()+1; + isDisplayed = true; + break; + } + } + + if (!isDisplayed) { + Domain myCollapsed = orgEntry.getValue(); + myCollapsed.setNewXafterColl(currDistFromLftM); + myCollapsed.setYafterColl(myCollapsed.getP().getY()); + currDistFromLftM += 4; + } + } + + setCollapsedDomains(collapsedDomainMap); + setCollapsedDomainsNewList(collapsedDomainNewL); + + + computeDomainPositionsModified(); + return this; + + } + + + public Layout collapseDomain(String domainsToCollapse) { + + Map<String,Domain> updatedRC = new HashMap<String, Domain>(); + + for (Map.Entry<String, Domain> copyEntry : domainRowCol.entrySet()) { + updatedRC.put(copyEntry.getKey(), copyEntry.getValue()); + //System.out.println("copyEntry.getKey() "+copyEntry.getKey()+ " copyEntry.getValue() "+copyEntry.getValue()); + } + + Map<String, Domain> updatedRCSorted = new TreeMap<String, Domain>(updatedRC); + + Map<String, Domain> collapsedDomainMap = getCollapsedDomains(); + + if (collapsedDomainMap.size() == 0) { + for (Map.Entry<String, Domain> copyEntry : domainRowCol.entrySet()) { + originalDomainRowCol.put(copyEntry.getKey(), copyEntry.getValue()); + // System.out.println("copyEntry.getKey() "+copyEntry.getKey()+ " copyEntry.getValue() "+copyEntry.getValue()); + } + } + + + // List<Domain> collapsedDomainsList = getCollapsedDomains(); + + /* for (Map.Entry<String, Domain> entry : updatedRCSorted.entrySet()) { + System.out.println("Sorted Key: "+entry.getKey()); + }*/ + + double prevDomXCordinate = 0.0; + Map<String, Domain> updatedRCSortedTrunc = new TreeMap<String, Domain>(); + // for (String dToCollapse : domainsToCollapse) { + int colToDelete = 0; + for (Map.Entry<String, Domain> entry : updatedRCSorted.entrySet()) { + if (entry.getValue().getName().equals(domainsToCollapse)) { + if (entry.getValue().isIndexChanged()) + collapsedDomainMap.put("0"+String.valueOf(Integer.parseInt(entry.getKey())+1), entry.getValue()); + //Domain toRemove = entry.getValue(); + else + collapsedDomainMap.put(entry.getKey(),entry.getValue()); + prevDomXCordinate = entry.getValue().getP().getX(); + entry.getValue().getP().setX(prevDomXCordinate-2); + // toRemove.setCollapsed(true); + setNumberofColsofDomains(getNumberofColsofDomains()-1); + updatedRC.remove(entry.getKey()); + colToDelete = Character.getNumericValue(entry.getKey().toCharArray()[1]); + // collapsedDomainList.put(entry.getKey(),entry.getValue()); + break; + } + } + + /* for (Map.Entry<String, Domain> entry : updatedRC.entrySet()) { + System.out.println("Sorted key: "+entry.getKey()+" Sorted value: "+entry.getValue().getName()); + }*/ + + setCollapsedDomains(collapsedDomainMap); + + for (Map.Entry<String, Domain> copyEntry : updatedRCSorted.entrySet()) { + updatedRCSortedTrunc.put(copyEntry.getKey(), copyEntry.getValue()); + //System.out.println("copyEntry.getKey() "+copyEntry.getKey()+ " copyEntry.getValue() "+copyEntry.getValue()); + } + + for (Map.Entry<String, Domain> rmv : updatedRCSorted.entrySet()) { + if (Character.getNumericValue(rmv.getKey().toCharArray()[1]) <= colToDelete) { + updatedRCSortedTrunc.remove(rmv.getKey()); + } + } + + + /* for (Map.Entry<String, Domain> entry : updatedRCSortedTrunc.entrySet()) { + System.out.println("Sorted key: "+entry.getKey()+" Sorted value: "+entry.getValue().getName()); + }*/ + + for (Map.Entry<String, Domain> updateOthers : updatedRCSortedTrunc.entrySet()) { + // if (!updateOthers.getValue().getName().equals(dToCollapse)) { + // if ((int)updateOthers.getKey().toCharArray()[1] > colToDelete) { + char update[] = updateOthers.getKey().toCharArray(); + int charToupdate = Character.getNumericValue(update[1]); + --charToupdate; + String resultRowCol = String.valueOf(update[0])+String.valueOf(charToupdate); + // update[1] = (char)charToupdate; + // updatedRC.put(String.valueOf(update), updateOthers.getValue()); + updateOthers.getValue().setIndexChanged(true); + updatedRC.put(resultRowCol, updateOthers.getValue()); + updatedRC.remove(updateOthers.getKey()); + // } + // } + } + + // } + setDomainRowCol(updatedRC); + + + + for (Map.Entry<String, Domain> entry : updatedRCSortedTrunc.entrySet()) { + Domain d = entry.getValue(); + // if (d.getName().equals("Datacenter with AIC") || d.getName().equals("VNI")) { + // d.setDomainToLayoutWd(d.getDomainToLayoutWd()-33); + if (collapsedDomains.size() == 2 && collapsedDomains.containsKey("00") && collapsedDomains.containsKey("01") && domainsToCollapse.equals("RAN")) { + if (d.getName().equals("USP")) + d.setDomainToLayoutWd(prevDomXCordinate); + else if (d.getName().equals("VNI")) + d.setDomainToLayoutWd(prevDomXCordinate+8); + else + d.setDomainToLayoutWd(prevDomXCordinate+10); + //System.out.println("Inside RAN EPC"); + } + else if (domainsToCollapse.equals("RAN") && !d.getName().equals("EPC") && collapsedDomains.size() < 3) + d.setDomainToLayoutWd(prevDomXCordinate+11); + else if (domainsToCollapse.equals("RAN") && collapsedDomains.size() == 3 && collapsedDomains.containsKey("01") && collapsedDomains.containsKey("04")) { + if (d.getName().equals("USP")) + d.setDomainToLayoutWd(prevDomXCordinate); + else + d.setDomainToLayoutWd(prevDomXCordinate+10); + } + + else if (collapsedDomains.containsKey("00") && collapsedDomains.size() == 3 && collapsedDomains.containsKey("01") && collapsedDomains.containsKey("02")) { + //System.out.println("Inside test"); + if (d.getName().equals("VNI")) + d.setDomainToLayoutWd(prevDomXCordinate+10); + else + d.setDomainToLayoutWd(prevDomXCordinate); + + } + + else if (collapsedDomains.containsKey("00") && collapsedDomains.size() == 3 && collapsedDomains.containsKey("01") && collapsedDomains.containsKey("03")) { + //System.out.println("Inside test"); + if (d.getName().equals("VNI")) + d.setDomainToLayoutWd(prevDomXCordinate+10); + else + d.setDomainToLayoutWd(prevDomXCordinate); + + } + + + + else { + d.setDomainToLayoutWd(prevDomXCordinate); + } + d.computeConatinerPositions(); + prevDomXCordinate = d.getP().getX(); + for (Map.Entry<String, Container> entry1 : d.getContainerRowCol().entrySet()) { + Container c = entry1.getValue(); + c.computeSize(); + c.computeElementPositions(); + if (c.getContainerRowCol() != null) { + for (Map.Entry<String, Container> entryInner : c.getContainerRowCol().entrySet()) { + Container inner = entryInner.getValue(); + inner.computeElementPositions(); + } + } + } + // } + // System.out.println("Sorted key: "+entry.getKey()+" Sorted value: "+entry.getValue().getName()); + } + // setNumberofColsofDomains(getNumberofColsofDomains()-1); + computeDomainPositions(); + return this; + /* CoordinateMain cm = new CoordinateMain(); + try { + cm.convertToYAML(this); + } catch (Exception e) { + + }*/ + + } + + public Layout uncollapseDomainModified(String domainToUnCollapse) { + Map<String, Domain> currentDomainsSorted = new TreeMap<String,Domain>(domainRowCol); + Map<String, Domain> updateDomains = new TreeMap<String,Domain>(); + Map<String, Domain> collapsedDomainList = getCollapsedDomains(); + Map<String, Domain> collapsedDomainListSorted = new TreeMap<String, Domain>(collapsedDomainList); + + List<Domain> domainstoUpd = new ArrayList<Domain>(); + + int colToUnCollapse = 99; + + Domain domainToInsert = null; + + if (collapsedDomains.size() == 0) { + for (Map.Entry<String, Domain> unindexDomain : originalDomainRowCol.entrySet()) { + Domain dm = unindexDomain.getValue(); + dm.setIndexChanged(false); + } + } + + + for (Map.Entry<String, Domain> entry : collapsedDomainListSorted.entrySet()) { + if (entry.getValue().getName().equals(domainToUnCollapse)) { + colToUnCollapse = Character.getNumericValue(entry.getKey().toCharArray()[1]); + domainToInsert = entry.getValue(); + collapsedDomainList.remove(entry.getKey()); + break; + } + } + + domainstoUpd.add(domainToInsert); + + //for (Map.Entry<String, Domain> e : originalDomainRowCol.entrySet()) + // System.out.println("Original key value"+e.getKey()+":"+e.getValue().getName()); + + int lastKeyCol = -1; + for (Map.Entry<String, Domain> entry : originalDomainRowCol.entrySet()) { + int currcol = Character.getNumericValue(entry.getKey().toCharArray()[1]); + if (currcol < colToUnCollapse) { + for (Map.Entry<String, Domain> currDomainsEntry : currentDomainsSorted.entrySet()) { + if (currDomainsEntry.getValue().getName().equals(entry.getValue().getName())) { + updateDomains.put(currDomainsEntry.getKey(), currDomainsEntry.getValue()); + lastKeyCol = Character.getNumericValue(currDomainsEntry.getKey().toCharArray()[1]); + break; + } + } + } else { + String newKey = "0"+String.valueOf(lastKeyCol+1); + if (currcol == colToUnCollapse) { + updateDomains.put(newKey, domainToInsert); + ++lastKeyCol; + } else { + for (Map.Entry<String, Domain> currDomainsEnt : currentDomainsSorted.entrySet()) { + if (currDomainsEnt.getValue().getName().equals(entry.getValue().getName())) { + updateDomains.put(newKey, currDomainsEnt.getValue()); + domainstoUpd.add(currDomainsEnt.getValue()); + ++lastKeyCol; + // lastKeyCol = Character.getNumericValue(currDomainsEntry.getKey().toCharArray()[1]); + break; + } + } + } + + } + } + + setNumberofColsofDomains(getNumberofColsofDomains()+1); + setDomainRowCol(updateDomains); + setCollapsedDomains(collapsedDomainList); + + //for (Map.Entry<String, Domain> e : updateDomains.entrySet()) + // System.out.println("me Updatedomains key value"+e.getKey()+":"+e.getValue().getName()); + + // for (int i = 1; i < domainstoUpd.size(); i++) { + for (int i = 0; i < domainstoUpd.size(); i++) { + Domain d = domainstoUpd.get(i); + double newX = 0.0; + if (i+1 < domainstoUpd.size()) + // newX = domainstoUpd.get(i-1).getP().getX()+domainstoUpd.get(i-1).computeSize().getWidth()+5; + newX = domainstoUpd.get(i+1).getP().getX(); + //d.setDomainToLayoutWd(domainstoUpd.get(i+1).getP().getX()); + else + newX = domainstoUpd.get(i).getP().getX()+32; + // d.setDomainToLayoutWd(domainstoUpd.get(i).getP().getX()+38); + /* if (i > 0) { + if (d.getWidth() < domainstoUpd.get(i-1).getWidth()) + newX+= domainstoUpd.get(i-1).getWidth() - d.getWidth(); + else if (d.getWidth() > domainstoUpd.get(i-1).getWidth()) + newX-= d.getWidth() - domainstoUpd.get(i-1).getWidth() ; + } else { + if (d.getWidth() < domainInserted.getWidth()) + newX+= domainInserted.getWidth() - d.getWidth(); + else if (d.getWidth() > domainInserted.getWidth()) + newX-= d.getWidth() - domainInserted.getWidth() ; + }*/ + if (d.getName().equals("Datacenter with AIC")) + newX+= 2; + d.setDomainToLayoutWd(newX); + /* if (i == 0) + d.setDomainToLayoutWd(domainInserted.getP().getX()+domainInserted.getWidth()); + else + d.setDomainToLayoutWd(domainstoUpd.get(i-1).getP().getX()+domainstoUpd.get(i-1).getWidth());*/ + d.computeConatinerPositions(); + for (Map.Entry<String, Container> entry1 : d.getContainerRowCol().entrySet()) { + Container c = entry1.getValue(); + c.computeSize(); + c.computeElementPositions(); + if (c.getContainerRowCol() != null) { + for (Map.Entry<String, Container> entryInner : c.getContainerRowCol().entrySet()) { + Container inner = entryInner.getValue(); + inner.computeElementPositions(); + } + } + } + // } + // System.out.println("Sorted key: "+entry.getKey()+" Sorted value: "+entry.getValue().getName()); + } + + computeDomainPositions(); + return this; + + } + + + + public Layout uncollapseDomain(String domainToCollapse) { + Map<String, Domain> currentDomainsSorted = new TreeMap<String,Domain>(domainRowCol); + Map<String, Domain> updateDomains = new TreeMap<String,Domain>(); + Map<String, Domain> collapsedDomainList = getCollapsedDomains(); + Map<String, Domain> collapsedDomainListSorted = new TreeMap<String, Domain>(collapsedDomainList); + + List<Domain> domainstoUpd = new ArrayList<Domain>(); + /* for (Map.Entry<String, Domain> entry : collapsedDomainListSorted.entrySet()) { + if (entry.getValue().getName().equals("domainToCollapse")) { + if (currentDomainsSorted != null) { + if (!currentDomainsSorted.containsKey(entry.getKey())) { + updateDomains.put(entry.getKey(), entry.getValue()); + collapsedDomainList.remove(entry.getKey()); + break; + } else { + int colToUnCollapse = Character.getNumericValue(entry.getKey().toCharArray()[1]); + for (Map.Entry<String, Domain> curr : currentDomainsSorted.entrySet()) { + if (Character.getNumericValue(curr.getKey().toCharArray()[1]) < colToUnCollapse) { + updateDomains.put(curr.getKey(),curr.getValue()); + } else { + updateDomains.put(curr.getKey()+1,curr.getValue()); + + } + } + updateDomains.put(entry.getKey(), entry.getValue()); + } + } + + + } + }*/ + + Domain domainInserted = null; + for (Map.Entry<String, Domain> entry : collapsedDomainListSorted.entrySet()) { + if (entry.getValue().getName().equals(domainToCollapse)) { + domainInserted = entry.getValue(); + if (currentDomainsSorted != null) { + int colToUnCollapse = Character.getNumericValue(entry.getKey().toCharArray()[1]); + for (Map.Entry<String, Domain> curr : currentDomainsSorted.entrySet()) { + if (Character.getNumericValue(curr.getKey().toCharArray()[1]) < colToUnCollapse) { + updateDomains.put(curr.getKey(),curr.getValue()); + } else { + updateDomains.put("0"+String.valueOf(Integer.parseInt(curr.getKey())+1),curr.getValue()); + domainstoUpd.add(curr.getValue()); + } + } + } + updateDomains.put(entry.getKey(), entry.getValue()); + collapsedDomainList.remove(entry.getKey()); + break; + + } + } + setNumberofColsofDomains(getNumberofColsofDomains()+1); + setDomainRowCol(updateDomains); + setCollapsedDomains(collapsedDomainList); + + //for (Map.Entry<String, Domain> e : updateDomains.entrySet()) + // System.out.println("Updatedomains key value"+e.getKey()+":"+e.getValue().getName()); + + + for (int i = 0; i < domainstoUpd.size(); i++) { + Domain d = domainstoUpd.get(i); + double newX = 0.0; + if (i+1 < domainstoUpd.size()) + newX = domainstoUpd.get(i+1).getP().getX(); + //d.setDomainToLayoutWd(domainstoUpd.get(i+1).getP().getX()); + else + newX = domainstoUpd.get(i).getP().getX()+38; + // d.setDomainToLayoutWd(domainstoUpd.get(i).getP().getX()+38); + /* if (i > 0) { + if (d.getWidth() < domainstoUpd.get(i-1).getWidth()) + newX+= domainstoUpd.get(i-1).getWidth() - d.getWidth(); + else if (d.getWidth() > domainstoUpd.get(i-1).getWidth()) + newX-= d.getWidth() - domainstoUpd.get(i-1).getWidth() ; + } else { + if (d.getWidth() < domainInserted.getWidth()) + newX+= domainInserted.getWidth() - d.getWidth(); + else if (d.getWidth() > domainInserted.getWidth()) + newX-= d.getWidth() - domainInserted.getWidth() ; + }*/ + if (d.getName().equals("Datacenter with AIC")) + newX+= 5; + d.setDomainToLayoutWd(newX); + /* if (i == 0) + d.setDomainToLayoutWd(domainInserted.getP().getX()+domainInserted.getWidth()); + else + d.setDomainToLayoutWd(domainstoUpd.get(i-1).getP().getX()+domainstoUpd.get(i-1).getWidth());*/ + d.computeConatinerPositions(); + for (Map.Entry<String, Container> entry1 : d.getContainerRowCol().entrySet()) { + Container c = entry1.getValue(); + c.computeSize(); + c.computeElementPositions(); + if (c.getContainerRowCol() != null) { + for (Map.Entry<String, Container> entryInner : c.getContainerRowCol().entrySet()) { + Container inner = entryInner.getValue(); + inner.computeElementPositions(); + } + } + } + // } + // System.out.println("Sorted key: "+entry.getKey()+" Sorted value: "+entry.getValue().getName()); + } + + computeDomainPositions(); + return this; + } + + public Layout uncollapseDomainNew(String domainToUnCollapse) { + Map<String, Domain> currentDomainsSorted = new TreeMap<String,Domain>(domainRowCol); + Map<String, Domain> updateDomains = new TreeMap<String,Domain>(); + Map<String, Domain> collapsedDomainList = getCollapsedDomains(); + Map<String, Domain> collapsedDomainListSorted = new TreeMap<String, Domain>(collapsedDomainList); + + List<Domain> domainstoUpd = new ArrayList<Domain>(); + + //nline + List<Domain> collapsedDomainNewLL = getCollapsedDomainsNewList(); + + int colToUnCollapse = 99; + + Domain domainToInsert = null; + + //nline + // if (collapsedDomains.size() == 0) { + if (collapsedDomainNewLL.size() == 0) { + for (Map.Entry<String, Domain> unindexDomain : originalDomainRowCol.entrySet()) { + Domain dm = unindexDomain.getValue(); + dm.setIndexChanged(false); + } + } + + + for (Map.Entry<String, Domain> entry : originalDomainRowCol.entrySet()) { + if (entry.getValue().getName().equals(domainToUnCollapse)) { + colToUnCollapse = Character.getNumericValue(entry.getKey().toCharArray()[1]); + domainToInsert = entry.getValue(); + collapsedDomainList.remove(entry.getKey()); + //nline + collapsedDomainNewLL.remove(entry.getValue()); + break; + } + } + + domainstoUpd.add(domainToInsert); + + // for (Map.Entry<String, Domain> e : originalDomainRowCol.entrySet()) + // System.out.println("Original key value"+e.getKey()+":"+e.getValue().getName()); + + int lastKeyCol = -1; + for (Map.Entry<String, Domain> entry : originalDomainRowCol.entrySet()) { + int currcol = Character.getNumericValue(entry.getKey().toCharArray()[1]); + if (currcol < colToUnCollapse) { + for (Map.Entry<String, Domain> currDomainsEntry : currentDomainsSorted.entrySet()) { + if (currDomainsEntry.getValue().getName().equals(entry.getValue().getName())) { + updateDomains.put(currDomainsEntry.getKey(), currDomainsEntry.getValue()); + lastKeyCol = Character.getNumericValue(currDomainsEntry.getKey().toCharArray()[1]); + break; + } + } + } else { + String newKey = "0"+String.valueOf(lastKeyCol+1); + if (currcol == colToUnCollapse) { + updateDomains.put(newKey, domainToInsert); + ++lastKeyCol; + } else { + for (Map.Entry<String, Domain> currDomainsEnt : currentDomainsSorted.entrySet()) { + if (currDomainsEnt.getValue().getName().equals(entry.getValue().getName())) { + updateDomains.put(newKey, currDomainsEnt.getValue()); + domainstoUpd.add(currDomainsEnt.getValue()); + ++lastKeyCol; + // lastKeyCol = Character.getNumericValue(currDomainsEntry.getKey().toCharArray()[1]); + break; + } + } + } + + } + } + + setNumberofColsofDomains(getNumberofColsofDomains()+1); + setDomainRowCol(updateDomains); + + //for (Map.Entry<String, Domain> e : updateDomains.entrySet()) + // System.out.println("me Updatedomains key value"+e.getKey()+":"+e.getValue().getName()); + + + + double currDistFromLftMargin = 11.0; + for (Map.Entry<String,Domain> cd : updateDomains.entrySet()) { + Domain d = cd.getValue(); + double accountPlus = accountForPlusSpaceBefore(d); + d.setDomainToLayoutWd(currDistFromLftMargin+accountPlus); + d.computeConatinerPositions(); + for (Map.Entry<String, Container> entry1 : d.getContainerRowCol().entrySet()) { + Container c = entry1.getValue(); + c.computeSize(); + c.computeElementPositions(); + if (c.getContainerRowCol() != null) { + for (Map.Entry<String, Container> entryInner : c.getContainerRowCol().entrySet()) { + Container inner = entryInner.getValue(); + inner.computeElementPositions(); + } + } + } + currDistFromLftMargin += d.computeSize().getWidth()+2; + + } + + //nline + updatePlusPosition(collapsedDomainNewLL, updateDomains); + + //order changed + setCollapsedDomains(collapsedDomainList); + + //nline + setCollapsedDomainsNewList(collapsedDomainNewLL); + + + computeDomainPositionsModified(); + return this; + + } + + public Layout uncollapseDomainNew1(String domainToUnCollapse) { + + if(domainToUnCollapse == null || domainToUnCollapse.isEmpty()) + return null; + + Map<String, Domain> currentDomainsSorted = new TreeMap<String,Domain>(domainRowCol); + Map<String, Domain> updateDomains = new TreeMap<String,Domain>(); + Map<String, Domain> collapsedDomainList = getCollapsedDomains(); + Map<String, Domain> collapsedDomainListSorted = new TreeMap<String, Domain>(collapsedDomainList); + + List<Domain> domainstoUpd = new ArrayList<Domain>(); + + //nline + List<Domain> collapsedDomainNewLL = getCollapsedDomainsNewList(); + + int colToUnCollapse = 99; + + Domain domainToInsert = null; + + //nline + // if (collapsedDomains.size() == 0) { + if (collapsedDomainNewLL.size() == 0) { + for (Map.Entry<String, Domain> unindexDomain : originalDomainRowCol.entrySet()) { + Domain dm = unindexDomain.getValue(); + dm.setIndexChanged(false); + } + } + + + for (Map.Entry<String, Domain> entry : originalDomainRowCol.entrySet()) { + if (entry.getValue().getName().equals(domainToUnCollapse)) { + colToUnCollapse = Character.getNumericValue(entry.getKey().toCharArray()[1]); + domainToInsert = entry.getValue(); + collapsedDomainList.remove(entry.getKey()); + //nline + collapsedDomainNewLL.remove(entry.getValue()); + break; + } + } + + domainstoUpd.add(domainToInsert); + + //for (Map.Entry<String, Domain> e : originalDomainRowCol.entrySet()) + // System.out.println("Original key value"+e.getKey()+":"+e.getValue().getName()); + + int lastKeyCol = -1; + for (Map.Entry<String, Domain> entry : originalDomainRowCol.entrySet()) { + int currcol = Character.getNumericValue(entry.getKey().toCharArray()[1]); + if (currcol < colToUnCollapse) { + for (Map.Entry<String, Domain> currDomainsEntry : currentDomainsSorted.entrySet()) { + if (currDomainsEntry.getValue().getName().equals(entry.getValue().getName())) { + updateDomains.put(currDomainsEntry.getKey(), currDomainsEntry.getValue()); + lastKeyCol = Character.getNumericValue(currDomainsEntry.getKey().toCharArray()[1]); + break; + } + } + } else { + String newKey = "0"+String.valueOf(lastKeyCol+1); + if (currcol == colToUnCollapse) { + updateDomains.put(newKey, domainToInsert); + ++lastKeyCol; + } else { + for (Map.Entry<String, Domain> currDomainsEnt : currentDomainsSorted.entrySet()) { + if (currDomainsEnt.getValue().getName().equals(entry.getValue().getName())) { + updateDomains.put(newKey, currDomainsEnt.getValue()); + domainstoUpd.add(currDomainsEnt.getValue()); + ++lastKeyCol; + // lastKeyCol = Character.getNumericValue(currDomainsEntry.getKey().toCharArray()[1]); + break; + } + } + } + + } + } + + setNumberofColsofDomains(getNumberofColsofDomains()+1); + setDomainRowCol(updateDomains); + + //for (Map.Entry<String, Domain> e : updateDomains.entrySet()) + // System.out.println("me Updatedomains key value"+e.getKey()+":"+e.getValue().getName()); + + + + + double currDistFromLftM = 11.0; + + boolean isDisplayed; + for (Map.Entry<String,Domain> orgEntry : originalDomainRowCol.entrySet()) { + isDisplayed = false; + for (Map.Entry<String,Domain> cd : updateDomains.entrySet()) { + if (cd.getValue().getName().equals(orgEntry.getValue().getName())) { + Domain d = cd.getValue(); + d.setDomainToLayoutWd(currDistFromLftM); + d.computeConatinerPositions(); + for (Map.Entry<String, Container> entry1 : d.getContainerRowCol().entrySet()) { + Container c = entry1.getValue(); + c.computeSize(); + c.computeElementPositions(); + if (c.getContainerRowCol() != null) { + for (Map.Entry<String, Container> entryInner : c.getContainerRowCol().entrySet()) { + Container inner = entryInner.getValue(); + inner.computeElementPositions(); + } + } + } + currDistFromLftM += d.computeSize().getWidth()+1; + isDisplayed = true; + break; + } + } + + if (!isDisplayed) { + Domain myCollapsed = orgEntry.getValue(); + myCollapsed.setNewXafterColl(currDistFromLftM); + currDistFromLftM += 4; + } + } + + // plus.setNewXafterColl(distOfCollFrmLft+1.5); + + //order changed + setCollapsedDomains(collapsedDomainList); + + //nline + setCollapsedDomainsNewList(collapsedDomainNewLL); + + + computeDomainPositionsModified(); + return this; + + } + + + + + + + + + + + + + + + private void updatePlusPosition(List<Domain> collapsedDNewL, Map<String, Domain> displayedDomainMap) { + List<Domain> copyCollapseList = new ArrayList<Domain>(); + + for (Domain copyCollapse : collapsedDNewL) { + copyCollapseList.add(copyCollapse); + } + + //double distOfCollFrmLft = 0.0; + int orgColofCollapsed = -1; + int orgColofDisplayed = -1; + int orgColofDisplayedOtherPlus = -1; + int orgColofInterDomainPlus = -1; + List<Domain> dsplyList = new ArrayList<Domain>(); + + for (Domain plus : collapsedDNewL) { + double distOfCollFrmLft = 0.0; + for (Map.Entry<String, Domain> colCheck : originalDomainRowCol.entrySet()) { + if (colCheck.getValue().getName().equals(plus.getName())) { + orgColofCollapsed = Character.getNumericValue(colCheck.getKey().toCharArray()[1]); + break; + } + } + for (Map.Entry<String, Domain> displayedEntry : displayedDomainMap.entrySet()) { + + for (Map.Entry<String, Domain> colCheck1 : originalDomainRowCol.entrySet()) { + if (colCheck1.getValue().getName().equals(displayedEntry.getValue().getName())) { + orgColofDisplayed = Character.getNumericValue(colCheck1.getKey().toCharArray()[1]); + break; + } + } + if (orgColofDisplayed < orgColofCollapsed) { + distOfCollFrmLft+= displayedEntry.getValue().computeSize().getWidth(); + + + /* if (dsplyList.size() > 0) { + Domain lastAdded = dsplyList.get(dsplyList.size()-1); + int orgColofLastAdded = -1; + for (Map.Entry<String, Domain> colCh : originalDomainRowCol.entrySet()) { + if (colCh.getValue().getName().equals(lastAdded.getName())) { + orgColofLastAdded = Character.getNumericValue(colCh.getKey().toCharArray()[1]); + break; + } + } + if (Math.abs(orgColofDisplayed - orgColofLastAdded) == 1) { + boolean adjDomainsWithPlus = false; + for (Domain colp : copyCollapseList) { + if (!colp.getName().equals(plus.getName())) { + for (Map.Entry<String, Domain> colCk2 : originalDomainRowCol.entrySet()) { + if (colCk2.getValue().getName().equals(colp.getName())) { + orgColofInterDomainPlus = Character.getNumericValue(colCk2.getKey().toCharArray()[1]); + break; + } + } + if (orgColofInterDomainPlus > orgColofLastAdded && orgColofInterDomainPlus < orgColofDisplayed) { + adjDomainsWithPlus = true; + break; + } + } + } + if (!adjDomainsWithPlus) + distOfCollFrmLft+=interDomainWd; + } + } + dsplyList.add(displayedEntry.getValue()); */ + + + + } + + } + + for (Domain collp : copyCollapseList) { + if (!collp.getName().equals(plus.getName())) { + for (Map.Entry<String, Domain> colCheck2 : originalDomainRowCol.entrySet()) { + if (colCheck2.getValue().getName().equals(collp.getName())) { + orgColofDisplayedOtherPlus = Character.getNumericValue(colCheck2.getKey().toCharArray()[1]); + break; + } + } + if (orgColofDisplayedOtherPlus < orgColofCollapsed) { + distOfCollFrmLft+=3.0; + } + } + } + + plus.setNewXafterColl(distOfCollFrmLft+1.5); + + + } + } + + + private double accountForPlusSpaceBefore(Domain d) { + + int orgColofCollapsed = 0; + int orgColofDisplayed = 0; + double distFromLftM = 0.0; + + for (Map.Entry<String, Domain> colCheckk : originalDomainRowCol.entrySet()) { + if (colCheckk.getValue().getName().equals(d.getName())) { + orgColofDisplayed = Character.getNumericValue(colCheckk.getKey().toCharArray()[1]); + break; + } + } + + for (Domain collapsed : getCollapsedDomainsNewList()) { + for (Map.Entry<String, Domain> colCheck : originalDomainRowCol.entrySet()) { + if (colCheck.getValue().getName().equals(collapsed.getName())) { + orgColofCollapsed = Character.getNumericValue(colCheck.getKey().toCharArray()[1]); + break; + } + } + + if (orgColofCollapsed < orgColofDisplayed) { + distFromLftM+= 2; + } + } + return distFromLftM; + + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/NameValueId.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/NameValueId.java new file mode 100644 index 00000000..fcb9f726 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/NameValueId.java @@ -0,0 +1,94 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.domain.support; + +import java.io.Serializable; + + +public class NameValueId implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 1L; + private String lab; + private String val; + + public NameValueId() { + } + + public NameValueId(String value, String label) { + setVal(value); + setLab(label); + } + + + public String getLab() { + return lab; + } + + + public String getVal() { + return val; + } + + + public void setLab(String label) { + this.lab = label; + } + + + public void setVal(String value) { + this.val = value; + } + + + public boolean equals(Object o) { + if (this == o) { + return true; + } + + if (o == null) { + return false; + } + + if (!(o instanceof NameValueId)) { + return false; + } + + final NameValueId nameValueId = (NameValueId)o; + + if (!getVal().equals(nameValueId.getVal())) { + return false; + } + + if (!getLab().equals(nameValueId.getLab())) { + return false; + } + + return true; + } + + + public int hashCode() { + return getVal().hashCode(); + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/Position.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/Position.java new file mode 100644 index 00000000..db137c80 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/Position.java @@ -0,0 +1,40 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.domain.support; + +public class Position { + double x; + double y; + + public double getX() { + return x; + } + public void setX(double x) { + this.x = x; + } + public double getY() { + return y; + } + public void setY(double y) { + this.y = y; + } + + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/Size.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/Size.java new file mode 100644 index 00000000..4ebfb962 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/domain/support/Size.java @@ -0,0 +1,40 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.domain.support; + +public class Size { + private double width; + private double height; + + public double getWidth() { + return width; + } + public void setWidth(double width) { + this.width = width; + } + public double getHeight() { + return height; + } + public void setHeight(double height) { + this.height = height; + } + + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/drools/DroolsRuleService.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/drools/DroolsRuleService.java new file mode 100644 index 00000000..c556aa13 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/drools/DroolsRuleService.java @@ -0,0 +1,27 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.drools; + +public interface DroolsRuleService { + + public void init(String... params); + public String getResultsString(); + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/drools/DroolsRuleServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/drools/DroolsRuleServiceImpl.java new file mode 100644 index 00000000..2aa0d1f2 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/drools/DroolsRuleServiceImpl.java @@ -0,0 +1,58 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.drools; + + +/** + * + * This is POC test class to execute sample rules + */ +public class DroolsRuleServiceImpl implements DroolsRuleService{ + + + private String state; + private String resultsString; + + public DroolsRuleServiceImpl() { + + } + + public void init(String... params) { + this.state = params[0]; + } + + + + public String getState() { + return state; + } + + public String accessLabel() { + return "Drools POC Test"; + } + + public String getResultsString() { + return resultsString; + } + + public void setResultsString(String resultsString) { + this.resultsString = resultsString; + } +}
\ No newline at end of file diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/exception/FusionExceptionResolver.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/exception/FusionExceptionResolver.java new file mode 100644 index 00000000..a2b4363a --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/exception/FusionExceptionResolver.java @@ -0,0 +1,50 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.exception; + +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.servlet.ModelAndView; + +@ControllerAdvice +public class FusionExceptionResolver { + + @ExceptionHandler(UrlAccessRestrictedException.class) + public ModelAndView handleUrlAccessException(UrlAccessRestrictedException ex) { + ModelAndView model = new ModelAndView("error"); + model.addObject("errMsg", ex.getMessage()); + return model; + + } + @ExceptionHandler(SessionExpiredException.class) + public ModelAndView handleSessionException(SessionExpiredException ex) { + ModelAndView model = new ModelAndView("error"); + model.addObject("errMsg", ex.getMessage()); + return model; + } + @ExceptionHandler(Exception.class) + public ModelAndView handleAllException(Exception ex) { + ModelAndView model = new ModelAndView("error"); + model.addObject("errMsg", ex.getMessage()); + return model; + + } + +}
\ No newline at end of file diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/exception/SessionExpiredException.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/exception/SessionExpiredException.java new file mode 100644 index 00000000..f4a19a9e --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/exception/SessionExpiredException.java @@ -0,0 +1,35 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.exception; + +import org.openecomp.portalsdk.core.exception.support.FusionRuntimeException; + +public class SessionExpiredException extends FusionRuntimeException { + + /** + * + */ + private static final long serialVersionUID = 1L; + public static final String MESSAGE = "Your session has expired. Please login again."; + + public SessionExpiredException() { + super(MESSAGE); + } +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/exception/UrlAccessRestrictedException.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/exception/UrlAccessRestrictedException.java new file mode 100644 index 00000000..adc56118 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/exception/UrlAccessRestrictedException.java @@ -0,0 +1,35 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.exception; + +import org.openecomp.portalsdk.core.exception.support.FusionRuntimeException; + +public class UrlAccessRestrictedException extends FusionRuntimeException { + + /** + * + */ + private static final long serialVersionUID = 1L; + public static final String MESSAGE = "Authorization Denied"; + + public UrlAccessRestrictedException() { + super(MESSAGE); + } +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/exception/support/FusionException.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/exception/support/FusionException.java new file mode 100644 index 00000000..135fc3e3 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/exception/support/FusionException.java @@ -0,0 +1,24 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.exception.support; + +import org.openecomp.portalsdk.core.FusionObject; + +public interface FusionException extends FusionObject {} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/exception/support/FusionRuntimeException.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/exception/support/FusionRuntimeException.java new file mode 100644 index 00000000..91a733d4 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/exception/support/FusionRuntimeException.java @@ -0,0 +1,35 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.exception.support; + +public class FusionRuntimeException extends RuntimeException implements FusionException { + /** + * + */ + private static final long serialVersionUID = 1L; + public FusionRuntimeException() { + this(""); + } + + public FusionRuntimeException(String message) { + super(message); + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/interceptor/ResourceInterceptor.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/interceptor/ResourceInterceptor.java new file mode 100644 index 00000000..ec6e4b6c --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/interceptor/ResourceInterceptor.java @@ -0,0 +1,167 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.interceptor; + +import java.net.HttpURLConnection; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.openecomp.portalsdk.core.controller.FusionBaseController; +import org.openecomp.portalsdk.core.domain.App; +import org.openecomp.portalsdk.core.exception.UrlAccessRestrictedException; +import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.objectcache.AbstractCacheManager; +import org.openecomp.portalsdk.core.onboarding.listener.PortalTimeoutHandler; +import org.openecomp.portalsdk.core.onboarding.util.CipherUtil; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.service.LoginService; +import org.openecomp.portalsdk.core.service.WebServiceCallService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.method.HandlerMethod; +import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; + +public class ResourceInterceptor extends HandlerInterceptorAdapter { + public static final String APP_METADATA = "APP.METADATA"; + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ResourceInterceptor.class); + + @Autowired + private DataAccessService dataAccessService; + @Autowired + private LoginService loginService; + @Autowired + private WebServiceCallService webServiceCallService; + + private AbstractCacheManager cacheManager; + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) + throws Exception { + String uri = request.getRequestURI(); + String url = uri.substring(uri.indexOf("/", 1) + 1); + logger.info(EELFLoggerDelegate.debugLogger, "Url - " + url); + logger.info(EELFLoggerDelegate.debugLogger, "lastIndexOf - " + uri.substring(uri.lastIndexOf("/") + 1)); + if (handler instanceof HandlerMethod) { + HandlerMethod method = (HandlerMethod) handler; + FusionBaseController controller = (FusionBaseController) method.getBean(); + if (!controller.isAccessible()) { + if (controller.isRESTfulCall()) { + // check user authentication for RESTful calls + String secretKey = null; + try { + if (!webServiceCallService.verifyRESTCredential(secretKey, request.getHeader("username"), + request.getHeader("password"))) { + logger.error(EELFLoggerDelegate.errorLogger, "Error accesing RESTful service. Un-authorized",AlarmSeverityEnum.MINOR); + throw new UrlAccessRestrictedException(); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Error authenticating RESTful service :" + e,AlarmSeverityEnum.MINOR); + //throw new UrlAccessRestrictedException(); + HttpSession httpSession = request.getSession(); + ((HttpServletResponse) response).setStatus(HttpURLConnection.HTTP_UNAUTHORIZED); + return false; + } + } + if (!UserUtils.isUrlAccessible(request, url)) { + logger.error(EELFLoggerDelegate.errorLogger, "Error accesing URL. Un-authorized",AlarmSeverityEnum.MINOR); + throw new UrlAccessRestrictedException(); + } + } + } + + logger.debug("successfully authorized rest call"); + logger.info(EELFLoggerDelegate.debugLogger, "successfully authorized rest call"); + handleSessionUpdates(request); + logger.debug("handled session updates for synchronization"); + logger.info(EELFLoggerDelegate.debugLogger, "handled session updates for synchronization"); + return super.preHandle(request, response, handler); + } + + /** + * + * @param request + */ + protected void handleSessionUpdates(HttpServletRequest request) { + + App app = null; + Object appObj = getCacheManager().getObject(APP_METADATA); + if (appObj == null) { + app = findApp(); + getCacheManager().putObject(APP_METADATA, app); + + } else { + app = (App) appObj; + } + + String ecompRestURL = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL); + String decreptedPwd = ""; + try { + decreptedPwd = CipherUtil.decrypt(app.getAppPassword(), + SystemProperties.getProperty(SystemProperties.Decryption_Key)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Could not decrypt Password" + e.getMessage(),AlarmSeverityEnum.MINOR); + } + + PortalTimeoutHandler.handleSessionUpdatesNative(request, app.getUsername(), decreptedPwd, + PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY), ecompRestURL, null); + } + + public App findApp() { + List<?> list = null; + StringBuffer criteria = new StringBuffer(); + criteria.append(" where id = 1"); + list = getDataAccessService().getList(App.class, criteria.toString(), null, null); + return (list == null || list.size() == 0) ? null : (App) list.get(0); + } + + public DataAccessService getDataAccessService() { + return dataAccessService; + } + + public void setDataAccessService(DataAccessService dataAccessService) { + this.dataAccessService = dataAccessService; + } + + public LoginService getLoginService() { + return loginService; + } + + public void setLoginService(LoginService loginService) { + this.loginService = loginService; + } + + @Autowired + public void setCacheManager(AbstractCacheManager cacheManager) { + this.cacheManager = cacheManager; + } + + public AbstractCacheManager getCacheManager() { + return cacheManager; + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/interceptor/SessionTimeoutInterceptor.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/interceptor/SessionTimeoutInterceptor.java new file mode 100644 index 00000000..e28ce866 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/interceptor/SessionTimeoutInterceptor.java @@ -0,0 +1,103 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.interceptor; + +import java.net.URLEncoder; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.openecomp.portalsdk.core.controller.FusionBaseController; +import org.openecomp.portalsdk.core.domain.User; +import org.openecomp.portalsdk.core.exception.SessionExpiredException; +import org.openecomp.portalsdk.core.listener.CollaborateListBindingListener; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.web.support.AppUtils; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.web.method.HandlerMethod; +import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; + +public class SessionTimeoutInterceptor extends HandlerInterceptorAdapter { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SessionTimeoutInterceptor.class); + + public SessionTimeoutInterceptor() { + } + + /** + * Checks all requests for valid session information. If not found, + * redirects to a controller that will establish a valid session. + */ + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) + throws Exception { + if (handler instanceof HandlerMethod) { + HandlerMethod method = (HandlerMethod) handler; + FusionBaseController controller = (FusionBaseController) method.getBean(); + if (!controller.isAccessible() && !controller.isRESTfulCall()) { + try { + // getSession() throws SessionExpiredException + HttpSession session = AppUtils.getSession(request); + User user = UserUtils.getUserSession(request); + // check if user is logging out + if (request.getRequestURI().indexOf("logout.htm") > -1) { + session.removeAttribute(CollaborateListBindingListener.SESSION_ATTR_NAME); + throw new SessionExpiredException(); + } else if (user == null) { + // Jump to the redirection code + throw new Exception("preHandle: user not found in session"); + } else { + // session binding listener will add this value to the + // map, and with session replication the listener will + // fire in all tomcat instances + session.setAttribute(CollaborateListBindingListener.SESSION_ATTR_NAME, + new CollaborateListBindingListener(user.getOrgUserId())); + } + } catch (Exception ex) { + // get the path within the webapp that the user requested (no host name etc.) + final String forwardUrl = request.getRequestURI().substring(request.getContextPath().length() + 1) + + (request.getQueryString() == null ? "" : "?" + request.getQueryString()); + final String forwardUrlParm = "forwardURL=" + URLEncoder.encode(forwardUrl, "UTF-8"); + final String singleSignonPrefix = "/single_signon.htm?"; + if (ex instanceof SessionExpiredException) { + // Session is expired; send to portal. + // Redirect to an absolute path in the webapp; e.g., "/context/single_signon.htm" + final String redirectUrl = request.getContextPath() + singleSignonPrefix + "redirectToPortal=Yes&" + forwardUrlParm; + logger.debug(EELFLoggerDelegate.debugLogger, "preHandle: session is expired, redirecting to {}", + redirectUrl); + response.sendRedirect(redirectUrl); + return false; + } else { + // Other issue; do not send to portal. + // Redirect to an absolute path in the webapp; e.g., "/context/single_signon.htm" + final String redirectUrl = request.getContextPath() + singleSignonPrefix + forwardUrlParm; + logger.debug(EELFLoggerDelegate.debugLogger, "preHandle: took exception {}, redirecting to {}", + ex.getMessage(), redirectUrl); + response.sendRedirect(redirectUrl); + return false; + } + } + } + } + + return super.preHandle(request, response, handler); + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/interfaces/SecurityInterface.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/interfaces/SecurityInterface.java new file mode 100644 index 00000000..b40c4713 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/interfaces/SecurityInterface.java @@ -0,0 +1,24 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.interfaces; + +public interface SecurityInterface { + public boolean isAccessible(); +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/listener/ApplicationContextListener.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/listener/ApplicationContextListener.java new file mode 100644 index 00000000..0cc99f0e --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/listener/ApplicationContextListener.java @@ -0,0 +1,49 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.listener; + +import javax.servlet.ServletContext; +import javax.servlet.annotation.WebListener; + +import org.openecomp.portalsdk.core.lm.FusionLicenseManager; +import org.openecomp.portalsdk.core.lm.FusionLicenseManagerUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationListener; +import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.stereotype.Component; + +@WebListener +@Component +public class ApplicationContextListener implements ApplicationListener<ContextRefreshedEvent> { + + @Autowired + ServletContext context; + @Autowired + FusionLicenseManager lm; + @Autowired + FusionLicenseManagerUtils fusionLicenseManagerUtils; + + + public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent ) { + int licenseStatus = fusionLicenseManagerUtils.verifyLicense(context); + context.setAttribute("licenseVerification", licenseStatus); + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/listener/CollaborateListBindingListener.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/listener/CollaborateListBindingListener.java new file mode 100644 index 00000000..9306aaf1 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/listener/CollaborateListBindingListener.java @@ -0,0 +1,61 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.listener; + +import java.io.Serializable; + +import javax.servlet.http.HttpSessionBindingEvent; +import javax.servlet.http.HttpSessionBindingListener; + +import org.openecomp.portalsdk.core.domain.support.CollaborateList; + +public class CollaborateListBindingListener implements HttpSessionBindingListener, Serializable { + + private static final long serialVersionUID = 1L; + private String userName; + public static final String SESSION_ATTR_NAME = "CollaborateListSessionAttrName"; + + public CollaborateListBindingListener(String _userName) { + userName = _userName; + } + + @Override + public void valueBound(HttpSessionBindingEvent event) { + final CollaborateListBindingListener value = ((CollaborateListBindingListener) event.getValue()); + CollaborateList.addUserName(value.getUserName()); + + } + + @Override + public void valueUnbound(HttpSessionBindingEvent event) { + final CollaborateListBindingListener value = ((CollaborateListBindingListener) event.getValue()); + if (value != null) + CollaborateList.delUserName(value.getUserName()); + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/listener/UserSessionListener.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/listener/UserSessionListener.java new file mode 100644 index 00000000..adc84775 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/listener/UserSessionListener.java @@ -0,0 +1,62 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.listener; + +import javax.servlet.annotation.WebListener; +import javax.servlet.http.HttpSession; +import javax.servlet.http.HttpSessionEvent; +import javax.servlet.http.HttpSessionListener; + +import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; + + +@WebListener +public class UserSessionListener implements HttpSessionListener{ + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserSessionListener.class); + + public void sessionCreated(HttpSessionEvent event){ + + } + + /** + * Removes sessions from the context scoped HashMap when they expire + * or are invalidated. + */ + public void sessionDestroyed(HttpSessionEvent event){ + try { + HttpSession session = event.getSession(); + session.removeAttribute(CollaborateListBindingListener.SESSION_ATTR_NAME); + + // Object user = session.getAttribute(SystemProperties.getProperty("user.attribute.name")); + + //if( user != null) + // { + session.removeAttribute(CollaborateListBindingListener.SESSION_ATTR_NAME); + //CollaborateList.getInstance().delUserName(user.getOrgUserId()); + // } + + } + catch(Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "sessionDestroyed" + e.getMessage(),AlarmSeverityEnum.MINOR); + } + } +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/lm/FusionLicenseManager.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/lm/FusionLicenseManager.java new file mode 100644 index 00000000..eb371575 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/lm/FusionLicenseManager.java @@ -0,0 +1,60 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.lm; + +import java.util.Date; +import java.util.List; +import java.util.Map; + +import javax.servlet.ServletContext; + +//import de.schlichtherle.license.LicenseContent; + +public interface FusionLicenseManager { + + + public static final int DEVELOPER_LICENSE = 0; + public static final int EXPIRED_LICENSE = 1; + public static final int VALID_LICENSE = 2; + public static final int INVALID_LICENSE = 3; + public static final int OPENSOURCE_LICENSE = 4; + + public void initKeyStoreParam(); + + public void initCipherParam(); + + public void initLicenseParam(); + + public void doInitWork(); + + public int installLicense(); + + public int verifyLicense(ServletContext context); + + //public LicenseContent createLicenseContent(Map<String, String> clientInfoMap, List<String> ipAddressList); + + public void generateLicense(Map<String, String> clientInfoMap, List<String> ipAddressList) throws Exception; + + public String nvl(String s); + + public Date getExpiredDate(); + + public void setExpiredDate(Date expiredDate); +}
\ No newline at end of file diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/lm/FusionLicenseManagerUtils.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/lm/FusionLicenseManagerUtils.java new file mode 100644 index 00000000..538709e8 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/lm/FusionLicenseManagerUtils.java @@ -0,0 +1,74 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.lm; + +import java.util.Date; + +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; + +import org.openecomp.portalsdk.core.util.SystemProperties; +//import org.openecomp.portalapp.lm.FusionLicenseManagerImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.servlet.support.RequestContextUtils; + +@Component +public class FusionLicenseManagerUtils { + + @Autowired + private FusionLicenseManager licenseManager; + + @Autowired + private SystemProperties sysProps; + static { + } + + public int verifyLicense(ServletContext context) { + if(sysProps == null) { + try { + sysProps = new SystemProperties(); + sysProps.setServletContext(context); +// sysProps.load(); +// licenseManager = new FusionLicenseManagerImpl(new LicenseableClassImpl()); + System.out.println(licenseManager); + licenseManager.installLicense(); + } + catch(Exception ex) { + ex.printStackTrace(); + } + } + + + +// WebApplicationContext ctx =RequestContextUtils.getWebApplicationContext(request); +// int flag = ((FusionLicenseManager)ctx.getBean("fusionLicenseManager")).verifyLicense(request); +// logger.debug("****************FLAG ******************** " + flag); +// return flag; +// return 2; + return licenseManager.verifyLicense(context); + } + + public static Date getLicenseExpiryDate(HttpServletRequest request) { + WebApplicationContext ctx =RequestContextUtils.getWebApplicationContext(request); + return ((FusionLicenseManager)ctx.getBean("fusionLicenseManager")).getExpiredDate(); + } +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/lm/LicenseableClass.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/lm/LicenseableClass.java new file mode 100644 index 00000000..296a1609 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/lm/LicenseableClass.java @@ -0,0 +1,38 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.lm; + +import java.io.*; + +/** + * created by Alvin Alexander of http://devdaily.com. + * modified by Sundar Ramalingam + */ +public interface LicenseableClass +{ + public String getApplicationName(); + public InputStream getPublicKeystoreAsInputStream() throws FileNotFoundException; + public String getAlias(); + public String getPublicKeystorePassword(); + public String getKeyPasswd(); + public String getCipherParamPassword(); + public Class getClassToLicense(); + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/aspect/AuditLog.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/aspect/AuditLog.java new file mode 100644 index 00000000..6cb661b1 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/aspect/AuditLog.java @@ -0,0 +1,32 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.logging.aspect; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + + +@Target({ElementType.METHOD, ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +public @interface AuditLog { + String value() default ""; +}
\ No newline at end of file diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/aspect/EELFLoggerAdvice.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/aspect/EELFLoggerAdvice.java new file mode 100644 index 00000000..da4e2aff --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/aspect/EELFLoggerAdvice.java @@ -0,0 +1,234 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.logging.aspect; + +import java.text.SimpleDateFormat; +import java.util.Date; + +import javax.servlet.http.HttpServletRequest; + +import org.openecomp.portalsdk.core.logging.format.AuditLogFormatter; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.AppService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.portalsdk.core.util.SystemProperties.SecurityEventTypeEnum; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; + +import com.att.eelf.configuration.Configuration; + +@org.springframework.context.annotation.Configuration +public class EELFLoggerAdvice { + + @Autowired + AppService appService; + + EELFLoggerDelegate adviceLogger = EELFLoggerDelegate.getLogger(EELFLoggerAdvice.class); + + // DateTime Format according to the ECOMP Application Logging Guidelines. + private static final SimpleDateFormat ecompLogDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + + /** + * Gets the current date and time in expected ECOMP log format. + * + * @return Current date and time + */ + public static String getCurrentDateTimeUTC() { + String currentDateTime = ecompLogDateFormat.format(new Date()); + return currentDateTime; + } + + /** + * + * @param securityEventType + * @param args + * @param passOnArgs + * @return One-element array containing an empty String object. + */ + public Object[] before(SecurityEventTypeEnum securityEventType, Object[] args, Object[] passOnArgs) { + try { + String className = ""; + if (passOnArgs[0] != null) { + className = passOnArgs[0].toString(); + } + + String methodName = ""; + if (passOnArgs[1] != null) { + methodName = passOnArgs[1].toString(); + } + + String appName = appService.getDefaultAppName(); + if (appName == null || appName == "") { + appName = SystemProperties.SDK_NAME; + } + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(className); + + // Initialize Request defaults only for controller methods. + MDC.put(className + methodName + SystemProperties.METRICSLOG_BEGIN_TIMESTAMP, getCurrentDateTimeUTC()); + MDC.put(SystemProperties.TARGET_ENTITY, appName + "_BE"); + MDC.put(SystemProperties.TARGET_SERVICE_NAME, methodName); + if (securityEventType != null) { + MDC.put(className + methodName + SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, getCurrentDateTimeUTC()); + HttpServletRequest req = null; + if (args[0] != null && args[0] instanceof HttpServletRequest) { + req = (HttpServletRequest) args[0]; + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(req, appName); + } + } + logger.debug(EELFLoggerDelegate.debugLogger, (methodName + " was invoked.")); + } catch (Exception e) { + adviceLogger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred in EELFLoggerAdvice.before() method. Details: " + e.getMessage()); + } + + return new Object[] { "" }; + } + + /** + * + * @param securityEventType + * @param result + * @param args + * @param returnArgs + * @param passOnArgs + */ + public void after(SecurityEventTypeEnum securityEventType, String result, Object[] args, Object[] returnArgs, + Object[] passOnArgs) { + try { + String className = ""; + if (passOnArgs[0] != null) { + className = passOnArgs[0].toString(); + } + + String methodName = ""; + if (passOnArgs[1] != null) { + methodName = passOnArgs[1].toString(); + } + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(className); + + String appName = appService.getDefaultAppName(); + if (appName == null || appName == "") { + appName = SystemProperties.SDK_NAME; + } + + if (MDC.get(SystemProperties.TARGET_SERVICE_NAME) == null + || MDC.get(SystemProperties.TARGET_SERVICE_NAME) == "") { + MDC.put(SystemProperties.TARGET_SERVICE_NAME, methodName); + } + + if (MDC.get(SystemProperties.TARGET_ENTITY) == null || MDC.get(SystemProperties.TARGET_ENTITY) == "") { + MDC.put(SystemProperties.TARGET_ENTITY, appName + "_BE"); + } + + MDC.put(SystemProperties.METRICSLOG_BEGIN_TIMESTAMP, + MDC.get(className + methodName + SystemProperties.METRICSLOG_BEGIN_TIMESTAMP)); + MDC.put(SystemProperties.METRICSLOG_END_TIMESTAMP, getCurrentDateTimeUTC()); + this.calculateDateTimeDifference(MDC.get(SystemProperties.METRICSLOG_BEGIN_TIMESTAMP), + MDC.get(SystemProperties.METRICSLOG_END_TIMESTAMP)); + + logger.info(EELFLoggerDelegate.metricsLogger, methodName + " operation is completed."); + logger.debug(EELFLoggerDelegate.debugLogger, "Finished executing " + methodName + "."); + + if (securityEventType != null) { + + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, + MDC.get(className + methodName + SystemProperties.AUDITLOG_BEGIN_TIMESTAMP)); + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, getCurrentDateTimeUTC()); + this.calculateDateTimeDifference(MDC.get(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP), + MDC.get(SystemProperties.AUDITLOG_END_TIMESTAMP)); + + this.logSecurityMessage(logger, securityEventType, result, methodName); + + // clear when finishes audit logging + MDC.remove(Configuration.MDC_KEY_REQUEST_ID); + MDC.remove(SystemProperties.PARTNER_NAME); + MDC.remove(SystemProperties.MDC_LOGIN_ID); + MDC.remove(SystemProperties.PROTOCOL); + MDC.remove(SystemProperties.FULL_URL); + MDC.remove(Configuration.MDC_SERVICE_NAME); + MDC.remove(SystemProperties.RESPONSE_CODE); + MDC.remove(SystemProperties.STATUS_CODE); + MDC.remove(className + methodName + SystemProperties.AUDITLOG_BEGIN_TIMESTAMP); + MDC.remove(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP); + MDC.remove(SystemProperties.AUDITLOG_END_TIMESTAMP); + } + + MDC.remove(className + methodName + SystemProperties.METRICSLOG_BEGIN_TIMESTAMP); + MDC.remove(SystemProperties.METRICSLOG_BEGIN_TIMESTAMP); + MDC.remove(SystemProperties.METRICSLOG_END_TIMESTAMP); + MDC.remove(SystemProperties.MDC_TIMER); + MDC.remove(SystemProperties.TARGET_ENTITY); + MDC.remove(SystemProperties.TARGET_SERVICE_NAME); + } catch (Exception e) { + adviceLogger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred in EELFLoggerAdvice.after() method. Details: " + e.getMessage()); + } + } + + /** + * + * @param logger + * @param securityEventType + * @param result + * @param restMethod + */ + private void logSecurityMessage(EELFLoggerDelegate logger, SecurityEventTypeEnum securityEventType, String result, + String restMethod) { + StringBuilder additionalInfoAppender = new StringBuilder(); + String auditMessage = ""; + + additionalInfoAppender.append(String.format("%s request was received.", restMethod)); + + // Status code + MDC.put(SystemProperties.STATUS_CODE, result); + + String fullURL = MDC.get(SystemProperties.FULL_URL); + if (fullURL != null && fullURL != "") { + additionalInfoAppender.append(" Request-URL:" + MDC.get(SystemProperties.FULL_URL)); + } + + auditMessage = AuditLogFormatter.getInstance().createMessage(MDC.get(SystemProperties.PROTOCOL), + securityEventType.name(), MDC.get(SystemProperties.MDC_LOGIN_ID), additionalInfoAppender.toString()); + + logger.info(EELFLoggerDelegate.auditLogger, auditMessage); + } + + /** + * + * @param beginDateTime + * @param endDateTime + */ + private void calculateDateTimeDifference(String beginDateTime, String endDateTime) { + if (beginDateTime != null && endDateTime != null) { + try { + Date beginDate = ecompLogDateFormat.parse(beginDateTime); + Date endDate = ecompLogDateFormat.parse(endDateTime); + String timeDifference = String.format("%d ms", endDate.getTime() - beginDate.getTime()); + MDC.put(SystemProperties.MDC_TIMER, timeDifference); + } catch (Exception e) { + adviceLogger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred in EELFLoggerAdvice.calculateDateTimeDifference() method. Details: " + + e.getMessage()); + } + } + } +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/aspect/EELFLoggerAspect.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/aspect/EELFLoggerAspect.java new file mode 100644 index 00000000..3138d21a --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/aspect/EELFLoggerAspect.java @@ -0,0 +1,88 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.logging.aspect; + +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Pointcut; +import org.openecomp.portalsdk.core.util.SystemProperties.SecurityEventTypeEnum; +import org.springframework.beans.factory.annotation.Autowired; + + +@Aspect +@org.springframework.context.annotation.Configuration +public class EELFLoggerAspect { + + @Autowired + EELFLoggerAdvice advice; + + /* + * Point-cut expression to handle all INCOMING_REST_MESSAGES + */ + @Pointcut("execution(public * org.openecomp.portalsdk.core.controller.*.*(..))") + public void incomingAuditMessages() {} + + @Around("incomingAuditMessages() && @annotation(auditLog)") + public Object logAuditMethodAround(ProceedingJoinPoint joinPoint, AuditLog auditLog) throws Throwable { + return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.INCOMING_REST_MESSAGE); + } + + @Around("incomingAuditMessages() && @within(auditLog)") + public Object logAuditMethodClassAround(ProceedingJoinPoint joinPoint, AuditLog auditLog) throws Throwable { + return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.INCOMING_REST_MESSAGE); + } + + /* + * Point cut expression to capture metrics logging + */ + @Pointcut("execution(public * *(..))") + public void publicMethod() {} + + @Around("publicMethod() && @within(metricsLog)") + public Object logMetricsClassAround(ProceedingJoinPoint joinPoint, MetricsLog metricsLog) throws Throwable { + return this.logAroundMethod(joinPoint, null); + } + + @Around("publicMethod() && @annotation(metricsLog)") + public Object logMetricsMethodAround(ProceedingJoinPoint joinPoint, MetricsLog metricsLog) throws Throwable { + return this.logAroundMethod(joinPoint, null); + } + + private Object logAroundMethod(ProceedingJoinPoint joinPoint, SecurityEventTypeEnum securityEventType) throws Throwable { + //Before + Object[] passOnArgs = new Object[] {joinPoint.getSignature().getDeclaringType().getName(),joinPoint.getSignature().getName()}; + Object[] returnArgs = advice.before(securityEventType, joinPoint.getArgs(), passOnArgs); + + //Execute the actual method + Object result = null; + String restStatus = "COMPLETE"; + try { + result = joinPoint.proceed(); + } catch(Exception e) { + restStatus = "ERROR"; + } + + //After + advice.after(securityEventType, restStatus, joinPoint.getArgs(), returnArgs, passOnArgs); + + return result; + } +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/aspect/MetricsLog.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/aspect/MetricsLog.java new file mode 100644 index 00000000..f795ffb1 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/aspect/MetricsLog.java @@ -0,0 +1,32 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.logging.aspect; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + + +@Target({ElementType.METHOD, ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +public @interface MetricsLog { + String value() default ""; +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/format/AlarmSeverityEnum.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/format/AlarmSeverityEnum.java new file mode 100644 index 00000000..360d8d81 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/format/AlarmSeverityEnum.java @@ -0,0 +1,28 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.logging.format; + +public enum AlarmSeverityEnum { + CRITICAL, + MAJOR, + MINOR, + INFORMATIONAL, + NONE, +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/format/AppMessagesEnum.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/format/AppMessagesEnum.java new file mode 100644 index 00000000..a6924ba0 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/format/AppMessagesEnum.java @@ -0,0 +1,249 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.logging.format; + +public enum AppMessagesEnum { + /* + 100-199 Security/Permission Related + - Authentication problems (from external client, to external server) + - Certification errors + - + + 200-299 Availability/Timeout Related + - connectivity error + - connection timeout + + 300-399 Data Access/Integrity Related + - Data in graph in invalid(E.g. no creator is found for service) + - Artifact is missing in ES, but exists in graph. + + 400-499 Schema Interface Type/Validation + - received Pay-load checksum is invalid + - received JSON is not valid + + 500-599 Business/Flow Processing Related + - check out to service is not allowed + - Roll-back is done + - failed to generate heat file + + + 600-899 Reserved - do not use + + 900-999 Unknown Errors + - Unexpected exception + */ + + BeUebAuthenticationError(ErrorCodesEnum.BEUEBAUTHENTICATIONERROR_ONE_ARGUMENT, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR100E", "An Authentication failure occurred during access to UEB server", "Details: {0}.", "Please check UEB server list and keys configured under Portal.Properties file."), + + BeRestApiAuthenticationError(ErrorCodesEnum.BERESTAPIAUTHENTICATIONERROR, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR101E", "Rejected an incoming REST API request due to invalid credentials", "", "Please check application credentials defined in Database or properties files."), + + InternalAuthenticationInfo(ErrorCodesEnum.INTERNALAUTHENTICATIONINFO_ONE_ARGUMENT, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO, + "ERR199I", "Internal authentication problem", "Details: {0}.", "Please check the logs for more information."), + + InternalAuthenticationWarning(ErrorCodesEnum.INTERNALAUTHENTICATIONWARNING_ONE_ARGUMENT, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.WARN, + "ERR199W", "Internal authentication problem", "Details: {0}.", "Please check the logs for more information."), + + InternalAuthenticationError(ErrorCodesEnum.INTERNALAUTHENTICATIONERROR_ONE_ARGUMENT, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR199E", "Internal authentication problem", "Details: {0}.", "Please check the logs for more information."), + + InternalAuthenticationFatal(ErrorCodesEnum.INTERNALAUTHENTICATIONFATAL_ONE_ARGUMENT, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.FATAL, + "ERR199F", "Internal authentication problem", "Details: {0}.", "Please check the logs for more information."), + + BeHealthCheckError(ErrorCodesEnum.BeHEALTHCHECKERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR, + "ERR200E", "ECOMP-PORTAL Back-end probably lost connectivity to either one of the following components: MySQL DB, UEB Cluster", "", "Please check the logs for more information."), + + BeHealthCheckMySqlError(ErrorCodesEnum.BEHEALTHCHECKMYSQLERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR, + "ERR201E", "ECOMP-PORTAL Back-end probably lost connectivity to MySQL DB", "", "Check connectivity to MYSQL is configured correctly under system.properties file."), + + BeHealthCheckUebClusterError(ErrorCodesEnum.BEHEALTHCHECKUEBCLUSTERERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR, + "ERR203E", "ECOMP-PORTAL Back-end probably lost connectivity to UEB Cluster", "", "Check connectivity to UEB cluster which is configured under portal.properties file."), + + FeHealthCheckError(ErrorCodesEnum.FEHEALTHCHECKERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR, + "ERR204E", "Unable to connect to a valid ECOMP-PORTAL Back-end Server.", "", "Please check connectivity from this FE instance towards BE or BE Load Balancer."), + + BeHealthCheckRecovery(ErrorCodesEnum.BEHEALTHCHECKRECOVERY, ErrorTypeEnum.RECOVERY, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO, + "ERR205I", "ECOMP-PORTAL Back-end Recovery to either one of the following components: MySQL DB, UEB Cluster", "", "Please check logs for more specific information about the problem."), + + BeHealthCheckMySqlRecovery(ErrorCodesEnum.BEHEALTHCHECKMYSQLRECOVERY, ErrorTypeEnum.RECOVERY, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO, + "ERR206I", "ECOMP-PORTAL Back-end connection recovery to MySQL DB", "", "Please check logs for more specific information about the problem."), + + BeHealthCheckUebClusterRecovery(ErrorCodesEnum.BEHEALTHCHECKUEBCLUSTERRECOVERY, ErrorTypeEnum.RECOVERY, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO, + "ERR208I", "ECOMP-PORTAL Back-end connection recovery to UEB Cluster", "", "Please check logs for more specific information about the problem."), + + FeHealthCheckRecovery(ErrorCodesEnum.FEHEALTHCHECKRECOVERY, ErrorTypeEnum.RECOVERY, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO, + "ERR209I", "Connectivity to ECOMP-PORTAL Front-end Server is recovered", "", "Please check logs for more specific information about the problem."), + + BeUebConnectionError(ErrorCodesEnum.BEUEBCONNECTIONERROR_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR210E", "ECOMP-PORTAL Back-end probably lost connectivity to UEB Cluster", "Details: {0}.", "Please check UEB server list and keys configured under Portal.Properties file."), + + BeUebUnkownHostError(ErrorCodesEnum.BEUEBUNKOWNHOSTERROR_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR211E", "ECOMP-PORTAL Back-end probably lost connectivity to UEB Cluster", "Cannot reach host: {0}.", "Please check UEB server list and keys configured under Portal.Properties file."), + + BeUebRegisterOnboardingAppError(ErrorCodesEnum.BEUEBREGISTERONBOARDINGAPPERROR, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR212E", "Failed to register the On-boarding application with UEB Communication server", "Details: {0}.", "Please check UEB server list and keys configured under Portal.Properties file."), + + BeHttpConnectionError(ErrorCodesEnum.BEHTTPCONNECTIONERROR_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR213E", "It could be that communication to an external application might resulted an exception or failed to reach the external application", + "Details: {0}.", "Please check logs for more information."), + + InternalConnectionInfo(ErrorCodesEnum.INTERNALCONNECTIONINFO_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO, + "ERR299I", "Internal Connection problem", "Details: {0}.", "Please check logs for more information."), + + InternalConnectionWarning(ErrorCodesEnum.INTERNALCONNECTIONWARNING_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.WARN, + "ERR299W", "Internal Connection problem", "Details: {0}.", "Please check logs for more information."), + + InternalConnectionError(ErrorCodesEnum.INTERNALCONNECTIONERROR_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR299E", "Internal Connection problem", "Details: {0}.", "Please check logs for more information."), + + InternalConnectionFatal(ErrorCodesEnum.INTERNALCONNECTIONFATAL_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.FATAL, + "ERR299F", "Internal Connection problem", "Details: {0}.", "Please check logs for more information."), + + BeUebObjectNotFoundError(ErrorCodesEnum.BEUEBOBJECTNOTFOUNDERROR_ONE_ARGUMENT, ErrorTypeEnum.DATA_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR303E", "Error occurred during access to U-EB Server.", "Data not found: {0}.", "An error occurred during access to UEB Server, {1} failed to either register or unregister to/from UEB topic."), + + BeUserMissingError(ErrorCodesEnum.BEUSERMISSINGERROR_ONE_ARGUMENT, ErrorTypeEnum.DATA_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR310E", "User is not found", "", "User {0} must be added to the corresponding application with proper user roles."), + + BeUserInactiveWarning(ErrorCodesEnum.BEUSERINACTIVEWARNING_ONE_ARGUMENT, ErrorTypeEnum.DATA_ERROR, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.WARN, + "ERR313W", "User is found but in-active", "", "User {0} must be added to the corresponding application with proper user roles."), + + BeUserAdminPrivilegesInfo(ErrorCodesEnum.BEUSERADMINPRIVILEGESINFO_ONE_ARGUMENT, ErrorTypeEnum.DATA_ERROR, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.WARN, + "ERR314W", "User is found but don't have administrative privileges", "", "User {0} should be given administrator role for the corresponding application to perform the necessary actions."), + + BeInvalidJsonInput(ErrorCodesEnum.BEINVALIDJSONINPUT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR405E", "Failed to convert JSON input to object", "", "Please check logs for more information."), + + BeIncorrectHttpStatusError(ErrorCodesEnum.BEINCORRECTHTTPSTATUSERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR407E", "Communication to an external application is resulted in with Incorrect Http response code", "", "Please check logs for more information."), + + BeInitializationError(ErrorCodesEnum.BEINITIALIZATIONERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR, + "ERR500E", "ECOMP-PORTAL Back-end was not initialized properly", "", "Please check logs for more information."), + + BeUebSystemError(ErrorCodesEnum.BEUEBSYSTEMERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR502E", "Error occurred during access to U-EB Server", "Details: {0}.", "An error occurred in {1} distribution mechanism. Please check the logs for more information."), + + BeDaoSystemError(ErrorCodesEnum.BEDAOSYSTEMERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR, + "ERR505E", "Performing DDL or DML operations on database might have failed", "", "Please check MySQL DB health or look at the logs for more details."), + + BeSystemError(ErrorCodesEnum.BESYSTEMERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR, + "ERR506E", "Unexpected error during operation", "", "Please check logs for more information."), + + BeExecuteRollbackError(ErrorCodesEnum.BEEXECUTEROLLBACKERROR, ErrorTypeEnum.DATA_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR507E", "Roll-back operation towards database has failed", "", "Please check MYSQL DB health or look at the logs for more details."), + + FeHttpLoggingError(ErrorCodesEnum.FEHTTPLOGGINGERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.ERROR, + "ERR517E", "Error when logging FE HTTP request/response", "", "Please check MYSQL DB health or look at the logs for more details."), + + FePortalServletError(ErrorCodesEnum.FEPORTALSERVLETERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR518E", "Error when trying to access FE Portal page.", "", "Please check logs for more information."), + + BeDaoCloseSessionError(ErrorCodesEnum.BEDAOCLOSESESSIONERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR519E", "Close local session operation with database failed", "", "Please check MYSQL DB health or look at the logs form more details."), + + BeRestApiGeneralError(ErrorCodesEnum.BERESTAPIGENERALERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR, + "ERR900E", "Unexpected error during ECOMP-PORTAL Back-end REST API execution", "", "Please check error log for more information."), + + FeHealthCheckGeneralError(ErrorCodesEnum.FEHEALTHCHECKGENERALERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR, + "ERR901E", "General error during FE Health Check", "", "Please check error log for more information."), + + InternalUnexpectedInfo(ErrorCodesEnum.INTERNALUNEXPECTEDINFO_ONE_ARGUMENT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO, + "ERR999I", "Unexpected error", "Details: {0}.", "Please check logs for more information."), + + InternalUnexpectedWarning(ErrorCodesEnum.INTERNALUNEXPECTEDWARNING_ONE_ARGUMENT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.WARN, + "ERR999W", "Unexpected error", "Details: {0}.", "Please check logs for more information."), + + InternalUnexpectedError(ErrorCodesEnum.INTERNALUNEXPECTEDERROR_ONE_ARGUMENT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR999E", "Unexpected error", "Details: {0}.", "Please check logs for more information."), + + InternalUnexpectedFatal(ErrorCodesEnum.INTERNALUNEXPECTEDFATAL_ONE_ARGUMENT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.FATAL, + "ERR999F", "Unexpected error", "Details: {0}.", "Please check logs for more information."), + + ; + + ErrorTypeEnum eType; + AlarmSeverityEnum alarmSeverity; + ErrorCodesEnum messageCode; + ErrorSeverityEnum errorSeverity; + String errorCode; + String errorDescription; + String details; + String resolution; + + AppMessagesEnum(ErrorCodesEnum messageCode, ErrorTypeEnum eType, AlarmSeverityEnum alarmSeverity, ErrorSeverityEnum errorSeverity, String errorCode, String errorDescription, + String details, String resolution) { + this.messageCode = messageCode; + this.eType = eType; + this.alarmSeverity = alarmSeverity; + this.errorSeverity = errorSeverity; + this.errorCode = errorCode; + this.errorDescription = errorDescription; + this.details = details; + this.resolution = resolution; + } + + public String getDetails() { + return this.details; + } + + public String getResolution() { + return this.resolution; + } + public String getErrorCode() { + return this.errorCode; + } + + public String getErrorDescription() { + return this.errorDescription; + } + + public ErrorSeverityEnum getErrorSeverity() { + return this.errorSeverity; + } + + public void setErrorSeverity(ErrorSeverityEnum errorSeverity) { + this.errorSeverity = errorSeverity; + } + + public ErrorCodesEnum getMessageCode() { + return messageCode; + } + + public void setMessageCode(ErrorCodesEnum messageCode) { + this.messageCode = messageCode; + } + + public AlarmSeverityEnum getAlarmSeverity() { + return alarmSeverity; + } + + public void setAlarmSeverity(AlarmSeverityEnum alarmSeverity) { + this.alarmSeverity = alarmSeverity; + } + + public ErrorTypeEnum getErrorType() { + return eType; + } + + public void setErrorType(ErrorTypeEnum eType) { + this.eType = eType; + } +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/format/ApplicationCodes.properties b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/format/ApplicationCodes.properties new file mode 100644 index 00000000..efd9ac24 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/format/ApplicationCodes.properties @@ -0,0 +1,221 @@ +### +# ================================================================================ +# eCOMP Portal SDK +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ================================================================================ +### +######################################################################## +#Resource key=Error Code|Message text|Resolution text |Description text +####### +#Newlines can be utilized to add some clarity ensuring continuing line +#has atleast one leading space +#ResourceKey=\ +# ERR0000E\ +# Sample error msg txt\ +# Sample resolution msg\ +# Sample description txt +# +###### +#Error code classification category +#100 Permission errors +#200 Availability errors/Timeouts +#300 Data errors +#400 Schema Interface type/validation errors +#500 Business process errors +#900 Unknown errors +# +######################################################################## + +#Health check +BEUEBAUTHENTICATIONERROR_ONE_ARGUMENT=\ + ERR100E|\ + Authentication problem towards U-EB server. Reason: {0}.|\ + An Authentication failure occurred during access to UEB server. Please check that UEB keys are configured correctly under fusion.properties file.| + +BERESTAPIAUTHENTICATIONERROR =\ + ERR101E|\ + Rejected an incoming REST API request to {0} from {1} due to invalid credentials.|\ + Please check application credentials defined in Database or portal.properties file.| + +INTERNALAUTHENTICATIONINFO_ONE_ARGUMENT=\ + ERR199I|\ + Internal authentication problem. Description: {0}.| + +INTERNALAUTHENTICATIONWARNING_ONE_ARGUMENT=\ + ERR199W|\ + Internal authentication problem. Description: {0}.| + +INTERNALAUTHENTICATIONERROR_ONE_ARGUMENT=\ + ERR199E|\ + Internal authentication problem. Description: {0}.| + +INTERNALAUTHENTICATIONFATAL_ONE_ARGUMENT=\ + ERR199F|\ + Internal authentication problem. Description: {0}.| + +BEHEALTHCHECKERROR=\ + ERR200E|\ + {0} probably lost connectivity to either one of the following components: MySQL DB, UEB Cluster. Please check the logs for more information.| + +BEHEALTHCHECKMYSQLERROR=\ + ERR201E|\ + {0} probably lost connectivity to MySQL DB. Please check the logs for more information.|\ + Check connectivity to MYSQL is configured correctly under system.properties file.| + +BEHEALTHCHECKUEBCLUSTERERROR=\ + ERR203E|\ + {0} probably lost connectivity to UEB Cluster. Please check the logs for more information.|\ + Check connectivity to UEB cluster which is configured under portal.properties file.| + +BEHEALTHCHECKRECOVERY=\ + ERR205I|\ + {0} Recovery to either one of the following components: MySQL DB, UEB Cluster.| + +BEHEALTHCHECKMYSQLRECOVERY=\ + ERR206I|\ + {0} connection recovery to MySQL DB.| + +BEHEALTHCHECKUEBCLUSTERRECOVERY=\ + ERR208I|\ + {0} connection recovery to UEB Cluster.| + +FEHEALTHCHECKRECOVERY=\ + ERR209I|\ + Connectivity to {0} Server is recovered.| + +#UEB communication +BEUEBCONNECTIONERROR_ONE_ARGUMENT=\ + ERR210E|\ + Connection problem towards U-EB server. Reason: {0}.|\ + Please check that that parameter uebServers in portal.properties points to a valid UEB Cluster.| + +BEUEBSYSTEMERROR=\ + ERR502E|\ + Error occurred during access to U-EB Server. Operation: {0}.|\ + An error occurred in {1} distribution mechanism. Please check the logs for more information.| + +BEUEBUNKOWNHOSTERROR_ONE_ARGUMENT=\ + ERR211E|\ + Connection problem towards U-EB server. Cannot reach host {0}.|\ + Please check that that parameter uebServers in portal.properties points to a valid UEB Cluster.| + +#Onboarding apps +BEUEBREGISTERONBOARDINGAPPERROR=\ + ERR212E|\ + Unable to register the On-boarding application with the U-EB server. Reason: {0}.|\ + Please check that that parameter uebServers in system.properties points to a valid UEB Cluster.| + +#HTTP communication +BEHTTPCONNECTIONERROR_ONE_ARGUMENT=\ + ERR213E|\ + HTTP connection to an external application is failed. Reason: {0}.|\ + Please check the logs for more information.| + +INTERNALCONNECTIONINFO_ONE_ARGUMENT=\ + ERR299I|\ + Internal Connection problem. Description: {0}.| + +INTERNALCONNECTIONWARNING_ONE_ARGUMENT=\ + ERR299W|\ + Internal Connection problem. Description: {0}.| + +INTERNALCONNECTIONERROR_ONE_ARGUMENT=\ + ERR299E|\ + Internal Connection problem. Description: {0}.| + +INTERNALCONNECTIONFATAL_ONE_ARGUMENT=\ + ERR299F|\ + Internal Connection problem. Description: {0}.| + +BEUEBOBJECTNOTFOUNDERROR_ONE_ARGUMENT=\ + ERR303E|\ + Error occurred during access to U-EB Server. Data not found: {0}.|\ + An error occurred during access to UEB Server, {1} failed to either register or unregister to/from UEB topic.| + +#Login error codes +BEUSERMISSINGERROR_ONE_ARGUMENT=\ + ERR310E|\ + User {0} requested is not found.| + +BEUSERINACTIVEWARNING_ONE_ARGUMENT=\ + ERR313W|\ + User {0} is found but inactive.| + +BEUSERADMINPRIVILEGESINFO_ONE_ARGUMENT=\ + ERR314W|\ + User {0} is found but don't have administrative privileges.| + +BEINVALIDJSONINPUT=\ + ERR405E|\ + Failed to convert JSON input to object.|\ + Please check error logs for more information.| + +BEINCORRECTHTTPSTATUSERROR=\ + ERR407E|\ + Incorrect HttpResponse Received.|\ + Please check error & metrics logs for more information.| + +BEINITIALIZATIONERROR=\ + ERR500E|\ + BE was not initialized properly.| + +BEDAOSYSTEMERROR=\ + ERR505E|\ + Operation towards database failed.|\ + Please check MySQL DB health or look at the logs for more details.| + +BESYSTEMERROR=\ + ERR506E|\ + Unexpected error during operation.| + +BEEXECUTEROLLBACKERROR=\ + ERR507E|\ + Roll-back operation towards database failed.|\ + Please check MYSQL DB health or look at the logs for more details.| + +FEHTTPLOGGINGERROR=\ + ERR517E|\ + Error when logging FE HTTP request/response.| + +BEDAOCLOSESESSIONERROR=\ + ERR519E|\ + Close local session operation with database failed.|\ + Please check MYSQL DB health or look at the logs form more details.| + +BERESTAPIGENERALERROR=\ + ERR900E|\ + Unexpected error during BE REST API execution.|\ + Please check error log for more information.| + +FEHEALTHCHECKGENERALERROR=\ + ERR901E|\ + General error during FE Health Check.| + +INTERNALUNEXPECTEDINFO_ONE_ARGUMENT=\ + ERR999I|\ + Unexpected error. Description: {0}.| + +INTERNALUNEXPECTEDWARNING_ONE_ARGUMENT=\ + ERR999W|\ + Unexpected error. Description: {0}.| + +INTERNALUNEXPECTEDERROR_ONE_ARGUMENT=\ + ERR999E|\ + Unexpected error. Description: {0}.| + +INTERNALUNEXPECTEDFATAL_ONE_ARGUMENT=\ + ERR999F|\ + Unexpected error. Description: {0}.| diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/format/AuditLogFormatter.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/format/AuditLogFormatter.java new file mode 100644 index 00000000..2cb336e2 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/format/AuditLogFormatter.java @@ -0,0 +1,106 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.logging.format; + +import java.text.MessageFormat; +import java.util.Map; + +import org.openecomp.portalsdk.core.util.SystemProperties; + +public class AuditLogFormatter { + //Singleton + private static AuditLogFormatter instance = new AuditLogFormatter(); + + public static AuditLogFormatter getInstance() { + + return instance; + } + + public String createMessage(String protocol,String set, + String loginId, String message) { + + Object[] securityMessageArgs = prepareFormatArgs( + protocol, + set, + loginId, + message ); + + return MessageFormat.format(SystemProperties.SECURITY_LOG_TEMPLATE, securityMessageArgs); + } + + /** + * A method for normalizing the security log field - returns + * the @Param defaultValue in case the entry is null or empty. + * If the @param entry is not empty, a single quotation is added to it. + * + * @param entry the entry + * @param defaultValue The default value in case the entry is empty + * @return String (formatted) + */ + private String formatEntry(Object entry, String defaultValue) { + return (entry!=null && !entry.toString().isEmpty()) ? addSingleQuotes(entry.toString()): defaultValue; + + } + + private String addSingleQuotes(String s) { + if (null!=s && !s.isEmpty()) { + s = SystemProperties.SINGLE_QUOTE+s+SystemProperties.SINGLE_QUOTE; + } + return s; + } + + + /** + * This method prepares an Object array of arguments that would be passed + * to the MessageFormat.format() method, to format the security log. + * + * @param protocol + * @param set + * @param loginId + * @param accessingClient + * @param isSuccess + * @param message + * @return + */ + private Object[] prepareFormatArgs(String protocol,String set, + String loginId, String message) { + + Object[] messageFormatArgs = { + formatEntry(protocol, SystemProperties.NA), + formatEntry(set, SystemProperties.NA), + formatEntry(loginId, SystemProperties.UNKNOWN), + message + }; + return messageFormatArgs; + } + + + public String createMessage(Map<String, String> logArgsMap) { + + Object[] securityMessageArgs = prepareFormatArgs( + logArgsMap.get(SystemProperties.PROTOCOL), + logArgsMap.get(SystemProperties.SECURIRY_EVENT_TYPE), + logArgsMap.get(SystemProperties.LOGIN_ID), + logArgsMap.get(SystemProperties.ADDITIONAL_INFO) + ); + + return MessageFormat.format(SystemProperties.SECURITY_LOG_TEMPLATE, securityMessageArgs); + } +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/format/ErrorCodesEnum.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/format/ErrorCodesEnum.java new file mode 100644 index 00000000..549d3262 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/format/ErrorCodesEnum.java @@ -0,0 +1,89 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.logging.format; + +import com.att.eelf.i18n.EELFResolvableErrorEnum; +//import com.att.eelf.i18n.EELFResourceManager; + +public enum ErrorCodesEnum implements EELFResolvableErrorEnum { + BERESTAPIAUTHENTICATIONERROR, + BEHTTPCONNECTIONERROR_ONE_ARGUMENT, + BEUEBAUTHENTICATIONERROR_ONE_ARGUMENT, + + INTERNALAUTHENTICATIONINFO_ONE_ARGUMENT, + INTERNALAUTHENTICATIONWARNING_ONE_ARGUMENT, + INTERNALAUTHENTICATIONERROR_ONE_ARGUMENT, + INTERNALAUTHENTICATIONFATAL_ONE_ARGUMENT, + + BEHEALTHCHECKRECOVERY, + BEHEALTHCHECKMYSQLRECOVERY, + BEHEALTHCHECKUEBCLUSTERRECOVERY, + FEHEALTHCHECKRECOVERY, + BeHEALTHCHECKERROR, + + BEHEALTHCHECKMYSQLERROR, + BEHEALTHCHECKUEBCLUSTERERROR, + FEHEALTHCHECKERROR, + BEUEBCONNECTIONERROR_ONE_ARGUMENT, + BEUEBUNKOWNHOSTERROR_ONE_ARGUMENT, + BEUEBREGISTERONBOARDINGAPPERROR, + + INTERNALCONNECTIONINFO_ONE_ARGUMENT, + INTERNALCONNECTIONWARNING_ONE_ARGUMENT, + INTERNALCONNECTIONERROR_ONE_ARGUMENT, + INTERNALCONNECTIONFATAL_ONE_ARGUMENT, + + BEUEBOBJECTNOTFOUNDERROR_ONE_ARGUMENT, + BEUSERMISSINGERROR_ONE_ARGUMENT, + + BEUSERINACTIVEWARNING_ONE_ARGUMENT, + BEUSERADMINPRIVILEGESINFO_ONE_ARGUMENT, + + BEINVALIDJSONINPUT, + BEINCORRECTHTTPSTATUSERROR, + + BEINITIALIZATIONERROR, + BEUEBSYSTEMERROR, + BEDAOSYSTEMERROR, + BESYSTEMERROR, + BEEXECUTEROLLBACKERROR, + + FEHTTPLOGGINGERROR, + FEPORTALSERVLETERROR, + BEDAOCLOSESESSIONERROR, + + BERESTAPIGENERALERROR, + FEHEALTHCHECKGENERALERROR, + + INTERNALUNEXPECTEDINFO_ONE_ARGUMENT, + INTERNALUNEXPECTEDWARNING_ONE_ARGUMENT, + INTERNALUNEXPECTEDERROR_ONE_ARGUMENT, + INTERNALUNEXPECTEDFATAL_ONE_ARGUMENT, + + ; + + /** + * Static initializer to ensure the resource bundles for this class are loaded... + * Here this application loads messages from three bundles + */ + //static { + // EELFResourceManager.loadMessageBundle("com/att/fusion/core/logging/format/ApplicationCodes"); + //} +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/format/ErrorSeverityEnum.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/format/ErrorSeverityEnum.java new file mode 100644 index 00000000..5908fda9 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/format/ErrorSeverityEnum.java @@ -0,0 +1,27 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.logging.format; + +public enum ErrorSeverityEnum { + INFO, + WARN, + ERROR, + FATAL, +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/format/ErrorTypeEnum.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/format/ErrorTypeEnum.java new file mode 100644 index 00000000..8ce2d4dc --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/format/ErrorTypeEnum.java @@ -0,0 +1,29 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.logging.format; + +public enum ErrorTypeEnum { + RECOVERY, + CONFIG_ERROR, + SYSTEM_ERROR, + DATA_ERROR, + CONNECTION_PROBLEM, + AUTHENTICATION_PROBLEM +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/logic/EELFLoggerDelegate.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/logic/EELFLoggerDelegate.java new file mode 100644 index 00000000..319caf3c --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/logging/logic/EELFLoggerDelegate.java @@ -0,0 +1,484 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.logging.logic; + +import static com.att.eelf.configuration.Configuration.MDC_ALERT_SEVERITY; +import static com.att.eelf.configuration.Configuration.MDC_INSTANCE_UUID; +import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID; +import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN; +import static com.att.eelf.configuration.Configuration.MDC_SERVER_IP_ADDRESS; +import static com.att.eelf.configuration.Configuration.MDC_SERVICE_INSTANCE_ID; +import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME; + +import java.net.InetAddress; +import java.text.MessageFormat; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +import javax.servlet.http.HttpServletRequest; + +import org.openecomp.portalsdk.core.domain.User; +import org.openecomp.portalsdk.core.logging.aspect.EELFLoggerAdvice; +import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum; +import org.openecomp.portalsdk.core.logging.format.AppMessagesEnum; +import org.openecomp.portalsdk.core.logging.format.ErrorSeverityEnum; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.slf4j.MDC; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.configuration.SLF4jWrapper; + +public class EELFLoggerDelegate extends SLF4jWrapper implements EELFLogger { + + public static EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger(); + public static EELFLogger applicationLogger = EELFManager.getInstance().getApplicationLogger(); + public static EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger(); + public static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); + public static EELFLogger debugLogger = EELFManager.getInstance().getDebugLogger(); + private String className; + private static ConcurrentMap<String, EELFLoggerDelegate> classMap = new ConcurrentHashMap<String, EELFLoggerDelegate>(); + + public EELFLoggerDelegate(String _className) { + super(_className); + className = _className; + } + + /** + * Convenience method that gets a logger for the specified class. + * + * @see #getLogger(String) + * + * @param clazz + * @return Instance of EELFLoggerDelegate + */ + public static EELFLoggerDelegate getLogger(Class<?> clazz) { + return getLogger(clazz.getName()); + } + + /** + * Gets a logger for the specified class name. If the logger does not + * already exist in the map, this creates a new logger. + * + * @param className + * If null or empty, uses EELFLoggerDelegate as the class name. + * @return Instance of EELFLoggerDelegate + */ + public static EELFLoggerDelegate getLogger(String className) { + if (className == null || className == "") + className = EELFLoggerDelegate.class.getName(); + EELFLoggerDelegate delegate = classMap.get(className); + if (delegate == null) { + delegate = new EELFLoggerDelegate(className); + classMap.put(className, delegate); + } + return delegate; + } + + /** + * Logs a message at the lowest level: trace. + * + * @param logger + * @param msg + */ + public void trace(EELFLogger logger, String msg) { + if (logger.isTraceEnabled()) { + MDC.put(SystemProperties.MDC_CLASS_NAME, className); + logger.trace(msg); + MDC.remove(SystemProperties.MDC_CLASS_NAME); + } + } + + /** + * Logs a message with parameters at the lowest level: trace. + * + * @param logger + * @param msg + * @param arguments + */ + public void trace(EELFLogger logger, String msg, Object... arguments) { + if (logger.isTraceEnabled()) { + MDC.put(SystemProperties.MDC_CLASS_NAME, className); + logger.trace(msg, arguments); + MDC.remove(SystemProperties.MDC_CLASS_NAME); + } + } + + /** + * Logs a message and throwable at the lowest level: trace. + * + * @param logger + * @param msg + * @param th + */ + public void trace(EELFLogger logger, String msg, Throwable th) { + if (logger.isTraceEnabled()) { + MDC.put(SystemProperties.MDC_CLASS_NAME, className); + logger.trace(msg, th); + MDC.remove(SystemProperties.MDC_CLASS_NAME); + } + } + + /** + * Logs a message at the second-lowest level: debug. + * + * @param logger + * @param msg + */ + public void debug(EELFLogger logger, String msg) { + if (logger.isDebugEnabled()) { + MDC.put(SystemProperties.MDC_CLASS_NAME, className); + logger.debug(msg); + MDC.remove(SystemProperties.MDC_CLASS_NAME); + } + } + + /** + * Logs a message with parameters at the second-lowest level: debug. + * + * @param logger + * @param msg + * @param arguments + */ + public void debug(EELFLogger logger, String msg, Object... arguments) { + if (logger.isDebugEnabled()) { + MDC.put(SystemProperties.MDC_CLASS_NAME, className); + logger.debug(msg, arguments); + MDC.remove(SystemProperties.MDC_CLASS_NAME); + } + } + + /** + * Logs a message and throwable at the second-lowest level: debug. + * + * @param logger + * @param msg + * @param th + */ + public void debug(EELFLogger logger, String msg, Throwable th) { + if (logger.isDebugEnabled()) { + MDC.put(SystemProperties.MDC_CLASS_NAME, className); + logger.debug(msg, th); + MDC.remove(SystemProperties.MDC_CLASS_NAME); + } + } + + /** + * Logs a message at info level. + * + * @param logger + * @param msg + */ + public void info(EELFLogger logger, String msg) { + MDC.put(SystemProperties.MDC_CLASS_NAME, className); + logger.info(msg); + MDC.remove(SystemProperties.MDC_CLASS_NAME); + } + + /** + * Logs a message with parameters at info level. + * + * @param logger + * @param msg + * @param arguments + */ + public void info(EELFLogger logger, String msg, Object... arguments) { + MDC.put(SystemProperties.MDC_CLASS_NAME, className); + logger.info(msg, arguments); + MDC.remove(SystemProperties.MDC_CLASS_NAME); + } + + /** + * Logs a message and throwable at info level. + * + * @param logger + * @param msg + * @param th + */ + public void info(EELFLogger logger, String msg, Throwable th) { + MDC.put(SystemProperties.MDC_CLASS_NAME, className); + logger.info(msg, th); + MDC.remove(SystemProperties.MDC_CLASS_NAME); + } + + /** + * Logs a message at warn level. + * + * @param logger + * @param msg + */ + public void warn(EELFLogger logger, String msg) { + MDC.put(SystemProperties.MDC_CLASS_NAME, className); + logger.warn(msg); + MDC.remove(SystemProperties.MDC_CLASS_NAME); + } + + /** + * Logs a message with parameters at warn level. + * + * @param logger + * @param msg + * @param arguments + */ + public void warn(EELFLogger logger, String msg, Object... arguments) { + MDC.put(SystemProperties.MDC_CLASS_NAME, className); + logger.warn(msg, arguments); + MDC.remove(SystemProperties.MDC_CLASS_NAME); + } + + /** + * Logs a message and throwable at warn level. + * + * @param logger + * @param msg + * @param th + */ + public void warn(EELFLogger logger, String msg, Throwable th) { + MDC.put(SystemProperties.MDC_CLASS_NAME, className); + logger.warn(msg, th); + MDC.remove(SystemProperties.MDC_CLASS_NAME); + } + + /** + * Logs a message at error level. + * + * @param logger + * @param msg + */ + public void error(EELFLogger logger, String msg) { + MDC.put(SystemProperties.MDC_CLASS_NAME, className); + logger.error(msg); + MDC.remove(SystemProperties.MDC_CLASS_NAME); + } + + /** + * Logs a message with parameters at error level. + * + * @param logger + * @param msg + * @param arguments + */ + public void error(EELFLogger logger, String msg, Object... arguments) { + MDC.put(SystemProperties.MDC_CLASS_NAME, className); + logger.warn(msg, arguments); + MDC.remove(SystemProperties.MDC_CLASS_NAME); + } + + /** + * Logs a message and throwable at error level. + * + * @param logger + * @param msg + * @param th + */ + public void error(EELFLogger logger, String msg, Throwable th) { + MDC.put(SystemProperties.MDC_CLASS_NAME, className); + logger.warn(msg, th); + MDC.remove(SystemProperties.MDC_CLASS_NAME); + } + + /** + * Logs a message with the associated alarm severity at error level. + * + * @param logger + * @param msg + * @param severtiy + */ + public void error(EELFLogger logger, String msg, AlarmSeverityEnum severtiy) { + MDC.put(MDC_ALERT_SEVERITY, severtiy.name()); + MDC.put(SystemProperties.MDC_CLASS_NAME, className); + logger.error(msg); + MDC.remove(MDC_ALERT_SEVERITY); + MDC.remove(SystemProperties.MDC_CLASS_NAME); + } + + /** + * Initializes the logger context. + */ + public void init() { + setGlobalLoggingContext(); + final String msg = "############################ Logging is started. ############################"; + // These loggers emit the current date-time without being told. + info(applicationLogger, msg); + error(errorLogger, msg); + debug(debugLogger, msg); + // Audit and metrics logger must be told start AND stop times + final String currentDateTime = EELFLoggerAdvice.getCurrentDateTimeUTC(); + // Set the MDC with audit properties + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, currentDateTime); + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, currentDateTime); + info(auditLogger, msg); + MDC.remove(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP); + MDC.remove(SystemProperties.AUDITLOG_END_TIMESTAMP); + // Set the MDC with metrics properties + MDC.put(SystemProperties.METRICSLOG_BEGIN_TIMESTAMP, currentDateTime); + MDC.put(SystemProperties.METRICSLOG_END_TIMESTAMP, currentDateTime); + info(metricsLogger, msg); + MDC.remove(SystemProperties.METRICSLOG_BEGIN_TIMESTAMP); + MDC.remove(SystemProperties.METRICSLOG_END_TIMESTAMP); + } + + /** + * Logs a standard message identified by the specified enum, using the + * specified parameters, at error level. Alarm and error severity are taken + * from the specified enum argument. + * + * @param epMessageEnum + * @param param + */ + public void logEcompError(AppMessagesEnum epMessageEnum, String... param) { + try { + AlarmSeverityEnum alarmSeverityEnum = epMessageEnum.getAlarmSeverity(); + ErrorSeverityEnum errorSeverityEnum = epMessageEnum.getErrorSeverity(); + + MDC.put(MDC_ALERT_SEVERITY, alarmSeverityEnum.name()); + MDC.put("ErrorCode", epMessageEnum.getErrorCode()); + MDC.put("ErrorDescription", epMessageEnum.getErrorDescription()); + + String resolution = this.formatMessage(epMessageEnum.getDetails() + " " + epMessageEnum.getResolution(), + (Object[]) param); + if (errorSeverityEnum == ErrorSeverityEnum.WARN) { + errorLogger.warn(resolution); + } else if (errorSeverityEnum == ErrorSeverityEnum.INFO) { + errorLogger.info(resolution); + } else { + errorLogger.error(resolution); + } + } catch (Exception e) { + errorLogger.error("Failed to log the error code. Details: " + UserUtils.getStackTrace(e)); + } finally { + MDC.remove("ErrorCode"); + MDC.remove("ErrorDescription"); + MDC.remove(MDC_ALERT_SEVERITY); + } + } + + /** + * Builds a message using a template string and the arguments. + * + * @param message + * @param args + * @return + */ + private String formatMessage(String message, Object... args) { + StringBuilder sbFormattedMessage = new StringBuilder(); + if (args != null && args.length > 0 && message != null && message != "") { + MessageFormat mf = new MessageFormat(message); + sbFormattedMessage.append(mf.format(args)); + } else { + sbFormattedMessage.append(message); + } + + return sbFormattedMessage.toString(); + } + + /** + * Loads all the default logging fields into the MDC context. + */ + private void setGlobalLoggingContext() { + MDC.put(MDC_SERVICE_INSTANCE_ID, ""); + MDC.put(MDC_ALERT_SEVERITY, AlarmSeverityEnum.INFORMATIONAL.toString()); + try { + MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName()); + MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress()); + MDC.put(MDC_INSTANCE_UUID, SystemProperties.getProperty(SystemProperties.INSTANCE_UUID)); + } catch (Exception e) { + } + } + + public static void mdcPut(String key, String value) { + MDC.put(key, value); + } + + public static String mdcGet(String key) { + return MDC.get(key); + } + + public static void mdcRemove(String key) { + MDC.remove(key); + } + + /** + * Loads the RequestId/TransactionId into the MDC which it should be + * receiving with an each incoming REST API request. Also, configures few + * other request based logging fields into the MDC context. + * + * @param req + * @param appName + */ + public void setRequestBasedDefaultsIntoGlobalLoggingContext(HttpServletRequest req, String appName) { + // Load the default fields + setGlobalLoggingContext(); + + // Load the request based fields + if (req != null) { + // Load the Request into MDC context. + String requestId = UserUtils.getRequestId(req); + MDC.put(MDC_KEY_REQUEST_ID, requestId); + + // Load user agent into MDC context, if available. + String accessingClient = "Unknown"; + accessingClient = req.getHeader(SystemProperties.USERAGENT_NAME); + if (accessingClient != null && accessingClient != "" && (accessingClient.contains("Mozilla") + || accessingClient.contains("Chrome") || accessingClient.contains("Safari"))) { + accessingClient = appName + "_FE"; + } + MDC.put(SystemProperties.PARTNER_NAME, accessingClient); + + // Protocol, Rest URL & Rest Path + String restURL = ""; + MDC.put(SystemProperties.FULL_URL, SystemProperties.UNKNOWN); + MDC.put(SystemProperties.PROTOCOL, SystemProperties.HTTP); + restURL = UserUtils.getFullURL(req); + if (restURL != null && restURL != "") { + MDC.put(SystemProperties.FULL_URL, restURL); + if (restURL.toLowerCase().contains("https")) { + MDC.put(SystemProperties.PROTOCOL, SystemProperties.HTTPS); + } + } + + // Rest Path + MDC.put(MDC_SERVICE_NAME, req.getServletPath()); + + // Client IPAddress i.e. IPAddress of the remote host who is making + // this request. + String clientIPAddress = ""; + clientIPAddress = req.getHeader("X-FORWARDED-FOR"); + if (clientIPAddress == null) { + clientIPAddress = req.getRemoteAddr(); + } + MDC.put(SystemProperties.CLIENT_IP_ADDRESS, clientIPAddress); + + // Load loginId into MDC context. + MDC.put(SystemProperties.MDC_LOGIN_ID, "Unknown"); + + String loginId = ""; + User user = UserUtils.getUserSession(req); + if (user != null) { + loginId = user.getLoginId(); + } + + if (loginId != null && loginId != "") { + MDC.put(SystemProperties.MDC_LOGIN_ID, loginId); + } + } + } +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/menu/MenuBuilder.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/menu/MenuBuilder.java new file mode 100644 index 00000000..d856e7ee --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/menu/MenuBuilder.java @@ -0,0 +1,163 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.menu; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import javax.servlet.http.HttpServletRequest; + +import org.openecomp.portalsdk.core.FusionObject; +import org.openecomp.portalsdk.core.domain.MenuData; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.beans.factory.annotation.Autowired; + +@SuppressWarnings("rawtypes") +public class MenuBuilder implements FusionObject { + + @Autowired + private DataAccessService dataAccessService; + + public MenuBuilder() { + } + + @SuppressWarnings("unchecked") + public Set getMenu(String menuSetName, DataAccessService dataAccessService) { + + Set menu = null; + MenuData root = null; + + HashMap params = new HashMap(); + + params.put("menu_set_cd", menuSetName); + + // execute a query of the latest configuration of the FN_MENU table for the given menu_set_cd. + List menuItems = dataAccessService.executeNamedQuery(SystemProperties.getProperty(SystemProperties.MENU_QUERY_NAME), params, null); + + Iterator i = menuItems.iterator(); + if (i.hasNext()) { + root = (MenuData)i.next(); + menu = root.getChildMenus(); + } + + return menu; + } + + @SuppressWarnings("unchecked") + public Set getMenu(String menuSetName) { + + Set menu = null; + MenuData root = null; + + HashMap params = new HashMap(); + + params.put("menu_set_cd", menuSetName); + + // execute a query of the latest configuration of the FN_MENU table for the given menu_set_cd. + List menuItems = getDataAccessService().executeNamedQuery(SystemProperties.getProperty(SystemProperties.MENU_QUERY_NAME), params, null); + + Iterator i = menuItems.iterator(); + if (i.hasNext()) { + root = (MenuData)i.next(); + menu = root.getChildMenus(); + } + + return menu; + } + + public static Set filterMenu(Set menus, HttpServletRequest request) { + Iterator j = menus.iterator(); + + while (j.hasNext()) { + MenuData menuItem = (MenuData)j.next(); + + if (!UserUtils.isAccessible(request, menuItem.getFunctionCd())) { + // remove the menu if the user doesn't have access to it + j.remove(); + } + else { + // if an accessible menu has a child menu, let's filter that recursively + + Set childMenus = menuItem.getChildMenus(); + if (childMenus != null && childMenus.size() > 0) { + filterMenu(childMenus, request); + } + + } + } + + return menus; + } + + + public static String getUrlHtml(MenuData menuData) { + String html = ""; + + if (menuData.getExternalUrl() != null && menuData.getExternalUrl().length() > 0) { + html = menuData.getExternalUrl(); + } + else if (menuData.getServlet() != null && menuData.getServlet().length() > 0) { + html = "/" + menuData.getServlet(); + } + else if (menuData.getAction() != null && menuData.getAction().length() > 0) { + html = "/" + menuData.getAction(); + } + + return html; + } + + + public static String getTargetHtml(MenuData menuData) { + String html = ""; + + if (menuData.getTarget() != null && menuData.getTarget().length() > 0) { + html = "target=\"" + menuData.getTarget() + "\""; + } + + return html; + } + + + public static String getQueryStringHtml(MenuData menuData) { + String html = ""; + + if (menuData.getQueryString() != null && menuData.getQueryString().length() > 0) { + html = "?" + menuData.getQueryString(); + } + + return html; + } + + public DataAccessService getDataAccessService() { + return dataAccessService; + } + + + public void setDataAccessService(DataAccessService dataAccessService) { + this.dataAccessService = dataAccessService; + } + +} + + diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/menu/MenuProperties.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/menu/MenuProperties.java new file mode 100644 index 00000000..e55baeb4 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/menu/MenuProperties.java @@ -0,0 +1,114 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.menu; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Properties; + +import javax.servlet.ServletContext; + +import org.openecomp.portalsdk.core.util.SystemProperties; + + +/* + MenuProperties contains a list of constants used during the creation, + privilege screening, and rendering of the application menu. +*/ +public class MenuProperties { + private MenuProperties() { + // cannot instantiate + } + + @SuppressWarnings("rawtypes") + private static HashMap menuProperties = new HashMap(); + + // keys used to reference values in the menu.properties file + public static final String WIDTH = "width"; + public static final String LEFT_POSITION = "left_position"; + public static final String TOP_POSITION = "top_position"; + public static final String FONT_COLOR = "font_color"; + public static final String MOUSEOVER_FONT_COLOR = "mouseover_font_color"; + public static final String BACKGROUND_COLOR = "background_color"; + public static final String MOUSEOVER_BACKGROUND_COLOR = "mouseover_background_color"; + public static final String BORDER_COLOR = "border_color"; + public static final String SEPARATOR_COLOR = "separator_color"; + public static final String IMAGE_SRC = "image_src"; + public static final String IMAGE_SRC_LEFT = "image_src_left"; + public static final String IMAGE_SRC_OVER = "image_src_over"; + public static final String IMAGE_SRC_LEFT_OVER = "image_src_left_over"; + public static final String EVALUATE_UPON_TREE_SHOW = "evaluate_upon_tree_show"; + public static final String EVALUATE_UPON_TREE_HIDE = "evaluate_upon_tree_hide"; + public static final String TOP_IS_PERMANENT = "top_is_permanent"; + public static final String TOP_IS_HORIZONTAL = "top_is_horizontal"; + public static final String TREE_IS_HORIZONTAL = "tree_is_horizontal"; + public static final String POSITION_UNDER = "position_under"; + public static final String TOP_MORE_IMAGES_VISIBLE = "top_more_images_visible"; + public static final String TREE_MORE_IMAGES_VISIBLE = "tree_more_images_visible"; + public static final String RIGHT_TO_LEFT = "right_to_left"; + public static final String DISPLAY_ON_CLICK = "display_on_click"; + public static final String TOP_IS_VARIABLE_WIDTH = "top_is_variable_width"; + public static final String TREE_IS_VARIABLE_WIDTH = "tree_is_variable_width"; + public static final String TOP_KEEP_IN_WINDOW_X = "top_keep_in_window_x"; + public static final String TOP_KEEP_IN_WINDOW_Y = "top_keep_in_window_y"; + public static final String MENU_ID_ADMIN = "menu_id_admin"; + public static final String MENU_ID_LOGOUT = "menu_id_logout"; + public static final String MENU_FRAME = "menu_frame"; + public static final String MAIN_FRAME = "main_frame"; + public static final String NESTED_MAIN_FRAME = "nested_main_frame"; + public static final String ROLE_FUNCTIONS_TAG = "role_functions_tag"; + + public static final String MAX_DISPLAYABLE_ADMIN_MENU_SORT_ORDER = "max_displayable_admin_menu_sort_order"; + public static final String MENU_PROPERTIES_FILENAME_KEY = "menu_properties_filename"; + public static final String DEFAULT_SERVLET_NAME = "dispatcher"; + public static final String DEFAULT_TARGET = "_self"; + + public static final String TOP_MENU_CLASS = "top_menu_class"; + public static final String TOP_MENU_LINK_CLASS = "top_menu_link_class"; + + public static final String ON_MOUSE_OUT_TRAILER = "on_mouse_out_trailer"; + public static final String ON_MOUSE_OVER_TRAILER = "on_mouse_over_trailer"; + public static final String ON_CLICK_TRAILER = "on_click_trailer"; + + public static final String MENU_ID_PREFIX = "menu_id_prefix"; + + + @SuppressWarnings("unchecked") + public static void loadFromFile(ServletContext servletContext, String filename, String menuSetName) throws IOException { + Properties p = new Properties(); + + if (filename == null) { + filename = SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_PROPERTIES_NAME); + } + + p.load(servletContext.getResourceAsStream(SystemProperties.getProperty(SystemProperties.MENU_PROPERTIES_FILE_LOCATION) + filename)); + menuProperties.put(menuSetName, p); + } // loadMenuProperties + + public static String getProperty(String key) { + return getProperty(key, SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_SET_NAME)); + } + + public static String getProperty(String key, String menuSetName) { + Properties p = (Properties)menuProperties.get(menuSetName); + return p.getProperty(key); + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/objectcache/AbstractCacheManager.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/objectcache/AbstractCacheManager.java new file mode 100644 index 00000000..7c553ad5 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/objectcache/AbstractCacheManager.java @@ -0,0 +1,60 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.objectcache; + +import java.io.*; + +import org.openecomp.portalsdk.core.objectcache.support.*; + + +public abstract class AbstractCacheManager implements FusionCacheManager { + public AbstractCacheManager() { + super(); + // TODO Auto-generated constructor stub + } + + public Object getObject(String key) { + // TODO Auto-generated method stub + return null; + } + + public void putObject(String key, Object objectToCache) { + // TODO Auto-generated method stub + } + + public boolean isObjectInCache(String key) { + // TODO Auto-generated method stub + return false; + } + + public void removeObject(String key) { + // TODO Auto-generated method stub + } + + public void clearCache() { + // TODO Auto-generated method stub + } + + public void configure() throws IOException { + // TODO Auto-generated method stub + + } +} + diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/objectcache/jcs/JCSCacheEventHandler.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/objectcache/jcs/JCSCacheEventHandler.java new file mode 100644 index 00000000..0695876f --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/objectcache/jcs/JCSCacheEventHandler.java @@ -0,0 +1,60 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.objectcache.jcs; + +import org.apache.jcs.engine.control.event.behavior.IElementEvent; +import org.apache.jcs.engine.control.event.behavior.IElementEventConstants; +import org.apache.jcs.engine.control.event.behavior.IElementEventHandler; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; + +public class JCSCacheEventHandler implements IElementEventHandler, IElementEventConstants { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JCSCacheEventHandler.class); + + public JCSCacheEventHandler() { + super(); + } + + public void handleElementEvent(IElementEvent event) { + // Handle code for various event notifications on cached elements by JCS. + switch (event.getElementEvent()) { + case ELEMENT_EVENT_EXCEEDED_MAXLIFE_BACKGROUND: + logger.error(EELFLoggerDelegate.errorLogger, "Event ELEMENT_EVENT_EXCEEDED_MAXLIFE_BACKGROUND occurred for element " + event); + break; + case ELEMENT_EVENT_EXCEEDED_MAXLIFE_ONREQUEST: + logger.error(EELFLoggerDelegate.errorLogger, "Event ELEMENT_EVENT_EXCEEDED_MAXLIFE_ONREQUEST occurred for element " + event); + break; + case ELEMENT_EVENT_EXCEEDED_IDLETIME_BACKGROUND: + logger.error(EELFLoggerDelegate.errorLogger, "Event ELEMENT_EVENT_EXCEEDED_IDLETIME_BACKGROUND occurred for element " + event); + break; + case ELEMENT_EVENT_EXCEEDED_IDLETIME_ONREQUEST: + logger.error(EELFLoggerDelegate.errorLogger, "Event ELEMENT_EVENT_EXCEEDED_IDLETIME_ONREQUEST occurred for element " + event); + break; + case ELEMENT_EVENT_SPOOLED_DISK_AVAILABLE: + logger.error(EELFLoggerDelegate.errorLogger, "Event ELEMENT_EVENT_SPOOLED_DISK_AVAILABLE occurred for element " + event); + break; + case ELEMENT_EVENT_SPOOLED_DISK_NOT_AVAILABLE: + logger.error(EELFLoggerDelegate.errorLogger, "Event ELEMENT_EVENT_SPOOLED_DISK_NOT_AVAILABLE occurred for element " + event); + break; + case ELEMENT_EVENT_SPOOLED_NOT_ALLOWED: + logger.error(EELFLoggerDelegate.errorLogger, "Event ELEMENT_EVENT_SPOOLED_NOT_ALLOWED occurred for element " + event); + } + } +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/objectcache/jcs/JCSCacheManager.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/objectcache/jcs/JCSCacheManager.java new file mode 100644 index 00000000..39b3f0cb --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/objectcache/jcs/JCSCacheManager.java @@ -0,0 +1,186 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.objectcache.jcs; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; +import java.util.Vector; + +import javax.annotation.PostConstruct; +import javax.servlet.ServletContext; + +import org.apache.jcs.JCS; +import org.apache.jcs.access.exception.CacheException; +import org.apache.jcs.engine.CacheConstants; +import org.apache.jcs.engine.behavior.IElementAttributes; +import org.apache.jcs.engine.control.CompositeCacheManager; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.objectcache.AbstractCacheManager; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.web.context.ServletContextAware; + +public abstract class JCSCacheManager extends AbstractCacheManager implements CacheConstants, ServletContextAware { + + public static String LOOKUP_OBJECT_CACHE_NAME = "lookUpObjectCache"; + public static String JCS_CONFIG_FILE_PATH = "cache_config_file_path"; + public static String CACHE_LOAD_ON_STARTUP = "cache_load_on_startup"; + public static String CACHE_PROPERTY_VALUE_TRUE = "true"; + public static String CACHE_CONTROL_SWITCH_ON = "1"; + public static String CACHE_CONTROL_SWITCH_OFF = "0"; + public static String CACHE_CONTROL_SWITCH = "cache_switch"; + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JCSCacheManager.class); + + private static JCS lookUpCache; + private ServletContext servletContext; + + private Properties cacheConfigProperties = null; + private final Vector<String> jscManagedCacheList = new Vector<String>(); + + private DataAccessService dataAccessService; + + public JCSCacheManager() { + super(); + jscManagedCacheList.add(LOOKUP_OBJECT_CACHE_NAME); + } + + @PostConstruct + public void configure() throws IOException { + super.configure(); + + String jcsConfigFilePath = SystemProperties.getProperty(JCS_CONFIG_FILE_PATH); + // getProperty throws if the key is missing; but check anyhow. + if (jcsConfigFilePath == null || jcsConfigFilePath.length() == 0) + throw new IOException("configure: failed to get value for config property " + JCS_CONFIG_FILE_PATH); + InputStream jcsConfigInputStream = getServletContext().getResourceAsStream(jcsConfigFilePath); + if (jcsConfigInputStream == null) + throw new IOException("configure: failed to open stream for config property " + JCS_CONFIG_FILE_PATH + + " with name " + jcsConfigFilePath); + logger.debug(EELFLoggerDelegate.debugLogger, + "configure: loading cache properties from classpath resource {} ", jcsConfigFilePath); + Properties p = new Properties(); + p.load(jcsConfigInputStream); + jcsConfigInputStream.close(); + + CompositeCacheManager ccm = CompositeCacheManager.getUnconfiguredInstance(); + ccm.configure(p); + setCacheConfigProperties(p); + + try { + initializeLookUpCache(); + } catch (CacheException ce) { + throw new IOException("configure: failed to initialize lookup cache", ce); + } + + } + + private void initializeLookUpCache() throws CacheException { + lookUpCache = JCS.getInstance(LOOKUP_OBJECT_CACHE_NAME); + + JCSCacheEventHandler eventHandler = new JCSCacheEventHandler(); + IElementAttributes elementAttributes = lookUpCache.getDefaultElementAttributes(); + + elementAttributes.addElementEventHandler(eventHandler); + + lookUpCache.setDefaultElementAttributes(elementAttributes); + + if (CACHE_PROPERTY_VALUE_TRUE.equalsIgnoreCase(SystemProperties.getProperty(CACHE_LOAD_ON_STARTUP))) { + loadDataOnStartUp(); + } + } + + public Object getObject(String key) { + if (CACHE_CONTROL_SWITCH_ON.equalsIgnoreCase(SystemProperties.getProperty(CACHE_CONTROL_SWITCH))) { + if (lookUpCache == null) + return null; + else + return lookUpCache.get(key); + } else + return null; + } + + public void putObject(String key, Object objectToCache) { + try { + if (CACHE_CONTROL_SWITCH_ON.equalsIgnoreCase(SystemProperties.getProperty(CACHE_CONTROL_SWITCH))) { + if (lookUpCache != null) { + lookUpCache.put(key, objectToCache); + } + } + } catch (CacheException ce) { + logger.error(EELFLoggerDelegate.errorLogger, "putObject: failed to put the object with key " + key, ce); + } + } + + public void clearCache(String region) { + try { + if (region.equals(LOOKUP_OBJECT_CACHE_NAME)) + lookUpCache.clear(); + } catch (CacheException ce) { + logger.error(EELFLoggerDelegate.errorLogger, + "clearCache: failed to clear the cache for the region " + region, ce); + } + } + + public void clearCache() { + clearCache(LOOKUP_OBJECT_CACHE_NAME); + } + + private void loadDataOnStartUp() { + loadLookUpCache(); + } + + public abstract void loadLookUpCache(); + + public void refreshLookUpCache() { + clearCache(LOOKUP_OBJECT_CACHE_NAME); + loadLookUpCache(); + } + + public Properties getCacheConfigProperties() { + return cacheConfigProperties; + } + + public void setCacheConfigProperties(Properties cacheConfigProperties) { + this.cacheConfigProperties = cacheConfigProperties; + } + + public Vector<String> getJscManagedCacheList() { + return jscManagedCacheList; + } + + public DataAccessService getDataAccessService() { + return dataAccessService; + } + + public void setDataAccessService(DataAccessService dataAccessService) { + this.dataAccessService = dataAccessService; + } + + public ServletContext getServletContext() { + return servletContext; + } + + public void setServletContext(ServletContext servletContext) { + this.servletContext = servletContext; + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/objectcache/support/FusionCacheManager.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/objectcache/support/FusionCacheManager.java new file mode 100644 index 00000000..dee566e3 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/objectcache/support/FusionCacheManager.java @@ -0,0 +1,36 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.objectcache.support; + +import java.io.*; + +import org.openecomp.portalsdk.core.FusionObject; + +public interface FusionCacheManager extends FusionObject { + + Object getObject(String key); + void putObject(String key, Object objectToCache); + boolean isObjectInCache(String key); + + void removeObject(String key); + void clearCache(); + void configure() throws IOException; +} + diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/client/AppContextManager.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/client/AppContextManager.java new file mode 100644 index 00000000..1f54a8ec --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/client/AppContextManager.java @@ -0,0 +1,45 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.onboarding.client; + +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.stereotype.Component; + +/** + * + * + * Use this class to get access to ApplicationContext for classes who were not created by Spring. + */ + + +@Component +public class AppContextManager implements ApplicationContextAware{ + private static ApplicationContext _appCtx; + + @Override + public void setApplicationContext(ApplicationContext ctx){ + _appCtx = ctx; + } + + public static ApplicationContext getAppContext(){ + return _appCtx; + } +}
\ No newline at end of file diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/session/TestClass.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/session/TestClass.java new file mode 100644 index 00000000..6bbf8c1d --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/session/TestClass.java @@ -0,0 +1,24 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.onboarding.session; + +public class TestClass { + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/sso/TestClass.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/sso/TestClass.java new file mode 100644 index 00000000..ccd903a9 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/sso/TestClass.java @@ -0,0 +1,24 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.onboarding.sso; + +public class TestClass { + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/ueb/Consumer.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/ueb/Consumer.java new file mode 100644 index 00000000..e9921d18 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/ueb/Consumer.java @@ -0,0 +1,155 @@ +/*- + * ================================================================================ + * ECOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.onboarding.ueb; + +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.LinkedList; +import java.util.UUID; +import java.util.concurrent.ConcurrentLinkedQueue; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties; + +import com.att.nsa.cambria.client.CambriaClientBuilders; +import com.att.nsa.cambria.client.CambriaConsumer; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * Provides a consumer that reads messages from a UEB topic. Intended to be + * passed to a separate thread as its runnable object. + */ +public class Consumer implements Runnable { + + private final Log logger = LogFactory.getLog(getClass()); + + private final LinkedList<String> urlList = Helper.uebUrlList(); + private final ConcurrentLinkedQueue<UebMsg> queue; + private final WaitingRequestersQueueList waitingRequestersList; + private final String consumerKey, consumerSecret, topicName, consumerGroupName; + + /** + * Accepts coordinates needed to subscribe to a UEB topic, as well as the + * queues for passing along messages that arrive. + * + * @param consumerKey + * UEB key used to subscribe to the topic + * @param consumerSecret + * UEB secret used to subscribe to the topic + * @param topicName + * UEB topic name + * @param queue + * Queue to receive UEB messages. All inbound messages are + * enqueued here; ignored if null. + * @param waitingRequestersList + * Collection of queues to receive UEB messages that arrive in + * response to requests; i.e., emulating a synchronous request + * via pub/sub. + */ + public Consumer(String consumerKey, String consumerSecret, String topicName, String consumerGroupName, + ConcurrentLinkedQueue<UebMsg> queue, WaitingRequestersQueueList waitingRequestersList) { + this.consumerKey = consumerKey; + this.consumerSecret = consumerSecret; + this.topicName = topicName; + this.consumerGroupName = consumerGroupName; + this.queue = queue; + this.waitingRequestersList = waitingRequestersList; + } + + /** + * Subscribes to a topic using credentials as supplied to the constructor. + * Distributes messages appropriately as they arrive: + * <UL> + * <LI>If the queue is not null, adds the message to the queue. + * <LI>If the message's getMsgId() method returns non-null and the ID is + * found in the collection of waiting requesters, adds the message in that + * requester's queue. + * </UL> + * + * This is intended to be called in a long running thread as a listener for + * any published messages on a topic. Typical async pub/sub model. We use a + * filter of "0" to prevent collisions with P2P messages with unique filter + * ids. + */ + protected void consume() throws IOException, UebException, GeneralSecurityException { + final String id = UUID.randomUUID().toString(); + + CambriaConsumer cc = null; + cc = new CambriaClientBuilders.ConsumerBuilder() + .usingHosts(urlList) + .authenticatedBy(consumerKey, consumerSecret) + .onTopic (topicName) + .knownAs (consumerGroupName,id) + .waitAtServer (15*1000) + .receivingAtMost (1000) + .build(); + + while (true) { + for (String msg : cc.fetch()) { + logger.debug(" <== consume from topicName " + topicName + " msg: " + msg); + UebMsg uebMsg = new ObjectMapper().readValue(msg, UebMsg.class); + if (queue != null) { + // Add to general queue allowing listeners to act on any + // incoming messages. We don't know if a listener is + // also going to be a responder to a synchronous + // request. So put all received messages on the general + // listener queue. + queue.add(uebMsg); + if (logger.isDebugEnabled()) + logger.debug("Added msg to queue " + this.queue + " queue count = " + queue.size() + " msg :" + + uebMsg.getPayload()); + } + if (waitingRequestersList != null && uebMsg.getMsgId() != null) { + // If a msgId is present, this could be a synchronous + // reply. Here we add it to the waiting requester's + // queue if we find a requester waiting for this msgId. + if (!(uebMsg.getMsgId() + .equals(PortalApiProperties.getProperty(PortalApiConstants.ECOMP_DEFAULT_MSG_ID)))) { + waitingRequestersList.addMsg(uebMsg.getMsgId(), uebMsg); + } + } + } + if (Thread.interrupted()) { + logger.warn(Thread.currentThread() + " interrupted, exiting"); + break; + } + Helper.sleep(10); + } + + } + + /* + * (non-Javadoc) + * + * @see java.lang.Runnable#run() + */ + @Override + public void run() { + try { + consume(); + } catch (Exception ex) { + Thread t = Thread.currentThread(); + t.getUncaughtExceptionHandler().uncaughtException(t, ex); + } + } + +}
\ No newline at end of file diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/ueb/FunctionalMenu.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/ueb/FunctionalMenu.java new file mode 100644 index 00000000..7cf3e91c --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/ueb/FunctionalMenu.java @@ -0,0 +1,61 @@ +/*- + * ================================================================================ + * ECOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.onboarding.ueb; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * Provides a convenience method for fetching the functional menu for a user + * from the ECOMP Portal via UEB. + */ +public class FunctionalMenu { + + private static final Log logger = LogFactory.getLog(FunctionalMenu.class); + + /** + * Makes a synchronous call to ECOMP Portal to get JSON with the functional + * menu, which arrives as the payload of the returned UEB message. + * + * @param userId + * User ID as known on the ECOMP Portal for customizing the + * functional menu appropriately + * @return JSON with functional menu + * @throws UebException + */ + public static String get(String userId) throws UebException { + String returnString = null; + logger.info("Making use of UEB communication and Requesting functional menu for user " + userId); + UebMsg funcMenuUebMsg = null; + UebMsg msg = new UebMsg(); + msg.putMsgType(UebMsgTypes.UEB_MSG_TYPE_GET_FUNC_MENU); + msg.putUserId(userId); + funcMenuUebMsg = UebManager.getInstance().requestReply(msg); + if (funcMenuUebMsg != null) { + if (funcMenuUebMsg.getPayload().startsWith("Error:")) { + logger.error("getFunctionalMenu received an error in UEB msg = " + funcMenuUebMsg.getPayload()); + } else { + returnString = funcMenuUebMsg.getPayload(); + } + } + return returnString; + } + +}
\ No newline at end of file diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/ueb/Helper.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/ueb/Helper.java new file mode 100644 index 00000000..6e6b4ae8 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/ueb/Helper.java @@ -0,0 +1,64 @@ +/*- + * ================================================================================ + * ECOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.onboarding.ueb; + +import java.util.LinkedList; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties; + +/** + * Provides utility methods. + */ +public class Helper { + + private static final Log logger = LogFactory.getLog(Helper.class); + + /** + * Parses a comma-separated list of UEB servers from properties file into a + * list. + * + * @return List of UEB server names + */ + public static LinkedList<String> uebUrlList() { + LinkedList<String> urlList = null; + String url = PortalApiProperties.getProperty(PortalApiConstants.UEB_URL_LIST); + if (url == null) { + logger.error("uebUrlList: failed to get property " + PortalApiConstants.UEB_URL_LIST); + return null; + } + urlList = new LinkedList<String>(); + for (String u : url.split(",")) { + urlList.add(u.trim()); + } + return urlList; + } + + public static void sleep(int milliseconds) { + try { + Thread.sleep(milliseconds); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/ueb/Publisher.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/ueb/Publisher.java new file mode 100644 index 00000000..8dbdda2b --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/ueb/Publisher.java @@ -0,0 +1,125 @@ +/*- + * ================================================================================ + * ECOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.onboarding.ueb; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.security.GeneralSecurityException; +import java.util.LinkedList; +import java.util.concurrent.TimeUnit; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants; + +import com.att.nsa.cambria.client.CambriaBatchingPublisher; +import com.att.nsa.cambria.client.CambriaClientBuilders; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; + +/** + * Provides a publisher that sends messages to a UEB topic. + * + * Utilizes AT&T's UEB/Cambria subscriber/publisher messaging service. + */ +public class Publisher { + + private final Log logger = LogFactory.getLog(getClass()); + + protected final LinkedList<String> urlList = Helper.uebUrlList(); + + private final String topicName; + private final String publisherKey; + private final String publisherSecret; + + /** + * Accepts coordinates needed to publish to a UEB topic. + * + * @param publisherKey + * UEB key used to publish to the topic + * @param publisherSecret + * UEB secret used to publish to the topic + * @param topicName + * UEB topic name + */ + public Publisher(String publisherKey, String publisherSecret, String topicName) { + this.publisherKey = publisherKey; + this.publisherSecret = publisherSecret; + this.topicName = topicName; + logger.info("Publisher instantiated for topic " + topicName); + } + + /** + * Creates a publisher, subscribes to the topic, sends the specified message + * to the topic, then closes the publisher. This ensures that the single + * message goes immediately. UEB is designed for high throughput and tries + * to batch up multiple messages in each send, but this method wants the + * single message to go immediately. + * + * @param uebMsg + * Message object to send as the payload. + * @throws UebException + * If anything goes wrong, including JSON serialization of the + * specified message object. + */ + public void send(UebMsg uebMsg) throws UebException { + String msg = null; + + CambriaBatchingPublisher pub; + try { + pub = new CambriaClientBuilders.PublisherBuilder() + .authenticatedBy(publisherKey, publisherSecret).usingHosts(urlList).onTopic(topicName).build(); + } catch (MalformedURLException e1) { + logger.error("pub.build Exception ", e1); + throw new UebException(PortalApiConstants.ECOMP_UEB_UNKNOWN_PUBLISH_ERROR, e1, topicName, null, msg); + } catch (GeneralSecurityException e1) { + logger.error("pub.build Exception ", e1); + throw new UebException(PortalApiConstants.ECOMP_UEB_UNKNOWN_PUBLISH_ERROR, e1, topicName, null, msg); + } + + try { + ObjectWriter mapper = new ObjectMapper().writer().withDefaultPrettyPrinter(); + msg = mapper.writeValueAsString(uebMsg); + } catch (JsonProcessingException e) { + throw new UebException(PortalApiConstants.ECOMP_UEB_INVALID_MSG, topicName, null, null); + } + + try { + logger.debug("Publishing to " + topicName + " msg: " + msg); + int NumSent = pub.send(PortalApiConstants.ECOMP_GENERAL_UEB_PARTITION, msg); + if (NumSent == 0) { + throw new UebException(PortalApiConstants.ECOMP_UEB_UNKNOWN_PUBLISH_ERROR, topicName, null, msg); + } + } catch (IOException ex) { + logger.error("Failed to publish", ex); + throw new UebException(PortalApiConstants.ECOMP_UEB_UNKNOWN_PUBLISH_ERROR, ex, topicName, null, msg); + } + + try { + // close the publisher to make sure everything's sent before exiting + pub.close(5, TimeUnit.SECONDS); + } catch (Exception ex) { + logger.error("pub.close Exception ", ex); + throw new UebException(PortalApiConstants.ECOMP_UEB_UNKNOWN_PUBLISH_ERROR, ex, topicName, null, msg); + } + + } +}
\ No newline at end of file diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/ueb/PublisherList.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/ueb/PublisherList.java new file mode 100644 index 00000000..6919236f --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/ueb/PublisherList.java @@ -0,0 +1,77 @@ +/*- + * ================================================================================ + * ECOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.onboarding.ueb; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * A thin wrapper around ConcurrentHashMap that stores a queue for each + * Requester that is waiting for a Reply. When a reply is received that has a + * matching msgId, that requesters queue is populated with the reply message. + * + * Primarily for Portal core to track the remote applications that have placed + * requests; never used by those applications. + */ +public class PublisherList { + + private final Log logger = LogFactory.getLog(getClass()); + + private final Map<String, Publisher> map; + + public PublisherList() { + map = new ConcurrentHashMap<>(); + } + + public void addPublisherToMap(String topicName, Publisher publisher) { + if (this.map.containsKey(topicName)) { + logger.error("Publisher already exists for " + topicName); + } else { + this.map.put(topicName, publisher); + } + } + + public Publisher getPublisher(String topicName) { + return this.map.get(topicName); + } + + public void removePublisherFromMap(String topicName) { + this.map.remove(topicName); + } + + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append("Map contains " + this.map.size() + " Publishers."); + for (Map.Entry<String, Publisher> entry : this.map.entrySet()) { + String key = entry.getKey().toString(); + Publisher pub = entry.getValue(); + sb.append("Entry msgId, " + key + " publisher" + pub); + } + return sb.toString(); + } + + public int size() { + return this.map.size(); + } + +}
\ No newline at end of file diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/ueb/TopicManager.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/ueb/TopicManager.java new file mode 100644 index 00000000..8593b5bb --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/ueb/TopicManager.java @@ -0,0 +1,135 @@ +/*- + * ================================================================================ + * ECOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.onboarding.ueb; + +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.LinkedList; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants; + +import com.att.nsa.apiClient.http.HttpClient; +import com.att.nsa.apiClient.http.HttpException; +import com.att.nsa.cambria.client.CambriaClient.CambriaApiException; +import com.att.nsa.cambria.client.CambriaClientBuilders; +import com.att.nsa.cambria.client.CambriaClientFactory; +import com.att.nsa.cambria.client.CambriaTopicManager; + +/** + * Provides methods to facilitate creating topics, and adding publishers and + * subscribers to existing topics. + * + * Utilizes UEB/Cambria subscriber/publisher messaging service. + */ +public class TopicManager { + + private final Log logger = LogFactory.getLog(getClass()); + + /** + * Creates a topic with the specified information. + * + * @param key + * Topic key + * @param secret + * Topic secret key + * @param topicName + * Topic name + * @param topicDescription + * Topic description + * @throws HttpException + * @throws CambriaApiException + * @throws IOException + */ + public void createTopic(String key, String secret, String topicName, String topicDescription) + throws HttpException, CambriaApiException, IOException { + final LinkedList<String> urlList = Helper.uebUrlList(); + if (logger.isInfoEnabled()) { + logger.info("==> createTopic"); + logger.info("topicName: " + topicName); + logger.info("topicDescription: " + topicDescription); + } + CambriaTopicManager tm =null; + try { + tm = CambriaClientFactory.createTopicManager(null, urlList, key, secret); + } catch (GeneralSecurityException e) { + logger.error("pub.build Exception ", e); + throw new CambriaApiException(topicName); + } + tm.createTopic(topicName, topicDescription, 1, 1); + } + + /** + * Modifies the specified topic to accept a subscriber using the specified + * key. + * + * @param topicOwnerKey + * @param topicOwnerSecret + * @param subscriberKey + * @param topicName + * @throws HttpException + * @throws CambriaApiException + * @throws IOException + */ + public void addSubscriber(String topicOwnerKey, String topicOwnerSecret, String subscriberKey, String topicName) + throws HttpException, CambriaApiException, IOException { + logger.info("==> addSubscriber to topic " + topicName); + final LinkedList<String> urlList = Helper.uebUrlList(); + CambriaTopicManager tm = null; + try { + tm = new CambriaClientBuilders.TopicManagerBuilder().usingHosts(urlList).authenticatedBy(topicOwnerKey, topicOwnerSecret).build(); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + //old version num : CambriaClientFactory.createTopicManager(urlList, topicOwnerKey,topicOwnerSecret); + tm.allowConsumer(topicName, subscriberKey); + } + + /** + * Modifies the specified topic to accept a publisher using the specified + * key. + * + * @param topicOwnerKey + * @param topicOwnerSecret + * @param publisherKey + * @param topicName + * @throws HttpException + * @throws CambriaApiException + * @throws IOException + */ + + @SuppressWarnings("deprecation") + public void addPublisher(String topicOwnerKey, String topicOwnerSecret, String publisherKey, String topicName) + throws HttpException, CambriaApiException, IOException { + logger.info("==> addPublisher to topic " + topicName); + final LinkedList<String> urlList = Helper.uebUrlList(); + CambriaTopicManager tm =null; + try { + tm = CambriaClientFactory.createTopicManager(HttpClient.ConnectionType.HTTPS, urlList, topicOwnerKey, + topicOwnerSecret); + } catch (GeneralSecurityException e) { + logger.error("pub.build Exception ", e); + throw new CambriaApiException(topicName); + } + tm.allowProducer(topicName, publisherKey); + } +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/ueb/UebException.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/ueb/UebException.java new file mode 100644 index 00000000..875ba58d --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/ueb/UebException.java @@ -0,0 +1,65 @@ +/*- + * ================================================================================ + * ECOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.onboarding.ueb; + +/** + * Stores UEB-specific information including topic, message ID and message body. + */ +public class UebException extends Exception { + + private static final long serialVersionUID = 1L; + private String topicName = null; + private String msgId = null; + private String msg = null; + + public UebException(String errorMsg, String topicName, String msgId, String msg) { + super(errorMsg); + this.topicName = topicName; + this.msgId = msgId; + this.msg = msg; + } + + public UebException(String errorMsg, Throwable ex, String topicName, String msgId, String msg) { + super(errorMsg, ex); + this.topicName = topicName; + this.msgId = msgId; + this.msg = msg; + } + + public UebException(String msg, Throwable ex) { + super(msg, ex); + } + + public UebException(Throwable ex) { + super(ex); + } + + public String getUebMsg() { + return this.msg; + } + + public String getTopicName() { + return this.topicName; + } + + public String getMsgId() { + return this.msgId; + } +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/ueb/UebManager.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/ueb/UebManager.java new file mode 100644 index 00000000..7bf6de35 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/ueb/UebManager.java @@ -0,0 +1,358 @@ +/*- + * ================================================================================ + * ECOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.onboarding.ueb; + +import java.io.IOException; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.LinkedBlockingQueue; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties; + +/** + * Manages UEB interactions and provides methods for publishing requests, + * replies and others. + */ +public class UebManager { + + private final Log logger = LogFactory.getLog(getClass()); + + private WaitingRequestersQueueList waitingRequestersQueueList; + private PublisherList publisherList = new PublisherList(); + private static UebManager uebManager = null; + + private final String inTopicName; + private final String consumerGroupName; + private final String outTopicName; + private final String appUebKey; + private final String appUebSecret; + + private Publisher appPublisher; + private Thread listenerThread; + private boolean bThisIsEcompPortalServer = false; + + /** + * Constructor initializes fields and validates values obtained from + * properties. + * + * The picture below is a simplified view of the relationships among ECOMP + * Portal and applications communicating via UEB: + * + * <PRE> + * ECOMP out to many. + * App out to only ECOMP. + * + * |----------------|<--------------------------------------------- + * | | | | | + * | |---------------------------> App 1 ------ | | + * | ECOMP Portal |---------------------------> App 2 --------- | + * | | ... | + * | |---------------------------> App n ----------- + * |----------------| + * </PRE> + * + * @throws IOException + */ + protected UebManager() throws UebException { + waitingRequestersQueueList = null; + listenerThread = null; + outTopicName = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME); + inTopicName = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_INBOUND_MAILBOX_NAME); + appUebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY); + appUebSecret = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET); + String consGrp = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_CONSUMER_GROUP_NAME); + + if (outTopicName == null || outTopicName.length() == 0) + throw new UebException("Failed to get property " + PortalApiConstants.ECOMP_PORTAL_INBOX_NAME, null, null, + null); + if (inTopicName == null || inTopicName.length() == 0) + throw new UebException("Failed to get property " + PortalApiConstants.UEB_APP_INBOUND_MAILBOX_NAME, null, + null, null); + if (consGrp == null || consGrp.length() == 0) + throw new UebException("Failed to get property " + PortalApiConstants.UEB_APP_CONSUMER_GROUP_NAME, null, + null, null); + if (appUebKey == null || appUebKey.length() == 0) + throw new UebException("Failed to get property " + PortalApiConstants.UEB_APP_KEY, null, null, null); + if (appUebSecret == null || appUebSecret.length() == 0) + throw new UebException("Failed to get property " + PortalApiConstants.UEB_APP_SECRET, null, null, null); + List<String> uebUrlList = Helper.uebUrlList(); + if (uebUrlList == null || uebUrlList.size() == 0) + throw new UebException("Failed to get property" + PortalApiConstants.UEB_URL_LIST, null, null, null); + // A bit of magic: if consumer group is a magic token, generate one. + consumerGroupName = (PortalApiConstants.UEB_APP_CONSUMER_GROUP_NAME_GENERATOR.equals(consGrp) + ? UUID.randomUUID().toString() : consGrp); + } + + /** + * Gets the static instance, creating it if necessary. + * + * @return Instance of UebManager + * @throws IOException + */ + public static synchronized UebManager getInstance() throws UebException { + if (uebManager == null) { + uebManager = new UebManager(); + } + return uebManager; + } + + /** + * Answers whether the getInstance() method has previously been called. + * + * @return True if a static instance is available, else false. + */ + public static boolean isInstanceAvailable() { + return uebManager != null; + } + + /** + * Creates a list of waiting requesters, creates and a consumer using cached + * information, and starts a new thread to run the consumer that listens for + * messages published to the inbound topic configured in the constructor. + * + * @param inboxQueue + * Queue supplied to the consumer. If not null, the consumer will + * enqueue every message it receives. + */ + public void initListener(ConcurrentLinkedQueue<UebMsg> inboxQueue) throws UebException { + waitingRequestersQueueList = new WaitingRequestersQueueList(); + Consumer runnable = new Consumer(appUebKey, appUebSecret, inTopicName, consumerGroupName, inboxQueue, + waitingRequestersQueueList); + this.listenerThread = new Thread(runnable, "UEBConsumerThread"); + this.listenerThread.start(); + Helper.sleep(400); // UEB functions more reliably when we give this some + // time + + logger.info("UEBManager instance starting... " + inTopicName + " listener thread " + + this.listenerThread.getName() + " state = " + this.listenerThread.getState()); + + /* + * ECOMP Portal manages a dynamic list of outbound topics and so the + * outTopicName is initialized in this logic with the same value as the + * inbound topic. The real outbound topics name will be added to the + * publisher list for ECOMP Portal. For an SDK/App instance only one + * publisher is needed, appPublisher. + */ + if (inTopicName.equalsIgnoreCase(outTopicName)) { + this.bThisIsEcompPortalServer = true; + } else { + appPublisher = new Publisher(appUebKey, appUebSecret, outTopicName); + Helper.sleep(400); + } + } + + /** + * Creates and adds a publisher to the list for the specified topic. This + * should only be called by the ECOMP Portal App, other Apps have just one + * publisher and use appPublisher + * + * @param topicName + */ + public void addPublisher(String topicName) { + logger.info("UEBManager adding publisher for " + topicName); + Publisher outBoxToAppPublisher = new Publisher(appUebKey, appUebSecret, topicName); + publisherList.addPublisherToMap(topicName, outBoxToAppPublisher); + } + + /** + * Removes a publisher from the list for the specified topic. + * + * This should only be called by the ECOMP Portal App, other Apps have just + * one publisher and use appPublisher + * + * @param topicName + */ + public void removePublisher(String topicName) { + logger.info("UEBManager removing publisher for " + topicName); + publisherList.removePublisherFromMap(topicName); + } + + /** + * Adds the default ECOMP message ID to the message and sends the message to + * the topic. + * + * @param msg + * @throws UebException + */ + public void publish(UebMsg msg) throws UebException { + msg.putMsgId(PortalApiConstants.ECOMP_DEFAULT_MSG_ID); + appPublisher.send(msg); + } + + /** + * Sends the message using the default publisher. + * + * @param msg + * @throws UebException + */ + public void publishReply(UebMsg msg) throws UebException { + // Caller populates msgId with the echoed value from the request + appPublisher.send(msg); + } + + /** + * Sends the message using the appropriate publisher for the specified + * topic. + * + * @param msg + * @param topicName + * @throws UebException + */ + public void publishEP(UebMsg msg, String topicName) throws UebException { + Publisher publisher = publisherList.getPublisher(topicName); + if (publisher != null) { + msg.putMsgId(PortalApiConstants.ECOMP_DEFAULT_MSG_ID); + publisher.send(msg); + } + } + + /** + * Publishes a reply using the appropriate publisher for the specified + * topic. + * + * @param msg + * @param topicName + * @throws UebException + */ + public void publishReplyEP(UebMsg msg, String topicName) throws UebException { + // Caller populates msgId with the echoed value from the request + Publisher publisher = publisherList.getPublisher(topicName); + if (publisher != null) { + publisher.send(msg); + } + } + + /** + * Sends the specified message using the specified publisher, and waits for + * a reply. Retransmits if no reply is received in 5 seconds; gives up after + * 3 retries. + * + * @param msg + * @param publisher + * @return Message from a remote publisher, or null if timeout happens. + * @throws UebException + */ + public UebMsg requestReplyUsingPublisher(UebMsg msg, Publisher publisher) throws UebException { + UebMsg reply = null; + if (waitingRequestersQueueList == null) { + logger.error("requestReplyUsingPublisher called but listener thread not initialized"); + } else { + // Storing a non-default message ID identifies this as a synchronous + // request + msg.putMsgId(UUID.randomUUID().toString()); + + /* + * Create a queue for this request, the consumer thread will insert + * the reply on this queue + */ + LinkedBlockingQueue<UebMsg> replyQueue = new LinkedBlockingQueue<UebMsg>(); + waitingRequestersQueueList.addQueueToMap(msg.getMsgId(), replyQueue); + + /* + * Send the request + */ + publisher.send(msg); + + /* + * Wait for reply up to 3 * 5 = 15 seconds + */ + int reTransmits = 0; + int maxRetransmits = 3; + int retransmitTimeMs = 5000; + long sendTimeStamp = System.currentTimeMillis(); + while (reTransmits < maxRetransmits) { + if ((reply = replyQueue.poll()) != null) + break; + + long now = System.currentTimeMillis(); + if (now - sendTimeStamp > retransmitTimeMs) { + logger.debug("Retransmitting send... msg = " + msg.getPayload() + msg.getMsgId()); + publisher.send(msg); + sendTimeStamp = System.currentTimeMillis(); + reTransmits++; + } + } + waitingRequestersQueueList.removeQueueFromMap(msg.getMsgId()); + if (reTransmits == maxRetransmits) + throw new UebException(PortalApiConstants.ECOMP_UEB_TIMEOUT_ERROR, inTopicName, null, msg.toString()); + + } + return reply; + } + + /** + * Sends the specified message using the default publisher and waits for a + * reply. + * + * @param msg + * @return Message from a remote publisher, or null if timeout happens. + * @throws UebException + */ + public UebMsg requestReply(UebMsg msg) throws UebException { + return requestReplyUsingPublisher(msg, appPublisher); + } + + /** + * Sends the specified message using the publisher appropriate for the + * specified topic name, and waits for a reply. + * + * @param msg + * @param topicName + * @return Message from a remote publisher, or null if timeout happens. + * @throws UebException + */ + public UebMsg requestReplyEP(UebMsg msg, String topicName) throws UebException { + UebMsg returnMsg = null; + Publisher publisher = publisherList.getPublisher(topicName); + if (publisher != null) { + returnMsg = requestReplyUsingPublisher(msg, publisher); + } + return returnMsg; + } + + /** + * Publishes the payload as a UEB widget-notification message on the default + * publisher. Intended for use by Apps inter widget communication, not EP + * itself. + * + * @param payload + * @param userId + */ + public void postWidgetNotification(String payload, String userId) throws UebException { + UebMsg msg = new UebMsg(); + msg.putPayload(payload); + msg.putUserId(userId); + msg.putMsgType(UebMsgTypes.UEB_MSG_TYPE_WIDGET_NOTIFICATION); + this.publish(msg); + } + + /** + * Interrupts the long-running thread that runs the consumer. + */ + public void shutdown() { + if (this.listenerThread != null) { + this.listenerThread.interrupt(); + } + } +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/ueb/UebMsg.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/ueb/UebMsg.java new file mode 100644 index 00000000..da18c4f8 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/ueb/UebMsg.java @@ -0,0 +1,119 @@ +/*- + * ================================================================================ + * ECOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.onboarding.ueb; + +import java.net.InetAddress; +import java.net.UnknownHostException; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class UebMsg { + + private final Log logger = LogFactory.getLog(getClass()); + + private String version; + private String msgId; + private long timeStamp; + private String payload; + private String msgType; + private String userId; + private String sourceTopicName; + private String sourceIP; + private String sourceHostName; + + /** + * Creates a new object and populates the fields source IP, source topic, + * time stamp, version, and message id. + */ + public UebMsg() { + InetAddress ip; + try { + ip = InetAddress.getLocalHost(); + // Do not attempt to get name, why wait on DNS every time? + // sourceHostName = ip.getHostName(); + sourceIP = ip.getHostAddress(); + } catch (UnknownHostException e) { + sourceHostName = "unknown"; + sourceIP = "unknown"; + } + + this.timeStamp = System.currentTimeMillis(); + this.version = "1.0"; + this.msgId = PortalApiConstants.ECOMP_DEFAULT_MSG_ID; + this.payload = "empty payload content"; + this.sourceTopicName = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_INBOUND_MAILBOX_NAME); + if (this.sourceTopicName == null) + logger.error("Failed to get property " + PortalApiConstants.UEB_APP_INBOUND_MAILBOX_NAME); + } + + public void putMsgId(String msgId) { + this.msgId = msgId; + } + + public String getMsgId() { + return msgId; + } + + public void putPayload(String payload) { + this.payload = payload; + } + + public String getPayload() { + return payload; + } + + public void putMsgType(String msgType) { + this.msgType = msgType; + } + + public String getMsgType() { + return this.msgType; + } + + public void putUserId(String userId) { + this.userId = userId; + } + + public String getUserId() { + return this.userId; + } + + public void putSourceTopicName(String topic) { + this.sourceTopicName = topic; + } + + public String getSourceTopicName() { + return this.sourceTopicName; + } + + @Override + public String toString() { + return "UebMsg [version=" + version + ", msgId=" + msgId + ", timeStamp=" + timeStamp + ", msgType=" + msgType + + ", userId=" + userId + ", sourceTopicName=" + sourceTopicName + ", sourceIP=" + sourceIP + + ", sourceHostName=" + sourceHostName + "]" + System.lineSeparator() + "payload=" + payload; + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/ueb/UebMsgTypes.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/ueb/UebMsgTypes.java new file mode 100644 index 00000000..28ab327f --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/ueb/UebMsgTypes.java @@ -0,0 +1,28 @@ +/*- + * ================================================================================ + * ECOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.onboarding.ueb; + +/** + * Publishes constants used in the UEB package. + */ +public interface UebMsgTypes { + public static final String UEB_MSG_TYPE_GET_FUNC_MENU = "uebMsgTypeGetFuncMenu"; + public static final String UEB_MSG_TYPE_WIDGET_NOTIFICATION = "uebMsgTypeWidgetNotification"; +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/ueb/WaitingRequestersQueueList.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/ueb/WaitingRequestersQueueList.java new file mode 100644 index 00000000..db0ee1b9 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/onboarding/ueb/WaitingRequestersQueueList.java @@ -0,0 +1,73 @@ +/*- + * ================================================================================ + * ECOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.onboarding.ueb; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.LinkedBlockingQueue; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * A thin wrapper around ConcurrentHashMap that stores a queue for each + * Requester that is waiting for a Reply. When a reply is received that has a + * matching msgId, that requesters queue is populated with the reply message. + * + * Primarily for the UebManager to track requests while it waits for responses. + */ +public class WaitingRequestersQueueList { + private final Log logger = LogFactory.getLog(getClass()); + + private final Map<String, LinkedBlockingQueue<UebMsg>> map; + + public WaitingRequestersQueueList() { + map = new ConcurrentHashMap<>(); + } + + public void addQueueToMap(String msgId, LinkedBlockingQueue<UebMsg> queue) { + this.map.put(msgId, queue); + } + + public void addMsg(String msgId, UebMsg message) { + LinkedBlockingQueue<UebMsg> queue = this.map.get(msgId); + if (queue != null) { + queue.add(message); + } else { + logger.warn("Did not find entry in WaitingRequestersQueueList for msgId " + msgId); + } + } + + public void removeQueueFromMap(String msgId) { + this.map.remove(msgId); + } + + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append("Map contains " + this.map.size() + " Publishers."); + for (Map.Entry<String, LinkedBlockingQueue<UebMsg>> entry : this.map.entrySet()) { + String key = entry.getKey().toString(); + LinkedBlockingQueue<UebMsg> queue = entry.getValue(); + sb.append("Entry msgId, " + key + " queue " + queue); + } + return sb.toString(); + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/restful/client/HttpStatusAndResponse.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/restful/client/HttpStatusAndResponse.java new file mode 100644 index 00000000..a8242234 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/restful/client/HttpStatusAndResponse.java @@ -0,0 +1,42 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.restful.client; + +/** + * Holds the status code and body that result from accessing an HTTP URL. + */ +public class HttpStatusAndResponse { + + private int statusCode; + private String response; + + public HttpStatusAndResponse(int status, String resp) { + this.statusCode = status; + this.response = resp; + } + + public int getStatusCode() { + return statusCode; + } + + public String getResponse() { + return response; + } +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/restful/client/PortalRestClientBase.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/restful/client/PortalRestClientBase.java new file mode 100644 index 00000000..b74d87c4 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/restful/client/PortalRestClientBase.java @@ -0,0 +1,171 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.restful.client; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; + +import javax.servlet.http.HttpServletResponse; + +import org.apache.http.Consts; +import org.apache.http.HttpEntity; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; +import org.openecomp.portalsdk.core.domain.App; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.util.CipherUtil; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties; +import org.openecomp.portalsdk.core.service.AppService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +/** + * Provides a basic client to access a REST endpoint at the Portal via get or + * post. Usage caveats: + * <OL> + * <LI>Must be auto-wired by Spring, because this in turn auto-wires a + * data-access service to read application credentials from the FN_APP table. + * <LI>If HTTP access is used and the server uses a self-signed certificate, the + * local trust store must be extended appropriately. The HTTP client throws + * exceptions if the JVM cannot validate the server certificate. + * </OL> + */ +@Component +public class PortalRestClientBase { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalRestClientBase.class); + + @Autowired + AppService appService; + + /** + * Constructs and sends a GET request for the URI, with REST application + * credentials in the header as the Portal expects. + * + * @param uri + * URI of the service + * @return Result of the get; null if an error happens + * @throws URISyntaxException + * @throws IOException + * @throws ClientProtocolException + */ + public HttpStatusAndResponse getRestWithCredentials(final URI uri) throws Exception { + + String uebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY); + App app = appService.getDefaultApp(); + if (uebKey == null || app == null || app.getUsername() == null || app.getAppPassword() == null) + throw new Exception("Missing one or more required properties and/or database entries"); + String decryptedPassword = CipherUtil.decrypt(app.getAppPassword()); + CloseableHttpClient httpClient = HttpClients.createDefault(); + HttpGet httpGet = new HttpGet(uri); + httpGet.setHeader("uebkey", uebKey); + httpGet.setHeader("username", app.getUsername()); + httpGet.setHeader("password", decryptedPassword); + + String responseJson = null; + CloseableHttpResponse response = null; + try { + logger.info(EELFLoggerDelegate.debugLogger, "GET from " + uri); + response = httpClient.execute(httpGet); + logger.info(EELFLoggerDelegate.debugLogger, "Status is " + response.getStatusLine()); + if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) + logger.info(EELFLoggerDelegate.debugLogger, "Status is " + response.getStatusLine().toString()); + HttpEntity entity = response.getEntity(); + if (entity == null) { + logger.info(EELFLoggerDelegate.debugLogger, "Entity is null!"); + } else { + // entity content length is never set. + // this naively tries to read everything. + responseJson = EntityUtils.toString(entity); + logger.info(EELFLoggerDelegate.debugLogger, responseJson); + EntityUtils.consume(entity); + } + } finally { + if (response != null) + response.close(); + } + if (response == null) + return null; + return new HttpStatusAndResponse(response.getStatusLine().getStatusCode(), responseJson); + } + + /** + * Constructs and sends a POST request using the specified body, with REST + * application credentials in the header as the Portal expects. + * + * @param uri + * REST endpoint + * @param json + * Content to post + * @return Result of the post; null if an error happens + * @throws Exception + */ + public HttpStatusAndResponse postRestWithCredentials(final URI uri, final String json) throws Exception { + + String uebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY); + App app = appService.getDefaultApp(); + if (uebKey == null || app == null || app.getUsername() == null || app.getAppPassword() == null) + throw new Exception("Missing one or more required properties and/or database entries"); + + CloseableHttpClient httpClient = HttpClients.createDefault(); + HttpPost httpPost = new HttpPost(uri); + httpPost.setHeader("uebkey", uebKey); + httpPost.setHeader("username", app.getUsername()); + httpPost.setHeader("password", app.getAppPassword()); + + StringEntity postEntity = new StringEntity(json, ContentType.create("application/json", Consts.UTF_8)); + httpPost.setEntity(postEntity); + + String responseJson = null; + CloseableHttpResponse response = null; + try { + logger.info(EELFLoggerDelegate.debugLogger, "POST to " + uri); + response = httpClient.execute(httpPost); + logger.info(EELFLoggerDelegate.debugLogger, "Status is " + response.getStatusLine()); + if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) + throw new Exception("Status is " + response.getStatusLine().toString()); + + HttpEntity entity = response.getEntity(); + if (entity == null) { + logger.info(EELFLoggerDelegate.debugLogger, "Entity is null!"); + } else { + // entity content length is never set. + // this naively tries to read everything. + responseJson = EntityUtils.toString(entity); + logger.info(EELFLoggerDelegate.debugLogger, responseJson); + EntityUtils.consume(entity); + } + } finally { + if (response != null) + response.close(); + } + return new HttpStatusAndResponse(response.getStatusLine().getStatusCode(), responseJson); + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/restful/client/SharedContextRestClient.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/restful/client/SharedContextRestClient.java new file mode 100644 index 00000000..91f4652a --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/restful/client/SharedContextRestClient.java @@ -0,0 +1,351 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.restful.client; + +import java.net.URI; +import java.util.HashMap; +import java.util.List; + +import org.apache.http.client.utils.URIBuilder; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties; +import org.openecomp.portalsdk.core.restful.domain.SharedContext; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * Provides convenience methods to use the shared-context service at Portal. + * This hides all JSON; instead it accepts and returns Java objects. Usage + * caveats (repeated from superclass): + * <OL> + * <LI>Must be auto-wired by Spring, because this in turn auto-wires a data + * access service to read application credentials from the FN_APP table. + * <LI>If HTTP access is used and the server uses a self-signed certificate, the + * local trust store must be extended appropriately. The HTTP client throws + * exceptions if the JVM cannot validate the server certificate. + * </OL> + */ +@Component +public class SharedContextRestClient extends PortalRestClientBase { + + @Autowired + SystemProperties systemProperties; + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SharedContextRestClient.class); + + /** + * Reusable JSON (de)serializer + */ + private final ObjectMapper mapper = new ObjectMapper(); + + /** + * Builds the URl for the shared context service using the portal.properties + * value for the AUXAPI endpoint. + * + * @throws Exception + * if the ECOMP_REST_URL property is not found + */ + private String getSharedContextUrl() throws Exception { + String restUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL); + if (restUrl == null || restUrl.length() == 0) + throw new Exception("getSharedContextUrl: no property " + PortalApiConstants.ECOMP_REST_URL); + String contextUrl = restUrl + (restUrl.endsWith("/") ? "" : "/") + "context/"; + return contextUrl; + } + + /** + * Gets the shared-context value for the specified context ID and key. + * + * @param contextId + * An Ecomp Portal session ID + * @param key + * Key for the shared-context entry; e.g., "lastName" + * @return SharedContext object; null if not found. + * @throws Exception + */ + public SharedContext getContextValue(String contextId, String key) throws Exception { + HttpStatusAndResponse hsr = getContext("get", contextId, key); + logger.info(EELFLoggerDelegate.debugLogger, "getSharedContext: resp is " + hsr); + if (hsr == null) { + logger.error(EELFLoggerDelegate.applicationLogger, "getContextValue: unexpected null response"); + return null; + } + SharedContext jsonObj = null; + try { + jsonObj = mapper.readValue(hsr.getResponse(), SharedContext.class); + } catch (JsonMappingException ex) { + logger.error(EELFLoggerDelegate.applicationLogger, + "getContextValue: failed to map response onto object" + ex.getMessage()); + } catch (JsonParseException ex) { + logger.info(EELFLoggerDelegate.applicationLogger, + "getContextValue: failed to parse response" + ex.getMessage()); + } + if (jsonObj != null && jsonObj.getResponse() != null) + return null; + return jsonObj; + } + + /** + * Gets user information for the specified context ID. + * + * @param contextId + * An Ecomp Portal session ID + * @return List of SharedContext objects corresponding to the following + * keys: USER_FIRST_NAME, USER_LAST_NAME, USER_EMAIL and + * USER_ORGUSERID; empty if none were found; null if an error + * happens. + * @throws Exception + */ + public List<SharedContext> getUserContext(String contextId) throws Exception { + HttpStatusAndResponse hsr = getContext("get_user", contextId, null); + logger.info(EELFLoggerDelegate.debugLogger, "getUserContext: resp is " + hsr); + if (hsr == null) { + logger.error(EELFLoggerDelegate.applicationLogger, "getUserContext: unexpected null response"); + return null; + } + List<SharedContext> jsonList = null; + try { + TypeReference<List<SharedContext>> typeRef = new TypeReference<List<SharedContext>>() { + }; + jsonList = mapper.readValue(hsr.getResponse(), typeRef); + } catch (JsonMappingException ex) { + logger.error(EELFLoggerDelegate.applicationLogger, + "getUserContext: failed to map response onto object" + ex.getMessage()); + } catch (JsonParseException ex) { + logger.error(EELFLoggerDelegate.applicationLogger, + "getUserContext: failed to parse response" + ex.getMessage()); + } + return jsonList; + } + + /** + * Checks whether a shared-context entry exists for the specified context ID + * and key. + * + * @param contextId + * An Ecomp Portal session ID + * @param key + * Key for the shared-context entry; e.g., "lastName" + * @return True if the object exists, false otherwise; null on error. + * @throws Exception + */ + public Boolean checkSharedContext(String contextId, String key) throws Exception { + HttpStatusAndResponse hsr = getContext("check", contextId, key); + logger.info(EELFLoggerDelegate.debugLogger, "checkSharedContext: resp is " + hsr); + if (hsr == null) { + logger.error(EELFLoggerDelegate.applicationLogger, "checkSharedContext: unexpected null response"); + return null; + } + String response = null; + try { + SharedContext jsonObj = mapper.readValue(hsr.getResponse(), SharedContext.class); + response = jsonObj.getResponse(); + } catch (JsonMappingException ex) { + logger.error(EELFLoggerDelegate.applicationLogger, + "checkSharedContext: failed to map response onto object" + ex.getMessage()); + } catch (JsonParseException ex) { + logger.error(EELFLoggerDelegate.applicationLogger, + "checkSharedContext: failed to parse response" + ex.getMessage()); + } + if (response == null) + return null; + return ("exists".equals(response)); + } + + /** + * Removes a shared-context entry with the specified context ID and key. + * + * @param contextId + * An Ecomp Portal session ID + * @param key + * Key for the shared-context entry; e.g., "lastName" + * @return True if the entry was removed, false otherwise; null on error. + * @throws Exception + */ + public Boolean removeSharedContext(String contextId, String key) throws Exception { + HttpStatusAndResponse hsr = getContext("remove", contextId, key); + logger.info(EELFLoggerDelegate.debugLogger, "removeSharedContext: resp is " + hsr); + if (hsr == null) { + logger.error(EELFLoggerDelegate.applicationLogger, "removeSharedContext: unexpected null response"); + return null; + } + SharedContext jsonObj = null; + try { + jsonObj = mapper.readValue(hsr.getResponse(), SharedContext.class); + } catch (JsonMappingException ex) { + logger.error(EELFLoggerDelegate.applicationLogger, + "removeSharedContext: failed to map response onto object" + ex.getMessage()); + } catch (JsonParseException ex) { + logger.error(EELFLoggerDelegate.applicationLogger, + "removeSharedContext: failed to parse response" + ex.getMessage()); + } + if (jsonObj == null) + return null; + String response = jsonObj.getResponse(); + return ("removed".equals(response)); + } + + /** + * Clears the shared context for the specified context ID; i.e., removes all + * key-value pairs. + * + * @param contextId + * An Ecomp Portal session ID + * @return Number of key-value pairs removed; -1 if not found or any + * problems occur. + * @throws Exception + */ + public int clearSharedContext(String contextId) throws Exception { + HttpStatusAndResponse hsr = getContext("remove", contextId, null); + logger.info(EELFLoggerDelegate.debugLogger, "clearSharedContext: resp is " + hsr); + if (hsr == null) { + logger.error(EELFLoggerDelegate.applicationLogger, "clearSharedContext: unexpected null response"); + return -1; + } + SharedContext jsonObj = null; + try { + jsonObj = mapper.readValue(hsr.getResponse(), SharedContext.class); + } catch (JsonMappingException ex) { + logger.error(EELFLoggerDelegate.applicationLogger, + "clearSharedContext: failed to map response onto object" + ex.getMessage()); + } catch (JsonParseException ex) { + logger.error(EELFLoggerDelegate.applicationLogger, + "clearSharedContext: failed to parse response" + ex.getMessage()); + } + if (jsonObj == null) + return -1; + String response = jsonObj.getResponse(); + if (response == null) + return -1; + return Integer.parseInt(response); + } + + /** + * Creates a shared-context entry. + * + * @param contextId + * An Ecomp Portal session ID + * @param key + * Key for the shared-context entry; e.g., "lastName" + * @param value + * Value for the entry + * @throws Exception + * @return True if the object previously existed, false otherwise; null if + * any problem happened. + */ + public Boolean setSharedContext(String contextId, String key, String value) throws Exception { + String body = buildContext(contextId, key, value); + HttpStatusAndResponse hsr = postContext("set", body); + logger.info(EELFLoggerDelegate.debugLogger, "setSharedContext: resp is " + hsr); + if (hsr == null) { + logger.error(EELFLoggerDelegate.applicationLogger, "setSharedContext: unexpected null response"); + return null; + } + SharedContext jsonObj = null; + try { + jsonObj = mapper.readValue(hsr.getResponse(), SharedContext.class); + } catch (JsonMappingException ex) { + logger.error(EELFLoggerDelegate.applicationLogger, + "setSharedContext: failed to map response onto object" + ex.getMessage()); + } catch (JsonParseException ex) { + logger.error(EELFLoggerDelegate.applicationLogger, + "setSharedContext: failed to parse response" + ex.getMessage()); + } + if (jsonObj == null) + return null; + String response = jsonObj.getResponse(); + return ("replaced".equals(response)); + } + + /** + * Builds the full URL with the specified parameters, then calls the method + * that adds credentials and GETs. + * + * @param requestPath + * @param contextId + * @param contextKey + * @return HttpStatusAndResponse object; may be null. + * @throws Exception + */ + private HttpStatusAndResponse getContext(String requestPath, String contextId, String contextKey) throws Exception { + URIBuilder uriBuilder = new URIBuilder(getSharedContextUrl() + requestPath); + uriBuilder.addParameter("context_id", contextId); + if (contextKey != null) + uriBuilder.addParameter("ckey", contextKey); + final URI uri = uriBuilder.build(); + return getRestWithCredentials(uri); + } + + /** + * Builds the full URL, then calls the method that adds credentials and + * POSTs. + * + * @param requestPath + * @param contextId + * @param contextKey + * @return HttpStatusAndResponse object; may be null. + * @throws Exception + */ + private HttpStatusAndResponse postContext(String requestPath, String json) throws Exception { + URIBuilder uriBuilder = new URIBuilder(getSharedContextUrl() + requestPath); + URI uri = uriBuilder.build(); + return postRestWithCredentials(uri, json); + } + + /** + * Builds a JSON block with a single shared-context entry. + * + * @param cxid + * Context ID + * @param ckey + * Context Key + * @param cvalue + * Context value + * @return JSON block + */ + private String buildContext(String cxid, String ckey, String cvalue) throws JsonProcessingException { + ObjectMapper mapper = new ObjectMapper(); + HashMap<String, String> stringMap = new HashMap<String, String>(); + stringMap.put("context_id", cxid); + stringMap.put("ckey", ckey); + stringMap.put("cvalue", cvalue); + String json = mapper.writeValueAsString(stringMap); + return json; + } + + // Simple test scaffold + public static void main(String[] args) throws Exception { + // ObjectMapper mapper = new ObjectMapper(); + // SharedContext cxt = mapper.readValue("{ \"response\":\"foo\" }", + // SharedContext.class); + SharedContextRestClient client = new SharedContextRestClient(); + SharedContext get = client.getContextValue("abc", "123"); + System.out.println("Get yields " + get.toString()); + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/scheduler/CoreRegister.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/scheduler/CoreRegister.java new file mode 100644 index 00000000..5f81308f --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/scheduler/CoreRegister.java @@ -0,0 +1,95 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.scheduler; + +import java.util.ArrayList; +import java.util.List; + +import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.quartz.CronTrigger; +import org.quartz.Trigger; +import org.springframework.context.annotation.DependsOn; +import org.springframework.stereotype.Component; + +@Component +@DependsOn({"systemProperties"}) +public class CoreRegister { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CoreRegister.class); + Trigger trigger[] = new Trigger[1]; + + + + //@Autowired + //private SessionMgtRegistry sessionMgtRegistry; + + protected List<Trigger> scheduleTriggers = new ArrayList<Trigger>(); + + + public void registerTriggers() { + // we can use this method to add any schedules to the core + + /* + try { + if(SystemProperties.getProperty(SystemProperties.SESSIONTIMEOUT_FEED_CRON) != null) + getScheduleTriggers().add(sessionMgtRegistry.getTrigger()); + + } catch(IllegalStateException ies) { + logger.info("Session Timout Cron not available"); + } + */ + + } + + protected void addTrigger(final String cron, final CronTrigger cronRegistryTrigger) { + // if the property value is not available; the cron will not be added and can be ignored. its safe to ignore the exceptions + + try { + + if(SystemProperties.getProperty(cron) != null) { + getScheduleTriggers().add(cronRegistryTrigger); + } + + } catch(IllegalStateException ies) { + logger.error(EELFLoggerDelegate.errorLogger, "Log Cron not available", AlarmSeverityEnum.MAJOR); + } + } + + + + + public List<Trigger> getScheduleTriggers() { + return scheduleTriggers; + } + + + + public void setScheduleTriggers(List<Trigger> scheduleTriggers) { + this.scheduleTriggers = scheduleTriggers; + } + + + + + + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/scheduler/CronRegistry.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/scheduler/CronRegistry.java new file mode 100644 index 00000000..dfd9a817 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/scheduler/CronRegistry.java @@ -0,0 +1,125 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.scheduler; + +import java.text.ParseException; +import java.util.Map; + +import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.quartz.CronTrigger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.quartz.CronTriggerFactoryBean; +import org.springframework.scheduling.quartz.JobDetailFactoryBean; +import org.springframework.scheduling.quartz.QuartzJobBean; + +import com.mchange.v2.c3p0.ComboPooledDataSource; + +public abstract class CronRegistry { + + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CronRegistry.class); + protected JobDetailFactoryBean jobDetailFactory; + protected CronTriggerFactoryBean cronTriggerFactory; + + private ComboPooledDataSource dataSource; + + public CronRegistry() { + try { + jobDetailFactoryBean(); + cronTriggerFactoryBean(); + } + catch(Exception e) { + logger.error(EELFLoggerDelegate.debugLogger, e.getMessage()); + } + } + + //@Autowired + public CronRegistry(ComboPooledDataSource dataSource) { + try { + this.dataSource = dataSource; + jobDetailFactoryBean(); + cronTriggerFactoryBean(); + } + catch(Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AlarmSeverityEnum.MAJOR); + } + } + + //@Autowired + public CronRegistry(Object... initializeObjects) { + try { + initializeObjects(initializeObjects); + jobDetailFactoryBean(); + cronTriggerFactoryBean(); + } + catch(Exception e) { + logger.info(EELFLoggerDelegate.errorLogger, e.getMessage()); + } + } + + protected void initializeObjects(Object... initializeObjects) { + } + + public abstract JobDetailFactoryBean jobDetailFactoryBean() throws ParseException; + + protected JobDetailFactoryBean jobDetailFactoryBean(String groupName, String jobName, + Class<? extends QuartzJobBean> jobClass, Map<String, Object> map) { + + jobDetailFactory = new JobDetailFactoryBean(); + jobDetailFactory.setJobClass(jobClass); + jobDetailFactory.setJobDataAsMap(map); + jobDetailFactory.setGroup(groupName); + jobDetailFactory.setName(jobName); + jobDetailFactory.afterPropertiesSet(); + + return jobDetailFactory; + } + + public abstract CronTriggerFactoryBean cronTriggerFactoryBean() throws ParseException; + + protected CronTriggerFactoryBean cronTriggerFactoryBean(String groupName, String triggerName, String cronExpression) throws ParseException { + cronTriggerFactory = new CronTriggerFactoryBean(); + cronTriggerFactory.setJobDetail(jobDetailFactory.getObject()); + cronTriggerFactory.setStartDelay(3000); + cronTriggerFactory.setName(triggerName); + cronTriggerFactory.setGroup(groupName); + logger.info(EELFLoggerDelegate.applicationLogger, triggerName + " Scheduled: " + cronExpression); + cronTriggerFactory.setCronExpression( cronExpression); //"0 * * * * ? *" + cronTriggerFactory.afterPropertiesSet(); + return cronTriggerFactory; + } + + public CronTrigger getTrigger() { + return cronTriggerFactory.getObject(); + } + + + public void setDataSource(ComboPooledDataSource dataSource) { + this.dataSource = dataSource; + } + + + public ComboPooledDataSource getDataSource() { + return dataSource; + } + + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/scheduler/Registerable.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/scheduler/Registerable.java new file mode 100644 index 00000000..e2e4c385 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/scheduler/Registerable.java @@ -0,0 +1,30 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.scheduler; + +import org.quartz.Trigger; + +public interface Registerable { + + public void registerTriggers(); + + public Trigger[] getTriggers(); + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/AppService.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/AppService.java new file mode 100644 index 00000000..55180fd7 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/AppService.java @@ -0,0 +1,61 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.service; + +import java.util.List; + +import org.openecomp.portalsdk.core.domain.App; + +/** + * Defines methods to fetch App domain objects. + * + * Very thin interface; Portal defines a much richer interface. + */ +public interface AppService { + + /** + * Gets all apps defined in the table. + * + * @return List of apps. + */ + List<App> getApps(); + + /** + * Gets the app with the specified ID. + * + * @param appId + * @return App with the specified ID. + */ + App getApp(Long appId); + + /** + * Gets the singleton entry - applications should have exactly 1 row in the + * FN_APP table. + */ + App getDefaultApp(); + + /** + * Fetches the application name once from database + * and keep refers to the same name later on as required. + * @return Default Application Name + */ + String getDefaultAppName(); + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/AppServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/AppServiceImpl.java new file mode 100644 index 00000000..b06b36fc --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/AppServiceImpl.java @@ -0,0 +1,106 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.service; + +import java.util.List; + +import org.openecomp.portalsdk.core.domain.App; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service("appService") +@Transactional +public class AppServiceImpl implements AppService{ + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppServiceImpl.class); + + @Autowired + private DataAccessService dataAccessService; + + /** + * Loads the appName once from database and + * keep refers to it as required. + */ + private static String defaultAppName = ""; + + /* + * (non-Javadoc) + * @see org.openecomp.portalsdk.core.service.AppService#getApps() + */ + @SuppressWarnings("unchecked") + @Override + public List<App> getApps() { + return getDataAccessService().getList(App.class, null); + } + + /* + * (non-Javadoc) + * @see org.openecomp.portalsdk.service.AppService#getApp(long) + */ + @Override + public App getApp(Long appId) { + return (App)getDataAccessService().getDomainObject(App.class, appId, null); + } + + /* + * (non-Javadoc) + * @see org.openecomp.portalsdk.service.AppService#getApp() + */ + @Override + public App getDefaultApp() { + return getApp(1L); + } + + /** + * Gets the data access service. + * @return DataAccessService + */ + public DataAccessService getDataAccessService() { + return dataAccessService; + } + + /** + * Sets the data access service. + * @param dataAccessService + */ + public void setDataAccessService(DataAccessService dataAccessService) { + this.dataAccessService = dataAccessService; + } + + /** + * Fetches the application name once from database + * and keep refers to the same name later on as required. + * @return Default Application Name + */ + @Override + public String getDefaultAppName() { + if (AppServiceImpl.defaultAppName==null || AppServiceImpl.defaultAppName=="") { + App app = getApp(1L); + if (app!=null) { + AppServiceImpl.defaultAppName = app.getName(); + } else { + logger.warn(EELFLoggerDelegate.errorLogger, ("Unable to locate the app information from the database.")); + } + } + return AppServiceImpl.defaultAppName; + } +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/AuditService.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/AuditService.java new file mode 100644 index 00000000..b228d1b1 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/AuditService.java @@ -0,0 +1,37 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.service; + +import java.util.HashMap; + +import org.openecomp.portalsdk.core.domain.AuditLog; + +public interface AuditService { + /** + * + * Update log data in database + * + * @param auditLog + * @param additionalParams + */ + + @SuppressWarnings("rawtypes") + void logActivity(AuditLog auditLog, HashMap additionalParams); +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/AuditServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/AuditServiceImpl.java new file mode 100644 index 00000000..433cd2ac --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/AuditServiceImpl.java @@ -0,0 +1,50 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.service; + +import java.util.HashMap; + +import org.openecomp.portalsdk.core.domain.AuditLog; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service("auditService") +@Transactional +public class AuditServiceImpl implements AuditService { + public AuditServiceImpl() {} + + @Autowired + private DataAccessService dataAccessService; + + @SuppressWarnings("rawtypes") + public void logActivity(AuditLog auditLog, HashMap additionalParams) { + getDataAccessService().saveDomainObject(auditLog, additionalParams); + } + + public DataAccessService getDataAccessService() { + return dataAccessService; + } + + public void setDataAccessService(DataAccessService dataAccessService) { + this.dataAccessService = dataAccessService; + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/BroadcastService.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/BroadcastService.java new file mode 100644 index 00000000..66315b92 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/BroadcastService.java @@ -0,0 +1,36 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.service; + +import java.util.*; + +import javax.servlet.http.HttpServletRequest; + +import org.openecomp.portalsdk.core.domain.BroadcastMessage; + +@SuppressWarnings("rawtypes") +public interface BroadcastService { + HashMap getBcModel(HttpServletRequest request); + Hashtable getBroadcastMessages(); + void loadMessages(); + BroadcastMessage getBroadcastMessage(HttpServletRequest request); + void saveBroadcastMessage(BroadcastMessage broadcastMessage); + void removeBroadcastMessage(BroadcastMessage broadcastMessage); +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/BroadcastServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/BroadcastServiceImpl.java new file mode 100644 index 00000000..92a77507 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/BroadcastServiceImpl.java @@ -0,0 +1,250 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.service; + +import java.util.Calendar; +import java.util.Collections; +import java.util.HashMap; +import java.util.Hashtable; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; + +import javax.servlet.http.HttpServletRequest; + +import org.openecomp.portalsdk.core.domain.BroadcastMessage; +import org.openecomp.portalsdk.core.domain.Lookup; +import org.openecomp.portalsdk.core.service.support.FusionService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.portalsdk.core.web.support.AppUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.ServletRequestBindingException; +import org.springframework.web.bind.ServletRequestUtils; + +@SuppressWarnings("rawtypes") +@Service("broadcastService") +@Transactional +public class BroadcastServiceImpl extends FusionService implements BroadcastService { + + public BroadcastServiceImpl() { + } + + @Autowired + private DataAccessService dataAccessService; + private static Hashtable broadcastMessages = new Hashtable(); + + @SuppressWarnings("unchecked") + public void loadMessages() { + List messageLocations = AppUtils.getLookupListNoCache("fn_lu_message_location", "message_location_id", "message_location_descr", "", "message_location_id"); + + for (int i=0; i < messageLocations.size(); i++) { + Lookup location = (Lookup)messageLocations.get(i); + String locationId = location.getValue(); + + broadcastMessages.put(locationId, getPersistedBroadcastMessages(locationId)); + } + } + + public HashMap getBcModel(HttpServletRequest request){ + HashMap bcModel = new HashMap(); + + List items = null; + int messageId = ServletRequestUtils.getIntParameter(request, "message_id", 0); + String task = ServletRequestUtils.getStringParameter(request, "task", "get"); + + // delete or toggle activation on the selected record (if applicable) + if (messageId != 0 && (task.equals("delete") || task.equals("toggleActive"))) { + BroadcastMessage message = (BroadcastMessage)getDataAccessService().getDomainObject(BroadcastMessage.class, new Long(messageId), null); + + if (task.equals("delete")) { + getDataAccessService().deleteDomainObject(message, null); + } + else if (task.equals("toggleActive")) { + HashMap additionalParams = new HashMap(); + additionalParams.put(Parameters.PARAM_HTTP_REQUEST, request); + + message.setActive(new Boolean(!message.getActive().booleanValue())); + getDataAccessService().saveDomainObject(message, additionalParams); + } + loadMessages(); + } + + items = getDataAccessService().getList(BroadcastMessage.class, null); + Collections.sort(items); + bcModel.put("messagesList", packageMessages(items)); + + List locations = AppUtils.getLookupList("fn_lu_message_location", "message_location_id", "message_location_descr", "", "message_location_id"); + bcModel.put("messageLocations", locations); + + if ("true".equals(SystemProperties.getProperty(SystemProperties.CLUSTERED))) { + List sites = AppUtils.getLookupList("fn_lu_broadcast_site", "broadcast_site_cd", "broadcast_site_descr", "", "broadcast_site_descr"); + bcModel.put("broadcastSites", sites); + } + + return bcModel; + } + + @SuppressWarnings("unchecked") + private HashMap packageMessages(List messages) { + HashMap messagesList = new HashMap(); + Set locationMessages = null; + + Integer previousLocationId = null; + + for (int i=0; i < messages.size(); i++) { + BroadcastMessage message = (BroadcastMessage)messages.get(i); + + if (!message.getLocationId().equals(previousLocationId)) { + if (previousLocationId != null) { + messagesList.put(previousLocationId.toString(), locationMessages); + } + + locationMessages = new TreeSet(); + previousLocationId = message.getLocationId(); + } + + locationMessages.add(message); + } + + if (previousLocationId != null) { + messagesList.put(previousLocationId.toString(), locationMessages); + } + + return messagesList; + } + + + @SuppressWarnings("unchecked") + private List getPersistedBroadcastMessages(String locationId) { + HashMap params = new HashMap(); + + + + params.put("location_id", new Integer(locationId)); + + Calendar calInstanceToday = Calendar.getInstance(); + calInstanceToday.set(Calendar.HOUR, 0); + calInstanceToday.set(Calendar.MINUTE, 0); + calInstanceToday.set(Calendar.SECOND, 0); + params.put("today_date", calInstanceToday.getTime()); + + return getDataAccessService().executeNamedQuery("broadcastMessages", params, null); + } + + public Hashtable getBroadcastMessages() { + return broadcastMessages; + } + + public static List getBroadcastMessages(String locationId) { + return (List)broadcastMessages.get(locationId); + } + + public static String displayMessages(String locationId) { + return displayServerMessages(locationId, null); + } + + public static String displayServerMessages(String locationId, String siteCd) { + StringBuffer html = new StringBuffer(); + + List messages = getBroadcastMessages(locationId); + + for (int i=0; i < messages.size(); i++) { + BroadcastMessage message = (BroadcastMessage)messages.get(i); + + if ((message.getSiteCd() == null) || ((message.getSiteCd() != null) && message.getSiteCd().equals(siteCd))) { + html.append("<li class=\"broadcastMessage\">") + .append(message.getMessageText()); + } + } + + if (html.length() > 0) { + html.insert(0, "<ul class=\"broadcastMessageList\">"); + html.append("</ul>"); + } + + return html.toString(); + } + + public static boolean hasMessages(String locationId) { + return hasServerMessages(locationId, null); + } + + public static boolean hasServerMessages(String locationId, String siteCd) { + List messages = getBroadcastMessages(locationId); + + boolean messagesExist = !((messages == null) || messages.size() == 0); + + if (siteCd == null) { + return messagesExist; + } + else { + for (int i=0; i < messages.size(); i++) { + BroadcastMessage message = (BroadcastMessage)messages.get(i); + + if ((message.getSiteCd() == null) || message.getSiteCd().equals(siteCd)) { + return true; + } + } + return false; + } + } + + public DataAccessService getDataAccessService() { + return dataAccessService; + } + + public void setDataAccessService(DataAccessService dataAccessService) { + dataAccessService = dataAccessService; + } + + public BroadcastMessage getBroadcastMessage(HttpServletRequest request) { + long messageId = ServletRequestUtils.getLongParameter(request, "message_id", 0); + + BroadcastMessage message = new BroadcastMessage(); + if(messageId!=0) + message = (BroadcastMessage)getDataAccessService().getDomainObject(BroadcastMessage.class, new Long(messageId), null); + + if (message.getLocationId() == null) { + try { + message.setLocationId(new Integer(ServletRequestUtils.getStringParameter(request, "message_location_id"))); + } catch (NumberFormatException e) { + e.printStackTrace(); + } catch (ServletRequestBindingException e) { + e.printStackTrace(); + } + message.setActive(Boolean.TRUE); + } + + return message; + } + + @Override + public void saveBroadcastMessage(BroadcastMessage broadcastMessage) { + dataAccessService.saveDomainObject(broadcastMessage, null); + } + + @Override + public void removeBroadcastMessage(BroadcastMessage broadcastMessage) { + dataAccessService.deleteDomainObject(broadcastMessage, null); + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/DataAccessService.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/DataAccessService.java new file mode 100644 index 00000000..26892b88 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/DataAccessService.java @@ -0,0 +1,80 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.service; + + +import java.io.Serializable; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.hibernate.FetchMode; +import org.hibernate.criterion.Criterion; +import org.hibernate.criterion.Order; +import org.hibernate.criterion.ProjectionList; +import org.openecomp.portalsdk.core.domain.support.DomainVo; + +@SuppressWarnings("rawtypes") +public interface DataAccessService { + + // generic view, save, delete methods + DomainVo getDomainObject(Class domainClass, Serializable id, HashMap additionalParams); + void deleteDomainObject(DomainVo domainObject, HashMap additionalParams); + void deleteDomainObjects(Class domainClass, String whereClause, HashMap additionalParams); + void saveDomainObject(DomainVo domainObject, HashMap additionalParams); + + // generic get list method(s) + List getList(Class domainClass, HashMap additionalParams); + List getList(Class domainClass, String filter, String orderBy, HashMap additionalParams); + List getList(Class domainClass, String filter, int fromIndex, int toIndex, String orderBy, HashMap additionalParams); + List<?> getList(Class<?> domainClass, ProjectionList projectionsList , List<Criterion> restrictionsList , List<Order> orderByList); + public List<?> getList(Class<?> domainClass, ProjectionList projectionsList, List<Criterion> restrictionsList, List<Order> orderByList,HashMap<String,FetchMode> fetchModeMap); + + List getLookupList(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy, HashMap additionalParams); + + // generic native-SQL execution methods + List executeSQLQuery(String sql, Class domainClass, HashMap additionalParams); + List executeSQLQuery(String sql, Class domainClass, Integer fromIndex, Integer toIndex,HashMap additionalParams); + + // generic HQL execution methods + List executeQuery(String hql, HashMap additionalParams); + List executeQuery(String hql, Integer fromIndex, Integer toIndex, HashMap additionalParams); + + // generic named query execution methods + List executeNamedQuery(String queryName, Integer fromIndex, Integer toIndex, HashMap additionalParams); + List executeNamedQuery(String queryName, Map params, HashMap additionalParams); + List executeNamedQuery(String queryName, Map params, Integer fromIndex, Integer toIndex, HashMap additionalParams); + + //with Where Clause for RAPTOR ZK + List executeNamedQueryWithOrderBy(Class entity, String queryName, Map params, String _orderBy, boolean asc, Integer fromIndex, Integer toIndex, HashMap additionalParams); + List executeNamedCountQuery(Class entity, String queryName, String whereClause, Map params); + List executeNamedQuery(Class entity, String queryName, String whereClause, Map params, Integer fromIndex, Integer toIndex, HashMap additionalParams); + List executeNamedQueryWithOrderBy(Class entity, String queryName, String whereClause, Map params, String _orderBy, boolean asc, Integer fromIndex, Integer toIndex, HashMap additionalParams); + + // generic update query execution method + int executeUpdateQuery(String sql, HashMap additionalParams) throws RuntimeException; + + // generic named update query execution method + int executeNamedUpdateQuery(String queryName, Map params, HashMap additionalParams) throws RuntimeException; + + // synchronizes the local updates with the database (and vice versa) + void synchronize(HashMap additionalParams); + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/DataAccessServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/DataAccessServiceImpl.java new file mode 100644 index 00000000..9c52b1b4 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/DataAccessServiceImpl.java @@ -0,0 +1,594 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.service; + +import java.io.Serializable; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.hibernate.Criteria; +import org.hibernate.FetchMode; +import org.hibernate.Query; +import org.hibernate.SQLQuery; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.criterion.Criterion; +import org.hibernate.criterion.Order; +import org.hibernate.criterion.ProjectionList; +import org.openecomp.portalsdk.core.domain.Lookup; +import org.openecomp.portalsdk.core.domain.support.DomainVo; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.support.FusionService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.annotation.Transactional; + +/** + * Provides implementations of methods in {@link DataAccessService}. + */ +@Transactional +public class DataAccessServiceImpl extends FusionService implements DataAccessService { + + @Autowired + private SessionFactory sessionFactory; + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DataAccessServiceImpl.class); + + /* + * (non-Javadoc) + * + * @see + * org.openecomp.portalsdk.core.service.DataAccessService#getDomainObject(java.lang. + * Class, java.io.Serializable, java.util.HashMap) + */ + @Override + public DomainVo getDomainObject(Class domainClass, Serializable id, HashMap additionalParams) { + DomainVo vo = null; + Session session = sessionFactory.getCurrentSession(); + logger.info(EELFLoggerDelegate.debugLogger, "Getting " + domainClass.getName() + " record for id - " + id.toString()); + vo = (DomainVo) session.get(domainClass, id); + + if (vo == null) { + try { + vo = (DomainVo) domainClass.newInstance(); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "An error occured while instantiating a class of " + domainClass.getName() + e.getMessage()); + } + } + return vo; + } + + /* + * (non-Javadoc) + * + */ + @Override + public void deleteDomainObject(DomainVo domainObject, HashMap additionalParams) { + Session session = sessionFactory.getCurrentSession(); + session.delete(domainObject); + } + + /* + * (non-Javadoc) + * + * @see + * org.openecomp.portalsdk.core.service.DataAccessService#deleteDomainObjects(java. + * lang.Class, java.lang.String, java.util.HashMap) + */ + @Override + public void deleteDomainObjects(Class domainClass, String whereClause, HashMap additionalParams) { + int rowsAffected = 0; + Session session = sessionFactory.getCurrentSession(); + + StringBuffer sql = new StringBuffer("delete from "); + + sql.append(domainClass.getName()).append(" where ").append(whereClause); + + rowsAffected = session.createQuery(sql.toString()).executeUpdate(); + /* return rowsAffected; */ + } + + /* + * (non-Javadoc) + * + * @see + * org.openecomp.portalsdk.core.service.DataAccessService#saveDomainObject + */ + @Override + public void saveDomainObject(DomainVo vo, HashMap additionalParams) { + Integer userId = 1; + if (additionalParams != null) { + // look for a passed user id + // userId = (Integer)additionalParams.get(Parameters.PARAM_USERID); + Object uid = additionalParams.get(Parameters.PARAM_USERID); + if (uid instanceof Integer) { + userId = (Integer) uid; + } else if (uid instanceof Long) { + userId = ((Long) uid).intValue(); + } + // if (userId == null) { + // look for a passed request to get the user id from + // userId = new + // Integer(UserUtils.getUserId((HttpServletRequest)additionalParams.get(Parameters.PARAM_HTTP_REQUEST))); + // } + } + _update(vo, userId); + } + + /** + * Creates or updates the specified virtual object. Uses the specified user + * ID as the creator and modifier if a new object is created; uses ID only + * as modifier if an object already exists. + * + * @param vo + * @param userId + * Ignored if value is zero. + */ + protected final void _update(DomainVo vo, int userId) { + Date timestamp = new Date(); + + Session session = sessionFactory.getCurrentSession(); + + if (vo.getId() == null || vo.getId().intValue() == 0) { // add new + vo.setCreated(timestamp); + vo.setModified(timestamp); + + if (userId != 0 + && userId != Integer.parseInt(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID))) { + vo.setCreatedId(new Long(userId)); + vo.setModifiedId(new Long(userId)); + } + } else { // update existing + vo.setModified(timestamp); + + if (userId != 0 + && userId != Integer.parseInt(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID))) { + vo.setModifiedId(new Long(userId)); + } + } + + session.saveOrUpdate(vo); + } + + /** + * generic get list method + * + * @param domainClass + * @param filterClause + * @param fromIndex + * @param toIndex + * @param orderBy + * @return + */ + private List getListCommon(Class domainClass, String filterClause, Integer fromIndex, Integer toIndex, + String orderBy) { + List list = null; + String className = domainClass.getName(); + Session session = sessionFactory.getCurrentSession(); + + if (logger.isInfoEnabled()) { + logger.info(EELFLoggerDelegate.debugLogger, "Getting " + className.toLowerCase() + " records" + + ((fromIndex != null) ? " from rows " + fromIndex.toString() + " to " + toIndex.toString() : "") + + "..."); + if (filterClause != null && filterClause.length() > 0) + logger.info(EELFLoggerDelegate.debugLogger, "Filtering " + className + " by: " + filterClause); + } + + list = session.createQuery("from " + className + Utilities.nvl(filterClause, "") + + ((orderBy != null) ? " order by " + orderBy : "")).list(); + list = (fromIndex != null) ? list.subList(fromIndex.intValue() - 1, toIndex.intValue()) : list; + + if (orderBy == null && list != null) + Collections.sort(list); + + return list; + } + + /* + * (non-Javadoc) + * + * @see + * org.openecomp.portalsdk.core.service.DataAccessService#getList(java.lang.Class, + * java.util.HashMap) + */ + @Override + public List getList(Class domainClass, HashMap additionalParams) { + return getListCommon(domainClass, null, null, null, null); + } + + /* + * (non-Javadoc) + * + * @see + * org.openecomp.portalsdk.core.service.DataAccessService#getList(java.lang.Class, + * java.lang.String, java.lang.String, java.util.HashMap) + */ + @Override + public List getList(Class domainClass, String filter, String orderBy, HashMap additionalParams) { + return getListCommon(domainClass, filter, null, null, orderBy); + } + + /* + * (non-Javadoc) + * + * @see + * org.openecomp.portalsdk.core.service.DataAccessService#getList(java.lang.Class, + * java.lang.String, int, int, java.lang.String, java.util.HashMap) + */ + @Override + public List getList(Class domainClass, String filter, int fromIndex, int toIndex, String orderBy, + HashMap additionalParams) { + return getListCommon(domainClass, filter, new Integer(fromIndex), new Integer(toIndex), orderBy); + } + + /* + * (non-Javadoc) + * + * @see + * org.openecomp.portalsdk.core.service.DataAccessService#getList(java.lang.Class, + * org.hibernate.criterion.ProjectionList, java.util.List, java.util.List) + */ + @Override + public List<?> getList(Class<?> domainClass, ProjectionList projectionsList, List<Criterion> restrictionsList, + List<Order> orderByList) { + + Session session = sessionFactory.getCurrentSession(); + + Criteria criteria = session.createCriteria(domainClass); + + if (projectionsList != null) { + criteria.setProjection(projectionsList); + } + + if (restrictionsList != null && !restrictionsList.isEmpty()) { + for (Criterion criterion : restrictionsList) + criteria.add(criterion); + } + + if (orderByList != null && !orderByList.isEmpty()) { + for (Order order : orderByList) + criteria.addOrder(order); + } + /* + * if(fetchModeMap!=null){ Iterator<String> itr = + * fetchModeMap.keySet().iterator(); String key=null; + * while(itr.hasNext()){ key = itr.next(); + * criteria.setFetchMode(key,fetchModeMap.get(key)); } } + */ + return criteria.list(); + } + + /* + * (non-Javadoc) + * + * @see + * org.openecomp.portalsdk.core.service.DataAccessService#getLookupList(java.lang. + * String, java.lang.String, java.lang.String, java.lang.String, + * java.lang.String, java.util.HashMap) + */ + @Override + public List getLookupList(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy, + HashMap additionalParams) { + if (logger.isInfoEnabled()) + logger.info(EELFLoggerDelegate.debugLogger, "Retrieving " + dbTable + " lookup list..."); + String dbOrderByCol = dbOrderBy; + + Session session = sessionFactory.getCurrentSession(); + + // default the orderBy if null; + if (Utilities.nvl(dbOrderBy).length() == 0) { + dbOrderByCol = dbLabelCol; + dbOrderBy = dbLabelCol; + } else { + if (dbOrderBy.lastIndexOf(" ") > -1) { + dbOrderByCol = dbOrderBy.substring(0, dbOrderBy.lastIndexOf(" ")); + } + } + + StringBuffer sql = new StringBuffer(); + + sql.append("select distinct ").append(dbLabelCol).append(" as lab, ").append(dbValueCol).append(" as val, ") + .append(dbOrderByCol).append(" as sortOrder ").append("from ").append(dbTable).append(" ") + .append((Utilities.nvl(dbFilter).length() == 0) ? "" : (" where " + dbFilter)).append(" order by ") + .append(dbOrderBy); + + List list = null; + try { + list = session.createSQLQuery(sql.toString()).addEntity(Lookup.class).list(); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.debugLogger, "Failed to create SQL lookup query for [" + sql + "]" + e.getMessage()); + } + return list; + } + + /* + * methods accepting a Map of additional params to passed to the DAO (for + * extensibility, just in case) + */ + + /* + * (non-Javadoc) + * + * @see + * org.openecomp.portalsdk.core.service.DataAccessService#executeSQLQuery(java.lang. + * String, java.lang.Class, java.util.HashMap) + */ + @Override + public List executeSQLQuery(String sql, Class domainClass, HashMap additionalParams) { + return executeSQLQuery(sql, domainClass, null, null, additionalParams); + } + + /* + * (non-Javadoc) + * + * @see + * org.openecomp.portalsdk.core.service.DataAccessService#executeSQLQuery(java.lang. + * String, java.lang.Class, java.lang.Integer, java.lang.Integer, + * java.util.HashMap) + */ + @Override + public List executeSQLQuery(String sql, Class domainClass, Integer fromIndex, Integer toIndex, + HashMap additionalParams) { + Session session = sessionFactory.getCurrentSession(); + + SQLQuery query = session.createSQLQuery(sql).addEntity(domainClass.getName().toLowerCase(), domainClass); + + if (fromIndex != null && toIndex != null) { + query.setFirstResult(fromIndex.intValue()); + int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1; + query.setMaxResults(pageSize); + } + + return query.list(); + } + + /* + * (non-Javadoc) + * + * @see + * org.openecomp.portalsdk.core.service.DataAccessService#executeQuery(java.lang. + * String, java.util.HashMap) + */ + @Override + public List executeQuery(String sql, HashMap additionalParams) { + return executeQuery(sql, null, null, additionalParams); + } + + /* + * (non-Javadoc) + * + * @see + * org.openecomp.portalsdk.core.service.DataAccessService#executeQuery(java.lang. + * String, java.lang.Integer, java.lang.Integer, java.util.HashMap) + */ + @Override + public List executeQuery(String sql, Integer fromIndex, Integer toIndex, HashMap additionalParams) { + Session session = sessionFactory.getCurrentSession(); + + Query query = session.createQuery(sql); + + if (fromIndex != null && toIndex != null) { + query.setFirstResult(fromIndex.intValue()); + int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1; + query.setMaxResults(pageSize); + } + + return query.list(); + } + + /* + * (non-Javadoc) + * + * @see + * org.openecomp.portalsdk.core.service.DataAccessService#executeNamedQuery(java.lang + * .String, java.lang.Integer, java.lang.Integer, java.util.HashMap) + */ + @Override + public List executeNamedQuery(String queryName, Integer fromIndex, Integer toIndex, HashMap additionalParams) { + return executeNamedQuery(queryName, null, fromIndex, toIndex, additionalParams); + } + + /* + * (non-Javadoc) + * + * @see + * org.openecomp.portalsdk.core.service.DataAccessService#executeNamedQuery(java.lang + * .String, java.util.Map, java.util.HashMap) + */ + @Override + public List executeNamedQuery(String queryName, Map params, HashMap additionalParams) { + return executeNamedQuery(queryName, params, null, null, additionalParams); + } + + /* + * (non-Javadoc) + * + * @see + * org.openecomp.portalsdk.core.service.DataAccessService#executeNamedQuery(java.lang + * .String, java.util.Map, java.lang.Integer, java.lang.Integer, + * java.util.HashMap) + */ + @Override + public List executeNamedQuery(String queryName, Map params, Integer fromIndex, Integer toIndex, + HashMap additionalParams) { + Session session = sessionFactory.getCurrentSession(); + Query query = session.getNamedQuery(queryName); + bindQueryParameters(query, params); + if (fromIndex != null && toIndex != null) { + query.setFirstResult(fromIndex.intValue()); + int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1; + query.setMaxResults(pageSize); + } + return query.list(); + } + + /** + * Stores parameters into the query using String keys from the map. Gives + * special treatment to map values of Collection and array type. + * + * @param query + * Query with parameters + * @param params + * Map of String to Object. + */ + private void bindQueryParameters(Query query, Map params) { + if (params != null) { + for (Iterator i = params.entrySet().iterator(); i.hasNext();) { + Map.Entry entry = (Map.Entry) i.next(); + + Object parameterValue = entry.getValue(); + + if (!(parameterValue instanceof Collection) && !(parameterValue instanceof Object[])) { + query.setParameter((String) entry.getKey(), parameterValue); + } else if (parameterValue instanceof Collection) { + query.setParameterList((String) entry.getKey(), (Collection) parameterValue); + } else if (parameterValue instanceof Object[]) { + query.setParameterList((String) entry.getKey(), (Object[]) parameterValue); + } + } + } + } + + // With Where Clause & RAPTOR's ZK + + /* + * (non-Javadoc) + * + * @see org.openecomp.portalsdk.core.service.DataAccessService# + * executeNamedQueryWithOrderBy(java.lang.Class, java.lang.String, + * java.util.Map, java.lang.String, boolean, java.lang.Integer, + * java.lang.Integer, java.util.HashMap) + */ + @Override + public List executeNamedQueryWithOrderBy(Class entity, String queryName, Map params, String _orderBy, boolean asc, + Integer fromIndex, Integer toIndex, HashMap additionalParams) { + // TODO Auto-generated method stub + logger.info(EELFLoggerDelegate.debugLogger, "Not implemented"); + return null; + } + + /* + * (non-Javadoc) + * + * @see + * org.openecomp.portalsdk.core.service.DataAccessService#executeNamedCountQuery(java + * .lang.Class, java.lang.String, java.lang.String, java.util.Map) + */ + @Override + public List executeNamedCountQuery(Class entity, String queryName, String whereClause, Map params) { + // TODO Auto-generated method stub + logger.info(EELFLoggerDelegate.debugLogger, "Not implemented"); + return null; + } + + /* + * (non-Javadoc) + * + * @see + * org.openecomp.portalsdk.core.service.DataAccessService#executeNamedQuery(java.lang + * .Class, java.lang.String, java.lang.String, java.util.Map, + * java.lang.Integer, java.lang.Integer, java.util.HashMap) + */ + @Override + public List executeNamedQuery(Class entity, String queryName, String whereClause, Map params, Integer fromIndex, + Integer toIndex, HashMap additionalParams) { + // TODO Auto-generated method stub + logger.info(EELFLoggerDelegate.debugLogger, "Not implemented"); + return null; + } + + /* + * (non-Javadoc) + * + * @see org.openecomp.portalsdk.core.service.DataAccessService# + * executeNamedQueryWithOrderBy(java.lang.Class, java.lang.String, + * java.lang.String, java.util.Map, java.lang.String, boolean, + * java.lang.Integer, java.lang.Integer, java.util.HashMap) + */ + @Override + public List executeNamedQueryWithOrderBy(Class entity, String queryName, String whereClause, Map params, + String _orderBy, boolean asc, Integer fromIndex, Integer toIndex, HashMap additionalParams) { + // TODO Auto-generated method stub + logger.info(EELFLoggerDelegate.debugLogger, "Not implemented"); + return null; + } + + /* + * (non-Javadoc) + * + * @see + * org.openecomp.portalsdk.core.service.DataAccessService#getList(java.lang.Class, + * org.hibernate.criterion.ProjectionList, java.util.List, java.util.List, + * java.util.HashMap) + */ + @Override + public List<?> getList(Class<?> domainClass, ProjectionList projectionsList, List<Criterion> restrictionsList, + List<Order> orderByList, HashMap<String, FetchMode> fetchModeMap) { + // TODO Auto-generated method stub + logger.info(EELFLoggerDelegate.debugLogger, "Not implemented"); + return null; + } + + /* + * (non-Javadoc) + * + * @see + * org.openecomp.portalsdk.core.service.DataAccessService#executeUpdateQuery(java. + * lang.String, java.util.HashMap) + */ + @Override + public int executeUpdateQuery(String sql, HashMap additionalParams) throws RuntimeException { + // TODO Auto-generated method stub + logger.info(EELFLoggerDelegate.debugLogger, "Not implemented"); + return 0; + } + + /* + * (non-Javadoc) + * + * @see + * org.openecomp.portalsdk.core.service.DataAccessService#executeNamedUpdateQuery( + * java.lang.String, java.util.Map, java.util.HashMap) + */ + @Override + public int executeNamedUpdateQuery(String queryName, Map params, HashMap additionalParams) throws RuntimeException { + // TODO Auto-generated method stub + logger.info(EELFLoggerDelegate.debugLogger, "Not implemented"); + return 0; + } + + /* + * (non-Javadoc) + * + * @see org.openecomp.portalsdk.core.service.DataAccessService#synchronize(java.util. + * HashMap) + */ + @Override + public void synchronize(HashMap additionalParams) { + // TODO Auto-generated method stub + logger.info(EELFLoggerDelegate.debugLogger, "Not implemented"); + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/ElementLinkService.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/ElementLinkService.java new file mode 100644 index 00000000..0cd90dc7 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/ElementLinkService.java @@ -0,0 +1,290 @@ +/*- + * ================================================================================ + * ECOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.service; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.portalsdk.core.util.YamlUtils; + +public class ElementLinkService { + + /** + * Builds renderable model of element links in the network map. Parses YAML + * files with metadata and builds input for JoinJS to render in the browser + * as SVG. + * + * @param args + * arg 0 - realPath; arg 1 - callFlowName; arg 2 - callFlowStep. + * @return Renderable model of element links + * @throws Exception + */ + public String buildElementLinkYaml(String[] args) throws Exception { + String relFilePath; + if (args[1].startsWith("custom")) + relFilePath = SystemProperties.getProperty("customCallFlow_path"); + else + relFilePath = SystemProperties.getProperty("element_map_file_path"); + final String yamlDirPath = new File(args[0], relFilePath).getPath(); + + String callFlowBusinessYml = ""; + String callFlowStep = ""; + + if (args != null && args.length > 0) { + if (args[1] != null) + callFlowBusinessYml = args[1] + ".yml"; + if (args[2] != null) + callFlowStep = args[2]; + } + + ElementLinkService mapper = new ElementLinkService(); + String linkYaml = mapper.createLinkFile(yamlDirPath, callFlowBusinessYml, callFlowStep); + return linkYaml; + } + + /* + * public String main2(String[] args) throws Exception { + * + * String filePath = SystemProperties.getProperty("element_map_file_path") + + * File.separator; String callFlowBusinessYml = ""; String callFlowStep = + * ""; + * + * if (args != null && args.length > 0) { + * + * if (args[0] != null) { callFlowBusinessYml = args[0] + "-Override.yml"; } + * + * if (args[1] != null) { callFlowStep = args[1]; } } + * + * ElementLinkService mapper = new ElementLinkService(); + * + * return mapper.createLinkFileAdditional(filePath, callFlowBusinessYml, + * callFlowStep); } + */ + + public static void main(String[] args) throws Exception { + + String filePath = "\\D2Platform\\war\\WEB-INF\\resources\\trisim_files"; + String callFlowBusinessYml = "call_flow_hc-origination-termination-to-volteue-3.3.16-Override.yml"; + + ElementLinkService mapper = new ElementLinkService(); + + // System.out.print(mapper.createLinkFile(filePath, networkToscaYml, + // networkToscaUeYml, networkLayoutYml, callFlowBusinessYml,"Step_1")); + System.out.print(mapper.createLinkFileAdditional(filePath, callFlowBusinessYml, "Step_2")); + } + + @SuppressWarnings("unchecked") + protected String createLinkFile(String resourceFilePath, String callFLowBsFileName, String callFlowStep) + throws Exception { + + Map<String, Object> callFlowBs = YamlUtils.readYamlFile(resourceFilePath, callFLowBsFileName); + + List<Map<String, Object>> callSteps = (List<Map<String, Object>>) callFlowBs.get("callSequenceSteps"); + String callFlowName = (String) callFlowBs.get("shortName"); + return addLinks(resourceFilePath, callFlowName, callSteps, callFlowStep); + + } + + @SuppressWarnings("unchecked") + protected String createLinkFileAdditional(String resourceFilePath, String callFLowBsFileName, String callFlowStep) + throws Exception { + + // Map<String, Object> callFlowBs = + // YamlUtils.readYamlFile(resourceFilePath, callFLowBsFileName); + + // return YamlUtils.returnYaml(callFlowBs); + + Map<String, Object> callFlowBs; + + try { + callFlowBs = YamlUtils.readYamlFile(resourceFilePath, callFLowBsFileName); + + List<Map<String, Object>> callSteps = (List<Map<String, Object>>) callFlowBs.get("callSequenceSteps"); + String callFlowName = (String) callFlowBs.get("shortName"); + return addLinksAdditional(resourceFilePath, callFlowName, callSteps, callFlowStep); + + } catch (Exception e) { + + return ""; + } + + } + + @SuppressWarnings("unchecked") + protected String addLinks(String filePath, String callFlowName, List<Map<String, Object>> callSteps, + String callFlowStep) throws IOException { + + Map<String, List<String>> checkDuplicateMap = new HashMap<String, List<String>>(); + + for (Map<String, Object> callStep : callSteps) { + + if (((String) callStep.get("name")).split(":")[0].trim().replace(" ", "_").equals(callFlowStep)) { + + // String callFlowStepName = callFlowName + "_" + + // ((String)callStep.get("name")).split("-")[0].trim().replace(" + // ", "_")+".yml"; + + List<Map<String, Object>> links = new ArrayList<Map<String, Object>>(); + + List<Map<String, Object>> subSteps = (List<Map<String, Object>>) callStep.get("subSteps"); + + for (Map<String, Object> subStep : subSteps) { + Map<String, Object> link = new HashMap<String, Object>(); + + String source = (String) subStep.get("source_tosca_id"); + String destination = (String) subStep.get("destination_tosca_id"); + + if ((checkDuplicateMap.get(source) == null || checkDuplicateMap.get(source).isEmpty() + || !checkDuplicateMap.get(source).contains(destination)) && !source.equals(destination)) { + if (checkDuplicateMap.get(destination) == null) { + List<String> toscaList = new ArrayList<String>(); + checkDuplicateMap.put(destination, toscaList); + } + + if (checkDuplicateMap.get(source) == null) { + List<String> toscaList = new ArrayList<String>(); + checkDuplicateMap.put(source, toscaList); + } + + List<String> toscaSourceList = checkDuplicateMap.get(destination); + toscaSourceList.add(source); + + List<String> toscaDestinationList = checkDuplicateMap.get(source); + toscaDestinationList.add(destination); + + link.put("s", source); + link.put("d", destination); + links.add(link); + + /* + * may be needed in future but nnot currently + * + * if((String) subStep.get("link_visibility")!=null){ + * if(((String) + * subStep.get("link_visibility")).equals("No")){ + * + * } }else{ + * + * links.add(link); } + */ + + } + + } + + Map<String, Object> callFlowUI = new HashMap<String, Object>(); + callFlowUI.put("linkList", links); + + return YamlUtils.returnYaml(callFlowUI); + + // YamlUtils.writeYamlFile(filePath, callFlowStepName, + // callFlowUI); + } + + } + return ""; + } + + protected String addLinksAdditional(String filePath, String callFlowName, List<Map<String, Object>> callSteps, + String callFlowStep) throws IOException { + + for (Map<String, Object> callStep : callSteps) { + + if (((String) callStep.get("name")).split(":")[0].trim().replace(" ", "_").equals(callFlowStep)) { + + // String callFlowStepName = callFlowName + "_" + + // ((String)callStep.get("name")).split("-")[0].trim().replace(" + // ", "_")+".yml"; + + Map<String, Object> callFlowUI = new HashMap<String, Object>(); + try { + List<Map<String, Object>> links = addLinkVertices(callStep); + callFlowUI.put("linkList", links); + } catch (Exception e) { + } + try { + List<String> activeIds = addActiveNodes(callStep); + callFlowUI.put("activeIds", activeIds); + } catch (Exception e) { + } + try { + List<Map<String, Object>> disconnectLinks = addDisconnectLinks(callStep); + callFlowUI.put("disconnectLinks", disconnectLinks); + } catch (Exception e) { + } + + return YamlUtils.returnYaml(callFlowUI); + } + } + + return ""; + } + + @SuppressWarnings("unchecked") + List<String> addActiveNodes(Map<String, Object> callStep) { + List<String> activeIds = (List<String>) callStep.get("activeIds"); + return activeIds; + } + + @SuppressWarnings("unchecked") + List<Map<String, Object>> addDisconnectLinks(Map<String, Object> callStep) { + List<Map<String, Object>> disconnectLinks = (List<Map<String, Object>>) callStep.get("disconnectLinks"); + return disconnectLinks; + } + + @SuppressWarnings("unchecked") + List<Map<String, Object>> addLinkVertices(Map<String, Object> callStep) { + List<Map<String, Object>> links = new ArrayList<Map<String, Object>>(); + + List<Map<String, Object>> vertices = (List<Map<String, Object>>) callStep.get("vertices"); + + for (int i = 0; i < vertices.size() - 1; i++) { + Map<String, Object> vertex = (Map<String, Object>) vertices.get(i); + Map<String, Object> vertexNext = (Map<String, Object>) vertices.get(i + 1); + + Integer sourceX = (Integer) vertex.get("x"); + Integer sourceY = (Integer) vertex.get("y"); + String sourceD = (String) vertex.get("D"); + String sourceL = (vertex.get("L") != null) ? (String) vertex.get("L") : "-"; + + if (sourceX == -999) // there is a break in the linkage + continue; + + Integer destinationX = (Integer) vertexNext.get("x"); + Integer destinationY = (Integer) vertexNext.get("y"); + String destinationD = (String) vertexNext.get("D"); + + if (destinationX == -999) // there is a break in the linkage + continue; + + Map<String, Object> link = new HashMap<String, Object>(); + + link.put("s", sourceX + "," + sourceY + "," + sourceD + "," + sourceL); + link.put("d", destinationX + "," + destinationY + "," + destinationD); + links.add(link); + } + return links; + } +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/ElementMapService.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/ElementMapService.java new file mode 100644 index 00000000..8213a5ba --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/ElementMapService.java @@ -0,0 +1,1029 @@ +/*- + * ================================================================================ + * ECOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.service; + +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; + +import org.apache.commons.lang.StringUtils; +import org.openecomp.portalsdk.core.domain.support.Container; +import org.openecomp.portalsdk.core.domain.support.Domain; +import org.openecomp.portalsdk.core.domain.support.Element; +import org.openecomp.portalsdk.core.domain.support.ElementDetails; +import org.openecomp.portalsdk.core.domain.support.Layout; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.portalsdk.core.util.YamlUtils; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.nodes.Tag; +import org.yaml.snakeyaml.representer.Representer; + +public class ElementMapService { + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ElementMapService.class); + + /** + * + * @param contextRealPath + * @param layout + * @return + * @throws Exception + */ + private String convertToYAML(String contextRealPath, Layout layout) throws Exception { + + // Used to build image file relative URLs + final String iconRelPath = SystemProperties.getProperty("element_map_icon_path"); // "static/img/map/icons/"; + + Map<String, Domain> resultAICDomain = layout.domainRowCol; + Map<String, List<Domain>> domainMap = new HashMap<String, List<Domain>>(); + List<Domain> domainList = new ArrayList<Domain>(); + for (Domain d : resultAICDomain.values()) { + d.setWidth(10 * d.computeSize().getWidth()); + d.setHeight(10 * d.computeSize().getHeight()); + d.setLeft(10 * d.getP().getX()); + d.setTop(10 * d.getP().getY()); + + List<Container> containerList = new ArrayList<Container>(); + for (Container c : d.getContainerRowCol().values()) { + c.setWidth(10 * c.computeSize().getWidth()); + c.setHeight(10 * c.computeSize().getHeight()); + c.setLeft(10 * c.getP().getX()); + c.setTop(10 * c.getP().getY()); + Element ue = (Element) c.getElementRowCol().values().toArray()[0]; + if (ue.getName().equals("ue1") || ue.getName().equals("ue2") || ue.getName().equals("ue3") + || ue.getName().equals("ue4") || ue.getName().equals("ue5") || ue.getName().equals("ue6")) { + c.setVisibilityType("invisible"); + } + + if (c.getContainerRowCol() != null) { + List<Container> innerContainerList = new ArrayList<Container>(); + for (Container innerC : c.getContainerRowCol().values()) { + innerC.setName(innerC.getName()); + innerC.setWidth(10 * innerC.computeSize().getWidth()); + innerC.setHeight(10 * innerC.computeSize().getHeight()); + innerC.setLeft(10 * innerC.getP().getX()); + innerC.setTop(10 * innerC.getP().getY()); + + if (innerC.getElementRowCol() != null) { + List<Element> innerContainerEList = new ArrayList<Element>(); + for (Element ele : innerC.getElementRowCol().values()) { + // ele.setName(ele.getName()); + ele.setWidth(10 * ele.computeSize().getWidth()); + ele.setHeight(10 * ele.computeSize().getHeight()); + ele.setLeft(10 * ele.getP().getX()); + ele.setTop(10 * ele.getP().getY() - 10); + ele.setImgFileName(iconRelPath + "/" + ele.getImgFileName()); + if (ele.getBorderType().equals("V")) + ele.setBorderType("dashed"); + else + ele.setBorderType("solid"); + innerContainerEList.add(ele); + } + innerC.setElementList(innerContainerEList); + } + innerContainerList.add(innerC); + } + c.setInnerCList(innerContainerList); + } + + if (c.getElementRowCol() != null) { + List<Element> elementList = new ArrayList<Element>(); + for (Element e : c.getElementRowCol().values()) { + // e.setName(e.getName()); + e.setWidth(10 * e.computeSize().getWidth()); + e.setHeight(10 * e.computeSize().getHeight()); + e.setLeft(10 * e.getP().getX()); + e.setTop(10 * e.getP().getY() - 10); + e.setImgFileName(iconRelPath + "/" + e.getImgFileName()); + + if (e.getBorderType().equals("V")) + e.setBorderType("dashed"); + else + e.setBorderType("solid"); + + if (e.getName().equals("ue1") || e.getName().equals("ue2") || e.getName().equals("ue3") + || e.getName().equals("ue4") || e.getName().equals("ue5") || e.getName().equals("ue6")) + e.setBgColor("white"); + elementList.add(e); + } + c.setElementList(elementList); + } + containerList.add(c); + } + d.setContainerList(containerList); + domainList.add(d); + + } + domainMap.put("domainList", domainList); + + List<Domain> collapsedDomains = new ArrayList<Domain>(); + + // nline + for (Domain collapsed : layout.getCollapsedDomainsNewList()) { + collapsed.setWidth(10 * collapsed.computeSize().getWidth()); + collapsed.setHeight(10 * collapsed.computeSize().getHeight()); + collapsed.setLeft(10 * collapsed.getP().getX()); + collapsed.setTop(10 * collapsed.getP().getY()); + // nline + collapsed.setNewXafterColl(10 * collapsed.getNewXafterColl()); + collapsed.setYafterColl(10 * collapsed.getYafterColl()); + collapsedDomains.add(collapsed); + } + + domainMap.put("collapsedDomainList", collapsedDomains); + + Representer representer = new Representer(); + representer.addClassTag(Domain.class, Tag.MAP); + + Yaml yaml = new Yaml(representer); + String output = yaml.dump(domainMap); + + return output; + + } + + private static HashMap<String, Object> toscaElementsMap = new HashMap<String, Object>(); + private static HashMap<String, Element> elementMap = new HashMap<String, Element>(); + private static HashMap<String, Element> miscElementMap = new HashMap<String, Element>(); + private static HashMap<String, Container> outercontainers = new HashMap<String, Container>(); + private static HashMap<String, Container> innercontainers = new HashMap<String, Container>(); + private static HashMap<String, Domain> domainMap = new HashMap<String, Domain>(); + + private static String filePath = SystemProperties.getProperty("element_map_file_path"); + private static String networkToscaYml = null;// "NetworkMap_topology_composition.yml"; + private static String networkLayoutYml = null;// "network_map_layout.yml"; + + /** + * Builds renderable model of elements in the network map. Parses YAML files + * with metadata and builds input for JoinJS to render in the browser as + * SVG. + * + * @param args + * arg 0 - collapsedDomains; arg 1 - expandedDomains; arg 2 - + * context real path; arg 3 - contentFileName; arg 4 - + * layoutFileName + * @return Renderable model of elements + * @throws Exception + */ + public String buildElementMapYaml(String args[]) throws Exception { + + final String yamlDirPath = new File(args[2], filePath).getPath(); + if (args != null && args.length > 4) { + if (args[3] != null) + networkToscaYml = args[3] + ".yml"; + if (args[4] != null) + networkLayoutYml = args[4] + ".yml"; + } + + Map<String, Object> toscaYaml = YamlUtils.readYamlFile(yamlDirPath, networkToscaYml); + Map<String, Object> networkMapLayoutYaml = YamlUtils.readYamlFile(yamlDirPath, networkLayoutYml); + + toscaElementsMap = new HashMap<String, Object>(); + elementMap = new HashMap<String, Element>(); + domainMap = new HashMap<String, Domain>(); + outercontainers = new HashMap<String, Container>(); + innercontainers = new HashMap<String, Container>(); + miscElementMap = new HashMap<String, Element>(); + + if (toscaYaml != null) { + for (String key : toscaYaml.keySet()) { + if ("topology_template".equalsIgnoreCase(key) && toscaYaml.get(key) instanceof HashMap) { + HashMap<String, Object> toscaTopologyDetails = (HashMap<String, Object>) toscaYaml.get(key); + + for (String detailsKey : toscaTopologyDetails.keySet()) { + + if ("node_templates".equalsIgnoreCase(detailsKey) + && toscaTopologyDetails.get(detailsKey) instanceof HashMap) { + + toscaElementsMap = (HashMap<String, Object>) toscaTopologyDetails.get(detailsKey); + + // for (String toscaElementKey : + // toscaElementsMap.keySet()) { + //// System.out.println("Element - "+ "key :" + + //// toscaElementKey); + // } + + } + } + } + + } + } + + if (networkMapLayoutYaml != null) { + if (networkMapLayoutYaml.containsKey("toscaNetworkMapElementStyleList") + && networkMapLayoutYaml.get("toscaNetworkMapElementStyleList") instanceof ArrayList) { + + ArrayList<Object> elementlist = (ArrayList<Object>) networkMapLayoutYaml + .get("toscaNetworkMapElementStyleList"); + String elementName; + String elementID; + String imgPath; + String row; + String column; + String mapKey; + int i = 0; + + if (elementlist != null) { + for (Object eachElement : elementlist) { + // System.out.println("toscaNetworkMapElementStyleList + // Container : " +eachElement); + if (eachElement != null && eachElement instanceof HashMap) { + HashMap<String, String> elementDetails = (HashMap<String, String>) eachElement; + if (elementDetails != null) { + elementName = "NA" + i; + elementID = "NA" + i; + imgPath = "NA" + i; + row = "0"; + column = "0"; + for (String detailsKey : elementDetails.keySet()) { + if ("tosca_id".equalsIgnoreCase(detailsKey)) + elementName = elementDetails.get(detailsKey).toString(); + if ("id".equalsIgnoreCase(detailsKey)) { + elementID = String.valueOf(elementDetails.get(detailsKey)); + } + if ("row".equalsIgnoreCase(detailsKey)) { + row = String.valueOf(elementDetails.get(detailsKey)); + } + if ("column".equalsIgnoreCase(detailsKey)) { + column = String.valueOf(elementDetails.get(detailsKey)); + } + if ("icon".equalsIgnoreCase(detailsKey)) + imgPath = elementDetails.get(detailsKey).toString(); + } + + if (elementMap.containsKey(elementName.concat("/").concat(row).concat(column))) { + if (elementMap.containsKey(elementName.concat("/").concat(String.valueOf(i)) + .concat(String.valueOf(i)))) { + mapKey = elementName; + } else + mapKey = elementName.concat("/").concat(String.valueOf(i)) + .concat(String.valueOf(i)); + + } else + mapKey = elementName.concat("/").concat(row).concat(column); + + elementMap.put(mapKey, fetchElementObject(elementID, elementName, imgPath)); + } + } + i++; + } + } + + for (String elementkey : elementMap.keySet()) { + Element c = (Element) elementMap.get(elementkey); + // System.out.println("Element - "+ "key :" +elementkey +" - + // " + "value :" + c.getName()); + } + + if (!elementMap.isEmpty()) { + miscElementMap = new HashMap<String, Element>(elementMap); + } + } + + if (networkMapLayoutYaml.containsKey("containerStyleList") + && networkMapLayoutYaml.get("containerStyleList") instanceof ArrayList) { + + ArrayList<Object> containerstylelist = (ArrayList<Object>) networkMapLayoutYaml + .get("containerStyleList"); + String containerName; + String containerID; + String domain; + String row; + String column; + String mapKey; + int i = 0; + + if (containerstylelist != null) { + // Inner Containers + for (Object eachContainer : containerstylelist) { + if (eachContainer != null && eachContainer instanceof HashMap) { + HashMap<String, String> containerDetails = (HashMap<String, String>) eachContainer; + if (containerDetails != null) { + containerName = "NA" + i; + containerID = "NA" + i; + domain = "NA" + i; + row = "0"; + column = "0"; + + for (String detailsKey : containerDetails.keySet()) { + if ("logical_group_name".equalsIgnoreCase(detailsKey)) + containerName = containerDetails.get(detailsKey).toString(); + if ("id".equalsIgnoreCase(detailsKey)) { + containerID = String.valueOf(containerDetails.get(detailsKey)); + } + if ("domain".equalsIgnoreCase(detailsKey)) { + domain = containerDetails.get(detailsKey).toString(); + } + if ("row".equalsIgnoreCase(detailsKey)) { + row = String.valueOf(containerDetails.get(detailsKey)); + } + if ("column".equalsIgnoreCase(detailsKey)) { + column = String.valueOf(containerDetails.get(detailsKey)); + } + } + if (containerName.contains("/")) { + + if (innercontainers.containsKey( + (domain + ":" + containerName).concat("/").concat(row).concat(column))) { + if (elementMap.containsKey((domain + ":" + containerName).concat("/") + .concat(String.valueOf(i)).concat(String.valueOf(i)))) { + mapKey = (domain + ":" + containerName); + } else + mapKey = (domain + ":" + containerName).concat("/") + .concat(String.valueOf(i)).concat(String.valueOf(i)); + + } else + mapKey = (domain + ":" + containerName).concat("/").concat(row).concat(column); + + innercontainers.put(mapKey, + fetchContainerObject(containerID, + containerName.substring(containerName.indexOf("/") + 1), true, + containerName, domain)); + } + } + } + i++; + } + + // OuterContainers + i = 0; + for (Object eachContainer : containerstylelist) { + if (eachContainer != null && eachContainer instanceof HashMap) { + HashMap<String, String> containerDetails = (HashMap<String, String>) eachContainer; + if (containerDetails != null) { + containerName = "NA" + i; + containerID = "NA" + i; + domain = "NA" + i; + row = "0"; + column = "0"; + + for (String detailsKey : containerDetails.keySet()) { + if ("logical_group_name".equalsIgnoreCase(detailsKey)) + containerName = containerDetails.get(detailsKey).toString(); + if ("id".equalsIgnoreCase(detailsKey)) { + containerID = String.valueOf(containerDetails.get(detailsKey)); + } + if ("domain".equalsIgnoreCase(detailsKey)) { + domain = containerDetails.get(detailsKey).toString(); + } + if ("row".equalsIgnoreCase(detailsKey)) { + row = String.valueOf(containerDetails.get(detailsKey)); + } + if ("column".equalsIgnoreCase(detailsKey)) { + column = String.valueOf(containerDetails.get(detailsKey)); + } + } + if (!containerName.contains("/")) { + if (outercontainers.containsKey( + (domain + ":" + containerName).concat("/").concat(row).concat(column))) { + if (outercontainers.containsKey((domain + ":" + containerName).concat("/") + .concat(String.valueOf(i)).concat(String.valueOf(i)))) { + mapKey = (domain + ":" + containerName); + } else + mapKey = (domain + ":" + containerName).concat("/") + .concat(String.valueOf(i)).concat(String.valueOf(i)); + + } else + mapKey = (domain + ":" + containerName).concat("/").concat(row).concat(column); + outercontainers.put(mapKey, fetchContainerObject(containerID, containerName, false, + containerName, domain)); + } + // else innercontainers.put(domain +":"+ + // containerName, + // fetchContainerObject(containerID,containerName.substring(containerName.indexOf("/")+1),false,containerName,domain)); + + } + } + i++; + } + } + + for (String innerContainerkey : innercontainers.keySet()) { + Container c = (Container) innercontainers.get(innerContainerkey); + } + + for (String outerContainerkey : outercontainers.keySet()) { + Container c = (Container) outercontainers.get(outerContainerkey); + } + + } + + if (networkMapLayoutYaml.containsKey("domainList") + && networkMapLayoutYaml.get("domainList") instanceof ArrayList) { + + ArrayList<Object> domainlist = (ArrayList<Object>) networkMapLayoutYaml.get("domainList"); + String domainName; + String domainID; + String row; + String column; + String mapKey; + int i = 0; + + if (domainlist != null) { + + HashMap<String, String> domainStagingMap = new HashMap<String, String>(); + for (Object eachDomain : domainlist) { + // System.out.println("domainlist Container : " + // +eachDomain); + if (eachDomain != null && eachDomain instanceof HashMap) { + HashMap<String, String> domainDetails = (HashMap<String, String>) eachDomain; + if (domainDetails != null) { + domainName = "NA" + i; + domainID = "NA" + i; + row = "0"; + column = "0"; + for (String detailsKey : domainDetails.keySet()) { + if ("name".equalsIgnoreCase(detailsKey)) + domainName = domainDetails.get(detailsKey).toString(); + if ("id".equalsIgnoreCase(detailsKey)) { + domainID = String.valueOf(domainDetails.get(detailsKey)); + } + if ("row".equalsIgnoreCase(detailsKey)) { + row = String.valueOf(domainDetails.get(detailsKey)); + } + if ("column".equalsIgnoreCase(detailsKey)) { + column = String.valueOf(domainDetails.get(detailsKey)); + } + } + + if (domainStagingMap.containsKey(row.concat(column))) { + mapKey = domainName; + } else + mapKey = row.concat(column); + + domainStagingMap.put(mapKey, domainID + "%" + domainName); + } + } + i++; + } + + if (domainStagingMap != null && !domainStagingMap.isEmpty()) { + for (String domainsKey : new TreeSet<String>(domainStagingMap.keySet())) { + String value = domainStagingMap.get(domainsKey); + if (value.contains("%")) { + domainMap.put(domainsKey, fetchDomainObject(value.substring(0, value.indexOf("%")), + value.substring(value.indexOf("%") + 1))); + } + } + } + } + + // for (String domainkey : domainMap.keySet()) { + // Domain c = (Domain) domainMap.get(domainkey); + // System.out.println("Domain - "+ "key :" +domainkey +" - " + // + "value :" + c.getName()); + // } + } + + } + + Layout dynamicLayout = new Layout(domainMap, 2, 10, 1, 5); + dynamicLayout.computeDomainPositionsModified(); + + /* + * Map<String, Domain> resultAICDomain2 = dynamicLayout.domainRowCol; + * for (String key : resultAICDomain2.keySet()) { if + * (resultAICDomain2.get(key).getP() != null) { + * System.out.println(resultAICDomain2.get(key).name+" "+"x:"+ + * resultAICDomain2.get(key).getP().getX()+","+"y:"+ + * resultAICDomain2.get(key).getP().getY()+","+"width:"+ + * resultAICDomain2.get(key).computeSize().getWidth() + * +","+"height:"+resultAICDomain2.get(key).computeSize(). getHeight()); + * + * } } + */ + + ElementMapService cm2 = new ElementMapService(); + try { + + if (args != null && args.length > 0) { + + if (args[0] != null) { + String collapsedDomains[] = args[0].split(","); + for (String collapsedDomain : collapsedDomains) + // dynamicLayout.collapseDomainModified(collapsedDomain); + dynamicLayout.collapseDomainNew(collapsedDomain); + } + + if (args[1] != null) { + String expandedDomains[] = args[1].split(","); + for (String expandedDomain : expandedDomains) + // dynamicLayout.uncollapseDomainNew(expandedDomain); + dynamicLayout.uncollapseDomainNew1(expandedDomain); + } + + return cm2.convertToYAML(args[2], dynamicLayout); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "buildElementMapYaml failed", e); + } + + return ""; + } + + private static int computeRows(Set<String> keys) { + int i = 0; + if (keys != null && !keys.isEmpty()) { + for (String s : keys) { + String r = s.substring(0, 1); + if (StringUtils.isNumeric(r)) { + int j = Integer.parseInt(r); + if (i <= j) { + i = j; + } + + } + } + + return i + 1; + } + + return 1; + } + + private static int computeColumns(Set<String> keys) { + int i = 0; + if (keys != null && !keys.isEmpty()) { + for (String s : keys) { + String r = s.substring(1, 2); + if (StringUtils.isNumeric(r)) { + int j = Integer.parseInt(r); + if (i <= j) { + i = j; + } + + } + } + + return i + 1; + } + + return 1; + } + + private static Container fetchContainerObject(String id, String name, boolean isInner, String logicalGroupName, + String domain) { + Map<String, Element> containerElementsMap = new HashMap<String, Element>(); + + containerElementsMap = fetchElementsMapForContainer(name, isInner, logicalGroupName, domain); + int rows = 1; + int columns = 1; + + if (isInner) { + + if (containerElementsMap != null && !containerElementsMap.isEmpty()) { + rows = computeRows(containerElementsMap.keySet()); + columns = computeColumns(containerElementsMap.keySet()); + } + + Container thisContainer = new Container(id, name, rows, columns, 1, 4, 8, 12, 1, 2); + thisContainer.setElements(containerElementsMap); + // thisContainer.setVisibilityType(""); + + return thisContainer; + } else { + Map<String, Container> innerContainersMap = fetchInnerContainersMapForOuter(name, isInner, logicalGroupName, + domain); + + if (innerContainersMap != null && !innerContainersMap.isEmpty()) { + if (containerElementsMap != null && !containerElementsMap.isEmpty()) { + Set<String> keys = new HashSet<String>(innerContainersMap.keySet()); + keys.addAll(containerElementsMap.keySet()); + rows = computeRows(keys); + columns = computeColumns(keys); + } else { + rows = computeRows(innerContainersMap.keySet()); + columns = computeColumns(innerContainersMap.keySet()); + } + } else if (containerElementsMap != null && !containerElementsMap.isEmpty()) { + rows = computeRows(containerElementsMap.keySet()); + columns = computeColumns(containerElementsMap.keySet()); + } + + Container thisContainer = new Container(id, name, rows, columns, 2, 6, 2, 5, 0, 0); + thisContainer.setElements(containerElementsMap); + thisContainer.setInnerContainer(innerContainersMap); + + if (containerElementsMap != null && !containerElementsMap.isEmpty()) { + for (Element thisElement : containerElementsMap.values()) { + if (thisElement.getId() != null + ) { + thisContainer.setVisibilityType("invisible"); + } + } + } + return thisContainer; + } + + } + + private static Domain fetchDomainObject(String id, String name) { + HashMap<String, Container> domainContainersMap = fetchContainersForDomain(name); + + int rows = 1; + int columns = 1; + if (domainContainersMap != null && !domainContainersMap.isEmpty()) { + rows = computeRows(domainContainersMap.keySet()); + columns = computeColumns(domainContainersMap.keySet()); + } + + double domainWidth = 11; + Domain thisDomain; + + if (domainMap != null && !domainMap.isEmpty()) { + int domainsCountSoFar = domainMap.size(); + switch (domainsCountSoFar) { + case 1: { + domainWidth = 12.1; + break; + } + case 2: { + domainWidth = 13.3; + break; + } + case 3: { + domainWidth = 14.5; + break; + } + case 4: { + domainWidth = 15.6; + break; + } + default: { + domainWidth = 11; + break; + } + } + + for (String domainsKey : new TreeSet<String>(domainMap.keySet())) { + Domain eachDomain = domainMap.get(domainsKey); + domainWidth += eachDomain.computeSize().getWidth(); + } + thisDomain = new Domain(id, name, 2, 2, domainWidth, 10, 3, rows, columns); + } else { + + thisDomain = new Domain(id, name, 2, 1, 11, 10, 3, rows, columns); + } + + // Domain thisDomain = new Domain(id, name, 2, 1, leftPosition, 10, 3, + // rows, columns); + thisDomain.setContainers(domainContainersMap); + + thisDomain.computeConatinerPositions(); + if (domainContainersMap != null && !domainContainersMap.isEmpty()) { + for (Container thisContainer : domainContainersMap.values()) { + thisContainer.computeSize(); + thisContainer.computeElementPositions(); + Map<String, Element> resultElementMap = thisContainer.elementRowCol; + for (String key : resultElementMap.keySet()) { + if (resultElementMap.get(key) == null || resultElementMap.get(key).getP() == null) { + // System.out.println("culprit " +key); + } + /* + * System.out.println(resultElementMap.get(key).name+" " + * +"x:"+resultElementMap.get(key).getP().getX()+","+"y:"+ + * resultElementMap.get(key).getP().getY()+","+"width:"+ + * resultElementMap.get(key).computeSize().getWidth() + * +","+"height:"+resultElementMap.get(key).computeSize(). + * getHeight()); + */ + + } + + HashMap<String, Container> innerContainersMap = (HashMap<String, Container>) thisContainer + .getContainerRowCol(); + if (innerContainersMap != null && !innerContainersMap.isEmpty()) { + for (Container thisInnerContainer : innerContainersMap.values()) { + // thisInnerContainer.computeSize(); + thisInnerContainer.computeElementPositions(); + /* + * Map<String,Element> resultInnerElementMap = + * thisContainer.elementRowCol; for (String key : + * resultElementMap.keySet()) { // + * System.out.println(resultElementMap.get(key).name+" " + * +"x:"+resultElementMap.get(key).getP().getX()+","+ + * "y:"+ + * resultElementMap.get(key).getP().getY()+","+"width:"+ + * resultElementMap.get(key).computeSize().getWidth() + * +","+"height:"+resultElementMap.get(key).computeSize( + * ).getHeight()); + * + * } + */ + } + } + } + } + + return thisDomain; + } + + private static HashMap<String, Container> fetchContainersForDomain(String domain) { + HashMap<String, Container> domainContainersMap = new HashMap<String, Container>(); + + domainContainersMap = fetchFromOuterContainers(domain); + + return domainContainersMap; + + } + + private static Element fetchElementObject(String id, String name, String imgPath) { + String bgColor = "bgColor"; + String logical_group; + String display_longname; + String display_shortname; + String description; + String primary_function; + String key_interfaces; + String location; + String vendor; + String vendor_shortname; + String enclosingContainer; + String borderType; + String network_function; + + if (toscaElementsMap.containsKey(name)) { + + if (toscaElementsMap.get(name) != null && toscaElementsMap.get(name) instanceof HashMap) { + HashMap<String, Object> toscaElementDetails = (HashMap<String, Object>) toscaElementsMap.get(name); + + for (String detailsKey : toscaElementDetails.keySet()) { + if ("properties".equalsIgnoreCase(detailsKey) + && toscaElementDetails.get(detailsKey) instanceof HashMap) { + HashMap<String, String> elementDetails = (HashMap<String, String>) toscaElementDetails + .get(detailsKey); + + if (elementDetails != null) { + logical_group = elementDetails.get("logical_group") == null ? "" + : elementDetails.get("logical_group").toString(); + display_longname = elementDetails.get("display_longname") == null ? "" + : elementDetails.get("display_longname").toString(); + display_shortname = elementDetails.get("display_shortname") == null ? "" + : elementDetails.get("display_shortname").toString(); + description = elementDetails.get("description") == null ? "" + : elementDetails.get("description").toString(); + primary_function = elementDetails.get("primary_function") == null ? "" + : elementDetails.get("primary_function").toString(); + key_interfaces = elementDetails.get("key_interfaces") == null ? "" + : elementDetails.get("key_interfaces").toString(); + location = elementDetails.get("location") == null ? "" + : elementDetails.get("location").toString(); + vendor = elementDetails.get("vendor") == null ? "" + : elementDetails.get("vendor").toString(); + vendor_shortname = elementDetails.get("vendor_shortname") == null ? "" + : elementDetails.get("vendor_shortname").toString(); + enclosingContainer = logical_group.replace("/", "-"); + network_function = elementDetails.get("network_function"); + borderType = elementDetails.get("network_function") == null ? "P" + : elementDetails.get("network_function").toString().toUpperCase(); + bgColor = elementDetails.get("background_color") == null ? "bgColor" + : elementDetails.get("background_color").toString(); + + ElementDetails details = new ElementDetails(logical_group, display_longname, description, + primary_function, network_function, key_interfaces, location, vendor, + vendor_shortname, enclosingContainer); + + return new Element(name, display_shortname, imgPath, bgColor, borderType, details); + } + + } + } + + } + + // Element(id, name, imgPath, bgColor, logical_group, + // display_longname, + // description, primary_function, key_interfaces, location, vendor, + // vendor_shortname); + } else { + return new Element(id, name); + } + + return new Element(id, name); + } + + private static String fetchDomainNameOfElement(String name) { + if (toscaElementsMap.containsKey(name)) { + + if (toscaElementsMap.get(name) != null && toscaElementsMap.get(name) instanceof HashMap) { + HashMap<String, Object> toscaElementDetails = (HashMap<String, Object>) toscaElementsMap.get(name); + + for (String detailsKey : toscaElementDetails.keySet()) { + if ("properties".equalsIgnoreCase(detailsKey) + && toscaElementDetails.get(detailsKey) instanceof HashMap) { + HashMap<String, String> elementDetails = (HashMap<String, String>) toscaElementDetails + .get(detailsKey); + + if (elementDetails != null) { + return elementDetails.get("domain") == null ? "" : elementDetails.get("domain").toString(); + } + + } + } + + } + + } else { + return ""; + } + + return ""; + } + + private static HashMap<String, Container> fetchInnerContainersMapForOuter(String name, boolean isInner, + String logicalGroupName, String domain) { + return fetchInnerContainersMap(name, logicalGroupName, domain); + } + + private static HashMap<String, Element> fetchElementsMapForContainer(String name, boolean isInner, + String logicalGroupName, String domain) { + return fetchElementsMap(logicalGroupName, domain); + } + + private static HashMap<String, Container> fetchInnerContainersMap(String name, String logicalGroupName, + String domain) { + HashMap<String, Container> containersMap = new HashMap<String, Container>(); + String rowColumnKey = ""; + int count = 0; + + if (innercontainers != null && !innercontainers.isEmpty()) { + for (String key : innercontainers.keySet()) { + + Container eachContainer = innercontainers.get(key); + + if (key.toUpperCase().contains((domain + ":" + name).toUpperCase())) { + if (key.contains("/")) { + rowColumnKey = key.substring(key.lastIndexOf("/") + 1); + } + + if (rowColumnKey.isEmpty() || containersMap.containsKey(rowColumnKey)) { + count = 0; + while (count <= 9) { + if (containersMap.containsKey(String.valueOf(count).concat(String.valueOf(count)))) { + count++; + } else { + rowColumnKey = String.valueOf(count).concat(String.valueOf(count)); + break; + } + } + + } + + containersMap.put(rowColumnKey, eachContainer); + } + + } + } + return containersMap.isEmpty() ? null : containersMap; + + } + + private static HashMap<String, Container> fetchFromOuterContainers(String domain) { + HashMap<String, Container> thisContainersMap = new HashMap<String, Container>(); + String rowColumnKey = ""; + int count = 0; + + if (outercontainers != null && !outercontainers.isEmpty()) { + for (String key : outercontainers.keySet()) { + Container eachContainer = outercontainers.get(key); + + if (key.toUpperCase().contains((domain + ":").toUpperCase())) { + if (key.contains("/")) { + rowColumnKey = key.substring(key.lastIndexOf("/") + 1); + } + + if (rowColumnKey.isEmpty() || thisContainersMap.containsKey(rowColumnKey)) { + count = 0; + while (count <= 9) { + if (thisContainersMap.containsKey(String.valueOf(count).concat(String.valueOf(count)))) { + count++; + } else { + rowColumnKey = String.valueOf(count).concat(String.valueOf(count)); + break; + } + } + + } + + thisContainersMap.put(rowColumnKey, eachContainer); + } + } + + } + + // Misc Elements Containers + + if (miscElementMap != null && !miscElementMap.isEmpty()) { + for (String key : miscElementMap.keySet()) { + Element eachElement = miscElementMap.get(key); + String elementName = eachElement.getName(); + String domainName = fetchDomainNameOfElement(elementName); + + if (domain.equalsIgnoreCase(domainName)) { + Container eachContainer = new Container(domainName + ":" + elementName, elementName, 1, 1, 3, 6, 2, + 5, 0, 0); + count = 0; + while (count <= 9) { + if (thisContainersMap.containsKey(String.valueOf(count).concat(String.valueOf(count)))) { + count++; + } else { + rowColumnKey = String.valueOf(count).concat(String.valueOf(count)); + break; + } + } + + thisContainersMap.put(rowColumnKey, eachContainer); + } + + } + + } + + return thisContainersMap.isEmpty() ? null : thisContainersMap; + } + + private static HashMap<String, Container> addOuterContainersForMiscElements(String domain) { + HashMap<String, Container> containerElementsMap = new HashMap<String, Container>(); + if (miscElementMap != null && !miscElementMap.isEmpty()) { + for (String key : miscElementMap.keySet()) { + Element eachElement = miscElementMap.get(key); + String elementName = eachElement.getName(); + String domainName = fetchDomainNameOfElement(elementName); + + if (domain.equalsIgnoreCase(domainName)) { + Container newContainer = new Container(domainName + ":" + elementName, elementName, 1, 1, 3, 6, 2, + 5, 0, 0); + containerElementsMap.put(domainName + ":" + elementName, newContainer); + } + + } + + } + return containerElementsMap.isEmpty() ? null : containerElementsMap; + } + + private static HashMap<String, Element> fetchElementsMap(String logicalGroupName, String domain) { + HashMap<String, Element> innerElementMap = new HashMap<String, Element>(); + String rowColumnKey = ""; + int count = 0; + + if (elementMap != null && !elementMap.isEmpty()) { + for (String key : elementMap.keySet()) { + Element eachElement = elementMap.get(key); + + String elementName = eachElement.getId(); + String elementLogicalGroup = eachElement.details == null ? "" : eachElement.details.logical_group; + if (elementLogicalGroup.equalsIgnoreCase(logicalGroupName) + && domain.equalsIgnoreCase(fetchDomainNameOfElement(elementName))) { + if (key.contains("/")) { + rowColumnKey = key.substring(key.indexOf("/") + 1); + } + + if (rowColumnKey.isEmpty() || innerElementMap.containsKey(rowColumnKey)) { + count = 0; + while (count <= 9) { + if (innerElementMap.containsKey(String.valueOf(count).concat(String.valueOf(count)))) { + count++; + } else { + rowColumnKey = String.valueOf(count).concat(String.valueOf(count)); + break; + } + } + + } + + innerElementMap.put(rowColumnKey, eachElement); + miscElementMap.remove(key); + } + + } + } + + return innerElementMap.isEmpty() ? null : innerElementMap; + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/FnMenuService.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/FnMenuService.java new file mode 100644 index 00000000..040c9d26 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/FnMenuService.java @@ -0,0 +1,46 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.service; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.openecomp.portalsdk.core.domain.Menu; +import org.openecomp.portalsdk.core.domain.MenuData; +import org.openecomp.portalsdk.core.domain.RoleFunction; + +/** + * Description: this java class is an interface of services for Admin to add/edit/delete menu items from FN_MENU + */ +public interface FnMenuService { + List<MenuData> getFnMenuItems(); + void saveFnMenuData(MenuData domainFnMenu); + void saveFnMenu(Menu domainFnMenu); + void removeMenuItem(MenuData domainFnMenu); + MenuData getMenuItemRow(Long id); + Menu getMenuItem(Long id); + List<Long> getParentId(String label); + @SuppressWarnings("rawtypes") + List<List> getParentList(); + List<RoleFunction> getFunctionCDList(); + void removeMenuItem(Menu domainFnMenu); + Map<String, List<MenuData>> setMenuDataStructure(List<List<MenuData>> childItemList, List<MenuData> parentList, Set<MenuData> menuResult) throws Exception; +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/FnMenuServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/FnMenuServiceImpl.java new file mode 100644 index 00000000..ca73339d --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/FnMenuServiceImpl.java @@ -0,0 +1,161 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.service; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; + +import org.openecomp.portalsdk.core.domain.FnMenu; +import org.openecomp.portalsdk.core.domain.Menu; +import org.openecomp.portalsdk.core.domain.MenuData; +import org.openecomp.portalsdk.core.domain.Role; +import org.openecomp.portalsdk.core.domain.RoleFunction; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +/** + * Description: this java class is an implementation of services for Admin to add/edit/delete menu items from FN_MENU + */ + +@Service("fnMenuService") +@Transactional +public class FnMenuServiceImpl implements FnMenuService{ + + @Autowired + private DataAccessService dataAccessService; + + @SuppressWarnings("unchecked") + public List<MenuData> getFnMenuItems() { + //List msgDB = getDataAccessService().getList(Profile.class, null); + return getDataAccessService().getList(MenuData.class, null, "1", null); + + } + + + public DataAccessService getDataAccessService() { + return dataAccessService; + } + + + public void setDataAccessService(DataAccessService dataAccessService) { + this.dataAccessService = dataAccessService; + } + + + @Override + public void saveFnMenuData(MenuData domainFnMenu) { + // TODO Auto-generated method stub + getDataAccessService().saveDomainObject(domainFnMenu, null); + + } + + @SuppressWarnings("unchecked") + @Override + public List<Long> getParentId(String label) { + // TODO Auto-generated method stub + //List<String> functioCDlist = new ArrayList<String>(); + //functioCDlist.add("Mahdy1"); + //functioCDlist.add("Mahdy2"); + Map<String, String> params = new HashMap<String, String>(); + params.put("paramLabel", label); + return getDataAccessService().executeNamedQuery("IdForLabelList", params, null); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Override + public List<List> getParentList() { + // TODO Auto-generated method stub + //List<String> functioCDlist = new ArrayList<String>(); + //functioCDlist.add("Mahdy1"); + //functioCDlist.add("Mahdy2"); + return getDataAccessService().executeNamedQuery("parentList", null, null); + + //return null; + } + + @SuppressWarnings("unchecked") + @Override + public List<RoleFunction> getFunctionCDList() { + // TODO Auto-generated method stub + //List<String> functioCDlist = new ArrayList<String>(); + //functioCDlist.add("Mahdy1"); + //functioCDlist.add("Mahdy2"); + return getDataAccessService().executeNamedQuery("functionCDlist", null, null); + + //return null; + } + + @Override + public void removeMenuItem(MenuData domainFnMenu) { + getDataAccessService().deleteDomainObject(domainFnMenu, null); + } + + @Override + public void removeMenuItem(Menu domainFnMenu) { + getDataAccessService().deleteDomainObject(domainFnMenu, null); + } + + public MenuData getMenuItemRow(Long id) { + return (MenuData)getDataAccessService().getDomainObject(MenuData.class, id, null); + } + + @Override + public Menu getMenuItem(Long id) { + return (Menu)getDataAccessService().getDomainObject(Menu.class, id, null); + } + + @Override + public void saveFnMenu(Menu domainFnMenu) { + // TODO Auto-generated method stub + getDataAccessService().saveDomainObject(domainFnMenu, null); + + } + @Override + public Map<String, List<MenuData>> setMenuDataStructure(List<List<MenuData>> childItemList, List<MenuData> parentList, Set<MenuData> menuResult) throws Exception{ + for(MenuData menu: menuResult){ + MenuData parentData = new MenuData(); + parentData.setLabel(menu.getLabel()); + parentData.setAction(menu.getAction()); + parentData.setImageSrc(menu.getImageSrc()); + parentList.add(parentData); + List<MenuData> tempList = new ArrayList<MenuData>(); + for(Object o:menu.getChildMenus()){ + MenuData m = (MenuData)o; + MenuData data = new MenuData(); + data.setLabel(m.getLabel()); + data.setAction(m.getAction()); + data.setImageSrc(m.getImageSrc()); + tempList.add(data); + } + childItemList.add(tempList); + } + return null; + } + + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/LdapService.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/LdapService.java new file mode 100644 index 00000000..9c790eb2 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/LdapService.java @@ -0,0 +1,31 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.service; + +import org.openecomp.portalsdk.core.command.support.SearchResult; +import org.openecomp.portalsdk.core.domain.support.DomainVo; + + +public interface LdapService { + + // search POST for users based on the criteria selected in the Request + SearchResult searchPost(DomainVo searchCriteria, String sortBy1, String sortBy2, String sortBy3, int pageNo, int dataSize, int userId) throws Exception; + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/LdapServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/LdapServiceImpl.java new file mode 100644 index 00000000..ba43e45f --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/LdapServiceImpl.java @@ -0,0 +1,267 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.service; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.naming.NamingEnumeration; +import javax.naming.NamingException; +import javax.naming.directory.Attribute; +import javax.naming.directory.Attributes; +import javax.naming.directory.DirContext; +import javax.naming.directory.SearchControls; + +import org.openecomp.portalsdk.core.command.support.SearchResult; +import org.openecomp.portalsdk.core.domain.User; +import org.openecomp.portalsdk.core.domain.support.DomainVo; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.support.FusionService; +import org.openecomp.portalsdk.core.service.support.ServiceLocator; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service("ldapService") +@Transactional +public class LdapServiceImpl extends FusionService implements LdapService { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LdapServiceImpl.class); + @Autowired + private ServiceLocator serviceLocator; + + @SuppressWarnings({ "unchecked", "rawtypes" }) + public SearchResult searchPost(DomainVo searchCriteria, String sortBy1, String sortBy2, String sortBy3, + int pageNo, int dataSize, int userId) throws Exception { + + // initialize the directory context to access POST + DirContext dirContext = serviceLocator.getDirContext(SystemProperties.getProperty(SystemProperties.POST_INITIAL_CONTEXT_FACTORY), + SystemProperties.getProperty(SystemProperties.POST_PROVIDER_URL), + SystemProperties.getProperty(SystemProperties.POST_SECURITY_PRINCIPAL)); + + SearchResult searchResult = new SearchResult(); + + try { + + String[] postAttributes = {"nickname","givenName","initials","sn","employeeNumber","mail","telephoneNumber", + "departmentNumber","a1","street","roomNumber","l","st","postalCode","zip4","physicalDeliveryOfficeName","bc", + "friendlyCountryName","bd","bdname","bu","buname","jtname","mgrid","a2","compcode","compdesc", + "costcenter","silo","b2"}; + + SearchControls searchControls = new SearchControls(); + searchControls.setTimeLimit(5000); + searchControls.setReturningAttributes(postAttributes); + + StringBuffer filterClause = new StringBuffer("(&(objectClass=*)"); + + User user = (User)searchCriteria; + + if(Utilities.nvl(user.getFirstName()).length() > 0) { + filterClause.append("(givenName=").append(user.getFirstName()).append("*)"); + } + if(Utilities.nvl(user.getLastName()).length() > 0) { + filterClause.append("(sn=").append(user.getLastName()).append("*)"); + } + if(Utilities.nvl(user.getHrid()).length() > 0) { + filterClause.append("(employeeNumber=").append(user.getHrid()).append("*)"); + } + if(Utilities.nvl(user.getOrgManagerUserId()).length() > 0) { + filterClause.append("(mgrid=").append(user.getOrgManagerUserId()).append("*)"); + } + if(Utilities.nvl(user.getOrgCode()).length() > 0) { + filterClause.append("(departmentNumber=").append(user.getOrgCode()).append("*)"); + } + if(Utilities.nvl(user.getEmail()).length() > 0) { + filterClause.append("(mail=").append(user.getEmail()).append("*)"); + } + if(Utilities.nvl(user.getOrgUserId()).length() > 0) { + filterClause.append("(a1=").append(user.getOrgUserId()).append("*)"); + } + filterClause.append("(c3=N)"); // this has been added to filter CP09 entries on the LDAP server that are duplicates of existing individuals + filterClause.append(")"); + + List list = new ArrayList(); + if (!filterClause.toString().equals("(&(objectClass=*))")) { + NamingEnumeration e = dirContext.search(SystemProperties.getProperty(SystemProperties.POST_PROVIDER_URL) + "/" + + SystemProperties.getProperty(SystemProperties.POST_SECURITY_PRINCIPAL), + filterClause.toString(), + searchControls); + + list = processResults(e); + } + + Collections.sort(list); + + searchResult = new SearchResult(list); + searchResult.setPageNo(pageNo); + if(dataSize >= 0) { + searchResult.setDataSize(dataSize); + } + else { + searchResult.setDataSize(list.size()); + } // else + + } + catch(NamingException ne) { + logger.error(EELFLoggerDelegate.errorLogger,ne.getMessage()); + } + finally { + dirContext.close(); + } + + return searchResult; + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + private ArrayList processResults(NamingEnumeration e) throws NamingException { + ArrayList results = new ArrayList(); + int count = 0; + + while (e.hasMore()) { + javax.naming.directory.SearchResult searchResult = (javax.naming.directory.SearchResult)e.next(); + results.add(processAttributes(searchResult.getAttributes())); + count++; + + if(count > Integer.parseInt(SystemProperties.getProperty(SystemProperties.POST_MAX_RESULT_SIZE))) { + break; + } + + } + + return results; + } + + @SuppressWarnings("rawtypes") + private DomainVo processAttributes(Attributes resultAttributes) throws NamingException { + User user = new User(); + + try { + if (resultAttributes == null) { + // System.out.println("This result has no attributes"); + } else { + for (NamingEnumeration e = resultAttributes.getAll(); e.hasMore();) { //why the nested loop? + Attribute attribute = (Attribute)e.next(); + for (NamingEnumeration ie = attribute.getAll(); ie.hasMore();) { + if (attribute.getID().equalsIgnoreCase("nickname")) { + user.setFirstName((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("initials")) { + user.setMiddleInitial((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("sn")) { + user.setLastName((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("employeeNumber")) { + user.setHrid((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("mail")) { + user.setEmail((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("telephoneNumber")) { + user.setPhone((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("departmentNumber")) { + user.setOrgCode((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("a1")) { + user.setOrgUserId((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("street")) { + user.setAddress1((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("roomNumber")) { + user.setAddress2((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("l")) { + user.setCity((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("st")) { + user.setState((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("postalCode")) { + user.setZipCode((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("zip4")) { + user.setZipCodeSuffix((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("physicalDeliveryOfficeName")) { + user.setLocationClli((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("bc")) { + user.setBusinessCountryCode((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("friendlyCountryName")) { + user.setBusinessCountryName((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("bd")) { + user.setDepartment((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("bdname")) { + user.setDepartmentName((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("jtname")) { + user.setJobTitle((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("mgrid")) { + user.setOrgManagerUserId((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("a2")) { + user.setCommandChain((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("compcode")) { + user.setCompanyCode((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("compdesc")) { + user.setCompany((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("bu")) { + user.setBusinessUnit((String)ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("buname")) { + user.setBusinessUnitName((String)ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("silo")) { + user.setSiloStatus((String)ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("costcenter")) { + user.setCostCenter((String)ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("b2")) { + user.setFinancialLocCode((String)ie.next()); + } + else { //we don't care about returned attribute, let's move on + ie.next(); + } + + } + } + } + } catch (NamingException e) { + logger.error(EELFLoggerDelegate.errorLogger, "An error occurred while processing the following user from POST with an ORGUSERID of " + user.getOrgUserId() + e.getMessage()); + } finally { + return user; + } + + } + + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/LoginService.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/LoginService.java new file mode 100644 index 00000000..4f004108 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/LoginService.java @@ -0,0 +1,36 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.service; + + +import java.util.*; + +import org.openecomp.portalsdk.core.command.*; + + +public interface LoginService { + + // validate user exists in the system + @SuppressWarnings("rawtypes") + LoginBean findUser(LoginBean bean, String menuPropertiesFilename, HashMap additionalParams) throws Exception; + + @SuppressWarnings("rawtypes") + LoginBean findUser(LoginBean bean, String menuPropertiesFilename, HashMap additionalParams, boolean matchPassword) throws Exception; +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/LoginServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/LoginServiceImpl.java new file mode 100644 index 00000000..e0a4b7c6 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/LoginServiceImpl.java @@ -0,0 +1,205 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.service; + +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import org.openecomp.portalsdk.core.command.LoginBean; +import org.openecomp.portalsdk.core.domain.Role; +import org.openecomp.portalsdk.core.domain.User; +import org.openecomp.portalsdk.core.domain.UserApp; +import org.openecomp.portalsdk.core.menu.MenuBuilder; +import org.openecomp.portalsdk.core.service.support.FusionService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.portalsdk.core.web.support.AppUtils; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service("loginService") +@Transactional +public class LoginServiceImpl extends FusionService implements LoginService { + + @SuppressWarnings("unused") + private MenuBuilder menuBuilder; + + @Autowired + private DataAccessService dataAccessService; + + @SuppressWarnings("rawtypes") + public LoginBean findUser(LoginBean bean, String menuPropertiesFilename, HashMap additionalParams ) throws Exception { + return findUser(bean, menuPropertiesFilename, additionalParams, true); + } + + @SuppressWarnings("rawtypes") + public LoginBean findUser(LoginBean bean, String menuPropertiesFilename, HashMap additionalParams, boolean matchPassword) throws Exception { + User user = null; + User userCopy = null; + + if (bean.getUserid() != null && bean.getUserid() != null) { + user = (User)findUser(bean); + } + else { + if (matchPassword) + user = (User)findUser(bean.getLoginId(), bean.getLoginPwd()); + else + user = (User)findUserWithoutPwd(bean.getLoginId()); + } + + if (user != null) { + + // raise an error if the application is locked and the user does not have system administrator privileges + if (AppUtils.isApplicationLocked() && !UserUtils.hasRole(user, SystemProperties.getProperty(SystemProperties.SYS_ADMIN_ROLE_ID))) { + bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_APPLICATION_LOCKED); + } + + // raise an error if the user is inactive + if (!user.getActive()) { + bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_USER_INACTIVE); + } + + // raise an error if no active roles exist for the user +// boolean hasActiveRole = false; +// Iterator roles = user.getRoles().iterator(); +// while (roles.hasNext()) { +// Role role = (Role)roles.next(); +// if (role.getActive()) { +// hasActiveRole = true; +// break; +// } +// } + +// if (!hasActiveRole) { +// bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_USER_INACTIVE); +// } + if (!userHasActiveRoles(user)) { + bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_USER_INACTIVE); + } + // only login the user if no errors have occurred + if (bean.getLoginErrorMessage() == null) { + + // this will be a snapshot of the user's information as retrieved from the database + userCopy = (User)user.clone(); + + // update the last logged in date for the user + user.setLastLoginDate(new Date()); + getDataAccessService().saveDomainObject(user, additionalParams); + + // update the audit log of the user + //Check for the client device type and set log attributes appropriately + + + // save the above changes to the User and their audit trail + + + + + // create the application menu based on the user's privileges + Set appMenu = getMenuBuilder().getMenu(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_SET_NAME),dataAccessService); + bean.setMenu(appMenu != null?appMenu:new HashSet()); + Set businessDirectMenu = getMenuBuilder().getMenu(SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_SET_NAME),dataAccessService); + bean.setBusinessDirectMenu(businessDirectMenu != null?businessDirectMenu:new HashSet()); + + bean.setUser(userCopy); + } + + } + + return bean; + } + + private boolean userHasActiveRoles(User user) { + boolean hasActiveRole = false; + Iterator roles = user.getRoles().iterator(); + while (roles.hasNext()) { + Role role = (Role)roles.next(); + if (role.getActive()) { + hasActiveRole = true; + break; + } + } + return hasActiveRole; + } + + @SuppressWarnings("rawtypes") + public User findUser(String loginId, String password) { + List list = null; + + StringBuffer criteria = new StringBuffer(); + criteria.append(" where login_id = '").append(loginId).append("'") + .append(" and login_pwd = '").append(password).append("'"); + + list = getDataAccessService().getList(User.class, criteria.toString(), null, null); + + return (list == null || list.size() == 0) ? null : (User)list.get(0); + } + + @SuppressWarnings("rawtypes") + private User findUserWithoutPwd(String loginId) { + List list = null; + + StringBuffer criteria = new StringBuffer(); + criteria.append(" where login_id = '").append(loginId).append("'"); + + list = getDataAccessService().getList(User.class, criteria.toString(), null, null); + + return (list == null || list.size() == 0) ? null : (User)list.get(0); + } + + @SuppressWarnings("rawtypes") + public User findUser(LoginBean bean) { + List list = null; + + StringBuffer criteria = new StringBuffer(); + criteria.append(" where org_user_id = '").append(bean.getUserid()).append("'"); + + list = getDataAccessService().getList(User.class, criteria.toString(), null, null); + + return (list == null || list.size() == 0) ? null : (User)list.get(0); + } + + + public MenuBuilder getMenuBuilder() { + return new MenuBuilder(); + } + + + public void setMenuBuilder(MenuBuilder menuBuilder) { + this.menuBuilder = menuBuilder; + } + + + public DataAccessService getDataAccessService() { + return dataAccessService; + } + + + public void setDataAccessService(DataAccessService dataAccessService) { + this.dataAccessService = dataAccessService; + } + + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/PostDroolsService.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/PostDroolsService.java new file mode 100644 index 00000000..596ebed2 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/PostDroolsService.java @@ -0,0 +1,34 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.service; + +import java.util.List; + +import org.openecomp.portalsdk.core.command.PostDroolsBean; + +public interface PostDroolsService { + + String execute(String droolsFile, String className, String selectedRules); + + List<PostDroolsBean> fetchDroolBeans(); + + String retrieveClass(String droolsFile); + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/PostDroolsServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/PostDroolsServiceImpl.java new file mode 100644 index 00000000..658de264 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/PostDroolsServiceImpl.java @@ -0,0 +1,186 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.service; + +import java.io.File; +import java.io.IOException; +import java.nio.file.DirectoryIteratorException; +import java.nio.file.DirectoryStream; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import org.kie.api.io.ResourceType; +import org.kie.internal.KnowledgeBase; +import org.kie.internal.KnowledgeBaseFactory; +import org.kie.internal.builder.KnowledgeBuilder; +import org.kie.internal.builder.KnowledgeBuilderFactory; +import org.kie.internal.definition.KnowledgePackage; +import org.kie.internal.io.ResourceFactory; +import org.kie.internal.runtime.StatefulKnowledgeSession; +import org.openecomp.portalsdk.core.command.PostDroolsBean; +import org.openecomp.portalsdk.core.drools.DroolsRuleService; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * TODO REFACTOR + * + */ +@Service("postDroolsService") +@Transactional +public class PostDroolsServiceImpl implements PostDroolsService{ + + static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PostDroolsServiceImpl.class); + + @Override + public String execute(String droolsFile, String className, String selectedRules) { + logger.info(EELFLoggerDelegate.applicationLogger, "Executing Drools..."); + String resultsString = executeDemoRules(droolsFile, className, selectedRules); + return resultsString; + } + + + public List<PostDroolsBean> fetchDroolBeans() { + + List<PostDroolsBean> beanList = new ArrayList<PostDroolsBean>(); + Path path = FileSystems.getDefault().getPath(SystemProperties.getProperty(SystemProperties.FILES_PATH)); + try (DirectoryStream<Path> stream = Files.newDirectoryStream(path,"*.{drl}")) { + for (Path entry: stream) { + + PostDroolsBean postDroolsBean = new PostDroolsBean(); + String fileName = entry.getName(entry.getNameCount()-1).toString(); + postDroolsBean.setDroolsFile(fileName);//sample populated + postDroolsBean.setClassName(retrieveClass(fileName)); + //postDroolsBean.setSelectedRules("[\"NJ\",\"NY\",\"KY\"]"); + beanList.add(postDroolsBean); + } + } catch (DirectoryIteratorException ex) { + logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage()); + } catch (IOException e) { + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); + } + return beanList; + } + + @Override + public String retrieveClass(String fileName) { + String resultsString = ""; + try { + // load up the knowledge base + final KnowledgeBuilder kbuilder = loadKBuilder(fileName); + final Collection<KnowledgePackage> pkgs = kbuilder.getKnowledgePackages(); + return pkgs.iterator().next().getFactTypes().iterator().next().getFactClass().getName(); + + } catch (Throwable t) { + logger.error(EELFLoggerDelegate.errorLogger, t.getMessage()); + } + + return resultsString; + } + + protected static KnowledgeBuilder loadKBuilder(String fileName) { + final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); + + // this will parse and compile in one step + kbuilder.add(ResourceFactory.newFileResource(SystemProperties.getProperty(SystemProperties.FILES_PATH) + File.separator + fileName), + //kbuilder.add(ResourceFactory.newClassPathResource(SystemProperties.getProperty(SystemProperties.FILES_PATH) + File.separator + drl_file_path, DroolsRuleService.class), + ResourceType.DRL); + // kbuilder.add(ResourceFactory.newClassPathResource("rules.drl",DroolsRuleService.class), + // ResourceType.DRL); + + // Check the builder for errors + if (kbuilder.hasErrors()) { + + logger.error(EELFLoggerDelegate.errorLogger, kbuilder.getErrors().toString()); + + throw new RuntimeException("Unable to compile \".drl\"."); + + } + return kbuilder; + } + + + @SuppressWarnings({ "deprecation", "unchecked" }) + public static String executeDemoRules(String fileName, String className, String ruleValue) { + String resultsString = ""; + try { + // load up the knowledge base + // KieServices ks = KieServices.Factory.get(); + // KieContainer kContainer = ks.getKieClasspathContainer(); + // KieSession kSession = kContainer.newKieSession("ksession-rules"); + + final KnowledgeBuilder kbuilder = loadKBuilder(fileName); + + // get the compiled packages (which are serializable) + + final Collection<KnowledgePackage> pkgs = kbuilder.getKnowledgePackages(); + + // add the packages to a knowledgebase (deploy the knowledge + // packages). + + final KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); + + kbase.addKnowledgePackages(pkgs); + + final StatefulKnowledgeSession kSession = kbase.newStatefulKnowledgeSession(); + + ObjectMapper mapper = new ObjectMapper(); + if(ruleValue == null || ruleValue.equals("")) { + resultsString = "Please enter valid rule"; + return resultsString; + } + List<String> selectedRules = mapper.readValue(ruleValue, List.class); + List<String> ruleResponse = new ArrayList<String>(); + + for(String rule : selectedRules){ + Class<DroolsRuleService> clazz = (Class<DroolsRuleService>) Class.forName(className); + DroolsRuleService droolsIntroduction =clazz.newInstance(); + droolsIntroduction.init(rule); + kSession.insert(droolsIntroduction); + kSession.fireAllRules(); + ruleResponse.add(droolsIntroduction.getResultsString()); + } + + resultsString = mapper.writeValueAsString(ruleResponse); + +// kSession.insert(new DroolsRuleService("KY")); +// kSession.fireAllRules(); +// +// kSession.setGlobal("age", "25"); +// kSession.insert(new DroolsRuleService("NY")); +// kSession.fireAllRules(); + } catch (Throwable t) { + logger.error(EELFLoggerDelegate.errorLogger, t.getMessage()); + } + + return resultsString; + } + + + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/PostSearchService.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/PostSearchService.java new file mode 100644 index 00000000..cde9a370 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/PostSearchService.java @@ -0,0 +1,37 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.service; + +import javax.servlet.http.HttpServletRequest; + +import org.openecomp.portalsdk.core.command.PostSearchBean; + +public interface PostSearchService { + + /** + * Imports the selected users in the search results as new users. + * + * @param request + * @param postSearch + * @return the number of users successfully imported + */ + int process(HttpServletRequest request, PostSearchBean postSearch); + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/PostSearchServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/PostSearchServiceImpl.java new file mode 100644 index 00000000..f2877d4d --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/PostSearchServiceImpl.java @@ -0,0 +1,207 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.service; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; + +import org.openecomp.portalsdk.core.FusionObject.Parameters; +import org.openecomp.portalsdk.core.command.PostSearchBean; +import org.openecomp.portalsdk.core.domain.Lookup; +import org.openecomp.portalsdk.core.domain.Role; +import org.openecomp.portalsdk.core.domain.User; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service("postSearchService") +@Transactional +public class PostSearchServiceImpl implements PostSearchService { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PostSearchServiceImpl.class); + + @Autowired + private DataAccessService dataAccessService; + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Override + public int process(HttpServletRequest request, PostSearchBean postSearch) { + HashMap additionalParams = new HashMap(); + additionalParams.put(Parameters.PARAM_HTTP_REQUEST, request); + int numUsersImported = 0; + + if (postSearch.getSelected() != null) { + // sort the selected users for quick validation + + Arrays.sort(postSearch.getSelected()); + // import the users that have been selected + for (int i = 0; i < postSearch.getPostOrgUserId().length; i++) { + if (Arrays.binarySearch(postSearch.getSelected(), postSearch.getPostOrgUserId()[i]) >= 0) { + logger.debug(EELFLoggerDelegate.debugLogger, + "Adding ORGUSERID - " + postSearch.getPostOrgUserId()[i]); + logger.debug(EELFLoggerDelegate.auditLogger, + "Import new user from webphone " + postSearch.getPostOrgUserId()[i]); + + User user = new User(); + user.setLastName(postSearch.getPostLastName()[i]); + user.setFirstName(postSearch.getPostFirstName()[i]); + + if (postSearch.getPostHrid() != null && postSearch.getPostHrid().length > 0) { + user.setHrid(postSearch.getPostHrid()[i]); + } + + if (postSearch.getPostPhone() != null && postSearch.getPostPhone().length > 0) { + user.setPhone(postSearch.getPostPhone()[i]); + } + + if (postSearch.getPostEmail() != null && postSearch.getPostEmail().length > 0) { + user.setEmail(postSearch.getPostEmail()[i]); + } + + if (postSearch.getPostOrgUserId() != null && postSearch.getPostOrgUserId().length > 0) { + user.setOrgUserId(postSearch.getPostOrgUserId()[i]); + user.setLoginId(postSearch.getPostOrgUserId()[i]); + } + + if (postSearch.getPostAddress1() != null && postSearch.getPostAddress1().length > 0) { + user.setAddress1(postSearch.getPostAddress1()[i]); + } + + if (postSearch.getPostAddress2() != null && postSearch.getPostAddress2().length > 0) { + user.setAddress2(postSearch.getPostAddress2()[i]); + } + + if (postSearch.getPostCity() != null && postSearch.getPostCity().length > 0) { + user.setCity(postSearch.getPostCity()[i]); + } + + if (postSearch.getPostState() != null && postSearch.getPostState().length > 0) { + user.setState(postSearch.getPostState()[i]); + } + + if (postSearch.getPostZipCode() != null && postSearch.getPostZipCode().length > 0) { + user.setZipCode(postSearch.getPostZipCode()[i]); + } + + if (postSearch.getPostLocationClli() != null && postSearch.getPostLocationClli().length > 0) { + user.setLocationClli(postSearch.getPostLocationClli()[i]); + } + + if (postSearch.getPostBusinessCountryCode() != null + && postSearch.getPostBusinessCountryCode().length > 0) { + user.setBusinessCountryCode(postSearch.getPostBusinessCountryCode()[i]); + } + + if (postSearch.getPostBusinessCountryName() != null + && postSearch.getPostBusinessCountryName().length > 0) { + + // find the country cd for the indicated country + List countries = dataAccessService.getLookupList("fn_lu_country", "country_cd", "country", + "country = '" + postSearch.getPostBusinessCountryName()[i] + "'", null, null); + + if (countries != null && countries.size() == 1) { + Lookup country = (Lookup) countries.get(0); + user.setCountry(country.getValue()); + } else { + logger.info(EELFLoggerDelegate.debugLogger, + "No countries or more than one country was found matching the country returned from WEBPHONE. " + + "Therefore, no country was set for this user."); + } + + } + + if (postSearch.getPostDepartment() != null && postSearch.getPostDepartment().length > 0) { + user.setDepartment(postSearch.getPostDepartment()[i]); + } + + if (postSearch.getPostDepartmentName() != null && postSearch.getPostDepartmentName().length > 0) { + user.setDepartmentName(postSearch.getPostDepartmentName()[i]); + } + + if (postSearch.getPostBusinessUnit() != null && postSearch.getPostBusinessUnit().length > 0) { + user.setBusinessUnit(postSearch.getPostBusinessUnit()[i]); + } + + if (postSearch.getPostBusinessUnitName() != null + && postSearch.getPostBusinessUnitName().length > 0) { + user.setBusinessUnitName(postSearch.getPostBusinessUnitName()[i]); + } + + if (postSearch.getPostJobTitle() != null && postSearch.getPostJobTitle().length > 0) { + user.setJobTitle(postSearch.getPostJobTitle()[i]); + } + + if (postSearch.getPostOrgManagerUserId() != null + && postSearch.getPostOrgManagerUserId().length > 0) { + user.setOrgManagerUserId(postSearch.getPostOrgManagerUserId()[i]); + } + + if (postSearch.getPostCommandChain() != null && postSearch.getPostCommandChain().length > 0) { + user.setCommandChain(postSearch.getPostCommandChain()[i]); + } + + if (postSearch.getPostCompanyCode() != null && postSearch.getPostCompanyCode().length > 0) { + user.setCompanyCode(postSearch.getPostCompanyCode()[i]); + } + + if (postSearch.getPostCompany() != null && postSearch.getPostCompany().length > 0) { + user.setCompany(postSearch.getPostCompany()[i]); + } + + if (postSearch.getPostCostCenter() != null && postSearch.getPostCostCenter().length > 0) { + user.setCostCenter(postSearch.getPostCostCenter()[i]); + } + + if (postSearch.getPostSiloStatus() != null && postSearch.getPostSiloStatus().length > 0) { + user.setSiloStatus(postSearch.getPostSiloStatus()[i]); + } + + if (postSearch.getPostFinancialLocCode() != null + && postSearch.getPostFinancialLocCode().length > 0) { + user.setFinancialLocCode(postSearch.getPostFinancialLocCode()[i]); + } + + user.setActive(true); + + try { + dataAccessService.saveDomainObject(user, additionalParams); + Role role = (Role) dataAccessService.getDomainObject(Role.class, + Long.valueOf(SystemProperties.getProperty(SystemProperties.POST_DEFAULT_ROLE_ID)), + null); + user.addRole(role); + numUsersImported++; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "process: saveDomainObject failed on user " + user.getLoginId(), e); + } + } + } + + } + + return numUsersImported; + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/ProfileService.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/ProfileService.java new file mode 100644 index 00000000..61bd3b6e --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/ProfileService.java @@ -0,0 +1,36 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.service; + +import java.util.List; + +import org.openecomp.portalsdk.core.domain.Profile; +import org.openecomp.portalsdk.core.domain.User; + + +public interface ProfileService { + List<Profile> findAll(); + + Profile getProfile(int id); + + User getUser(String id); + + void saveUser(User user); +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/ProfileServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/ProfileServiceImpl.java new file mode 100644 index 00000000..2d6fcfee --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/ProfileServiceImpl.java @@ -0,0 +1,74 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.service; + +import java.util.List; + +import org.openecomp.portalsdk.core.dao.ProfileDao; +import org.openecomp.portalsdk.core.domain.Profile; +import org.openecomp.portalsdk.core.domain.User; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service("profileService") +@Transactional +public class ProfileServiceImpl implements ProfileService{ + + @Autowired + private ProfileDao profileDao; + + @Autowired + private DataAccessService dataAccessService; + + @SuppressWarnings("unchecked") + public List<Profile> findAll() { + //List msgDB = getDataAccessService().getList(Profile.class, null); + return getDataAccessService().getList(Profile.class, null); + } + + public User getUser(String userId){ + return (User) getDataAccessService().getDomainObject(User.class, Long.parseLong(userId), null); + } + + public void saveUser(User user){ + + getDataAccessService().saveDomainObject(user, null); + } + + + public Profile getProfile(int id) { + return profileDao.getProfile(id); + } + + + public DataAccessService getDataAccessService() { + return dataAccessService; + } + + + public void setDataAccessService(DataAccessService dataAccessService) { + this.dataAccessService = dataAccessService; + } + + + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/RoleService.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/RoleService.java new file mode 100644 index 00000000..01367ecd --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/RoleService.java @@ -0,0 +1,50 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.service; + +import java.util.List; + +import org.openecomp.portalsdk.core.domain.Role; +import org.openecomp.portalsdk.core.domain.RoleFunction; + + +public interface RoleService { + List<RoleFunction> getRoleFunctions(); + + List<Role> getAvailableChildRoles(Long roleId); + + Role getRole(Long id); + + void saveRole(Role domainRole); + + void deleteRole(Role domainRole); + + List<Role> getAvailableRoles(); + + List<Role> getActiveRoles(); + + RoleFunction getRoleFunction(String code); + + void saveRoleFunction(RoleFunction domainRoleFunction); + + void deleteRoleFunction(RoleFunction domainRoleFunction); + + void deleteDependcyRoleRecord(Long id); +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/RoleServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/RoleServiceImpl.java new file mode 100644 index 00000000..2e780998 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/RoleServiceImpl.java @@ -0,0 +1,171 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.service; + +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; + +import javax.sql.DataSource; + +import org.openecomp.portalsdk.core.domain.Role; +import org.openecomp.portalsdk.core.domain.RoleFunction; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service("roleService") +@Transactional +public class RoleServiceImpl implements RoleService { + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RoleServiceImpl.class); + + @Autowired + private DataAccessService dataAccessService; + + DataSource dataSource; + + public DataSource getDataSource() { + return dataSource; + } + + @Autowired + public void setDataSource(DataSource dataSource) { + this.dataSource = dataSource; + } + + @SuppressWarnings("unchecked") + public List<RoleFunction> getRoleFunctions() { + // List msgDB = getDataAccessService().getList(Profile.class, null); + return getDataAccessService().getList(RoleFunction.class, null); + } + + @SuppressWarnings("unchecked") + public List<Role> getAvailableChildRoles(Long roleId) { + List<Role> availableChildRoles = (List<Role>) getDataAccessService().getList(Role.class, null); + if (roleId == null || roleId == 0) { + return availableChildRoles; + } + + Role currentRole = (Role) getDataAccessService().getDomainObject(Role.class, roleId, null); + Set<Role> allParentRoles = new TreeSet<Role>(); + allParentRoles = getAllParentRolesAsList(currentRole, allParentRoles); + + Iterator<Role> availableChildRolesIterator = availableChildRoles.iterator(); + while (availableChildRolesIterator.hasNext()) { + Role role = availableChildRolesIterator.next(); + if (!role.getActive() || allParentRoles.contains(role) || role.getId().equals(roleId)) { + availableChildRolesIterator.remove(); + } + } + return availableChildRoles; + } + + @SuppressWarnings("unchecked") + private Set<Role> getAllParentRolesAsList(Role role, Set<Role> allParentRoles) { + Set<Role> parentRoles = role.getParentRoles(); + allParentRoles.addAll(parentRoles); + Iterator<Role> parentRolesIterator = parentRoles.iterator(); + while (parentRolesIterator.hasNext()) { + getAllParentRolesAsList(parentRolesIterator.next(), allParentRoles); + } + return allParentRoles; + } + + public RoleFunction getRoleFunction(String code) { + return (RoleFunction) getDataAccessService().getDomainObject(RoleFunction.class, code, null); + } + + public void saveRoleFunction(RoleFunction domainRoleFunction) { + getDataAccessService().saveDomainObject(domainRoleFunction, null); + } + + public void deleteRoleFunction(RoleFunction domainRoleFunction) { + getDataAccessService().deleteDomainObject(domainRoleFunction, null); + } + + public Role getRole(Long id) { + return (Role) getDataAccessService().getDomainObject(Role.class, id, null); + } + + public void saveRole(Role domainRole) { + getDataAccessService().saveDomainObject(domainRole, null); + } + + public void deleteRole(Role domainRole) { + getDataAccessService().deleteDomainObject(domainRole, null); + } + + @SuppressWarnings("unchecked") + public List<Role> getAvailableRoles() { + return getDataAccessService().getList(Role.class, null); + } + + @SuppressWarnings("unchecked") + @Override + public List<Role> getActiveRoles() { + String filter = " where active_yn = 'Y' "; + return getDataAccessService().getList(Role.class, filter, null, null); + } + + public DataAccessService getDataAccessService() { + return dataAccessService; + } + + public void setDataAccessService(DataAccessService dataAccessService) { + this.dataAccessService = dataAccessService; + } + + @Override + public void deleteDependcyRoleRecord(Long id) { + Connection conn = null; + Statement stmt = null; + try { + conn = getDataSource().getConnection(); + stmt = conn.createStatement(); + String sql = "delete from fn_user_role where role_id = '" + id + "'"; + stmt.executeUpdate(sql); + stmt.close(); + conn.close(); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "deleteDependcyRoleRecord failed", e); + } finally { + try { + if (stmt != null) + stmt.close(); + } catch (SQLException se2) { + logger.error(EELFLoggerDelegate.errorLogger, "deleteDependcyRoleRecord failed", se2); + } + try { + if (conn != null) + conn.close(); + } catch (SQLException se) { + logger.error(EELFLoggerDelegate.errorLogger, "deleteDependcyRoleRecord failed", se); + } + } + + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/RoleServiceNonSpringImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/RoleServiceNonSpringImpl.java new file mode 100644 index 00000000..a7374d0c --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/RoleServiceNonSpringImpl.java @@ -0,0 +1,122 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.service; +/*package org.openecomp.portalsdk.core.service; + +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import org.openecomp.portalsdk.core.domain.Role; +import org.openecomp.portalsdk.core.domain.RoleFunction; + +@Service("roleService") +@Transactional +public class RoleServiceNonSpringImpl implements RoleService{ + + @Autowired + private DataAccessService dataAccessService; + + @SuppressWarnings("unchecked") + public List<RoleFunction> getRoleFunctions() { + //List msgDB = getDataAccessService().getList(Profile.class, null); + return getDataAccessService().getList(RoleFunction.class, null); + } + + @SuppressWarnings("unchecked") + public List<Role> getAvailableChildRoles(Long roleId) { + List<Role> availableChildRoles = (List<Role>)getDataAccessService().getList(Role.class,null); + if(roleId==null || roleId==0){ + return availableChildRoles; + } + + Role currentRole = (Role)getDataAccessService().getDomainObject(Role.class,roleId,null); + Set<Role> allParentRoles = new TreeSet<Role>(); + allParentRoles = getAllParentRolesAsList(currentRole, allParentRoles); + + + Iterator<Role> availableChildRolesIterator = availableChildRoles.iterator(); + while (availableChildRolesIterator.hasNext()) { + Role role = availableChildRolesIterator.next(); + if(!role.getActive() || allParentRoles.contains(role) || role.getId().equals(roleId)){ + availableChildRolesIterator.remove(); + } + } + return availableChildRoles; + } + + @SuppressWarnings("unchecked") + private Set<Role> getAllParentRolesAsList(Role role, Set<Role> allParentRoles) { + Set<Role> parentRoles = role.getParentRoles(); + allParentRoles.addAll(parentRoles); + Iterator<Role> parentRolesIterator = parentRoles.iterator(); + while (parentRolesIterator.hasNext()) { + getAllParentRolesAsList(parentRolesIterator.next(),allParentRoles); + } + return allParentRoles; + } + + public RoleFunction getRoleFunction(String code) { + return (RoleFunction)getDataAccessService().getDomainObject(RoleFunction.class, code, null); + } + + public void saveRoleFunction(RoleFunction domainRoleFunction) { + getDataAccessService().saveDomainObject(domainRoleFunction, null); + } + + public void deleteRoleFunction(RoleFunction domainRoleFunction) { + getDataAccessService().deleteDomainObject(domainRoleFunction, null); + } + + public Role getRole(Long id) { + return (Role)getDataAccessService().getDomainObject(Role.class, id, null); + } + + public void saveRole(Role domainRole) { + getDataAccessService().saveDomainObject(domainRole, null); + } + + public void deleteRole(Role domainRole) { + getDataAccessService().deleteDomainObject(domainRole, null); + } + + @SuppressWarnings("unchecked") + public List<Role> getAvailableRoles() { + return getDataAccessService().getList(Role.class, null); + } + + public DataAccessService getDataAccessService() { + return dataAccessService; + } + + + public void setDataAccessService(DataAccessService dataAccessService) { + this.dataAccessService = dataAccessService; + } + + + +} +*/
\ No newline at end of file diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/UserProfileService.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/UserProfileService.java new file mode 100644 index 00000000..b844fb0c --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/UserProfileService.java @@ -0,0 +1,34 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.service; + +import java.util.List; + +import org.openecomp.portalsdk.core.domain.User; + + +public interface UserProfileService { + List<User> findAll(); + User getUser(String id); + User getUserByLoginId(String loginId); + void saveUser(User user); + public List<User> findAllUserWithOnOffline(String originOrgUserId); + List<User> findAllActive(); +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/UserProfileServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/UserProfileServiceImpl.java new file mode 100644 index 00000000..2d134725 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/UserProfileServiceImpl.java @@ -0,0 +1,116 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.service; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.SortedSet; + +import org.hibernate.criterion.Criterion; +import org.hibernate.criterion.Restrictions; +import org.openecomp.portalsdk.core.domain.Role; +import org.openecomp.portalsdk.core.domain.User; +import org.openecomp.portalsdk.core.domain.support.CollaborateList; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service("userProfileService") +@Transactional +public class UserProfileServiceImpl implements UserProfileService{ + + + @Autowired + private DataAccessService dataAccessService; + + public List<User> findAll() { + return getDataAccessService().getList(User.class, null); + } + + public User getUser(String userId){ + return (User) getDataAccessService().getDomainObject(User.class, Long.parseLong(userId), null); + } + + @SuppressWarnings("unchecked") + public User getUserByLoginId(String loginId){ + User user=null; + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion criterion1= Restrictions.eq("loginId",loginId); + restrictionsList.add(criterion1); + List<User> users = (List<User>) getDataAccessService().getList(User.class,null, restrictionsList, null); + if(users!=null && users.size()==1) + user = users.get(0); + return user; + } + + public void saveUser(User user){ + + getDataAccessService().saveDomainObject(user, null); + } + + public DataAccessService getDataAccessService() { + return dataAccessService; + } + + + public void setDataAccessService(DataAccessService dataAccessService) { + this.dataAccessService = dataAccessService; + } + + @SuppressWarnings("unchecked") + public List<User> findAllUserWithOnOffline(String originOrgUserId) { + HashSet<String> onlineUser = CollaborateList.getInstance().getAllUserName(); + List<User> users = getDataAccessService().getList(User.class, null); + for(User u:users){ + if(onlineUser.contains(u.getOrgUserId())) + u.setOnline(true); + if(u.getOrgUserId()!=null){ + if(originOrgUserId.compareTo(u.getOrgUserId()) > 0) { + u.setChatId(originOrgUserId + "-" + u.getOrgUserId()); + } else u.setChatId(u.getOrgUserId() + "-" + originOrgUserId ); + } + } + return users; + + } + + public List<User> findAllActive() { + List<User> users = getDataAccessService().getList(User.class, null); + Iterator<User> itr = users.iterator(); + while(itr.hasNext()){ + User u = (User) itr.next(); + if(!u.getActive()) + itr.remove();//if not active remove user from list + else { + SortedSet<Role> roles = u.getRoles(); + Iterator<Role> itrRoles = roles.iterator(); + while(itrRoles.hasNext()){ + Role role = (Role) itrRoles.next(); + if(!role.getActive()) + u.removeRole(role.getId());//if not active remove role from list + } + } + } + return users; + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/WebServiceCallService.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/WebServiceCallService.java new file mode 100644 index 00000000..a7a5ad07 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/WebServiceCallService.java @@ -0,0 +1,26 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.service; + + +public interface WebServiceCallService { + public boolean verifyRESTCredential(String secretKey, String requestAppName, String requestPassword)throws Exception; + /*public String get(String restURL, String restPath);*/ +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/WebServiceCallServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/WebServiceCallServiceImpl.java new file mode 100644 index 00000000..557af2dd --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/WebServiceCallServiceImpl.java @@ -0,0 +1,189 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.service; + +import java.util.List; + +import org.openecomp.portalsdk.core.domain.App; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.util.CipherUtil; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service("webServiceCallService") +@Transactional +public class WebServiceCallServiceImpl implements WebServiceCallService{ + + @Autowired + private DataAccessService dataAccessService; + + @Autowired + AppService appService; + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WebServiceCallServiceImpl.class); + + /** + * Verify REST Credential + * @return true if the credential is accepted; else false. + */ + @Override + public boolean verifyRESTCredential(String secretKey, String requestAppName, String requestPassword)throws Exception { + App app = appService.getDefaultApp(); + if (app!=null) { + String encriptedPwdDB = app.getAppPassword(); + String appUserName = app.getUsername(); + String decreptedPwd = CipherUtil.decrypt(encriptedPwdDB, secretKey==null?SystemProperties.getProperty(SystemProperties.Decryption_Key):secretKey); + if(decreptedPwd.equals(requestPassword) && appUserName.equals(requestAppName)) { + return true; + } + } + return false; + } + + /** + * Getting App information from FN_APP table + * @return App domain object, or null if not found. + */ + public App findApp(){ + List<?> list = null; + StringBuffer criteria = new StringBuffer(); + criteria.append(" where id = 1"); + list = getDataAccessService().getList(App.class, criteria.toString(), null, null); + return (list == null || list.size() == 0) ? null : (App) list.get(0); + } + + public DataAccessService getDataAccessService() { + return dataAccessService; + } + + public void setDataAccessService(DataAccessService dataAccessService) { + this.dataAccessService = dataAccessService; + } + + /*/ + @Override + public String get(String restURL, String restPath) { + String appUserName = ""; + String appUebKey = ""; + String decreptedPwd = ""; + String appName = ""; + String inputLine = ""; + String serviceName = ""; + String loginId = ""; + StringBuffer jsonResponse = new StringBuffer(); + + StopWatch stopWatch = new StopWatch("WebServiceCallServiceImpl.get"); + stopWatch.start(); + try { + logger.info(EELFLoggerDelegate.metricsLogger, "WebServiceCallServiceImpl.get (" + restPath + ") operation is started."); + logger.debug(EELFLoggerDelegate.debugLogger, "WebServiceCallServiceImpl.get (" + restPath + ") operation is started."); + loginId = MDC.get("LoginId"); + appUebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY); + App app = appService.getDefaultApp(); + if (app!=null) { + appName = app.getName(); + appUserName = app.getUsername(); + try{ + decreptedPwd = CipherUtil.decrypt(app.getAppPassword(), SystemProperties.getProperty(SystemProperties.Decryption_Key)); + } catch(Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in WebServiceCallServiceImpl.get while decrypting the password. Details: " + e.getMessage()); + } + } else { + logger.warn(EELFLoggerDelegate.errorLogger, "Unable to locate the app information from the database."); + appName = SystemProperties.SERVICE_NAME; + } + + //Create the connection object + URL obj = new URL(restURL + restPath); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + con.setRequestMethod("GET"); + con.setConnectTimeout(3000); + con.setReadTimeout(8000); + + //add request header + con.setRequestProperty("username", appUserName); + con.setRequestProperty("password", decreptedPwd); + con.setRequestProperty("uebkey", appUebKey); + con.setRequestProperty(SystemProperties.LOGIN_ID, loginId); + con.setRequestProperty(SystemProperties.USERAGENT_NAME, appName); + con.setRequestProperty(SystemProperties.ECOMP_REQUEST_ID, MDC.get(MDC_KEY_REQUEST_ID)); + + //set MDC context for outgoing audit logging + serviceName = String.format("%s:%s.%s", appName, SystemProperties.ECOMP_PORTAL_BE, restPath); + MDC.put(Configuration.MDC_SERVICE_NAME, serviceName); + MDC.put(Configuration.MDC_REMOTE_HOST, restURL); + MDC.put(SystemProperties.MDC_APPNAME, appName); + MDC.put(SystemProperties.MDC_REST_PATH, restPath); + MDC.put(SystemProperties.MDC_REST_METHOD, "GET"); + + int responseCode = con.getResponseCode(); + logger.info(EELFLoggerDelegate.errorLogger, "Received the response code '" + responseCode + "' while getting the '" + restPath + "' for user: " + loginId); + + BufferedReader in = new BufferedReader( + new InputStreamReader(con.getInputStream())); + + while ((inputLine = in.readLine()) != null) { + jsonResponse.append(inputLine); + } + in.close(); + + logSecurityMessage(RESULT_ENUM.SUCCESS); + logger.debug(EELFLoggerDelegate.debugLogger, restPath + " response: " + jsonResponse.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, "WebServiceCallServiceImpl.get (" + restPath + ") operation is started."); + } catch(UrlAccessRestrictedException e) { + logger.error(EELFLoggerDelegate.errorLogger, "Authentication exception occurred in WebServiceCallServiceImpl.get (" + restPath + "). Details: " + e.getMessage()); + logSecurityMessage(RESULT_ENUM.FAILURE); + } catch(Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in WebServiceCallServiceImpl.get (" + restPath + "). Details: " + e.getMessage()); + logSecurityMessage(RESULT_ENUM.FAILURE); + } finally { + if (stopWatch.isRunning()) stopWatch.stop(); + MDC.put(SystemProperties.MDC_TIMER, stopWatch.getTotalTimeMillis() + "ms"); + logger.info(EELFLoggerDelegate.metricsLogger, "WebServiceCallServiceImpl.get (" + restPath + ") operation is completed."); + + //clear the temporary MDC context values + MDC.remove(SystemProperties.MDC_TIMER); + MDC.remove(SystemProperties.MDC_REST_METHOD); + MDC.remove(SystemProperties.MDC_REST_PATH); + MDC.remove(SystemProperties.MDC_APPNAME); + MDC.remove(Configuration.MDC_REMOTE_HOST); + MDC.remove(Configuration.MDC_SERVICE_NAME); + } + + return jsonResponse.toString(); + } + + //Handles all the outgoing rest/ueb messages. + public void logSecurityMessage(RESULT_ENUM isSuccess) { + String additionalInfo = ""; + String protocol = "HTTP"; + String loginId = MDC.get("LoginId"); + additionalInfo = String.format("Rest API=%s, Rest Method=%s, App-Name=%s, Request-URL=%s", + MDC.get(SystemProperties.MDC_REST_PATH), MDC.get(SystemProperties.MDC_REST_METHOD), + MDC.get(SystemProperties.MDC_APPNAME), MDC.get(Configuration.MDC_REMOTE_HOST)); + + logger.info(EELFLoggerDelegate.auditLogger, AuditLogFormatter.getInstance().createMessage( + protocol, SecurityEventTypeEnum.OUTGOING_REST_MESSAGE.name(), loginId, SystemProperties.SERVICE_NAME, + isSuccess.name(), additionalInfo)); + } + /**/ +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/support/FusionService.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/support/FusionService.java new file mode 100644 index 00000000..34649ee1 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/support/FusionService.java @@ -0,0 +1,27 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.service.support; + + +import org.openecomp.portalsdk.core.FusionObject; + +public class FusionService implements FusionObject { + /** Logger for this class and subclasses */ +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/support/ServiceLocator.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/support/ServiceLocator.java new file mode 100644 index 00000000..5858c3fa --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/support/ServiceLocator.java @@ -0,0 +1,27 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.service.support; + +import javax.naming.directory.DirContext; + + +public interface ServiceLocator { + DirContext getDirContext(String initialContextFactory, String providerUrl, String securityPrincipal); +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/support/ServiceLocatorImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/support/ServiceLocatorImpl.java new file mode 100644 index 00000000..97f4875d --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/service/support/ServiceLocatorImpl.java @@ -0,0 +1,105 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.service.support; + +import java.util.*; + +import javax.naming.*; +import javax.naming.directory.*; +import javax.naming.ldap.*; + +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.stereotype.Service; + +/** + * This class implements the J2EE service locator pattern. It provides lookup + * facilities for various services. Currenttly LDAP (pre-v3) is supported + */ +@Service("serviceLocator") +public class ServiceLocatorImpl implements ServiceLocator { + + //private static ServiceLocator locator; // The singleton instance + + private Context context; // JNDI context (not currently in use) + private Context rootContext; // Java env root context (not currently in use) + private DirContext dirContext; // LDAP DIR context + private InitialLdapContext ldapContext; // LDAP context LDAPv3-style (not currently in use) + + + // cannot directly instantiate + public ServiceLocatorImpl() {} + + /*public static ServiceLocator getLocator() { + if (locator == null) + locator = new ServiceLocator(); + return locator; + } + + public Object clone() throws CloneNotSupportedException { + throw new CloneNotSupportedException(); + }*/ + + + // Get an LDAP directory context + public DirContext getDirContext(String initialContextFactory, String providerUrl, String securityPrincipal) { + + if (dirContext == null) { + + Properties properties = new Properties(); + properties.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory); + properties.put(Context.PROVIDER_URL, providerUrl); + properties.put(Context.SECURITY_PRINCIPAL, securityPrincipal); + + try { + dirContext = new InitialDirContext(properties); + } + catch (NamingException ne) { + logger.error(EELFLoggerDelegate.errorLogger, "An error has occurred while creating an Initial Directory Context: " + ne.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, "Explanation: " + ne.getExplanation()); + } + } + + return dirContext; + } + + // Get an LDAP directory context - LDAPv3-style + /*public InitialLdapContext getLdapContext() { //throws NamingException { + if (ldapContext == null) { + Properties properties = new Properties(); + // @todo - need to parameterize context factoy class and url + properties.put(Context.INITIAL_CONTEXT_FACTORY, AttLdap.DIR_INITIAL_CONTEXT_FACTORY); + properties.put(Context.PROVIDER_URL, AttLdap.DIR_PROVIDER_URL); + properties.put(Context.SECURITY_PRINCIPAL, AttLdap.DIR_SECURITY_PRINCIPAL); + Control[] ctrl = null; + try { + ldapContext = new InitialLdapContext(properties, ctrl); + } + catch (NamingException ne) { + // MJ FIX log exception? + } + } + return ldapContext; + }*/ + + + /** Logger for this class and subclasses */ + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ServiceLocatorImpl.class); + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/util/CacheManager.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/util/CacheManager.java new file mode 100644 index 00000000..e26ac884 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/util/CacheManager.java @@ -0,0 +1,43 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.util; + +import org.openecomp.portalsdk.core.objectcache.jcs.JCSCacheManager; +import org.springframework.context.annotation.Configuration; +@Configuration +public class CacheManager extends JCSCacheManager { + public CacheManager() { + + } + + /* The following can be customized for your application to cache the appropriate data upon application startup. The provided + example retrieves a list of sample lookup data and puts the list in the Cache Manager. To retrieve that data, simply call the + Cache Manager's getObject(String key) method which will return an Object instance. To put additional data in the Cache Manager + outside of application startup, call the Cache Manager's putObject(String key, Object objectToCache) method. */ + public void loadLookUpCache() { + /* + List<Role> result = (List<Role>)getDataAccessService().getList(Role.class,null); + + if (result != null) { + putObject("lookupRoles", result); + }*/ + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/util/EncDecUtilTest.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/util/EncDecUtilTest.java new file mode 100644 index 00000000..23d90cc9 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/util/EncDecUtilTest.java @@ -0,0 +1,112 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.util; +import java.security.AlgorithmParameters; +import java.security.SecureRandom; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.SecretKey; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.PBEKeySpec; +import javax.crypto.spec.SecretKeySpec; + +import org.apache.commons.codec.binary.Base64; + +public class EncDecUtilTest { + + private static final String password = "test"; + private static final String salt = "r n�HN~��|f��X�" ; + private static int pswdIterations = 65536 ; + private static int keySize = 256; + private byte[] ivBytes; + + public String encrypt(String plainText) throws Exception { + + //get salt + //salt = generateSalt(); + byte[] saltBytes = salt.getBytes("UTF-8"); + + // Derive the key + SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); + PBEKeySpec spec = new PBEKeySpec( + password.toCharArray(), + saltBytes, + pswdIterations, + keySize + ); + + SecretKey secretKey = factory.generateSecret(spec); + SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES"); + + //encrypt the message + Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); + cipher.init(Cipher.ENCRYPT_MODE, secret); + AlgorithmParameters params = cipher.getParameters(); + ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV(); + byte[] encryptedTextBytes = cipher.doFinal(plainText.getBytes("UTF-8")); + return new Base64().encodeAsString(encryptedTextBytes); + } + + @SuppressWarnings("static-access") + public String decrypt(String encryptedText) throws Exception { + + byte[] saltBytes = salt.getBytes("UTF-8"); + byte[] encryptedTextBytes = new Base64().decodeBase64(encryptedText); + + // Derive the key + SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); + PBEKeySpec spec = new PBEKeySpec( + password.toCharArray(), + saltBytes, + pswdIterations, + keySize + ); + + SecretKey secretKey = factory.generateSecret(spec); + SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES"); + + // Decrypt the message + Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); + cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(ivBytes)); + + + byte[] decryptedTextBytes = null; + try { + decryptedTextBytes = cipher.doFinal(encryptedTextBytes); + } catch (IllegalBlockSizeException e) { + e.printStackTrace(); + } catch (BadPaddingException e) { + e.printStackTrace(); + } + + return new String(decryptedTextBytes); + } + + public String generateSalt() { + SecureRandom random = new SecureRandom(); + byte bytes[] = new byte[20]; + random.nextBytes(bytes); + String s = new String(bytes); + return s; + } +}
\ No newline at end of file diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/util/JSONUtil.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/util/JSONUtil.java new file mode 100644 index 00000000..6b849e81 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/util/JSONUtil.java @@ -0,0 +1,56 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.util; + +import java.util.HashMap; +import java.util.Map; + +import org.openecomp.portalsdk.core.domain.User; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class JSONUtil { + public static String convertResponseToJSON(String response) throws JsonProcessingException{ + ObjectMapper mapper = new ObjectMapper(); + Map<String, String> responseMap = new HashMap<String, String>(); + responseMap.put("response", response); + response = mapper.writeValueAsString(responseMap); + return response; + } + + public static User mapToDomainUser(User domainUser, User editUser) { + domainUser.setOrgId(editUser.getOrgId()); + domainUser.setManagerId(editUser.getManagerId()); + domainUser.setFirstName(editUser.getFirstName()); + domainUser.setMiddleInitial(editUser.getMiddleInitial()); + domainUser.setLastName(editUser.getLastName()); + domainUser.setPhone(editUser.getPhone()); + domainUser.setEmail(editUser.getEmail()); + domainUser.setHrid(editUser.getHrid()); + domainUser.setOrgUserId(editUser.getOrgUserId()); + domainUser.setOrgCode(editUser.getOrgCode()); + domainUser.setOrgManagerUserId(editUser.getOrgManagerUserId()); + domainUser.setJobTitle(editUser.getJobTitle()); + domainUser.setLoginId(editUser.getLoginId()); + domainUser.setActive(editUser.getActive()); + return domainUser; + } +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/util/SystemProperties.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/util/SystemProperties.java new file mode 100644 index 00000000..6a705aed --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/util/SystemProperties.java @@ -0,0 +1,327 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.util; + +import javax.servlet.ServletContext; + +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; + +/** + * SystemProperties contains a list of constants used throughout portions of the + * application. Populated by Spring from multiple configuration files. + * + * Should be used like this: + * + * <pre> + * + * @Autowired + * SystemProperties systemProperties; + * </pre> + */ +@Configuration +@PropertySource(value = { "${container.classpath:}/WEB-INF/conf/system.properties", + "${container.classpath:}/WEB-INF/fusion/conf/fusion.properties", + "${container.classpath:}/WEB-INF/conf/sql.properties" }) +public class SystemProperties { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SystemProperties.class); + + private static Environment environment; + + private ServletContext servletContext; + + public SystemProperties() { + } + + protected Environment getEnvironment() { + return environment; + } + + @Autowired + public void setEnvironment(Environment environment) { + SystemProperties.environment = environment; + } + + public ServletContext getServletContext() { + return servletContext; + } + + public void setServletContext(ServletContext servletContext) { + this.servletContext = servletContext; + } + + /** + * Tests whether a property value is available for the specified key. + * + * @param key + * @return True if the key is known, otherwise false. + */ + public static boolean containsProperty(String key) { + return environment.containsProperty(key); + } + + /** + * Returns the property value associated with the given key (never + * {@code null}), after trimming any trailing space. + * + * @throws IllegalStateException + * if the key cannot be resolved + * @param key + * Property key + * @return Property value; the empty string if the environment was not + * autowired, which should never happen. + */ + public static String getProperty(String key) { + String value = ""; + if (environment == null) { + logger.error(EELFLoggerDelegate.errorLogger, "getProperty: environment is null, should never happen!"); + } + else { + value = environment.getRequiredProperty(key); + // java.util.Properties preserves trailing space + if (value != null) + value = value.trim(); + } + return value; + } + + /** + * Gets the property value for the key {@link #APPLICATION_NAME}. + * + * method created to get around JSTL 1.0 limitation of not being able to + * access a static method of a bean + * + * @return Application name + */ + public String getApplicationName() { + return getProperty(APPLICATION_NAME); + } + + /** + * Gets the property value for the key {@link #APP_DISPLAY_NAME}. + * + * @return Application display name + */ + public String getAppDisplayName() { + return getProperty(APP_DISPLAY_NAME); + } + + // keys used to reference values in the system properties file + public static final String DOMAIN_CLASS_LOCATION = "domain_class_location"; + public static final String DEFAULT_ERROR_MESSAGE = "default_error_message"; + + public static final String CSP_COOKIE_NAME = "csp_cookie_name"; + public static final String CSP_GATE_KEEPER_DATA_KEY = "csp_gate_keeper_data_key"; + public static final String CSP_GATE_KEEPER_PROD_KEY = "csp_gate_keeper_prod_key"; + public static final String CSP_LOGIN_URL = "csp_login_url"; + public static final String CSP_LOGOUT_URL = "csp_logout_url"; + + public static final String WEB_JUNCTION_USER_ID_HEADER_NAME = "web_junction_user_id_header_name"; + + public static final String AUTHENTICATION_MECHANISM = "authentication_mechanism"; + + public static final String APPLICATION_NAME = "application_name"; + public static final String HIBERNATE_CONFIG_FILE_PATH = "hibernate_config_file_path"; + public static final String APPLICATION_USER_ID = "application_user_id"; + + public static final String POST_INITIAL_CONTEXT_FACTORY = "post_initial_context_factory"; + public static final String POST_PROVIDER_URL = "post_provider_url"; + public static final String POST_SECURITY_PRINCIPAL = "post_security_principal"; + public static final String POST_MAX_RESULT_SIZE = "post_max_result_size"; + public static final String POST_DEFAULT_ROLE_ID = "post_default_role_id"; + + public static final String FILES_PATH = "files_path"; + public static final String TEMP_PATH = "temp_path"; + + public static final String NUM_UPLOAD_FILES = "num_upload_files"; + + public static final String SYS_ADMIN_ROLE_ID = "sys_admin_role_id"; + + public static final String SYS_ADMIN_ROLE_FUNCTION_DELETE_FROM_UI = "sys_admin_role_function_delete_from_ui"; + public static final String USER_NAME = "user_name"; + public static final String FIRST_NAME = "first_name"; + public static final String LAST_NAME = "last_name"; + public static final String APP_DISPLAY_NAME = "app_display_name"; + // Application base URL is a proper prefix of the on-boarding URL + public static final String APP_BASE_URL = "app_base_url"; + + public static final String MENU_PROPERTIES_FILE_LOCATION = "menu_properties_file_location"; + public static final String MENU_QUERY_NAME = "menu_query_name"; + public static final String APPLICATION_MENU_SET_NAME = "application_menu_set_name"; + public static final String APPLICATION_MENU_ATTRIBUTE_NAME = "application_menu_attribute_name"; + public static final String APPLICATION_MENU_PROPERTIES_NAME = "application_menu_properties_name"; + public static final String BUSINESS_DIRECT_MENU_SET_NAME = "business_direct_menu_set_name"; + public static final String BUSINESS_DIRECT_MENU_ATTRIBUTE_NAME = "business_direct_menu_attribute_name"; + public static final String BUSINESS_DIRECT_MENU_PROPERTIES_NAME = "business_direct_menu_properties_name"; + public static final String RAPTOR_CONFIG_FILE_PATH = "raptor_config_file_path"; + public static final String HOMEPAGE_DATA_CALLBACK_CLASS = "homepage_data_callback_class"; + public static final String ERROR_EMAIL_DISTRIBUTION = "error_email_distribution"; + public static final String ERROR_EMAIL_SOURCE_ADDRESS = "error_email_source_address"; + public static final String ERROR_EMAIL_SUBJECT_LINE = "error_email_subject_line"; + public static final String PROFILE_SEARCH_REPORT_ID = "profile_search_report_id"; + public static final String CALLABLE_PROFILE_SEARCH_REPORT_ID = "callable_profile_search_report_id"; + public static final String CLUSTERED = "clustered"; + + public static final String USER_ATTRIBUTE_NAME = "user_attribute_name"; + public static final String ROLES_ATTRIBUTE_NAME = "roles_attribute_name"; + public static final String ROLE_FUNCTIONS_ATTRIBUTE_NAME = "role_functions_attribute_name"; + public static final String CLIENT_DEVICE_ATTRIBUTE_NAME = "client_device_attribute_name"; + public static final String CLIENT_DEVICE_EMULATION = "client_device_emulation"; + public static final String CLIENT_DEVICE_TYPE_TO_EMULATE = "client_device_type_to_emulate"; + // File generation - Document + public static final String TEMPLATES_PATH = "templates_path"; + public static final String DOCUMENT_XML_ENCODING = "document_xml_encoding"; + + // Transaction + public static final String ROUTING_DATASOURCE_KEY = "routing_datasource_key"; + + // Document Library keys + public static final String DOCLIB_ADMIN_ROLE_ID = "doclib_admin_role_id"; + public static final String DOCLIB_USER_ROLE_ID = "doclib_user_role_id"; + + public static final String SYSTEM_PROPERTIES_FILENAME = "system.properties"; + public static final String FUSION_PROPERTIES_FILENAME = "fusion.properties"; + public static final String SUCCESS_TASKS_PROPERTIES_FILENAME = "success_tasks.properties"; + + // login methods + public static final String LOGIN_METHOD_CSP = "login_method_csp"; + public static final String LOGIN_METHOD_WEB_JUNCTION = "login_method_web_junction"; + public static final String LOGIN_METHOD_BACKDOOR = "login_method_backdoor"; + public static final String LOGIN_METHOD_ATTRIBUTE_NAME = "login_method_attribute_name"; + + // login error message keys + public static final String MESSAGE_KEY_LOGIN_ERROR_COOKIE_EMPTY = "login.error.hrid.empty"; + public static final String MESSAGE_KEY_LOGIN_ERROR_HEADER_EMPTY = "login.error.header.empty"; + public static final String MESSAGE_KEY_LOGIN_ERROR_USER_INACTIVE = "login.error.user.inactive"; + public static final String MESSAGE_KEY_LOGIN_ERROR_USER_NOT_FOUND = "login.error.hrid.not-found"; + public static final String MESSAGE_KEY_LOGIN_ERROR_APPLICATION_LOCKED = "login.error.application.locked"; + public static final String MESSAGE_KEY_AUTOLOGIN_NONE = "webphone.autoimport.nouser"; + public static final String MESSAGE_KEY_AUTOLOGIN_MULTIPLE = "webphone.autoimport.multiple"; + + // Application Mobile capability + public static final String MOBILE_ENABLE = "mobile_enable"; + + public static final String DATABASE_TIME_ZONE = "db.time_zone"; + + public static final String AUTO_USER_IMPORT_ENABLE = "auto_user_import_enable"; + public static final String AUTO_USER_IMPORT_ROLE = "auto_user_import_role"; + + public static final String ITRACKER_EMAIL_SOURCE_ADDRESS = "itracker_email_source_address"; + public static final String ITRACKER_EMAIL_DISTRIBUTION = "itracker_email_distribution"; + public static final String ITRACKER_SYSTEM_USER = "itracker_system_user_id"; + + public static final String MAIL_SERVER_HOST = "mail_server_host"; + public static final String MAIL_SERVER_PORT = "mail_server_port"; + + // Routing Data Source keys + public static final String ROUTING_DATASOURCE_KEY_NON_XA = "NON-XA"; + public static final String ROUTING_DATASOURCE_KEY_XA = "XA"; + public static final String QUARTZ_JOB_ENABLED = "quartz_job_enable"; + public static final String WORKFLOW_EMAIL_SENDER = "workflow_email_sender"; + public static final String DROOLS_GUVNOR_HOME = "drools.guvnor.home"; + + // Hibernate Config + public static final String HB_DIALECT = "hb.dialect"; + public static final String HB_SHOW_SQL = "hb.show_sql"; + + // DataSource + public static final String DB_DRIVER = "db.driver"; + public static final String DB_CONNECTIONURL = "db.connectionURL"; + public static final String DB_USERNAME = "db.userName"; + public static final String DB_PASSWOR = "db.password"; + public static final String DB_MIN_POOL_SIZE = "db.min_pool_size"; + public static final String DB_MAX_POOL_SIZE = "db.max_pool_size"; + public static final String IDLE_CONNECTION_TEST_PERIOD = "hb.idle_connection_test_period"; + + public static final String MYLOGINS_FEED_CRON = "mylogins_feed_cron"; + public static final String SESSIONTIMEOUT_FEED_CRON = "sessiontimeout_feed_cron"; + public static final String LOG_CRON = "log_cron"; + + public static final String DB_ENCRYPT_FLAG = "db.encrypt_flag"; + + // Decryption Key + public static final String Decryption_Key = "decryption_key"; + + // Logging/Audit Fields + public static final String MDC_APPNAME = "AppName"; + public static final String MDC_REST_PATH = "RestPath"; + public static final String MDC_REST_METHOD = "RestMethod"; + public static final String INSTANCE_UUID = "instance_uuid"; + public static final String MDC_CLASS_NAME = "ClassName"; + public static final String MDC_LOGIN_ID = "LoginId"; + public static final String MDC_TIMER = "Timer"; + public static final String SDK_NAME = "ECOMP_SDK"; + public static final String ECOMP_REQUEST_ID = "X-ECOMP-RequestID"; + public static final String PARTNER_NAME = "PartnerName"; + public static final String FULL_URL = "Full-URL"; + public static final String AUDITLOG_BEGIN_TIMESTAMP = "AuditLogBeginTimestamp"; + public static final String AUDITLOG_END_TIMESTAMP = "AuditLogEndTimestamp"; + public static final String METRICSLOG_BEGIN_TIMESTAMP = "MetricsLogBeginTimestamp"; + public static final String METRICSLOG_END_TIMESTAMP = "MetricsLogEndTimestamp"; + public static final String CLIENT_IP_ADDRESS = "ClientIPAddress"; + public static final String STATUS_CODE = "StatusCode"; + public static final String RESPONSE_CODE = "ResponseCode"; + // Component or sub component name + public static final String TARGET_ENTITY = "TargetEntity"; + // API or operation name + public static final String TARGET_SERVICE_NAME = "TargetServiceName"; + + // Logging Compliance + public static final String DOUBLE_WHITESPACE_SEPARATOR = " "; + public static final String SINGLE_WHITESPACE_SEPARATOR = " "; + public static final String SINGLE_QUOTE = "'"; + public static final String NA = "N/A"; + public static final String UNKNOWN = "Unknown"; + public static final String SECURITY_LOG_TEMPLATE = "Protocol:{0} Security-Event-Type:{1} Login-ID:{2} {3}"; + public static final String ECOMP_PORTAL_BE = "ECOMP_PORTAL_BE"; + public static final String PROTOCOL = "PROTOCOL"; + public static final String SECURIRY_EVENT_TYPE = "SECURIRY_EVENT_TYPE"; + public static final String LOGIN_ID = "LOGIN_ID"; + public static final String ACCESSING_CLIENT = "ACCESSING_CLIENT"; + public static final String RESULT_STR = "RESULT"; + public static final String ECOMP_PORTAL_FE = "ECOMP_PORTAL_FE"; + public static final String ADDITIONAL_INFO = "ADDITIONAL_INFO"; + public static final String INTERFACE_NAME = "INTERFACE_NAME"; + public static final String USERAGENT_NAME = "user-agent"; + + // Protocols + public static final String HTTP = "HTTP"; + public static final String HTTPS = "HTTPS"; + public static final String SSO_VALUE = "sso"; + + public enum RESULT_ENUM { + SUCCESS, FAILURE + } + + public enum SecurityEventTypeEnum { + FE_LOGIN_ATTEMPT, FE_LOGOUT, SSO_LOGIN_ATTEMPT_PHASE_1, SSO_LOGIN_ATTEMPT_PHASE_2, SSO_LOGOUT, LDAP_PHONEBOOK_USER_SEARCH, INCOMING_REST_MESSAGE, OUTGOING_REST_MESSAGE, REST_AUTHORIZATION_CREDENTIALS_MODIFIED, ECOMP_PORTAL_USER_MODIFIED, ECOMP_PORTAL_USER_ADDED, ECOMP_PORTAL_USER_REMOVED, ECOMP_PORTAL_WIDGET, INCOMING_UEB_MESSAGE, ECOMP_PORTAL_HEALTHCHECK + } + + // Menu + public static final String CONTACT_US_LINK = "contact_us_link"; + + // Left Menu + public static final String LEFT_MENU_PARENT = "parentList"; + public static final String LEFT_MENU_CHILDREND = "childItemList"; +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/util/UsageUtils.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/util/UsageUtils.java new file mode 100644 index 00000000..a8cc7fd7 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/util/UsageUtils.java @@ -0,0 +1,92 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.util; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; + +import javax.servlet.http.HttpSession; + +import org.openecomp.portalsdk.core.command.UserRowBean; +import org.openecomp.portalsdk.core.domain.User; + +public class UsageUtils { + @SuppressWarnings("rawtypes") + public static ArrayList<UserRowBean> getActiveUsers(HashMap activeUsers) { + ArrayList<UserRowBean> rows = new ArrayList<UserRowBean>(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + + for(Iterator i = activeUsers.keySet().iterator(); i.hasNext(); ){ + String sessionId = (String)i.next(); + HttpSession session = (HttpSession)activeUsers.get(sessionId); + User userBean = (User)session.getAttribute("user"); + // + // Not all sessions will be valid logins + // Skip those ones + // + if(null == userBean) + continue; + + UserRowBean userRow = new UserRowBean(); + userRow.setFirstName(userBean.getFirstName()); + userRow.setLastName(userBean.getLastName()); + userRow.setEmail(userBean.getEmail()); + userRow.setId(userBean.getId()); + userRow.setSessionId(sessionId); + userRow.setLoginTime(sdf.format(new Date(session.getCreationTime()))); + userRow.setLastLoginTime(sdf.format(userBean.getLastLoginDate())); + + // + // Calculate the last time and time remaining for these sessions. + // + int sessionLength = session.getMaxInactiveInterval(); + long now = new java.util.Date().getTime(); + long lastAccessed = (now - session.getLastAccessedTime()) / 1000; + long lengthInactive = (now - session.getLastAccessedTime()); + long minutesRemaining = sessionLength - (lengthInactive / 1000); + + userRow.setLastAccess((lastAccessed / 60) + ":" + String.format("%02d", (lastAccessed % 60))); + userRow.setRemaining((minutesRemaining / 60) + ":" + String.format("%02d", (minutesRemaining % 60))); + + rows.add(userRow); + } + + return rows; + } + + @SuppressWarnings("rawtypes") + public static ArrayList<UserRowBean> getActiveUsersAfterDelete(HashMap activeUsers, final java.lang.Object data) { + return getActiveUsers(deleteSession(activeUsers,data)); + + } + + @SuppressWarnings("rawtypes") + private static HashMap deleteSession(HashMap activeUsers, Object data) { + String sessionId = ((UserRowBean)data).getSessionId(); + HttpSession session = (HttpSession)activeUsers.get(sessionId); + session.invalidate(); + activeUsers.remove(sessionId); + + return activeUsers; + } +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/util/YamlUtils.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/util/YamlUtils.java new file mode 100644 index 00000000..da69b729 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/util/YamlUtils.java @@ -0,0 +1,72 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.util; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.util.Map; + +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.representer.Representer; + +public class YamlUtils { + + static Yaml yaml; + + static { + + Representer representer = new Representer(); + //representer.addClassTag(Domain.class, Tag.MAP); + + + yaml = new Yaml(representer); + + } + + public static void writeYamlFile(String filePath, String fileName, + Map<String, Object> model) throws IOException { + FileWriter writer = new FileWriter(filePath + File.separator + fileName); + yaml.dump(model, writer); + writer.close(); + } + + public static String returnYaml( + Map<String, Object> model) throws IOException { + + return yaml.dump(model); + + } + + @SuppressWarnings("unchecked") + public static Map<String, Object> readYamlFile( + String filePath, String fileName) throws FileNotFoundException, + IOException { + FileReader reader = new FileReader(filePath + File.separator + fileName); + + Map<String,Object> callFlowBs = (Map<String,Object>)yaml.load(reader); + reader.close(); + return callFlowBs; + } + + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/web/socket/PeerBroadcastSocket.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/web/socket/PeerBroadcastSocket.java new file mode 100644 index 00000000..ddf08c8f --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/web/socket/PeerBroadcastSocket.java @@ -0,0 +1,104 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.web.socket; + +import java.io.IOException; +import java.util.Hashtable; +import java.util.Map; + +import javax.websocket.OnClose; +import javax.websocket.OnMessage; +import javax.websocket.OnOpen; +import javax.websocket.Session; +import javax.websocket.server.ServerEndpoint; + +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; + +import com.fasterxml.jackson.databind.ObjectMapper; + +@ServerEndpoint("/contact") +public class PeerBroadcastSocket { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PeerBroadcastSocket.class); + + public static Map<String, Object> channelMap = new Hashtable<String, Object>(); + public Map<String, String> sessionMap = new Hashtable<String, String>(); + ObjectMapper mapper = new ObjectMapper(); + + @OnMessage + public void message(String message, Session session) { + try { + // JSONObject jsonObject = new JSONObject(message); + @SuppressWarnings("unchecked") + Map<String, Object> jsonObject = mapper.readValue(message, Map.class); + try { + Object from = jsonObject.get("from"); + if (from != null) { + channelMap.put(from.toString(), session); + sessionMap.put(session.getId(), from.toString()); + } + } catch (Exception je) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to read value" + je.getMessage()); + } + + try { + Object to = jsonObject.get("to"); + if (to == null) + return; + Object toSessionObj = channelMap.get(to); + if (toSessionObj != null) { + Session toSession = null; + toSession = (Session) toSessionObj; + toSession.getBasicRemote().sendText(message); + } + + } catch (Exception ex) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to send text" + ex.getMessage()); + } + + } catch (Exception ex) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed" + ex.getMessage()); + } + + } + + @OnOpen + public void open(Session session) { + logger.info(EELFLoggerDelegate.debugLogger, "Channel opened"); + } + + @OnClose + public void close(Session session) { + String channel = sessionMap.get(session.getId()); + if (channel != null) { + Object sessObj = channelMap.get(channel); + if (sessObj != null) { + try { + ((Session) sessObj).close(); + } catch (IOException e) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to close" + e.getMessage()); + } + } + channelMap.remove(channel); + } + logger.info(EELFLoggerDelegate.debugLogger, "Channel closed"); + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/web/socket/WebRTCSocket.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/web/socket/WebRTCSocket.java new file mode 100644 index 00000000..810cba5c --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/web/socket/WebRTCSocket.java @@ -0,0 +1,143 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.web.socket; + +import java.util.Hashtable; +import java.util.Map; + +import javax.websocket.OnClose; +import javax.websocket.OnMessage; +import javax.websocket.OnOpen; +import javax.websocket.Session; +import javax.websocket.server.ServerEndpoint; + +import com.fasterxml.jackson.databind.ObjectMapper; + +@ServerEndpoint("/webrtc") +public class WebRTCSocket { + + + public static Map<String,Hashtable<String,Object[]>> channelMap = new Hashtable<String,Hashtable<String,Object[]>>(); + public Map<String,String> sessionMap = new Hashtable<String,String>(); + ObjectMapper mapper = new ObjectMapper(); + + + @OnMessage + public void message(String message, Session session) { + try { + //JSONObject jsonObject = new JSONObject(message); + @SuppressWarnings("unchecked") + Map<String,Object> jsonObject = mapper.readValue(message, Map.class); + try { + Object isOpen = jsonObject.get("open"); + if(isOpen != null && (Boolean)isOpen == true) { + String channel = (String) jsonObject.get("channel"); + Object value = channelMap.get(channel); + Hashtable<String,Object[]> sourceDestMap = null; + if(value == null) + sourceDestMap = new Hashtable<String,Object[]>(); + else + sourceDestMap = (Hashtable<String,Object[]>) value; + + sourceDestMap.put(session.getId(), new Object[]{session}); + channelMap.put(channel, sourceDestMap); + sessionMap.put(session.getId(), channel); + + + } + } + catch (Exception je) { + je.printStackTrace(); + } + + try{ + + Object dataObj = jsonObject.get("data"); + if(dataObj == null) + return; + Map<String,Object> dataMapObj = ( Map<String,Object>)dataObj; + //Object thisUserId = dataMapObj.get("userid"); + String channel = null; + try{ + Object channelObj = dataMapObj.get("sessionid"); + if(channelObj != null) + channel = (String) channelObj; + else + channel = (String) jsonObject.get("channel"); + } + catch(Exception json) { + json.printStackTrace(); + } + + /* + JSONObject dataMapObj = (JSONObject)dataObj; + Object thisUserId = dataMapObj.get("userid"); + String channel = (String) dataMapObj.get("sessionid"); + Hashtable<String,Object> sourceDestMap = sessionMap.get(channel); + + if(thisUserId != null && sourceDestMap.get((String)thisUserId) == null) { + sourceDestMap.put((String)thisUserId, new Object[] {message, session}); + } + + for(String userId : sourceDestMap.keySet()){ + if(!userId.equals(thisUserId)) { + Session otherSession = (Session) ((Object[])sourceDestMap.get(userId))[1]; + otherSession.getBasicRemote().sendText(message); + } + } + */ + + Hashtable<String,Object[]> sourceDestMap = channelMap.get(channel); + if(sourceDestMap != null) + for(String id : sourceDestMap.keySet()){ + if(!id.equals(session.getId())) { + Session otherSession = (Session) ((Object[])sourceDestMap.get(id))[0]; + if(otherSession.isOpen()) + otherSession.getBasicRemote().sendText(mapper.writeValueAsString(dataObj)); + } + + } + } + catch (Exception je) { + je.printStackTrace(); + } + + } + catch (Exception je) { + je.printStackTrace(); + } + //System.out.println("Message received:" + message); + } + + @OnOpen + public void open(Session session) { + // System.out.println("Channel opened"); + } + + @OnClose + public void close(Session session) { + String channel = sessionMap.get(session.getId()); + if (channel != null) { + channelMap.remove(channel); + } + // System.out.println("Channel closed"); + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/web/support/AppUtils.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/web/support/AppUtils.java new file mode 100644 index 00000000..295cff42 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/web/support/AppUtils.java @@ -0,0 +1,213 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.web.support; + +import java.io.File; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.Date; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Vector; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import javax.sql.DataSource; + +import org.hibernate.Session; +import org.openecomp.portalsdk.core.exception.SessionExpiredException; +import org.openecomp.portalsdk.core.objectcache.AbstractCacheManager; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.FileSystemResource; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + + +public class AppUtils { + + + + private static DataAccessService dataAccessService; + + private static AbstractCacheManager cacheManager; + + private static boolean applicationLocked; + + private static Hashtable feedback = new Hashtable(); + + private static DataSource datasource; + + public static DataSource getDatasource() { + return datasource; + } + + @Autowired + public void setDatasource(DataSource datasource) { + AppUtils.datasource = datasource; + } + + public AppUtils() { + } + + public static HttpSession getSession(HttpServletRequest request) { + HttpSession session = null; + if (request != null) { + session = request.getSession(false); + if (session == null) { + throw new SessionExpiredException(); + } + } else { + throw new SessionExpiredException(); + } + return session; + } + + public static List getLookupList(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy) { + return getLookupList(dbTable, dbValueCol, dbLabelCol, dbFilter, dbOrderBy, null); + } // getLookupList + + public static List getLookupList(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy, Session session) { + String cacheKey = dbTable + "|" + dbValueCol + "|" + dbLabelCol + "|" + dbFilter + "|" + dbOrderBy; + List list = getLookupListFromCache(cacheKey); + if (list == null) { + list = getDataAccessService().getLookupList(dbTable, dbValueCol, dbLabelCol, dbFilter, dbOrderBy, null); + if (list != null) { + addLookupListToCache(cacheKey, list); + } + } // if + return list; + } // getLookupList + + private static List getLookupListFromCache(String key) { + return (List)getObjectFromCache(key); + } // getLookupListFromCache + + public static Object getObjectFromCache(String key) { + if (isCacheManagerAvailable()) { + return getCacheManager().getObject(key); + } else { + return null; + } + } // getObjectFromCache + + private static void addLookupListToCache(String key, List list) { + addObjectToCache(key, list); + } // addLookupListToCache + + public static void addObjectToCache(String key, Object o) { + if (isCacheManagerAvailable()) { + getCacheManager().putObject(key, o); + } + } // addObjectToCache + + @Autowired + public void setCacheManager(AbstractCacheManager cacheManager) { + this.cacheManager = cacheManager; + } + + public static AbstractCacheManager getCacheManager() { + return cacheManager; + } + + public static boolean isCacheManagerAvailable() { + return (getCacheManager() != null); + } + + public void setFeedback(Hashtable feedback) { + this.feedback = feedback; + } + + public static boolean isApplicationLocked() { + return applicationLocked; + } + + public static DataAccessService getDataAccessService() { + return dataAccessService; + } + + @Autowired + public void setDataAccessService(DataAccessService dataAccessService) { + this.dataAccessService = dataAccessService; + } + + public static void setApplicationLocked(boolean locked) { + applicationLocked = locked; + } + + public static String getLookupValueByLabel(String label, String dbTable, String dbValueCol, String dbLabelCol) { + if (label == null || label.equals("")) { + return ""; + } + + List<org.openecomp.portalsdk.core.domain.Lookup> lstResult = getLookupListNoCache(dbTable, dbValueCol, dbLabelCol, dbLabelCol + "='" + label.replaceAll("'", "''") + "'", ""); + if (lstResult == null) { + return ""; + } + if (lstResult.size() > 0) { + return ((org.openecomp.portalsdk.core.domain.Lookup)lstResult.toArray()[0]).getValue(); + } else { + return ""; + } + } + + public static String getLookupValueByLabel(String label, List lookupList) { + Iterator i = null; + + if (label == null || label.equalsIgnoreCase("")) { + return ""; + } + + if (lookupList == null || lookupList.size() == 0) { + return ""; + } + + i = lookupList.iterator(); + while (i.hasNext()) { + org.openecomp.portalsdk.core.domain.Lookup lookup = (org.openecomp.portalsdk.core.domain.Lookup)i.next(); + + if (lookup.getLabel().equals(label)) { + return lookup.getValue(); + } + } + + return ""; +} + public static List getLookupListNoCache(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy) { + return getLookupListNoCache(dbTable, dbValueCol, dbLabelCol, dbFilter, dbOrderBy, null); + } // getLookupListNoCache + + + public static List getLookupListNoCache(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy, Session session) { + return getDataAccessService().getLookupList(dbTable, dbValueCol, dbLabelCol, dbFilter, dbOrderBy, null); + } // getLookupListNoCache + + + +} // AppUtils diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/web/support/ControllerProperties.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/web/support/ControllerProperties.java new file mode 100644 index 00000000..1d09eba0 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/web/support/ControllerProperties.java @@ -0,0 +1,41 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.web.support; + +public interface ControllerProperties { + + static final String TASK_GET = "get"; + static final String TASK_DELETE = "delete"; + static final String TASK_SAVE = "save"; + static final String TASK_PROCESS = "process"; + static final String TASK_TOGGLE_ACTIVE = "toggleActive"; + static final String TASK_DOWNLOAD = "download"; + static final String TASK_POPUP = "popup"; + static final String TASK_LOOKUP = "lookup"; + static final String TASK_ADD_ROW = "addRow"; + static final String TASK_APPROVE = "approve"; + static final String TASK_REJECT = "reject"; + static final String TASK_RESET = "reset"; + static final String TASK_ASSIGN = "assign"; + static final String TASK_CUT = "cut"; + static final String TASK_COPY = "copy"; + static final String TASK_PASTE = "paste"; + static final String TASK_SELECT = "select"; +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/web/support/FeedbackMessage.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/web/support/FeedbackMessage.java new file mode 100644 index 00000000..d8993b03 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/web/support/FeedbackMessage.java @@ -0,0 +1,80 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.web.support; + +public class FeedbackMessage { + + private String message; + private int messageType; + private boolean keyed; + + public static final int MESSAGE_TYPE_ERROR = 10; + public static final int MESSAGE_TYPE_WARNING = 20; + public static final int MESSAGE_TYPE_INFO = 30; + public static final int MESSAGE_TYPE_SUCCESS = 40; + + public static final String DEFAULT_MESSAGE_SUCCESS = "Update successful."; + public static final String DEFAULT_MESSAGE_ERROR = "An error occurred while processing the request: "; + + public static final String DEFAULT_MESSAGE_SYSTEM_ADMINISTRATOR = "If the problem persists, please contact your Administrator."; + + public FeedbackMessage() { + } + + public FeedbackMessage(String message) { + this(message, MESSAGE_TYPE_ERROR); + } + + public FeedbackMessage(String message, int messageType) { + this(message, messageType, false); + } + + public FeedbackMessage(String message, int messageType, boolean keyed) { + this.message = message; + this.messageType = messageType; + this.keyed = keyed; + } + + public String getMessage() { + return message; + } + + public int getMessageType() { + return messageType; + } + + public boolean isKeyed() { + return keyed; + } + + public void setMessage(String message) { + this.message = message; + } + + public void setMessageType(int messageType) { + this.messageType = messageType; + } + + public void setKeyed(boolean keyed) { + this.keyed = keyed; + } + + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/web/support/JsonMessage.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/web/support/JsonMessage.java new file mode 100644 index 00000000..5566bf90 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/web/support/JsonMessage.java @@ -0,0 +1,118 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.web.support; + +import java.io.PrintWriter; +import java.io.StringWriter; + +import org.openecomp.portalsdk.core.onboarding.crossapi.PortalAPIResponse; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class JsonMessage { + + private String data; + private String data2; + private String data3; + public JsonMessage(String data) { + super(); + this.data = data; + } + public JsonMessage(String data,String data2) { + super(); + this.data = data; + this.data2 = data2; + } + + public JsonMessage(String data,String data2,String data3) { + super(); + this.data = data; + this.data2 = data2; + this.data3 = data3; + } + + public String getData() { + return data; + } + + public void setData(String data) { + this.data = data; + } + public String getData2() { + return data2; + } + public void setData2(String data2) { + this.data2 = data2; + } + public String getData3() { + return data3; + } + public void setData3(String data3) { + this.data3 = data3; + } + + + /** + * 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> + */ + public static String buildJsonResponse(boolean success, String msg) { + PortalAPIResponse response = new PortalAPIResponse(success, msg); + String json = null; + try { + json = new ObjectMapper().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> + */ + public static String buildJsonResponse(Throwable t) { + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + t.printStackTrace(pw); + return buildJsonResponse(false, sw.toString()); + } + + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/web/support/MessagesList.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/web/support/MessagesList.java new file mode 100644 index 00000000..0cf628aa --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/web/support/MessagesList.java @@ -0,0 +1,92 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.web.support; + +import java.util.*; + +public class MessagesList { + + private boolean successMessageDisplayed = true; + private boolean includeCauseInCustomExceptions = false; + + private List successMessages; + private List exceptionMessages; + + public MessagesList() { + setExceptionMessages(new ArrayList()); + setSuccessMessages(new ArrayList()); + } + + public MessagesList(boolean displaySuccess) { + this(); + setSuccessMessageDisplayed(displaySuccess); + } + + public List getExceptionMessages() { + return exceptionMessages; + } + + public List getSuccessMessages() { + return successMessages; + } + + public boolean isSuccessMessageDisplayed() { + return successMessageDisplayed; + } + + public boolean isIncludeCauseInCustomExceptions() { + return includeCauseInCustomExceptions; + } + + + public void setExceptionMessages(List exceptionMessages) { + this.exceptionMessages = exceptionMessages; + } + + public void setSuccessMessages(List successMessages) { + this.successMessages = successMessages; + } + + public void setSuccessMessageDisplayed(boolean successMessageDisplayed) { + this.successMessageDisplayed = successMessageDisplayed; + } + + public void setIncludeCauseInCustomExceptions(boolean includeCauseInCustomExceptions) { + this.includeCauseInCustomExceptions = includeCauseInCustomExceptions; + } + + + public void addSuccessMessage(FeedbackMessage message) { + getSuccessMessages().add(message); + } + + public void addExceptionMessage(FeedbackMessage message) { + getExceptionMessages().add(message); + } + + public boolean hasExceptionMessages() { + return!getExceptionMessages().isEmpty(); + } + + public boolean hasSuccessMessages() { + return!getSuccessMessages().isEmpty(); + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/web/support/UserUtils.java b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/web/support/UserUtils.java new file mode 100644 index 00000000..37eaccad --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/main/java/org/openecomp/portalsdk/core/web/support/UserUtils.java @@ -0,0 +1,423 @@ +/*- + * ================================================================================ + * ECOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.web.support; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import java.util.UUID; + +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import org.openecomp.portalsdk.core.domain.Role; +import org.openecomp.portalsdk.core.domain.RoleFunction; +import org.openecomp.portalsdk.core.domain.UrlsAccessible; +import org.openecomp.portalsdk.core.domain.User; +import org.openecomp.portalsdk.core.exception.SessionExpiredException; +import org.openecomp.portalsdk.core.lm.FusionLicenseManager; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.menu.MenuBuilder; +import org.openecomp.portalsdk.core.restful.domain.EcompRole; +import org.openecomp.portalsdk.core.restful.domain.EcompUser; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; + +@SuppressWarnings("rawtypes") +public class UserUtils { + + static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserUtils.class); + + public static final String KEY_USER_ROLES_CACHE = "userRoles"; + + private static DataAccessService dataAccessService; + + public static void setUserSession(HttpServletRequest request, User user, Set applicationMenuData, + Set businessDirectMenuData, String loginMethod) { + HttpSession session = request.getSession(true); + + UserUtils.clearUserSession(request); // let's clear the current user + // session to avoid any + // conflicts during the set + + session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user); + session.setAttribute(SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_ATTRIBUTE_NAME), loginMethod); + + getRoleFunctions(request); + + // truncate the role (and therefore the role function) data to save + // memory in the session + user.setRoles(null); + session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_NAME), user.getFullName()); + session.setAttribute(SystemProperties.FIRST_NAME, user.getFirstName()); + session.setAttribute(SystemProperties.LAST_NAME, user.getLastName()); + ServletContext context = session.getServletContext(); + int licenseVarificationFlag = 3; + try { + licenseVarificationFlag = (Integer) context.getAttribute("licenseVerification"); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.debugLogger, "Error while get license varification " + e.getMessage()); + } + String displayName = ""; + if (SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME) != null) + displayName = SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME); + switch (licenseVarificationFlag) { + case FusionLicenseManager.DEVELOPER_LICENSE: + session.setAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME), + displayName + " [Development Version]"); + break; + case FusionLicenseManager.EXPIRED_LICENSE: + session.setAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME), + displayName + " [LICENSE EXPIRED]"); + break; + case FusionLicenseManager.VALID_LICENSE: + session.setAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME), displayName); + break; + default: + session.setAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME), + displayName + " [INVALID LICENSE]"); + break; + } + + session.setAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME), + MenuBuilder.filterMenu(applicationMenuData, request)); + session.setAttribute(SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_ATTRIBUTE_NAME), + MenuBuilder.filterMenu(businessDirectMenuData, request)); + } + + public static void clearUserSession(HttpServletRequest request) { + HttpSession session = AppUtils.getSession(request); + + if (session == null) { + throw new SessionExpiredException(); + } + + // removes all stored attributes from the current user's session + session.removeAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME)); + session.removeAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME)); + session.removeAttribute(SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_ATTRIBUTE_NAME)); + session.removeAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME)); + session.removeAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME)); + session.removeAttribute(SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_ATTRIBUTE_NAME)); + } + + @SuppressWarnings("unchecked") + public static Set getRoleFunctions(HttpServletRequest request) { + HashSet roleFunctions = null; + + HttpSession session = request.getSession(); + roleFunctions = (HashSet) session + .getAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME)); + + if (roleFunctions == null) { + HashMap roles = getRoles(request); + roleFunctions = new HashSet(); + + Iterator i = roles.keySet().iterator(); + + while (i.hasNext()) { + Long roleKey = (Long) i.next(); + Role role = (Role) roles.get(roleKey); + + Iterator j = role.getRoleFunctions().iterator(); + + while (j.hasNext()) { + RoleFunction function = (RoleFunction) j.next(); + roleFunctions.add(function.getCode()); + } + } + + session.setAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME), + roleFunctions); + } + + return roleFunctions; + } + + public static HashMap getRoles(HttpServletRequest request) { + HashMap roles = null; + + // HttpSession session = request.getSession(); + HttpSession session = AppUtils.getSession(request); + roles = (HashMap) session.getAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME)); + + // if roles are not already cached, let's grab them from the user + // session + if (roles == null) { + User user = getUserSession(request); + + // get all user roles (including the tree of child roles) + roles = getAllUserRoles(user); + + session.setAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME), + getAllUserRoles(user)); + } + + return roles; + } + + public static User getUserSession(HttpServletRequest request) { + HttpSession session = AppUtils.getSession(request); + + if (session == null) { + throw new SessionExpiredException(); + } + + return (User) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME)); + } + + @SuppressWarnings("unchecked") + public static HashMap getAllUserRoles(User user) { + HashMap roles = new HashMap(); + Iterator i = user.getRoles().iterator(); + + while (i.hasNext()) { + Role role = (Role) i.next(); + + if (role.getActive()) { + roles.put(role.getId(), role); + + // let's take a recursive trip down the tree to add all child + // roles + addChildRoles(role, roles); + } + } + + return roles; + } + + @SuppressWarnings("unchecked") + private static void addChildRoles(Role role, HashMap roles) { + Set childRoles = role.getChildRoles(); + if (childRoles != null && childRoles.size() > 0) { + Iterator j = childRoles.iterator(); + while (j.hasNext()) { + Role childRole = (Role) j.next(); + if (childRole.getActive()) { + roles.put(childRole.getId(), childRole); + addChildRoles(childRole, roles); + } + } + } + + } + + /** + * Answers whether the specified URL is accessible. + * + * @param request + * @param currentUrl + * @return true if yes, false if no. + */ + public static boolean isUrlAccessible(HttpServletRequest request, String currentUrl) { + boolean isAccessible = false; + Map<String,String> params = new HashMap<>(); + params.put("current_url", currentUrl); + List list = getDataAccessService().executeNamedQuery("restrictedUrls", params, null); + // loop through the list of restricted URL's + if (list != null && list.size() > 0) { + for (int i = 0; i < list.size(); i++) { + /* + * Object[] restrictedUrl = (Object[])list.get(i); + * + * String url = (String)restrictedUrl[0]; String functionCd = + * (String)restrictedUrl[1]; + */ + UrlsAccessible urlFunctions = (UrlsAccessible) list.get(i); + // String url = (String) urlFunctions.getUrl(); + String functionCd = (String) urlFunctions.getFunctionCd(); + if (UserUtils.isAccessible(request, functionCd)) { + isAccessible = true; + } + } + return isAccessible; + } + return true; + } + + public static boolean hasRole(HttpServletRequest request, String roleKey) { + return getRoles(request).keySet().contains(new Long(roleKey)); + } + + public static boolean hasRole(User user, String roleKey) { + return getAllUserRoles(user).keySet().contains(new Long(roleKey)); + } + + public static boolean isAccessible(HttpServletRequest request, String functionKey) { + return getRoleFunctions(request).contains(functionKey); + } + + public static String getLoginMethod(HttpServletRequest request) { + HttpSession session = AppUtils.getSession(request); + + if (session == null) { + throw new SessionExpiredException(); + } + + return (String) session + .getAttribute(SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_ATTRIBUTE_NAME)); + } + + public static DataAccessService getDataAccessService() { + return dataAccessService; + } + + @Autowired + public void setDataAccessService(DataAccessService dataAccessService) { + UserUtils.dataAccessService = dataAccessService; + } + + public static int getUserId(HttpServletRequest request) { + return getUserIdAsLong(request).intValue(); + } + + public static Long getUserIdAsLong(HttpServletRequest request) { + Long userId = new Long(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID)); + + if (request != null) { + if (getUserSession(request) != null) { + userId = getUserSession(request).getId(); + } + } + return userId; + } + + + private static final Object stackTraceLock = new Object(); + /** + * Serializes a stack trace of the specified throwable and returns it as a string. + * + * TODO: why is synchronization required? + * + * @param t + * @return String version of stack trace + */ + public static String getStackTrace(Throwable t) { + synchronized (stackTraceLock) { + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + t.printStackTrace(pw); + return sw.toString(); + } + } + + /** + * Gets the full URL of the request by joining the request and any query string. + * + * @param request + * @return Full URL of the request including query parameters + */ + public static String getFullURL(HttpServletRequest request) { + if (request != null) { + StringBuffer requestURL = request.getRequestURL(); + String queryString = request.getQueryString(); + + if (queryString == null) { + return requestURL.toString(); + } else { + return requestURL.append('?').append(queryString).toString(); + } + } + return ""; + } + + /** + * Gets or generates a request ID by searching for header X-ECOMP-RequestID. + * If not found, generates a new random UUID. + * + * @param request + * @return Request ID for the specified request + */ + public static String getRequestId(HttpServletRequest request) { + Enumeration<String> headerNames = request.getHeaderNames(); + + String requestId = ""; + try { + while (headerNames.hasMoreElements()) { + String headerName = (String) headerNames.nextElement(); + if (logger.isTraceEnabled()) + logger.trace(EELFLoggerDelegate.debugLogger, + "getRequestId: header {} = {}", headerName, request.getHeader(headerName)); + if (headerName.equalsIgnoreCase(SystemProperties.ECOMP_REQUEST_ID)) { + requestId = request.getHeader(headerName); + break; + } + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.debugLogger, "getRequestId: failed to get headder", e); + } + + if (requestId.isEmpty()) + requestId = UUID.randomUUID().toString(); + logger.debug(EELFLoggerDelegate.debugLogger, "getRequestId: result is {}", requestId); + return requestId; + } + + /** + * Converts a Hibernate-mapped User object to a JSON-serializable EcompUser object. + * + * @param user + * @return EcompUser with a subset of fields. + */ + public static EcompUser convertToEcompUser(User user) { + EcompUser userJson = new EcompUser(); + userJson.setEmail(user.getEmail()); + userJson.setFirstName(user.getFirstName()); + userJson.setHrid(user.getHrid()); + userJson.setJobTitle(user.getJobTitle()); + userJson.setLastName(user.getLastName()); + userJson.setLoginId(user.getLoginId()); + userJson.setOrgManagerUserId(user.getOrgManagerUserId()); + userJson.setMiddleInitial(user.getMiddleInitial()); + userJson.setOrgCode(user.getOrgCode()); + userJson.setOrgId(user.getOrgId()); + userJson.setPhone(user.getPhone()); + userJson.setOrgUserId(user.getOrgUserId()); + Set<EcompRole> ecompRoles = new TreeSet<EcompRole>(); + for (Role role : user.getRoles()) { + ecompRoles.add(convertToEcompRole(role)); + } + userJson.setRoles(ecompRoles); + return userJson; + } + + /** + * Converts a Hibernate-mapped Role object to a JSON-serializable EcompRole object. + * + * @param role + * @return EcompRole with a subset of fields: ID and name + */ + public static EcompRole convertToEcompRole(Role role) { + EcompRole ecompRole = new EcompRole(); + ecompRole.setId(role.getId()); + ecompRole.setName(role.getName()); + return ecompRole; + } + +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/openecomp/fusion/core/MockApplicationContextTestSuite.java b/ecomp-sdk/epsdk-core/src/test/java/org/openecomp/fusion/core/MockApplicationContextTestSuite.java new file mode 100644 index 00000000..0867f2a7 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/openecomp/fusion/core/MockApplicationContextTestSuite.java @@ -0,0 +1,114 @@ +package org.openecomp.fusion.core; + +import java.io.IOException; + +import org.junit.Before; +import org.junit.runner.RunWith; +import org.openecomp.portalsdk.core.conf.AppConfig; +import org.openecomp.portalsdk.core.objectcache.AbstractCacheManager; +import org.openecomp.portalsdk.core.util.CacheManager; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.AnnotationConfigWebContextLoader; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; + +/** + * In order to write a unit test, 1. inherit this class - See SanityTest.java 2. + * place the "war" folder on your test class's classpath 3. run the test with + * the following VM argument; This is important because when starting the + * application from Container, the System Properties file + * (SystemProperties.java) can have the direct path but, when running from the + * Mock Junit container, the path should be prefixed with "classpath" to enable + * the mock container to search for the file in the classpath + * -Dcontainer.classpath="classpath:" + * + */ + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(loader = AnnotationConfigWebContextLoader.class, classes = { MockAppConfig.class }) +@ActiveProfiles(value = "test") +public class MockApplicationContextTestSuite { + + @Autowired + public WebApplicationContext wac; + + private MockMvc mockMvc; + + @Before + public void setup() { + if (mockMvc == null) { + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); + + } + } + + public Object getBean(String name) { + return this.wac.getBean(name); + } + + public MockMvc getMockMvc() { + return mockMvc; + } + + public void setMockMvc(MockMvc mockMvc) { + this.mockMvc = mockMvc; + } + + public WebApplicationContext getWebApplicationContext() { + return wac; + } + +} + +@Configuration +@ComponentScan(basePackages = "org.openecomp", excludeFilters = {}) +@Profile("test") +class MockAppConfig extends AppConfig { + + @Bean + public SystemProperties systemProperties() { + return new MockSystemProperties(); + } + + @Bean + public AbstractCacheManager cacheManager() { + return new CacheManager() { + + public void configure() throws IOException { + + } + }; + } + + protected String[] tileDefinitions() { + return new String[] { "classpath:/WEB-INF/fusion/defs/definitions.xml", + "classpath:/WEB-INF/defs/definitions.xml" }; + } + + @Override + public void addInterceptors(InterceptorRegistry registry) { + // registry.addInterceptor(new + // SessionTimeoutInterceptor()).excludePathPatterns(getExcludeUrlPathsForSessionTimeout()); + // registry.addInterceptor(resourceInterceptor()); + } + + public static class MockSystemProperties extends SystemProperties { + + public MockSystemProperties() { + } + + } + +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/openecomp/fusion/core/MockHibernateMappingLocations.java b/ecomp-sdk/epsdk-core/src/test/java/org/openecomp/fusion/core/MockHibernateMappingLocations.java new file mode 100644 index 00000000..fea7cdda --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/openecomp/fusion/core/MockHibernateMappingLocations.java @@ -0,0 +1,23 @@ +package org.openecomp.fusion.core; + +import org.openecomp.portalsdk.core.conf.HibernateMappingLocatable; +import org.springframework.context.annotation.Profile; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.stereotype.Component; + +@Component +@Profile("test") +public class MockHibernateMappingLocations implements HibernateMappingLocatable{ + + @Override + public Resource[] getMappingLocations() { + return new Resource[]{new ClassPathResource("WEB-INF/fusion/orm/Fusion.hbm.xml"), new ClassPathResource("WEB-INF/fusion/orm/Workflow.hbm.xml")}; + } + + @Override + public String[] getPackagesToScan() { + return new String[] { "org.openecomp" }; + } + +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/openecomp/portalsdk/MockApplicationContextTestSuite.java b/ecomp-sdk/epsdk-core/src/test/java/org/openecomp/portalsdk/MockApplicationContextTestSuite.java new file mode 100644 index 00000000..812d438a --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/openecomp/portalsdk/MockApplicationContextTestSuite.java @@ -0,0 +1,143 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk; + +import java.io.IOException; + +import org.junit.Before; +import org.junit.runner.RunWith; +import org.openecomp.portalsdk.core.conf.AppConfig; +import org.openecomp.portalsdk.core.objectcache.AbstractCacheManager; +import org.openecomp.portalsdk.core.util.CacheManager; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.AnnotationConfigWebContextLoader; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; + +/** + * + * + * + * In order to write a unit test, + * 1. inherit this class - See SanityTest.java + * 2. place the "war" folder on your test class's classpath + * 3. run the test with the following VM argument; This is important because when starting the application from Container, the System Properties file (SystemProperties.java) can have the direct path + * but, when running from the Mock Junit container, the path should be prefixed with "classpath" to enable the mock container to search for the file in the classpath + * -Dcontainer.classpath="classpath:" + * + */ + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(loader = AnnotationConfigWebContextLoader.class, classes = {MockAppConfig.class}) +@ActiveProfiles(value="test") +public class MockApplicationContextTestSuite { + + @Autowired + public WebApplicationContext wac; + + private MockMvc mockMvc; + + @Before + public void setup() { + if(mockMvc == null) { + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); + + } + } + + public Object getBean(String name) { + return this.wac.getBean(name); + } + + + public MockMvc getMockMvc() { + return mockMvc; + } + + public void setMockMvc(MockMvc mockMvc) { + this.mockMvc = mockMvc; + } + + public WebApplicationContext getWebApplicationContext() { + return wac; + } + + + + +} + + + @Configuration + @ComponentScan(basePackages = "org.openecomp", + excludeFilters = { } + ) + @Profile("test") + class MockAppConfig extends AppConfig { + + @Bean + public SystemProperties systemProperties(){ + return new MockSystemProperties(); + } + + @Bean + public AbstractCacheManager cacheManager() { + return new CacheManager() { + + public void configure() throws IOException { + + } + }; + } + + protected String[] tileDefinitions() { + return new String[] {"classpath:/WEB-INF/fusion/defs/definitions.xml", "classpath:/WEB-INF/defs/definitions.xml"}; + } + + @Override + public void addInterceptors(InterceptorRegistry registry) { + //registry.addInterceptor(new SessionTimeoutInterceptor()).excludePathPatterns(getExcludeUrlPathsForSessionTimeout()); + //registry.addInterceptor(resourceInterceptor()); + } + + public static class MockSystemProperties extends SystemProperties { + + public MockSystemProperties() { + } + + } + + } + + + + diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/openecomp/portalsdk/MockHibernateMappingLocations.java b/ecomp-sdk/epsdk-core/src/test/java/org/openecomp/portalsdk/MockHibernateMappingLocations.java new file mode 100644 index 00000000..a9fdebb4 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/openecomp/portalsdk/MockHibernateMappingLocations.java @@ -0,0 +1,42 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk; + +import org.openecomp.portalsdk.core.conf.HibernateMappingLocatable; +import org.springframework.context.annotation.Profile; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.stereotype.Component; + +@Component +@Profile("test") +public class MockHibernateMappingLocations implements HibernateMappingLocatable { + + public Resource[] getMappingLocations() { + return new Resource[] { new ClassPathResource("WEB-INF/fusion/orm/Fusion.hbm.xml"), + new ClassPathResource("WEB-INF/fusion/orm/Workflow.hbm.xml") }; + } + + @Override + public String[] getPackagesToScan() { + return new String[] { "org.openecomp" }; + } + +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/openecomp/portalsdk/controller/sessionmgt/PortalCommunicationTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/openecomp/portalsdk/controller/sessionmgt/PortalCommunicationTest.java new file mode 100644 index 00000000..6b87dbe4 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/openecomp/portalsdk/controller/sessionmgt/PortalCommunicationTest.java @@ -0,0 +1,75 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.controller.sessionmgt; +/*package org.openecomp.portalsdk.controller.sessionmgt; + +import org.junit.Assert; +import org.junit.Test; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.test.web.servlet.ResultActions; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import org.openecomp.portalsdk.MockApplicationContextTestSuite; +import org.openecomp.portalsdk.service.sessionmgt.CoreTimeoutHandler; + +public class PortalCommunicationTest extends MockApplicationContextTestSuite{ + + + @Test + public void testGetTimeoutSessions() throws Exception { + + MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/api/sessionTimeOuts"); + MockHttpSession httpSession = new MockHttpSession(this.wac.getServletContext(),"1234"); + CoreTimeoutHandler.sessionCreated("12", "1234", httpSession); + + ResultActions ra = this.getMockMvc().perform(requestBuilder); + + System.out.println(" %%%%%%%%%%%%%%%%%%%%%%%%% " + ra.andReturn().getResponse().getContentAsString()); + System.out.println(" %%%%%%%%%%%%%%%%%%%%%%%%% " + "{\"12\":{\"jSessionId\":\"1234\",\"sessionTimOutMilliSec\":"); + + Assert.assertTrue(ra.andReturn().getResponse().getContentAsString().startsWith("{\"12\":{\"jSessionId\":\"1234\",\"sessionTimOutMilliSec\":")); + + } + + @Test + public void testUpdateTimeoutSessions() throws Exception { + + // pre condition + MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/api/sessionTimeOuts"); + MockHttpSession httpSession = new MockHttpSession(this.wac.getServletContext(),"1234"); + CoreTimeoutHandler.sessionCreated("12", "1234", httpSession); + ResultActions ra = this.getMockMvc().perform(requestBuilder); + + String responseSessMapStr = ra.andReturn().getResponse().getContentAsString(); + + + // test + requestBuilder = MockMvcRequestBuilders.post("/api/updateSessionTimeOuts"); + requestBuilder.param("sessionMap", responseSessMapStr); + ra = this.getMockMvc().perform(requestBuilder); + + + } + + + +} +*/ |