diff options
author | Christopher Lott (cl778h) <clott@research.att.com> | 2017-09-07 08:52:41 -0400 |
---|---|---|
committer | Christopher Lott (cl778h) <clott@research.att.com> | 2017-09-07 08:54:52 -0400 |
commit | 8cd208ebaa33627daf05d8ffff7b28e53a7067d0 (patch) | |
tree | 0b07ec3c6305c46f34eae69d8fb6fa824aaae256 /ecomp-sdk/epsdk-core/src/main | |
parent | b52d4cebc430a083ec1e6881c4f01dfe709ac726 (diff) |
Adjust code for Sonar issues
Made non-functional updates to address static code analysis issues.
Update license header with simple double-quote characters.
Issue: PORTAL-72, PORTAL-90
Change-Id: Ic2c330daea07d721f0e6b350ebf03da97073f7ce
Signed-off-by: Christopher Lott (cl778h) <clott@research.att.com>
Diffstat (limited to 'ecomp-sdk/epsdk-core/src/main')
169 files changed, 6562 insertions, 7683 deletions
diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/FusionObject.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/FusionObject.java index d44fb7e6..17e20f54 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/FusionObject.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/FusionObject.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -47,16 +47,19 @@ package org.onap.portalsdk.core; * 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 { + /** + * Inner class provides static constants to any class that implements the + * interface. + */ public class Parameters { + + private Parameters() { + // Static content only + } + // HashMap parameters passed to the Service and Dao tiers public static final String PARAM_USERID = "userId"; public static final String PARAM_HTTP_REQUEST = "request"; @@ -67,46 +70,39 @@ public interface FusionObject { } /** - * <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 + * Inner class provides static utility functions to any class that implements + * the interface. */ public class Utilities { + + private Utilities() { + // Static content only + } + /** * 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. + * @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; + return s == null ? "" : s; } /** - * nvl - replaces a string value with a default value if null. + * nvl - replaces a string value with a default value if null or empty. * * @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. + * @return String - returns the original string value if not null nor empty. * Otherwise the default value is returned. */ public static String nvl(String s, String sDefault) { - return nvl(s).equals("") ? sDefault : s; + return "".equals(nvl(s)) ? sDefault : s; } /** @@ -118,10 +114,7 @@ public interface FusionObject { * 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; + return a == null || a.length() == 0 || a.equalsIgnoreCase("null"); } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/auth/LoginStrategy.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/auth/LoginStrategy.java index 7fe4f632..baebac2f 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/auth/LoginStrategy.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/auth/LoginStrategy.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,6 +37,7 @@ */ package org.onap.portalsdk.core.auth; +import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -71,65 +72,45 @@ public abstract class LoginStrategy { @Autowired private LoginService loginService; - + @Autowired - RoleService roleService; + private RoleService roleService; 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 { - + public ModelAndView doExternalLogin(HttpServletRequest request, HttpServletResponse response) throws IOException { + 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); - List<RoleFunction> roleFunctionList= roleService.getRoleFunctions(loginId); - - + (String) request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY), new HashMap()); + List<RoleFunction> roleFunctionList = roleService.getRoleFunctions(loginId); if (commandBean.getUser() == null) { String loginErrorMessage = (commandBean.getLoginErrorMessage() != null) ? commandBean.getLoginErrorMessage() : "login.error.external.invalid"; + Map<String, String> model = new HashMap<>(); 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), roleFunctionList); 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){ + + protected void invalidateExistingSession(HttpServletRequest request) { request.getSession().invalidate(); } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/command/LoginBean.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/command/LoginBean.java index 0f156bce..dc6806a8 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/command/LoginBean.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/command/LoginBean.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -44,163 +44,170 @@ import org.onap.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() { + 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; } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/command/PostDroolsBean.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/command/PostDroolsBean.java index 89052495..005ecd5e 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/command/PostDroolsBean.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/command/PostDroolsBean.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -42,28 +42,32 @@ import com.fasterxml.jackson.databind.annotation.JsonSerialize; @JsonSerialize public class PostDroolsBean { - private String droolsFile; - private String className; - private String selectedRules; - + 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/onap/portalsdk/core/command/PostSearchBean.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/command/PostSearchBean.java index 3b32364e..b18cfc93 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/command/PostSearchBean.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/command/PostSearchBean.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -47,271 +47,347 @@ 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() { + 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; + + public PostSearchBean() { + this(null); + } + + @SuppressWarnings("rawtypes") + public PostSearchBean(List items) { + super(items); + user = new User(); + userOrig = new User(); + setSortBy1(""); + setSortBy1Orig(""); + } + + 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; } @@ -367,27 +443,25 @@ public class PostSearchBean extends SearchBase { this.postFinancialLocCode = postFinancialLocCode; } + @Override public void resetSearch() { - super.resetSearch(); - setUser(new User()); - } // resetSearch - + super.resetSearch(); + setUser(new User()); + } + @Override 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 + 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.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()))); + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/command/UserRowBean.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/command/UserRowBean.java index 49854e6b..8c768102 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/command/UserRowBean.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/command/UserRowBean.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -41,63 +41,50 @@ import org.onap.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; - } - + private String sessionId; + private String lastAccess; + private String remaining; + private String loginTime; + private String lastLoginTime; + + public String getLastAccess() { + return this.lastAccess; + } - public String getRemaining(){ - return this.remaining; - } + public void setLastAccess(final String lastAccess) { + this.lastAccess = lastAccess; + } - - public void setRemaining(String remaining){ - this.remaining = remaining; - } + public String getRemaining() { + return this.remaining; + } + public void setRemaining(final String remaining) { + this.remaining = remaining; + } public String getSessionId() { return sessionId; } - - public void setSessionId(String sessionId) { + public void setSessionId(final String sessionId) { this.sessionId = sessionId; } - public String getLoginTime() { return loginTime; } - - public void setLoginTime(String loginTime) { + public void setLoginTime(final String loginTime) { this.loginTime = loginTime; } - public String getLastLoginTime() { - return LastLoginTime; + return lastLoginTime; } - - public void setLastLoginTime(String lastLoginTime) { - LastLoginTime = lastLoginTime; + public void setLastLoginTime(final String lastLoginTime) { + this.lastLoginTime = lastLoginTime; } }
\ No newline at end of file diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/command/support/SearchBase.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/command/support/SearchBase.java index c053d95b..dcd14b91 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/command/support/SearchBase.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/command/support/SearchBase.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,252 +37,240 @@ */ package org.onap.portalsdk.core.command.support; -import java.util.*; +import java.util.List; import org.onap.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"; + public static final String SORT_BY_MODIFIER_DESC = "D"; + public static final String SORT_BY_MODIFIER_ASC = "A"; + public static final String SORT_BY_MODIFIER_DESC_IMAGE_NAME = "sort_desc.gif"; + public static final String SORT_BY_MODIFIER_ASC_IMAGE_NAME = "sort_asc.gif"; + private String sortBy1 = null; + private String sortBy2 = null; + private String sortBy3 = null; - 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 sortBy1Orig = null; - private String sortBy2Orig = null; - private String sortBy3Orig = null; + private String sortByModifier1 = null; + private String sortByModifier2 = null; + private String sortByModifier3 = 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 sortByModifier1Orig = null; - private String sortByModifier2Orig = null; - private String sortByModifier3Orig = null; + private String accessType = "WRITE"; - private String accessType = "WRITE"; //null; + private String submitAction = ""; + private String masterId = ""; + private String detailId = ""; - private String submitAction = ""; - private String masterId = ""; - private String detailId = ""; + private String showResult = "Y"; - private String showResult = "Y"; + private SearchResult searchResult = null; - private SearchResult searchResult = null; - private boolean sortingUpdated; + @SuppressWarnings("rawtypes") + public SearchBase(List items) { + searchResult = (items == null) ? (new SearchResult()) : (new SearchResult(items)); + } // SearchBase - @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 getSortBy1() { - return sortBy1; - } + public String getSortBy3() { + return sortBy3; + } - public String getSortBy2() { - return sortBy2; - } + public String getSortBy1Orig() { + return sortBy1; + } - public String getSortBy3() { - return sortBy3; - } + public String getSortBy2Orig() { + return sortBy2; + } - public String getSortBy1Orig() { - return sortBy1; - } + public String getSortBy3Orig() { + return sortBy3; + } - public String getSortBy2Orig() { - return sortBy2; - } + public String getAccessType() { + return accessType; + } - public String getSortBy3Orig() { - return sortBy3; - } + public String getSubmitAction() { + return submitAction; + } - public String getAccessType() { - return accessType; - } + public String getMasterId() { + return masterId; + } - public String getSubmitAction() { - return submitAction; - } + public String getDetailId() { + return detailId; + } - public String getMasterId() { - return masterId; - } + public String getShowResult() { + return showResult; + } - public String getDetailId() { - return detailId; - } + public SearchResult getSearchResult() { + return searchResult; + } - public String getShowResult() { - return showResult; - } + public String getSortByModifier1() { + return sortByModifier1; + } - //public ArrayList getSortByList() { return sortByList; } + public String getSortByModifier1Orig() { + return sortByModifier1; + } - public SearchResult getSearchResult() { - return searchResult; - } + public String getSortByModifier2() { + return sortByModifier2; + } - public String getSortByModifier1() { - return sortByModifier1; - } + public String getSortByModifier2Orig() { + return sortByModifier2; + } - public String getSortByModifier1Orig() { - return sortByModifier1; - } + public String getSortByModifier3() { + return sortByModifier3; + } - public String getSortByModifier2() { - return sortByModifier2; - } + public String getSortByModifier3Orig() { + return sortByModifier3; + } - public String getSortByModifier2Orig() { - return sortByModifier2; - } + public int getPageNo() { + return (isCriteriaUpdated() || isSortingUpdated()) ? 0 : getSearchResult().getPageNo(); + } - public String getSortByModifier3() { - return sortByModifier3; - } + public int getPageSize() { + return getSearchResult().getPageSize(); + } - public String getSortByModifier3Orig() { - return sortByModifier3; - } + public int getDataSize() { + return getSearchResult().getDataSize(); + } - 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 + 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 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); + } + + 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))); + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/command/support/SearchResult.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/command/support/SearchResult.java index d1c1f315..35985c9f 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/command/support/SearchResult.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/command/support/SearchResult.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,49 +37,62 @@ */ package org.onap.portalsdk.core.command.support; -import java.util.*; +import java.util.ArrayList; +import java.util.List; @SuppressWarnings("rawtypes") public class SearchResult extends ArrayList implements java.io.Serializable { - /** - * - */ + private static final long serialVersionUID = -451947878984459011L; - private int pageNo = 0; + 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 - + private String accessType = null; - public SearchResult() {} + public SearchResult() { + super(); + } @SuppressWarnings("unchecked") public SearchResult(List items) { super(items); - } // SearchResult + } + + public int getPageNo() { + return pageNo; + } + + public int getPageSize() { + return pageSize; + } - /*public SearchResult(boolean empty) { - this(); - this.empty = empty; - } // SearchResult*/ + public int getDataSize() { + return dataSize; + } + public int getSize() { + return size(); + } // for Struts bean property access - public int getPageNo() { return pageNo; } - public int getPageSize() { return pageSize; } - public int getDataSize() { return dataSize; } + public String getAccessType() { + return accessType; + } - public int getSize() { return size(); } // for Struts bean property access - //public boolean isEmpty() { return empty; } + public void setPageNo(int pageNo) { + this.pageNo = pageNo; + } - public String getAccessType() { return accessType; } + public void setPageSize(int pageSize) { + this.dataSize = pageSize; + } - 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 setDataSize(int dataSize) { + this.dataSize = dataSize; + } - public void setAccessType(String accessType) { this.accessType = accessType; } + public void setAccessType(String accessType) { + this.accessType = accessType; + } -} // SearchResult +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/conf/AppConfig.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/conf/AppConfig.java index 26624359..60888b6d 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/conf/AppConfig.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/conf/AppConfig.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -51,17 +51,12 @@ import org.onap.portalsdk.core.menu.MenuBuilder; import org.onap.portalsdk.core.onboarding.util.CipherUtil; import org.onap.portalsdk.core.service.DataAccessService; import org.onap.portalsdk.core.service.DataAccessServiceImpl; -import org.onap.portalsdk.core.service.LocalAccessCondition; -import org.onap.portalsdk.core.service.RestApiRequestBuilder; import org.onap.portalsdk.core.util.SystemProperties; import org.onap.portalsdk.core.web.support.AppUtils; import org.onap.portalsdk.core.web.support.UserUtils; -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Conditional; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; @@ -83,7 +78,9 @@ public class AppConfig extends WebMvcConfigurerAdapter implements Configurable, private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppConfig.class); - private final List<String> tileDefinitions = new ArrayList<String>(); + private final List<String> tileDefinitions = new ArrayList<>(); + private String[] excludeUrlPathsForSessionTimeout = {}; + protected ApplicationContext appApplicationContext = null; public AppConfig() { @@ -94,12 +91,13 @@ public class AppConfig extends WebMvcConfigurerAdapter implements Configurable, /** * 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. + * {@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 + @Override public ViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setViewClass(JstlView.class); @@ -110,21 +108,20 @@ public class AppConfig extends WebMvcConfigurerAdapter implements Configurable, } /** - * Loads all the default logging fields into the global MDC context and - * marks each log file type that logging has been started. + * 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 + * 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("/"); } @@ -134,6 +131,7 @@ public class AppConfig extends WebMvcConfigurerAdapter implements Configurable, * @return New instance of {@link DataAccessService}. */ @Bean + @Override public DataAccessService dataAccessService() { return new DataAccessServiceImpl(); } @@ -157,15 +155,14 @@ public class AppConfig extends WebMvcConfigurerAdapter implements Configurable, 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() - { + public UserUtils userUtil() { return new UserUtils(); } @@ -213,7 +210,7 @@ public class AppConfig extends WebMvcConfigurerAdapter implements Configurable, String password = SystemProperties.getProperty(SystemProperties.DB_PASSWORD); if (SystemProperties.containsProperty(SystemProperties.DB_ENCRYPT_FLAG)) { String encryptFlag = SystemProperties.getProperty(SystemProperties.DB_ENCRYPT_FLAG); - if (encryptFlag != null && encryptFlag.equalsIgnoreCase("true")) { + if (encryptFlag != null && "true".equalsIgnoreCase(encryptFlag)) { password = CipherUtil.decrypt(password); } } @@ -227,14 +224,12 @@ public class AppConfig extends WebMvcConfigurerAdapter implements Configurable, dataSource.setTestConnectionOnCheckout(getConnectionOnCheckout()); dataSource.setPreferredTestQuery(getPreferredTestQuery()); } catch (Exception e) { + // Show details logger.error(EELFLoggerDelegate.errorLogger, - "Error initializing database, verify database settings in properties file: " - + UserUtils.getStackTrace(e), - AlarmSeverityEnum.CRITICAL); + "Error initializing database, verify database settings in properties file", e); + // Include alarm in log logger.error(EELFLoggerDelegate.debugLogger, - "Error initializing database, verify database settings in properties file: " - + UserUtils.getStackTrace(e), - AlarmSeverityEnum.CRITICAL); + "Error initializing database", AlarmSeverityEnum.CRITICAL); // Raise an alarm that opening a connection to the database failed. logger.logEcompError(AppMessagesEnum.BeDaoSystemError); throw e; @@ -243,9 +238,8 @@ public class AppConfig extends WebMvcConfigurerAdapter implements Configurable, } /** - * Gets the value of the property - * {@link SystemProperties#PREFERRED_TEST_QUERY}; defaults to "Select 1" if - * the property is not defined. + * Gets the value of the property {@link SystemProperties#PREFERRED_TEST_QUERY}; + * defaults to "Select 1" if the property is not defined. * * @return String value that is a SQL query */ @@ -266,8 +260,8 @@ public class AppConfig extends WebMvcConfigurerAdapter implements Configurable, /** * Gets the value of the property - * {@link SystemProperties#TEST_CONNECTION_ON_CHECKOUT}; defaults to true if - * the property is not defined. + * {@link SystemProperties#TEST_CONNECTION_ON_CHECKOUT}; defaults to true if the + * property is not defined. * * @return Boolean value */ @@ -288,8 +282,8 @@ public class AppConfig extends WebMvcConfigurerAdapter implements Configurable, } /* - * TODO: Check whether it is appropriate to extend the list of tile - * definitions at every invocation. + * 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"); @@ -304,8 +298,9 @@ public class AppConfig extends WebMvcConfigurerAdapter implements Configurable, * * @return An empty list. */ + @Override public List<String> addTileDefinitions() { - return new ArrayList<String>(); + return new ArrayList<>(); } /** @@ -324,9 +319,8 @@ public class AppConfig extends WebMvcConfigurerAdapter implements Configurable, } /** - * Adds new instances of the following interceptors to the specified - * interceptor registry: {@link SessionTimeoutInterceptor}, - * {@link ResourceInterceptor} + * Adds new instances of the following interceptors to the specified interceptor + * registry: {@link SessionTimeoutInterceptor}, {@link ResourceInterceptor} */ @Override public void addInterceptors(InterceptorRegistry registry) { @@ -345,8 +339,6 @@ public class AppConfig extends WebMvcConfigurerAdapter implements Configurable, return new ResourceInterceptor(); } - private String[] excludeUrlPathsForSessionTimeout = {}; - /** * Gets the array of Strings that are paths excluded for session timeout. * @@ -374,9 +366,8 @@ public class AppConfig extends WebMvcConfigurerAdapter implements Configurable, * (org.springframework.context.ApplicationContext) */ @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) { appApplicationContext = applicationContext; - } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/conf/AppInitializer.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/conf/AppInitializer.java index 0865b987..d2690c8d 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/conf/AppInitializer.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/conf/AppInitializer.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -46,34 +46,29 @@ import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatche public abstract class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppInitializer.class); - - private final String activeProfile = "src"; + + private static 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); + logger.error(EELFLoggerDelegate.errorLogger, "Unable to set the active profile" + e.getMessage(), + AlarmSeverityEnum.MAJOR); throw e; - } - return context; } @Override protected Class<?>[] getRootConfigClasses() { - return null; + return new Class<?>[0]; } @Override protected Class<?>[] getServletConfigClasses() { - return new Class[] { AppConfig.class }; } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/conf/Configurable.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/conf/Configurable.java index d890e609..647315d5 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/conf/Configurable.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/conf/Configurable.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -44,13 +44,13 @@ 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(); - + + 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/onap/portalsdk/core/conf/HibernateConfiguration.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/conf/HibernateConfiguration.java index 54512865..4c142a2c 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/conf/HibernateConfiguration.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/conf/HibernateConfiguration.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -48,7 +48,6 @@ import java.util.Properties; import javax.sql.DataSource; import org.hibernate.SessionFactory; -import org.onap.portalsdk.core.logging.format.AlarmSeverityEnum; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; import org.springframework.beans.factory.annotation.Autowired; @@ -83,7 +82,8 @@ public class HibernateConfiguration { } /** - * Builds a properties object with Hibernate properties in te system.properties file. + * Builds a properties object with Hibernate properties in te system.properties + * file. * * @return Properties object */ @@ -107,27 +107,18 @@ public class HibernateConfiguration { String 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"; 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); + ComboPooledDataSource pool = new ComboPooledDataSource(); + pool.setDriverClass(rs.getString("driver_class")); + pool.setJdbcUrl(rs.getString("connection_url")); + pool.setUser(rs.getString("user_name")); + pool.setPassword(rs.getString("password")); + pool.setMinPoolSize(rs.getInt("min_pool_size")); + pool.setMaxPoolSize(rs.getInt("max_pool_size")); + pool.setIdleConnectionTestPeriod(rs.getInt("idle_connection_test_period")); + dataSourceMap.put(rs.getString("schema_id"), pool); } - rs.close(); - rs = null; - stmt.close(); - stmt = null; - conn.close(); - conn = null; } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, - "Error initializing database, verify database settings in properties file: " + e.getMessage(), - AlarmSeverityEnum.CRITICAL); - e.printStackTrace(); + logger.error(EELFLoggerDelegate.errorLogger, "dataSourceMap failed", e); dataSourceMap = null; throw e; } finally { @@ -139,15 +130,9 @@ public class HibernateConfiguration { if (conn != null) conn.close(); } catch (SQLException se2) { - } - try { - if (conn != null) - conn.close(); - } catch (SQLException se) { - se.printStackTrace(); + logger.warn(EELFLoggerDelegate.errorLogger, "dataSourceMap failed to close", se2); } } - return dataSourceMap; } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/conf/HibernateMappingLocatable.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/conf/HibernateMappingLocatable.java index 743d4b76..11effb62 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/conf/HibernateMappingLocatable.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/conf/HibernateMappingLocatable.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -43,19 +43,20 @@ 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. + * @return Array of Resource objects (usually ClassPathResource that's a file) + * which contain Hibernate mapping information. */ - public Resource [] getMappingLocations(); + public Resource[] getMappingLocations(); /** * Gets package names. * - * @return Array of Java package names to scan for classes with Hibernate annotations. + * @return Array of Java package names to scan for classes with Hibernate + * annotations. */ - public String [] getPackagesToScan(); + public String[] getPackagesToScan(); } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/controller/FusionBaseController.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/controller/FusionBaseController.java index 48c145b3..980feaec 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/controller/FusionBaseController.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/controller/FusionBaseController.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -63,77 +63,70 @@ import org.springframework.web.bind.annotation.ModelAttribute; import com.fasterxml.jackson.databind.ObjectMapper; @Controller -public abstract class FusionBaseController implements SecurityInterface{ - +public abstract class FusionBaseController implements SecurityInterface { + private static final 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; - + private MenuBuilder menuBuilder; + @Autowired - private DataAccessService dataAccessService; - + private DataAccessService dataAccessService; + @Autowired - AppService appService; - + private 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>(); + Map<String, Object> model = new HashMap<>(); try { - try { - String appName = appService.getDefaultAppName(); - if (appName==null || appName=="") { - appName = SystemProperties.SDK_NAME; - } - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, appName); - } catch (Exception e) { - } - + String appName = appService.getDefaultAppName(); + if (appName == null || appName == "") + appName = SystemProperties.SDK_NAME; + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, appName); + 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)); + 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); + model = setMenu(menuResult); } } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, "getMenu failed", e); } return model; } - - public Map<String, Object> setMenu(Set<MenuData> menuResult) throws Exception{ + + 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()); - } + List<List<MenuData>> childItemList = new ArrayList<>(); + List<MenuData> parentList = new ArrayList<>(); + try { + fnMenuService.setMenuDataStructure(childItemList, parentList, menuResult); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "setMenu failed", e); + } + Map<String, Object> model = new HashMap<>(); model.put("childItemList", mapper.writeValueAsString(childItemList)); model.put("parentList", mapper.writeValueAsString(parentList)); return model; } - + public MenuBuilder getMenuBuilder() { return menuBuilder; } @@ -149,5 +142,14 @@ public abstract class FusionBaseController implements SecurityInterface{ public void setDataAccessService(DataAccessService dataAccessService) { this.dataAccessService = dataAccessService; } - + + @Override + public boolean isAccessible() { + return true; + } + + public boolean isRESTfulCall() { + return true; + } + } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/controller/RestrictedBaseController.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/controller/RestrictedBaseController.java index 1659dc32..5fdac61b 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/controller/RestrictedBaseController.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/controller/RestrictedBaseController.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,32 +37,35 @@ */ package org.onap.portalsdk.core.controller; -public class RestrictedBaseController extends FusionBaseController{ - +public class RestrictedBaseController extends FusionBaseController { + protected String viewName; private String exceptionView; + @Override public boolean isAccessible() { return false; } + @Override - public boolean isRESTfulCall(){ + 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; + 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/onap/portalsdk/core/controller/RestrictedRESTfulBaseController.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/controller/RestrictedRESTfulBaseController.java index 1dfffaa0..5a33c752 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/controller/RestrictedRESTfulBaseController.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/controller/RestrictedRESTfulBaseController.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,32 +37,35 @@ */ package org.onap.portalsdk.core.controller; -public class RestrictedRESTfulBaseController extends FusionBaseController{ - +public class RestrictedRESTfulBaseController extends FusionBaseController { + protected String viewName; private String exceptionView; + @Override public boolean isAccessible() { return false; } + @Override - public boolean isRESTfulCall(){ + 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; + 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/onap/portalsdk/core/controller/UnRestrictedBaseController.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/controller/UnRestrictedBaseController.java index 81f0c54d..b78f7bfb 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/controller/UnRestrictedBaseController.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/controller/UnRestrictedBaseController.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,17 +37,19 @@ */ package org.onap.portalsdk.core.controller; -public class UnRestrictedBaseController extends FusionBaseController{ +public class UnRestrictedBaseController extends FusionBaseController { protected String viewName; - + @Override public boolean isAccessible() { return true; } + @Override - public boolean isRESTfulCall(){ + public boolean isRESTfulCall() { return false; } + protected String getViewName() { return viewName; } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/dao/AbstractDao.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/dao/AbstractDao.java index c1d063a9..e70468c6 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/dao/AbstractDao.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/dao/AbstractDao.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -36,6 +36,7 @@ * ECOMP is a trademark and service mark of AT&T Intellectual Property. */ package org.onap.portalsdk.core.dao; + import java.io.Serializable; import java.lang.reflect.ParameterizedType; @@ -43,38 +44,39 @@ 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); - } - + +public abstract class AbstractDao<K extends Serializable, T> { + + private final Class<T> persistentClass; + + @Autowired + private SessionFactory sessionFactory; + + @SuppressWarnings("unchecked") + public AbstractDao() { + this.persistentClass = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()) + .getActualTypeArguments()[1]; + } + + protected Session getSession() { + return sessionFactory.getCurrentSession(); + } + + @SuppressWarnings("unchecked") + public T getByKey(K 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/onap/portalsdk/core/dao/ProfileDao.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/dao/ProfileDao.java index bb93ac36..a34737c8 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/dao/ProfileDao.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/dao/ProfileDao.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -43,5 +43,6 @@ import org.onap.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/onap/portalsdk/core/dao/ProfileDaoImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/dao/ProfileDaoImpl.java index ee6c32d3..471aed01 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/dao/ProfileDaoImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/dao/ProfileDaoImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -41,29 +41,24 @@ import java.util.List; import org.hibernate.Criteria; import org.hibernate.criterion.Restrictions; -import org.onap.portalsdk.core.dao.AbstractDao; import org.onap.portalsdk.core.domain.Profile; import org.springframework.stereotype.Repository; @Repository("profileDao") -public class ProfileDaoImpl extends AbstractDao<Integer, Profile> implements ProfileDao{ +public class ProfileDaoImpl extends AbstractDao<Integer, Profile> implements ProfileDao { - + @Override + @SuppressWarnings("unchecked") public List<Profile> findAll() { Criteria crit = getSession().createCriteria(Profile.class); - @SuppressWarnings("unchecked") - List<Profile> p = crit.list(); - - return p; + return crit.list(); } - + @Override public Profile getProfile(int id) { Criteria crit = getSession().createCriteria(Profile.class); crit.add(Restrictions.eq("id", id)); - Profile profile = (Profile) crit.uniqueResult(); - - return profile; + return (Profile) crit.uniqueResult(); } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/dao/hibernate/ModelOperationsCommon.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/dao/hibernate/ModelOperationsCommon.java index 2c3fa5da..f1fcd889 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/dao/hibernate/ModelOperationsCommon.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/dao/hibernate/ModelOperationsCommon.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -67,7 +67,6 @@ public abstract class ModelOperationsCommon extends FusionDao { @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(); @@ -76,19 +75,15 @@ public abstract class ModelOperationsCommon extends FusionDao { + ((fromIndex != null) ? " from rows " + fromIndex.toString() + " to " + toIndex.toString() : "") + "..."); - - if (filterClause != null && filterClause.length() > 0) { + if (filterClause != null && filterClause.length() > 0) logger.info(EELFLoggerDelegate.debugLogger, "Filtering " + className + " by: " + filterClause); - } - - list = session.createQuery("from " + className + Utilities.nvl(filterClause, "") + List 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) { + if (orderBy == null && list != null) Collections.sort(list); - } return list; } @@ -121,9 +116,8 @@ public abstract class ModelOperationsCommon extends FusionDao { if (fetchModeMap != null) { Iterator<String> itr = fetchModeMap.keySet().iterator(); - String key = null; while (itr.hasNext()) { - key = itr.next(); + String key = itr.next(); criteria.setFetchMode(key, fetchModeMap.get(key)); } @@ -133,21 +127,20 @@ public abstract class ModelOperationsCommon extends FusionDao { @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()); + logger.info(EELFLoggerDelegate.debugLogger, + "Getting " + domainClass.getName() + " record for id - " + id.toString()); - - vo = (DomainVo) session.get(domainClass, id); + DomainVo 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()); - + logger.error(EELFLoggerDelegate.errorLogger, + "Failed while instantiating a class of " + domainClass.getName(), e); } } @@ -156,7 +149,7 @@ public abstract class ModelOperationsCommon extends FusionDao { @SuppressWarnings("rawtypes") public List _getLookupList(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy, - HashMap additionalParams) { + Map additionalParams) { logger.info(EELFLoggerDelegate.debugLogger, "Retrieving " + dbTable + " lookup list..."); List list = null; @@ -164,7 +157,7 @@ public abstract class ModelOperationsCommon extends FusionDao { Session session = getSessionFactory().getCurrentSession(); - // default the orderBy if null; + // default the orderBy if null if (Utilities.nvl(dbOrderBy).length() == 0) { dbOrderByCol = dbLabelCol; dbOrderBy = dbLabelCol; @@ -174,8 +167,7 @@ public abstract class ModelOperationsCommon extends FusionDao { } } - StringBuffer sql = new StringBuffer(); - + StringBuilder sql = new StringBuilder(); 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 ") @@ -185,19 +177,23 @@ public abstract class ModelOperationsCommon extends FusionDao { 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."); + logger.error(EELFLoggerDelegate.errorLogger, "_getLookupList failed on SQL: [" + sql + "]", e); } return list; } // getLookupList - /* This method is used to execute SQL queries */ + /** + * 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 */ + /** + * 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(); @@ -213,13 +209,17 @@ public abstract class ModelOperationsCommon extends FusionDao { return query.list(); } - /* This method is used to execute HQL queries */ + /** + * 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 */ + /** + * 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(); @@ -235,22 +235,22 @@ public abstract class ModelOperationsCommon extends FusionDao { 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. + * 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. + /** + * 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) { @@ -266,37 +266,32 @@ public abstract class ModelOperationsCommon extends FusionDao { } // 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. + + /** + * 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 "); + StringBuilder modifiedSql = new StringBuilder("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. + /** + * 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, @@ -305,12 +300,13 @@ public abstract class ModelOperationsCommon extends FusionDao { Query query = session.getNamedQuery(queryName); bindQueryParameters(query, params); String queryStr = query.getQueryString(); - StringBuffer modifiedSql = new StringBuffer(" select * from (" + queryStr + " ) al "); + StringBuilder modifiedSql = new StringBuilder(" select * from (" + queryStr + " ) al "); if (whereClause != null && whereClause.length() > 0) modifiedSql.append("where " + whereClause); SQLQuery sqlQuery = session.createSQLQuery(modifiedSql.toString()); bindQueryParameters(sqlQuery, params); + // why is reportSearch hardcoded here? sqlQuery.addEntity("reportSearch", entity); if (fromIndex != null && toIndex != null) { @@ -321,11 +317,11 @@ public abstract class ModelOperationsCommon extends FusionDao { 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. + /** + * x 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, @@ -346,7 +342,6 @@ public abstract class ModelOperationsCommon extends FusionDao { 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) { @@ -355,10 +350,7 @@ public abstract class ModelOperationsCommon extends FusionDao { 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 + " "); + StringBuilder modifiedSql = new StringBuilder(" select * from (" + queryStr + " ) al "); if (whereClause != null && whereClause.length() > 0) modifiedSql.append("where " + whereClause); SQLQuery sqlQuery = session.createSQLQuery(modifiedSql.toString()); @@ -375,7 +367,7 @@ public abstract class ModelOperationsCommon extends FusionDao { // RAPTOR ZK END /* Processes custom Insert/Update/Delete SQL statements */ - protected final int _executeUpdateQuery(String sql) throws Exception { + protected final int _executeUpdateQuery(String sql) { Session session = getSessionFactory().getCurrentSession(); Query query = session.createSQLQuery(sql); return query.executeUpdate(); @@ -383,7 +375,7 @@ public abstract class ModelOperationsCommon extends FusionDao { /* Processes Insert/Update/Delete Named SQL statements */ @SuppressWarnings("rawtypes") - protected final int _executeNamedUpdateQuery(String queryName, Map params) throws Exception { + protected final int _executeNamedUpdateQuery(String queryName, Map params) { Session session = getSessionFactory().getCurrentSession(); Query query = session.getNamedQuery(queryName); bindQueryParameters(query, params); @@ -391,7 +383,7 @@ public abstract class ModelOperationsCommon extends FusionDao { } protected final void _update(DomainVo vo, Integer userId) { - _update(vo, ((userId != null) ? userId.intValue() : 0)); + _update(vo, (userId != null) ? userId.intValue() : 0); } protected final void _update(DomainVo vo, int userId) { @@ -427,16 +419,10 @@ public abstract class ModelOperationsCommon extends FusionDao { @SuppressWarnings("rawtypes") protected final int _remove(Class domainClass, String whereClause) { - int rowsAffected = 0; - Session session = getSessionFactory().getCurrentSession(); - - StringBuffer sql = new StringBuffer("delete from "); - + StringBuilder sql = new StringBuilder("delete from "); sql.append(domainClass.getName()).append(" where ").append(whereClause); - - rowsAffected = session.createQuery(sql.toString()).executeUpdate(); - + int rowsAffected = session.createQuery(sql.toString()).executeUpdate(); return rowsAffected; } @@ -452,17 +438,14 @@ public abstract class ModelOperationsCommon extends FusionDao { 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); } else { - if (parameterValue instanceof Collection) { - query.setParameterList((String) entry.getKey(), (Collection) parameterValue); - } else { - if (parameterValue instanceof Object[]) { - query.setParameterList((String) entry.getKey(), (Object[]) parameterValue); - } - } + logger.warn("bindQueryParameters: unimplemented case for {}", parameterValue); } } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/dao/support/FusionDao.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/dao/support/FusionDao.java index a3ff27fd..3ff2e47a 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/dao/support/FusionDao.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/dao/support/FusionDao.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -41,13 +41,13 @@ import org.hibernate.SessionFactory; import org.onap.portalsdk.core.FusionObject; public class FusionDao implements FusionObject { - private SessionFactory sessionFactory; + private SessionFactory sessionFactory; - public void setSessionFactory(SessionFactory sessionFactory) { - this.sessionFactory = sessionFactory; - } + public void setSessionFactory(SessionFactory sessionFactory) { + this.sessionFactory = sessionFactory; + } - public SessionFactory getSessionFactory() { - return this.sessionFactory; - } + public SessionFactory getSessionFactory() { + return this.sessionFactory; + } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/App.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/App.java index dfc4ae3c..0fa94a10 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/App.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/App.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -58,7 +58,7 @@ public class App extends DomainVo { 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 mlAppAdminId; // ml_app_admin_id private String motsId; // mots_id private String appPassword; // app_password private String open; @@ -216,6 +216,7 @@ public class App extends DomainVo { /** * Answers true if the objects have the same ID. */ + @Override public int compareTo(Object obj) { Long c1 = getId(); Long c2 = ((App) obj).getId(); diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/AuditLog.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/AuditLog.java index 7cebc1af..b9f49519 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/AuditLog.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/AuditLog.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -47,61 +47,60 @@ 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 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; @@ -118,7 +117,5 @@ public class AuditLog extends DomainVo { public void setUserId(Long userId) { this.userId = userId; } - - } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/BroadcastMessage.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/BroadcastMessage.java index d75a030a..01d6caed 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/BroadcastMessage.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/BroadcastMessage.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,106 +37,99 @@ */ package org.onap.portalsdk.core.domain; -import java.util.*; +import java.util.Date; import org.onap.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); - } + + private static final long serialVersionUID = 1L; + + 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; + } + + @Override + 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/onap/portalsdk/core/domain/DomainVo.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/DomainVo.java index 355f36cb..2818bf04 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/DomainVo.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/DomainVo.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -48,7 +48,7 @@ import java.util.Set; /* Super class from which all data objects descend * - * Per Sunder T on 3 June 2016: + * @deprecated 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. */ @@ -56,9 +56,6 @@ import java.util.Set; @Deprecated public class DomainVo extends FusionVo implements Serializable, Cloneable, Comparable { - /** - * - */ private static final long serialVersionUID = 1L; protected Long id; protected Date created; @@ -71,9 +68,6 @@ public class DomainVo extends FusionVo implements Serializable, Cloneable, Compa Set auditTrail = null; - public DomainVo() { - } - public void setId(Long i) { id = i; } @@ -147,10 +141,6 @@ public class DomainVo extends FusionVo implements Serializable, Cloneable, Compa getAuditTrail().add(auditLog); } - public Object clone() throws CloneNotSupportedException { - return super.clone(); - } - public Object copy() { return copy(false); } @@ -185,6 +175,7 @@ public class DomainVo extends FusionVo implements Serializable, Cloneable, Compa return newVo; } + @Override public int compareTo(Object obj) { Long c1 = getId(); Long c2 = ((DomainVo) obj).getId(); diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/FnMenu.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/FnMenu.java index f4ed41e4..894c35f1 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/FnMenu.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/FnMenu.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,123 +37,148 @@ */ package org.onap.portalsdk.core.domain; - import org.onap.portalsdk.core.domain.support.DomainVo; /** - * <p>RoleFunction.java</p> + * <p> + * RoleFunction.java + * </p> * - * <p>Represents a role function data object.</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; - + + 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/onap/portalsdk/core/domain/FusionVo.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/FusionVo.java index bf2321ba..ac25ae10 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/FusionVo.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/FusionVo.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -40,6 +40,7 @@ package org.onap.portalsdk.core.domain; import org.onap.portalsdk.core.FusionObject; public class FusionVo implements FusionObject { - public FusionVo() { - } + public FusionVo() { + // No-argument constructor + } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/LoginBean.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/LoginBean.java index 742f26b6..f6675a01 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/LoginBean.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/LoginBean.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -44,162 +44,169 @@ import org.onap.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; - } + 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/onap/portalsdk/core/domain/Lookup.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/Lookup.java index 6248de85..cf7163ca 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/Lookup.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/Lookup.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -44,56 +44,56 @@ import org.onap.portalsdk.core.domain.support.NameValueId; public class Lookup extends FusionVo implements Serializable { - /** - * - */ private static final long serialVersionUID = 1L; - private NameValueId nameValueId = new NameValueId(); + private NameValueId nameValueId = new NameValueId(); - public Lookup() {} + public Lookup() { + super(); + } - public Lookup(String label, String value) { - this(); - setLabel(label); - setValue(value); - } + public Lookup(String label, String value) { + this(); + setLabel(label); + setValue(value); + } - public String getValue() { - return getNameValueId().getVal(); - } + public String getValue() { + return getNameValueId().getVal(); + } - public String getLabel() { - return getNameValueId().getLab(); - } + public String getLabel() { + return getNameValueId().getLab(); + } - public void setValue(String value) { - getNameValueId().setVal(value); - } + public void setValue(String value) { + getNameValueId().setVal(value); + } - public void setLabel(String label) { - getNameValueId().setLab(label); - } + public void setLabel(String label) { + getNameValueId().setLab(label); + } - public NameValueId getNameValueId() { - return nameValueId; - } + public NameValueId getNameValueId() { + return nameValueId; + } - public void setNameValueId(NameValueId nameValueId) { - this.nameValueId = 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) - @Override - public int hashCode() { - return Objects.hash(getValue(), getLabel()); - } + // required by ZK for to set the selectedItems of Listboxes (used heavily for + // <select>-style drop-downs) + @Override + public int hashCode() { + return Objects.hash(getValue(), getLabel()); + } + + @Override + public boolean equals(Object obj) { + if (obj == null || !(obj instanceof Lookup)) + return false; + Lookup lookup = (Lookup) obj; + return Objects.equals(lookup.getValue(), getValue()) && Objects.equals(lookup.getLabel(), getLabel()); + } - @Override - public boolean equals( Object obj ) { - if (obj == null || !(obj instanceof Lookup)) - return false; - Lookup lookup = (Lookup)obj; - return Objects.equals(lookup.getValue(), getValue()) && Objects.equals(lookup.getLabel(), getLabel()); - } - } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/LuCountry.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/LuCountry.java index 2aa8a7db..c3f1c6ed 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/LuCountry.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/LuCountry.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,43 +37,39 @@ */ package org.onap.portalsdk.core.domain; - -import org.onap.portalsdk.core.domain.support.*; - - /** - * <p>luCountry.java</p> * - * <p>Represents a country data object.</p> + * <p> + * Represents a country data object. + * </p> * * @version 1.0 */ public class LuCountry extends DomainVo { - /** - * - */ private static final long serialVersionUID = 1L; - LuCountry() {} + private String abbr; + private String country; + private String fullName; + private String webphoneCountryLabel; - public String getCountry() { - return country; - } - - public String getAbbr() { - return abbr; - } + public String getCountry() { + return country; + } - public void setCountry(String country) { - this.country = country; - } + public String getAbbr() { + return abbr; + } - public void setAbbr(String abbr) { - this.abbr = abbr; - } + public void setCountry(String country) { + this.country = country; + } + public void setAbbr(String abbr) { + this.abbr = abbr; + } - public String getFullName() { + public String getFullName() { return fullName; } @@ -89,17 +85,11 @@ public class LuCountry extends DomainVo { 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; + @Override + public int compareTo(Object obj) { + String c1 = getCountry(); + String c2 = ((LuCountry) obj).getCountry(); + return c1.compareTo(c2); + } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/LuState.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/LuState.java index 23b1ec99..d82eab65 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/LuState.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/LuState.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,52 +37,42 @@ */ package org.onap.portalsdk.core.domain; - -import org.onap.portalsdk.core.domain.support.*; - - /** - * <p>State.java</p> - * - * <p>Represents a state data object.</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; - } + private String abbr; + private String state; - public void setAbbr(String abbr) { - this.abbr = abbr; - } + public String getState() { + return state; + } + public String getAbbr() { + return abbr; + } - public int compareTo(Object obj){ - String c1 = getState(); - String c2 = ((LuState)obj).getState(); + public void setState(String state) { + this.state = state; + } - return c1.compareTo(c2); - } + public void setAbbr(String abbr) { + this.abbr = abbr; + } + @Override + public int compareTo(Object obj) { + String c1 = getState(); + String c2 = ((LuState) obj).getState(); - private String abbr; - private String state; + return c1.compareTo(c2); + } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/LuTimeZone.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/LuTimeZone.java index ad17754a..f1494627 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/LuTimeZone.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/LuTimeZone.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,44 +37,41 @@ */ package org.onap.portalsdk.core.domain; - -import org.onap.portalsdk.core.domain.support.*; - - /** - * <p>LuTimeZone.java</p> + * <p> + * LuTimeZone.java + * </p> * - * <p>Represents a LuTimeZone data object.</p> + * <p> + * Represents a LuTimeZone data object. + * </p> * * @version 1.0 */ public class LuTimeZone extends DomainVo { - /** - * - */ private static final long serialVersionUID = 1L; - - LuTimeZone() {} + private String name; + private Long timezoneId; + private String value; - public String getName() { - return name; - } - - public String getValue() { - return value; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public String getValue() { + return value; + } - public void setValue(String value) { - this.value = value; - } + public void setName(String name) { + this.name = name; + } + public void setValue(String value) { + this.value = value; + } - public Long getTimezoneId() { + public Long getTimezoneId() { return timezoneId; } @@ -82,16 +79,11 @@ public class LuTimeZone extends DomainVo { 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; + @Override + public int compareTo(Object obj) { + Long c1 = getId(); + Long c2 = ((LuTimeZone) obj).getId(); + return c1.compareTo(c2); + } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/Menu.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/Menu.java index 9f3f83e2..a13f17a4 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/Menu.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/Menu.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,114 +37,124 @@ */ package org.onap.portalsdk.core.domain; - import org.onap.portalsdk.core.domain.support.DomainVo; public class Menu extends DomainVo { - - /** - * - */ + private static final long serialVersionUID = 1L; - public Menu() {} - public String getAction() { - return action; - } + 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; + + public String getAction() { + return action; + } - public boolean isActive() { - return active; - } + public boolean isActive() { + return active; + } - public String getExternalUrl() { - return externalUrl; - } + public String getExternalUrl() { + return externalUrl; + } - public String getFunctionCd() { - return functionCd; - } + public String getFunctionCd() { + return functionCd; + } - public String getLabel() { - return label; - } + public String getLabel() { + return label; + } - public String getMenuLevel() { - return menuLevel; - } + public String getMenuLevel() { + return menuLevel; + } - public Long getParentId() { - return parentId; - } + public Long getParentId() { + return parentId; + } - public String getQueryString() { - return queryString; - } + public String getQueryString() { + return queryString; + } - public String getServlet() { - return servlet; - } + public String getServlet() { + return servlet; + } - public Short getSortOrder() { - return sortOrder; - } + public Short getSortOrder() { + return sortOrder; + } - public String getTarget() { - return target; - } + public String getTarget() { + return target; + } - public String getMenuSetCode() { - return menuSetCode; - } + public String getMenuSetCode() { + return menuSetCode; + } - public void setAction(String action) { - this.action = action; - } + public void setAction(String action) { + this.action = action; + } - public void setActive(boolean active) { - this.active = active; - } + public void setActive(boolean active) { + this.active = active; + } - public void setExternalUrl(String externalUrl) { - this.externalUrl = externalUrl; - } + public void setExternalUrl(String externalUrl) { + this.externalUrl = externalUrl; + } - public void setFunctionCd(String functionCd) { - this.functionCd = functionCd; - } + public void setFunctionCd(String functionCd) { + this.functionCd = functionCd; + } - public void setLabel(String label) { - this.label = label; - } + public void setLabel(String label) { + this.label = label; + } - public void setMenuLevel(String menuLevel) { - this.menuLevel = menuLevel; - } + public void setMenuLevel(String menuLevel) { + this.menuLevel = menuLevel; + } - public void setParentId(Long parentId) { - this.parentId = parentId; - } + public void setParentId(Long parentId) { + this.parentId = parentId; + } - public void setQueryString(String queryString) { - this.queryString = queryString; - } + public void setQueryString(String queryString) { + this.queryString = queryString; + } - public void setServlet(String servlet) { - this.servlet = servlet; - } + public void setServlet(String servlet) { + this.servlet = servlet; + } - public void setSortOrder(Short sortOrder) { - this.sortOrder = sortOrder; - } + public void setSortOrder(Short sortOrder) { + this.sortOrder = sortOrder; + } - public void setTarget(String target) { - this.target = target; - } + public void setTarget(String target) { + this.target = target; + } - public void setMenuSetCode(String menuSetCode) { - this.menuSetCode = menuSetCode; - } + public void setMenuSetCode(String menuSetCode) { + this.menuSetCode = menuSetCode; + } - public boolean isSeparator() { + public boolean isSeparator() { return separator; } @@ -160,19 +170,4 @@ public class Menu extends DomainVo { 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/onap/portalsdk/core/domain/MenuData.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/MenuData.java index 8967b4f4..be8264a6 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/MenuData.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/MenuData.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,54 +37,51 @@ */ package org.onap.portalsdk.core.domain; -import java.util.*; +import java.util.Set; +import java.util.TreeSet; public class MenuData extends Menu { - /** - * - */ - private static final long serialVersionUID = 1L; - private MenuData parentMenu; - private Set childMenus = new TreeSet(); + private static final long serialVersionUID = 1L; + private MenuData parentMenu; + private Set childMenus = new TreeSet(); - public MenuData() {} + public MenuData() { + } - public Set getChildMenus() { - return childMenus; - } + public Set getChildMenus() { + return childMenus; + } - public MenuData getParentMenu() { - return parentMenu; - } + public void setChildMenus(Set childMenus) { + this.childMenus = childMenus; + } - public void setChildMenus(Set childMenus) { - this.childMenus = childMenus; - } + public MenuData getParentMenu() { + return parentMenu; + } - public void setParentMenu(MenuData parentMenu) { - this.parentMenu = parentMenu; - } + public void setParentMenu(MenuData parentMenu) { + this.parentMenu = parentMenu; + } - public int compareTo(Object obj){ + public String getActiveAsString() { + return String.valueOf(isActive()); + } - 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 getParentIdAsString(){ - return String.valueOf(getParentId()); - } - - public String getSeparatorAsString(){ - return String.valueOf(isSeparator()); - } + public String getSeparatorAsString() { + return String.valueOf(isSeparator()); + } + @Override + 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)); + } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/Profile.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/Profile.java index 02d1c838..9df131de 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/Profile.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/Profile.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -36,9 +36,10 @@ * ECOMP is a trademark and service mark of AT&T Intellectual Property. */ package org.onap.portalsdk.core.domain; + import org.onap.portalsdk.core.domain.support.DomainVo; -public class Profile extends DomainVo{ +public class Profile extends DomainVo { private static final long serialVersionUID = 3409056457412656883L; @@ -49,19 +50,17 @@ public class Profile extends DomainVo{ private String orgManagerUserId; private String active_yn; private String orgUserId; - public Profile() {} - + @Override public Long getId() { return id; } - + @Override public void setId(Long id) { this.id = id; } - public String getFirst_name() { return first_name; } @@ -109,6 +108,5 @@ public class Profile extends DomainVo{ public void setOrgUserId(String orgUserId) { this.orgUserId = orgUserId; } - - + } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/Role.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/Role.java index b2cdce05..2d772943 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/Role.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/Role.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,7 +37,6 @@ */ package org.onap.portalsdk.core.domain; - import java.util.Iterator; import java.util.Set; import java.util.TreeSet; @@ -47,146 +46,140 @@ import org.onap.portalsdk.core.domain.support.DomainVo; import com.fasterxml.jackson.annotation.JsonIgnore; /** - * <p>Role.java</p> - * <p>Represents a role data object.</p> + * <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(); - } - + 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 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" ); + 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); - } - + + 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; + } + } + } + + @Override + 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/onap/portalsdk/core/domain/RoleFunction.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/RoleFunction.java index 448cc232..1114bca0 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/RoleFunction.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/RoleFunction.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,53 +37,50 @@ */ package org.onap.portalsdk.core.domain; - import org.onap.portalsdk.core.domain.support.DomainVo; /** - * <p>RoleFunction.java</p> + * <p> + * RoleFunction.java + * </p> * - * <p>Represents a role function data object.</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; - } + private static final long serialVersionUID = 1L; + private String code; + private String name; - public String getCode() { - return code; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public String getCode() { + return code; + } - public void setCode(String code) { - this.code = code; - } + public void setName(String name) { + this.name = name; + } - public String getEditUrl() { - return "/role_function.htm?role_function_id=" + getCode(); - } - - public int compareTo(Object obj){ - String c1 = getName(); - String c2 = ((RoleFunction)obj).getName(); + public void setCode(String code) { + this.code = code; + } - return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2); - } + public String getEditUrl() { + return "/role_function.htm?role_function_id=" + getCode(); + } - private String code; - private String name; - private String editUrl; + @Override + public int compareTo(Object obj) { + String c1 = getName(); + String c2 = ((RoleFunction) obj).getName(); + return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2); + } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/UrlsAccessible.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/UrlsAccessible.java index f7237ed5..55fe3624 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/UrlsAccessible.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/UrlsAccessible.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -42,55 +42,54 @@ import java.util.Objects; public class UrlsAccessible extends FusionVo implements Serializable { - /** - * - */ private static final long serialVersionUID = 1L; - private UrlsAccessibleKey urlsAccessibleKey = new UrlsAccessibleKey(); + private UrlsAccessibleKey urlsAccessibleKey = new UrlsAccessibleKey(); - public UrlsAccessible() {} + public UrlsAccessible() { + super(); + } - public UrlsAccessible(String url, String functionCd) { - this(); - setUrl(url); - setFunctionCd(functionCd); - } + public UrlsAccessible(String url, String functionCd) { + this(); + setUrl(url); + setFunctionCd(functionCd); + } - public String getUrl() { - return getUrlsAccessibleKey().getUrl(); - } + public String getUrl() { + return getUrlsAccessibleKey().getUrl(); + } - public String getFunctionCd() { - return getUrlsAccessibleKey().getFunctionCd(); - } + public String getFunctionCd() { + return getUrlsAccessibleKey().getFunctionCd(); + } - public void setUrl(String url) { - getUrlsAccessibleKey().setUrl(url); - } + public void setUrl(String url) { + getUrlsAccessibleKey().setUrl(url); + } - public void setFunctionCd(String functionCd) { - getUrlsAccessibleKey().setFunctionCd(functionCd); - } + public void setFunctionCd(String functionCd) { + getUrlsAccessibleKey().setFunctionCd(functionCd); + } - public UrlsAccessibleKey getUrlsAccessibleKey() { - return urlsAccessibleKey; - } + public UrlsAccessibleKey getUrlsAccessibleKey() { + return urlsAccessibleKey; + } - public void setUrlsAccessibleKey(UrlsAccessibleKey urlsAccessibleKey) { - this.urlsAccessibleKey = urlsAccessibleKey; - } + public void setUrlsAccessibleKey(UrlsAccessibleKey urlsAccessibleKey) { + this.urlsAccessibleKey = urlsAccessibleKey; + } - @Override - public int hashCode() { - return Objects.hash(getUrl(), getFunctionCd()); - } + @Override + public int hashCode() { + return Objects.hash(getUrl(), getFunctionCd()); + } + + @Override + public boolean equals(Object obj) { + if (obj == null || !(obj instanceof UrlsAccessible)) + return false; + UrlsAccessible ua = (UrlsAccessible) obj; + return Objects.equals(ua.getUrl(), getUrl()) && Objects.equals(ua.getFunctionCd(), getFunctionCd()); + } - @Override - public boolean equals( Object obj ) { - if (obj == null || !(obj instanceof UrlsAccessible)) - return false; - UrlsAccessible ua = (UrlsAccessible)obj; - return Objects.equals(ua.getUrl(), getUrl()) && Objects.equals(ua.getFunctionCd(), getFunctionCd()); - } - } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/UrlsAccessibleKey.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/UrlsAccessibleKey.java index e7bdc5a6..59732b27 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/UrlsAccessibleKey.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/UrlsAccessibleKey.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,72 +37,57 @@ */ package org.onap.portalsdk.core.domain; -import java.io.*; - +import java.io.Serializable; 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(); - } + private String url; + private String functionCd; + + public UrlsAccessibleKey() { + super(); + } + + 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; + } + + @Override + 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; + } + + @Override + public int hashCode() { + return getUrl().hashCode() + getFunctionCd().hashCode(); + } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/User.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/User.java index a72f1d6a..6d823817 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/User.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/User.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,7 +37,6 @@ */ package org.onap.portalsdk.core.domain; - import java.util.Date; import java.util.Iterator; import java.util.Set; @@ -47,374 +46,370 @@ import java.util.TreeSet; import org.onap.portalsdk.core.domain.support.DomainVo; /** - * <p>User.java</p> + * <p> + * User.java + * </p> * - * <p>Represents a user data object.</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; - } + 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 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 getCountry() { - return country; - } + public String getOrgCode() { + return orgCode; + } - public String getState() { - return state; - } + public Long getOrgId() { + return orgId; + } - public String getZipCode() { - return zipCode; - } + public String getPhone() { + return phone; + } - public String getBusinessCountryCode() { - return businessCountryCode; - } + public String getOrgUserId() { + return orgUserId; + } - public String getCommandChain() { - return commandChain; - } + public boolean getActive() { + return active; + } - public String getCompany() { - return company; - } + public boolean getInternal() { + return internal; + } - public String getCompanyCode() { - return companyCode; - } + public String getAddress1() { + return address1; + } - public String getDepartment() { - return department; - } + public String getAddress2() { + return address2; + } - public String getJobTitle() { - return jobTitle; - } + 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 getLocationClli() { - return locationClli; - } + public String getOrgManagerUserId() { + return orgManagerUserId; + } - public String getOrgManagerUserId() { - return orgManagerUserId; - } + public String getZipCodeSuffix() { + return zipCodeSuffix; + } - public String getZipCodeSuffix() { - return zipCodeSuffix; - } + public String getBusinessCountryName() { + return businessCountryName; + } - public String getBusinessCountryName() { - return businessCountryName; - } + public Set getPseudoRoles() { + return pseudoRoles; + } - public Set getPseudoRoles() { - return pseudoRoles; - } + public Long getSelectedProfileId() { + return selectedProfileId; + } - public Long getSelectedProfileId() { - return selectedProfileId; - } + public void setAddressId(Long addressId) { + this.addressId = addressId; + } - public void setAddressId(Long addressId) { - this.addressId = addressId; - } + public void setAlertMethodCd(String alertMethodCd) { + this.alertMethodCd = alertMethodCd; + } - public void setAlertMethodCd(String alertMethodCd) { - this.alertMethodCd = alertMethodCd; - } + public void setCellular(String cellular) { + this.cellular = cellular; + } - public void setCellular(String cellular) { - this.cellular = cellular; - } + public void setEmail(String email) { + this.email = email; + } - public void setEmail(String email) { - this.email = email; - } + public void setFax(String fax) { + this.fax = fax; + } - public void setFax(String fax) { - this.fax = fax; - } + public void setFirstName(String firstName) { + this.firstName = firstName; + } - public void setFirstName(String firstName) { - this.firstName = firstName; - } + public void setHrid(String hrid) { + this.hrid = hrid; + } - public void setHrid(String hrid) { - this.hrid = hrid; - } + public void setLastLoginDate(Date lastLoginDate) { + this.lastLoginDate = lastLoginDate; + } - public void setLastLoginDate(Date lastLoginDate) { - this.lastLoginDate = lastLoginDate; - } + public void setLastName(String lastName) { + this.lastName = lastName; + } - public void setLastName(String lastName) { - this.lastName = lastName; - } + public void setLoginId(String loginId) { + this.loginId = loginId; + } - public void setLoginId(String loginId) { - this.loginId = loginId; - } + public void setLoginPwd(String loginPwd) { + this.loginPwd = loginPwd; + } - public void setLoginPwd(String loginPwd) { - this.loginPwd = loginPwd; - } + public void setManagerId(Long managerId) { + this.managerId = managerId; + } - public void setManagerId(Long managerId) { - this.managerId = managerId; - } + public void setMiddleInitial(String middleInitial) { + this.middleInitial = middleInitial; + } - public void setMiddleInitial(String middleInitial) { - this.middleInitial = middleInitial; - } + public void setOrgCode(String orgCode) { + this.orgCode = orgCode; + } - public void setOrgCode(String orgCode) { - this.orgCode = orgCode; - } + public void setOrgId(Long orgId) { + this.orgId = orgId; + } - public void setOrgId(Long orgId) { - this.orgId = orgId; - } + public void setPhone(String phone) { + this.phone = phone; + } - public void setPhone(String phone) { - this.phone = phone; - } + public void setOrgUserId(String orgUserId) { + this.orgUserId = orgUserId; + } - public void setOrgUserId(String orgUserId) { - this.orgUserId = orgUserId; - } + public void setActive(boolean active) { + this.active = active; + } - public void setActive(boolean active) { - this.active = active; - } + public void setInternal(boolean internal) { + this.internal = internal; + } - public void setInternal(boolean internal) { - this.internal = internal; - } + public void setAddress1(String address1) { + this.address1 = address1; + } - public void setAddress1(String address1) { - this.address1 = address1; - } + public void setAddress2(String address2) { + this.address2 = address2; + } - public void setAddress2(String address2) { - this.address2 = address2; - } + public void setCity(String city) { + this.city = city; + } - public void setCity(String city) { - this.city = city; - } + public void setCountry(String country) { + this.country = country; + } - public void setCountry(String country) { - this.country = country; - } + public void setState(String state) { + this.state = state; + } - public void setState(String state) { - this.state = state; - } + public void setZipCode(String zipCode) { + this.zipCode = zipCode; + } - public void setZipCode(String zipCode) { - this.zipCode = zipCode; - } + public void setBusinessCountryCode(String businessCountryCode) { + this.businessCountryCode = businessCountryCode; + } - public void setBusinessCountryCode(String businessCountryCode) { - this.businessCountryCode = businessCountryCode; - } + public void setCommandChain(String commandChain) { + this.commandChain = commandChain; + } - public void setCommandChain(String commandChain) { - this.commandChain = commandChain; - } + public void setCompany(String company) { + this.company = company; + } - public void setCompany(String company) { - this.company = company; - } + public void setCompanyCode(String companyCode) { + this.companyCode = companyCode; + } - public void setCompanyCode(String companyCode) { - this.companyCode = companyCode; - } + public void setDepartment(String department) { + this.department = department; + } - public void setDepartment(String department) { - this.department = department; - } + public void setJobTitle(String jobTitle) { + this.jobTitle = jobTitle; + } - public void setJobTitle(String jobTitle) { - this.jobTitle = jobTitle; - } + public void setLocationClli(String locationClli) { + this.locationClli = locationClli; + } - public void setLocationClli(String locationClli) { - this.locationClli = locationClli; - } + public void setOrgManagerUserId(String orgManagerUserId) { + this.orgManagerUserId = orgManagerUserId; + } - public void setOrgManagerUserId(String orgManagerUserId) { - this.orgManagerUserId = orgManagerUserId; - } + public void setZipCodeSuffix(String zipCodeSuffix) { + this.zipCodeSuffix = zipCodeSuffix; + } - public void setZipCodeSuffix(String zipCodeSuffix) { - this.zipCodeSuffix = zipCodeSuffix; - } + public void setBusinessCountryName(String businessCountryName) { + this.businessCountryName = businessCountryName; + } - public void setBusinessCountryName(String businessCountryName) { - this.businessCountryName = businessCountryName; - } + public void setPseudoRoles(Set pseudoRoles) { + this.pseudoRoles = pseudoRoles; + } - public void setPseudoRoles(Set pseudoRoles) { - this.pseudoRoles = pseudoRoles; - } + public void setSelectedProfileId(Long selectedProfileId) { + this.selectedProfileId = selectedProfileId; + } - public void setSelectedProfileId(Long selectedProfileId) { - this.selectedProfileId = selectedProfileId; - } - public Long getTimeZoneId() { return timeZoneId; } @@ -454,7 +449,7 @@ public class User extends DomainVo { public void setFinancialLocCode(String financialLocCode) { this.financialLocCode = financialLocCode; } - + public String getBusinessUnitName() { return businessUnitName; } @@ -471,15 +466,6 @@ public class User extends DomainVo { 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; } @@ -503,28 +489,27 @@ public class User extends DomainVo { 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(); + if (roles != null) { + // add all + Set newUserApps = new TreeSet(); Iterator itr = roles.iterator(); - while(itr.hasNext()){ + 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); + newUserApps.add(userApp); } - setUserApps(userApps); + setUserApps(newUserApps); } else { - //remove all + // remove all this.userApps.clear(); } - } @SuppressWarnings("unchecked") @@ -532,13 +517,11 @@ public class User extends DomainVo { 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()); + // getting default app + while (appsItr.hasNext()) { + UserApp tempUserApp = (UserApp) appsItr.next(); + if (tempUserApp.getApp().getId().equals(app.getId())) { + roles.add(tempUserApp.getRole()); } } return roles; @@ -550,53 +533,62 @@ public class User extends DomainVo { app.setName("Default"); return getAppRoles(app); } - - public UserApp getDefaultUserApp(){ + + 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))){ + // getting default app + while (appsItr.hasNext()) { + UserApp tempApp = (UserApp) appsItr.next(); + if (tempApp.getApp().getId().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); + 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(); - } + // 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){ + public void addRole(Role role) { + if (role != null) { SortedSet<Role> roles = getRoles(); - if(roles==null){ + if (roles == null) { roles = new TreeSet(); - } + } roles.add(role); - setRoles(roles); + setRoles(roles); } + } + + @Override + 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); } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/UserApp.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/UserApp.java index 74f7dd75..edaf0013 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/UserApp.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/UserApp.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,29 +37,16 @@ */ package org.onap.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; } @@ -83,7 +70,7 @@ public class UserApp implements java.io.Serializable, Comparable { public void setRole(Role role) { this.role = role; } - + public Short getPriority() { return this.priority; } @@ -92,10 +79,11 @@ public class UserApp implements java.io.Serializable, Comparable { this.priority = priority; } + @Override public boolean equals(Object other) { - if ((this == other)) + if (this == other) return true; - if ((other == null)) + if (other == null) return false; if (!(other instanceof UserApp)) return false; @@ -104,26 +92,32 @@ public class UserApp implements java.io.Serializable, Comparable { 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())); + && ((this.priority == null && castOther.getPriority() == null) + || this.getPriority().equals(castOther.getPriority())); } + @Override 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); + 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); - } + @Override + 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/onap/portalsdk/core/domain/UserAppId.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/UserAppId.java index a9ec9760..d1fac039 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/UserAppId.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/UserAppId.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -80,26 +80,26 @@ public class UserAppId implements java.io.Serializable { this.role = role; } + @Override public boolean equals(Object other) { - if ((this == other)) + if (this == other) return true; - if ((other == null)) + 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()) + return (this.getUserId() == castOther.getUserId()) && (this.getApp().getId() == castOther.getApp().getId()) && (this.getRole().getId() == castOther.getRole().getId()); } + @Override 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.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/onap/portalsdk/core/domain/sessionmgt/TimeoutVO.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/sessionmgt/TimeoutVO.java index cf296175..22b8b80a 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/sessionmgt/TimeoutVO.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/sessionmgt/TimeoutVO.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,19 +37,19 @@ */ package org.onap.portalsdk.core.domain.sessionmgt; -public class TimeoutVO implements Comparable<TimeoutVO>{ - +public class TimeoutVO implements Comparable<TimeoutVO> { + private String jSessionId; private Long sessionTimOutMilliSec; - - public TimeoutVO(){ - + + public TimeoutVO() { + super(); } - + public TimeoutVO(String _jSessionId, Long _sessionTimOutMilliSec) { setjSessionId(_jSessionId); setSessionTimOutMilliSec(_sessionTimOutMilliSec); - + } public String getjSessionId() { @@ -69,13 +69,20 @@ public class TimeoutVO implements Comparable<TimeoutVO>{ } @Override + public boolean equals(Object other) { + if (this == other) + return true; + if (other == null) + return false; + if (!(other instanceof TimeoutVO)) + return false; + TimeoutVO castOther = (TimeoutVO) other; + return this.getSessionTimOutMilliSec() == castOther.getSessionTimOutMilliSec(); + } + + @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/onap/portalsdk/core/domain/support/Attribute.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/Attribute.java index e78589f8..948d78a0 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/Attribute.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/Attribute.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -38,43 +38,50 @@ package org.onap.portalsdk.core.domain.support; public class Attribute { - public double width; - public double top; - public double left; - public String name; - public double height; - + private double width; + private double top; + private double left; + private String name; + private 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/onap/portalsdk/core/domain/support/CollaborateList.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/CollaborateList.java index 2f0c5d50..32828b78 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/CollaborateList.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/CollaborateList.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -39,36 +39,34 @@ package org.onap.portalsdk.core.domain.support; import java.io.Serializable; import java.util.HashSet; +import java.util.Set; + +public class CollaborateList implements Serializable { -public class CollaborateList implements Serializable { - private static final long serialVersionUID = -4104440747626736243L; - private HashSet<String> userNameList = new HashSet<String>(); + private HashSet<String> userNameList = new HashSet<>(); private static CollaborateList userListData = new CollaborateList(); - private CollaborateList(){} - public static CollaborateList getInstance(){ + private CollaborateList() { + } + + public static CollaborateList getInstance() { return userListData; } - - public HashSet<String> getAllUserName(){ + + public Set<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{ + + public static void addUserName(String name) { + final Set<String> allUserName = CollaborateList.getInstance().getAllUserName(); + if (!allUserName.contains(name)) allUserName.add(name); - } } - - public static void delUserName(String name){ - final HashSet<String> allUserName = CollaborateList.getInstance().getAllUserName(); + + public static void delUserName(String name) { + final Set<String> allUserName = CollaborateList.getInstance().getAllUserName(); allUserName.remove((String) name); } - - } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/Container.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/Container.java index cdbf6611..ed065b4a 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/Container.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/Container.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -40,56 +40,64 @@ package org.onap.portalsdk.core.domain.support; import java.util.List; import java.util.Map; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; + public class Container { - + + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(Container.class); + String id; - - public String name; - + + String name; + Size size; - + Position p; - - public Map<String,Container> containerRowCol; - - public Map<String,Element> elementRowCol; - + + Map<String, Container> containerRowCol; + + 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) { - + + double top; + + double left; + + double height; + + double width; + + String visibilityType; + + List<Container> innerCList; + + List<Element> elementList; + + public Container() { + + } + + 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; @@ -100,27 +108,13 @@ public class Container { 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; } @@ -133,16 +127,14 @@ public class Container { this.name = name; } - - public void setInnerContainer(Map<String,Container> innerCon) { + public void setInnerContainer(Map<String, Container> innerCon) { containerRowCol = innerCon; } - - public void setElements(Map<String,Element> innerE) { + + public void setElements(Map<String, Element> innerE) { elementRowCol = innerE; } - - + public Position getP() { return p; } @@ -151,33 +143,26 @@ public class Container { 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; } @@ -187,103 +172,92 @@ public class Container { } public Size computeSize() { + logger.debug("computeSize: name is {}", getName()); 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; + 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(); + } 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; + || 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; + 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 j = 0; j < numOfCols; j++) { + if ((containerRowCol != null && containerRowCol.containsKey(String.valueOf(numOfRows - 1) + j)) + || (elementRowCol != null && elementRowCol.containsKey(String.valueOf(numOfRows - 1) + j))) { 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 (containerRowCol != null && containerRowCol.containsKey(i + String.valueOf(j))) { + height += 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; + || 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; + || 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)); + 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; + 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(); + 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(); + 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)); + } 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(); + 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; } } @@ -292,55 +266,52 @@ public class Container { 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); + 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; } 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; - } + 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; + || 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); + p.y = this.getP().getY() + ysum + i * interEleH + (interEleToContainerH); + } else + p.y = this.getP().getY() + ysum + i * interEleH + interEleToContainerH; } - 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 += e.computeSize().getWidth(); + e.setP(p); + } } xsum = 0; } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/Domain.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/Domain.java index b4adaf95..2ef50419 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/Domain.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/Domain.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,32 +37,18 @@ */ package org.onap.portalsdk.core.domain.support; -import java.util.ArrayList; import java.util.List; import java.util.Map; public class Domain { - // Unique identifier of the domain + // Unique identifier of the domain String id; - // List<Container> cList; - - public String name; - Size size; + 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 + // Horizontal space between a pair of containers double interContWd = 1.0; - //Vertical space between a pair of containers + // Vertical space between a pair of containers double interContH; double domainToLayoutWd; double domainToContH; @@ -70,7 +56,15 @@ public class Domain { int numOfRowsofContainer; int numOfColsofContainer; boolean indexChanged; - Map<String,Container> containerRowCol; + Map<String, Container> containerRowCol; + double top; + double left; + double height; + double width; + List<Container> containerList; + double newXafterColl; + double YafterColl; + public Domain(String id, String name, double interContWd, double interContH, double domainToLayoutWd, double domainToLayoutH, double domainToContH, int numOfRowsofContainer, int numOfColsofContainer) { this.id = id; @@ -82,26 +76,16 @@ public class Domain { 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 Position getP() { + return p; + } + + public void setP(Position p) { + this.p = p; + } + public void setNewXafterColl(double newXafterColl) { this.newXafterColl = newXafterColl; } @@ -109,7 +93,7 @@ public class Domain { public double getNewXafterColl() { return newXafterColl; } - + public double getYafterColl() { return YafterColl; } @@ -121,7 +105,7 @@ public class Domain { public void setDomainToLayoutWd(double domainToLayoutWd) { this.domainToLayoutWd = domainToLayoutWd; } - + public double getDomainToLayoutWd() { return domainToLayoutWd; } @@ -166,38 +150,18 @@ public class Domain { return name; } - public void setContainers(Map<String,Container> containerRowCol) { + 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; } @@ -206,72 +170,63 @@ public class Domain { this.indexChanged = indexChanged; } - //Compute the size of any domain + // Compute the size of any domain public Size computeSize() { size = new Size(); size.setHeight(5); - double width = 0; + double myWidth = 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; - } - + if (containerRowCol != null + && containerRowCol.containsKey(String.valueOf(i) + String.valueOf(numOfColsofContainer - 1))) { + for (int j = 0; j < numOfColsofContainer; j++) { + myWidth += containerRowCol.get(String.valueOf(i) + String.valueOf(j)).computeSize().getWidth(); + } + break; + } + } - width+=(numOfColsofContainer-1)*interContWd; - if (this.getName().equals("VNI")) - size.setWidth(width-4); + myWidth += (numOfColsofContainer - 1) * interContWd; + if (this.getName().equals("VNI")) + size.setWidth(myWidth - 4); else - size.setWidth(width); + size.setWidth(myWidth); 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(); - } + 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)); + Position p = new Position(); + if (this.getName().equals("VNI")) { + p.x = j * (interContWd - 2) + xsum + domainToLayoutWd; + } else + p.x = j * interContWd + xsum + domainToLayoutWd; + double 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 (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(); - - } + } + p.y = domainToLayoutH + ysum + this.computeSize().getHeight() + domainToContH + i * interContH; + c.setP(p); + xsum += c.computeSize().getWidth(); } - xsum = 0; - + } + xsum = 0; + } } } - - diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/DomainVo.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/DomainVo.java index 57718ed4..ba4a1f34 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/DomainVo.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/DomainVo.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -46,139 +46,150 @@ import java.util.Date; import java.util.Set; import org.onap.portalsdk.core.domain.FusionVo; - +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; /* 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; - } - - + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DomainVo.class); + + 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; + protected Set auditTrail = null; + + public DomainVo() { + super(); + } + + 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 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) { + logger.error(EELFLoggerDelegate.errorLogger, "copy failed", e); + } + + return newVo; + } + + @Override 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); - } - + + @Override + public boolean equals(Object other) { + if (this == other) + return true; + if (other == null) + return false; + if (!(other instanceof DomainVo)) + return false; + DomainVo castOther = (DomainVo) other; + return this.getId() == castOther.getId() + && this.getCreated().equals(castOther.getCreated()) + && this.getCreatedId() == castOther.getCreatedId() + && this.getModified().equals(castOther.getModified()) + && this.getModifiedId() == castOther.getModifiedId() + ; + } + + @Override + 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/onap/portalsdk/core/domain/support/Element.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/Element.java index 85147e48..1bf6a150 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/Element.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/Element.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,32 +37,45 @@ */ package org.onap.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; - - + + String id; + String name; + + double top; + + double left; + + double height; + + double width; + + String imgFileName; + + String borderType; + + String bgColor; + + ElementDetails details; + + Position p; + + 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 setBgColor(String bgColor) { this.bgColor = bgColor; } @@ -87,15 +100,10 @@ public class Element { this.width = width; } - - public double width; - - public String getId() { return id; } - - + public String getName() { return name; } @@ -103,10 +111,7 @@ public class Element { public void setName(String name) { this.name = name; } - - Position p; - public Position getP() { return p; } @@ -115,34 +120,6 @@ public class Element { 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; } @@ -154,29 +131,23 @@ public class Element { 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); + Size size = new Size(); + size.setWidth(0.5 * 7.0); + size.setHeight(0.5 * 3.0); return size; } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/ElementDetails.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/ElementDetails.java index 58c8d416..73ccd5d6 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/ElementDetails.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/ElementDetails.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,37 +37,23 @@ */ package org.onap.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; + 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; -// public Map<String,String> details1; + 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) { -// 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; @@ -80,10 +66,12 @@ public class ElementDetails { this.enclosingContainer = enclosingContainer; } + public String getLogical_group() { + return logical_group; + } + public void setLogical_group(String logical_group) { this.logical_group = logical_group; } - - - + } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/FusionCommand.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/FusionCommand.java index 08736f0d..3ee8f642 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/FusionCommand.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/FusionCommand.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -41,17 +41,14 @@ import org.onap.portalsdk.core.FusionObject; public class FusionCommand implements FusionObject { - private String task; + private String task; - public FusionCommand() { - } + public String getTask() { + return task; + } - public String getTask() { - return task; - } - - public void setTask(String task) { - this.task = task; - } + public void setTask(String task) { + this.task = task; + } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/Layout.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/Layout.java index 957bb9af..09c8372d 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/Layout.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/Layout.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -39,36 +39,43 @@ package org.onap.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 + + Map<String, Domain> domainRowCol; + + Map<String, Domain> originalDomainRowCol; + + // Horizontal space between a pair of domains double interDomainWd; - //Vertical space between a pair of domains + // Vertical space between a pair of domains double interDomainH; - //Computing the co-ordinates of any domain + // Computing the co-ordinates of any domain int numberofRowsofDomains; - + int numberofColsofDomains; - + Map<String, Domain> collapsedDomains; - + List<Domain> collapsedDomainsNewList; - + + 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<>(); + this.originalDomainRowCol = new TreeMap<>(); + // nline + this.collapsedDomainsNewList = new ArrayList<>(); + } + public List<Domain> getCollapsedDomainsNewList() { return collapsedDomainsNewList; } @@ -93,20 +100,6 @@ public class Layout { 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; } @@ -114,60 +107,54 @@ public class Layout { 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)); + 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; + if (j == 0) p.x = domainTolayout; else - // p.x = (j+1)* interDomainWd + xsum; - p.x = j*interDomainWd + xsum + domainTolayout; + 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.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; + 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)); + 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(); + 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(); + 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; + p.y = (i + 1) * interDomainH + ysum; d.setP(p); break; } @@ -175,118 +162,80 @@ public class Layout { } } } - - + } + public Layout collapseDomainModified(String domainsToCollapse) { - - if(domainsToCollapse == null || domainsToCollapse.isEmpty()) - return null; - - Map<String,Domain> updatedRC = new HashMap<String, Domain>(); - + + if (domainsToCollapse == null || domainsToCollapse.isEmpty()) + return null; + + Map<String, Domain> updatedRC = new HashMap<>(); + 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(); - + + Map<String, Domain> updatedRCSorted = new TreeMap<>(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()); + + Map<String, Domain> updatedRCSortedTrunc = new TreeMap<>(); + + 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()); + + } 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> 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()); - + } + + for (Map.Entry<String, Domain> copyEntry : updatedRCSorted.entrySet()) { + updatedRCSortedTrunc.put(copyEntry.getKey(), 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> 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; - } - }*/ + for (Map.Entry<String, Domain> cd : updatedRC.entrySet()) { Domain d = cd.getValue(); double accountPlus = accountForPlusSpaceBefore(d); - // currDistFromLftM+= accountForPlusSpaceBefore(d); - d.setDomainToLayoutWd(currDistFromLftM+accountPlus); + d.setDomainToLayoutWd(currDistFromLftM + accountPlus); d.computeConatinerPositions(); for (Map.Entry<String, Container> entry1 : d.getContainerRowCol().entrySet()) { Container c = entry1.getValue(); @@ -296,420 +245,331 @@ public class Layout { for (Map.Entry<String, Container> entryInner : c.getContainerRowCol().entrySet()) { Container inner = entryInner.getValue(); inner.computeElementPositions(); - } + } } } - currDistFromLftM += d.computeSize().getWidth()+2; - + currDistFromLftM += d.computeSize().getWidth() + 2; } - - - - - //nline + + // nline // Insert method invocation updatePlusPosition(collapsedDomainNewL, updatedRC); - - //order changed + + // 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>(); - + + if (domainsToCollapse == null || domainsToCollapse.isEmpty()) + return null; + + Map<String, Domain> updatedRC = new HashMap<>(); + + for (Map.Entry<String, Domain> copyEntry : domainRowCol.entrySet()) { + updatedRC.put(copyEntry.getKey(), copyEntry.getValue()); + } + + Map<String, Domain> updatedRCSorted = new TreeMap<>(updatedRC); + + Map<String, Domain> collapsedDomainMap = getCollapsedDomains(); + + List<Domain> collapsedDomainNewL = getCollapsedDomainsNewList(); + + if (collapsedDomainNewL.isEmpty()) { 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()); + originalDomainRowCol.put(copyEntry.getKey(), 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<>(); + + 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()); + + } 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; } - - - 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(); - } + } + + for (Map.Entry<String, Domain> copyEntry : updatedRCSorted.entrySet()) { + updatedRCSortedTrunc.put(copyEntry.getKey(), 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> 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; + currDistFromLftM += d.computeSize().getWidth() + 1; + isDisplayed = true; + break; } } - - setCollapsedDomains(collapsedDomainMap); - setCollapsedDomainsNewList(collapsedDomainNewL); - - - computeDomainPositionsModified(); - return this; - + + 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>(); - + + Map<String, Domain> updatedRC = new HashMap<>(); + 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(); - + + Map<String, Domain> updatedRCSorted = new TreeMap<>(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()); + Map<String, Domain> updatedRCSortedTrunc = new TreeMap<>(); + 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()); + else + collapsedDomainMap.put(entry.getKey(), entry.getValue()); + prevDomXCordinate = entry.getValue().getP().getX(); + entry.getValue().getP().setX(prevDomXCordinate - 2); + setNumberofColsofDomains(getNumberofColsofDomains() - 1); + updatedRC.remove(entry.getKey()); + colToDelete = Character.getNumericValue(entry.getKey().toCharArray()[1]); + break; } - - 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()); - // } - // } + } + + setCollapsedDomains(collapsedDomainMap); + + for (Map.Entry<String, Domain> copyEntry : updatedRCSorted.entrySet()) { + updatedRCSortedTrunc.put(copyEntry.getKey(), 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> 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 : 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 { + if (collapsedDomains.size() == 2 && collapsedDomains.containsKey("00") && collapsedDomains.containsKey("01") + && domainsToCollapse.equals("RAN")) { + if (d.getName().equals("USP")) 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(); - } + else if (d.getName().equals("VNI")) + d.setDomainToLayoutWd(prevDomXCordinate + 8); + else + d.setDomainToLayoutWd(prevDomXCordinate + 10); + } 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")) { + 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")) { + 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; - } - } + Map<String, Domain> currentDomainsSorted = new TreeMap<>(domainRowCol); + Map<String, Domain> updateDomains = new TreeMap<>(); + Map<String, Domain> collapsedDomainList = getCollapsedDomains(); + Map<String, Domain> collapsedDomainListSorted = new TreeMap<>(collapsedDomainList); + + List<Domain> domainstoUpd = new ArrayList<>(); + + 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); + + 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); + 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; - } - } + if (currDomainsEnt.getValue().getName().equals(entry.getValue().getName())) { + updateDomains.put(newKey, currDomainsEnt.getValue()); + domainstoUpd.add(currDomainsEnt.getValue()); + ++lastKeyCol; + 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++) { + } + + setNumberofColsofDomains(getNumberofColsofDomains() + 1); + setDomainRowCol(updateDomains); + setCollapsedDomains(collapsedDomainList); + + 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()); + if (i + 1 < domainstoUpd.size()) + newX = 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() ; - }*/ + newX = domainstoUpd.get(i).getP().getX() + 32; + if (d.getName().equals("Datacenter with AIC")) - newX+= 2; + 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(); @@ -719,108 +579,62 @@ public class Layout { 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; - + + } + + 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++) { + Map<String, Domain> currentDomainsSorted = new TreeMap<>(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<>(); + for (Map.Entry<String, Domain> entry : collapsedDomainListSorted.entrySet()) { + if (entry.getValue().getName().equals(domainToCollapse)) { + Domain 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 (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()); + 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() ; - }*/ + newX = domainstoUpd.get(i).getP().getX() + 38; + if (d.getName().equals("Datacenter with AIC")) - newX+= 5; + 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(); @@ -830,102 +644,88 @@ public class Layout { 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; + } + + 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; - } - } + Map<String, Domain> currentDomainsSorted = new TreeMap<String, Domain>(domainRowCol); + Map<String, Domain> updateDomains = new TreeMap<String, Domain>(); + Map<String, Domain> collapsedDomainList = getCollapsedDomains(); + + List<Domain> domainstoUpd = new ArrayList<>(); + + // nline + List<Domain> collapsedDomainNewLL = getCollapsedDomainsNewList(); + + int colToUnCollapse = 99; + + Domain domainToInsert = null; + + // nline + if (collapsedDomainNewLL.isEmpty()) { + 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); + + 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); + 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; - } - } + if (currDomainsEnt.getValue().getName().equals(entry.getValue().getName())) { + updateDomains.put(newKey, currDomainsEnt.getValue()); + domainstoUpd.add(currDomainsEnt.getValue()); + ++lastKeyCol; + break; + } + } } - + } - } - - setNumberofColsofDomains(getNumberofColsofDomains()+1); + } + + 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()) { + for (Map.Entry<String, Domain> cd : updateDomains.entrySet()) { Domain d = cd.getValue(); double accountPlus = accountForPlusSpaceBefore(d); - d.setDomainToLayoutWd(currDistFromLftMargin+accountPlus); + d.setDomainToLayoutWd(currDistFromLftMargin + accountPlus); d.computeConatinerPositions(); for (Map.Entry<String, Container> entry1 : d.getContainerRowCol().entrySet()) { Container c = entry1.getValue(); @@ -935,119 +735,105 @@ public class Layout { for (Map.Entry<String, Container> entryInner : c.getContainerRowCol().entrySet()) { Container inner = entryInner.getValue(); inner.computeElementPositions(); - } + } } } - currDistFromLftMargin += d.computeSize().getWidth()+2; - + currDistFromLftMargin += d.computeSize().getWidth() + 2; + } - - //nline + + // nline updatePlusPosition(collapsedDomainNewLL, updateDomains); - - //order changed + + // order changed setCollapsedDomains(collapsedDomainList); - - //nline + + // 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; - } - } + + 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(); + + List<Domain> domainstoUpd = new ArrayList<>(); + + // nline + List<Domain> collapsedDomainNewLL = getCollapsedDomainsNewList(); + + int colToUnCollapse = 99; + + Domain domainToInsert = null; + + // nline + if (collapsedDomainNewLL.isEmpty()) { + 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); + + 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); + 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; - } - } + if (currDomainsEnt.getValue().getName().equals(entry.getValue().getName())) { + updateDomains.put(newKey, currDomainsEnt.getValue()); + domainstoUpd.add(currDomainsEnt.getValue()); + ++lastKeyCol; + break; + } + } } - + } - } - - setNumberofColsofDomains(getNumberofColsofDomains()+1); + } + + 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()) { + for (Map.Entry<String, Domain> orgEntry : originalDomainRowCol.entrySet()) { isDisplayed = false; - for (Map.Entry<String,Domain> cd : updateDomains.entrySet()) { + for (Map.Entry<String, Domain> cd : updateDomains.entrySet()) { if (cd.getValue().getName().equals(orgEntry.getValue().getName())) { Domain d = cd.getValue(); d.setDomainToLayoutWd(currDistFromLftM); @@ -1060,168 +846,112 @@ public class Layout { for (Map.Entry<String, Container> entryInner : c.getContainerRowCol().entrySet()) { Container inner = entryInner.getValue(); inner.computeElementPositions(); - } + } } } - currDistFromLftM += d.computeSize().getWidth()+1; + currDistFromLftM += d.computeSize().getWidth() + 1; isDisplayed = true; break; } } - + if (!isDisplayed) { - Domain myCollapsed = orgEntry.getValue(); + Domain myCollapsed = orgEntry.getValue(); myCollapsed.setNewXafterColl(currDistFromLftM); currDistFromLftM += 4; } } - - // plus.setNewXafterColl(distOfCollFrmLft+1.5); - - //order changed + + // order changed setCollapsedDomains(collapsedDomainList); - - //nline + + // nline setCollapsedDomainsNewList(collapsedDomainNewLL); - - + computeDomainPositionsModified(); return this; - - } - - - - - - - - - - - - - - + + } + private void updatePlusPosition(List<Domain> collapsedDNewL, Map<String, Domain> displayedDomainMap) { - List<Domain> copyCollapseList = new ArrayList<Domain>(); - + List<Domain> copyCollapseList = new ArrayList<>(); + 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; + 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; + 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()); */ - - - + distOfCollFrmLft += displayedEntry.getValue().computeSize().getWidth(); } - + } - + 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; + break; } } if (orgColofDisplayedOtherPlus < orgColofCollapsed) { - distOfCollFrmLft+=3.0; + distOfCollFrmLft += 3.0; } } } - - plus.setNewXafterColl(distOfCollFrmLft+1.5); - - + + plus.setNewXafterColl(distOfCollFrmLft + 1.5); + } } - private double accountForPlusSpaceBefore(Domain d) { - + int orgColofCollapsed = 0; - int orgColofDisplayed = 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; + break; } } - - for (Domain collapsed : getCollapsedDomainsNewList()) { + + 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; + break; } } - + if (orgColofCollapsed < orgColofDisplayed) { - distFromLftM+= 2; + distFromLftM += 2; } } return distFromLftM; - + } - + } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/NameValueId.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/NameValueId.java index cc05ea3f..eef7c27a 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/NameValueId.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/NameValueId.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -39,74 +39,67 @@ package org.onap.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; - } + private String lab; + private String val; + public NameValueId() { + // No-arg constructor + } - public void setLab(String label) { - this.lab = label; - } + public NameValueId(String value, String label) { + setVal(value); + setLab(label); + } + public String getLab() { + return lab; + } - public void setVal(String value) { - this.val = value; - } + public String getVal() { + return val; + } + public void setLab(String label) { + this.lab = label; + } - public boolean equals(Object o) { - if (this == o) { - return true; - } + public void setVal(String value) { + this.val = value; + } - if (o == null) { - return false; - } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } - if (!(o instanceof NameValueId)) { - return false; - } + if (o == null) { + return false; + } - final NameValueId nameValueId = (NameValueId)o; + if (!(o instanceof NameValueId)) { + return false; + } - if (!getVal().equals(nameValueId.getVal())) { - return false; - } + final NameValueId nameValueId = (NameValueId) o; - if (!getLab().equals(nameValueId.getLab())) { - return false; - } + if (!getVal().equals(nameValueId.getVal())) { + return false; + } - return true; - } + if (!getLab().equals(nameValueId.getLab())) { + return false; + } + return true; + } - public int hashCode() { - return getVal().hashCode(); - } + @Override + public int hashCode() { + return getVal().hashCode(); + } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/Position.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/Position.java index 29771e97..e0946d0b 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/Position.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/Position.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -40,19 +40,21 @@ package org.onap.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/onap/portalsdk/core/domain/support/Size.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/Size.java index bbaaeac3..6fcd178e 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/Size.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/domain/support/Size.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -40,19 +40,21 @@ package org.onap.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/onap/portalsdk/core/drools/DroolsRuleService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/drools/DroolsRuleService.java index 3f05af1b..1be2a7e8 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/drools/DroolsRuleService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/drools/DroolsRuleService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -38,8 +38,9 @@ package org.onap.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/onap/portalsdk/core/drools/DroolsRuleServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/drools/DroolsRuleServiceImpl.java index 85187b4c..78de0b47 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/drools/DroolsRuleServiceImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/drools/DroolsRuleServiceImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,27 +37,20 @@ */ package org.onap.portalsdk.core.drools; - /** * * This is POC test class to execute sample rules */ -public class DroolsRuleServiceImpl implements DroolsRuleService{ - - +public class DroolsRuleServiceImpl implements DroolsRuleService { + private String state; private String resultsString; - public DroolsRuleServiceImpl() { - - } - + @Override public void init(String... params) { this.state = params[0]; } - - public String getState() { return state; } @@ -66,6 +59,7 @@ public class DroolsRuleServiceImpl implements DroolsRuleService{ return "Drools POC Test"; } + @Override public String getResultsString() { return resultsString; } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/exception/FusionExceptionResolver.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/exception/FusionExceptionResolver.java index e376f318..1e605176 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/exception/FusionExceptionResolver.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/exception/FusionExceptionResolver.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -44,25 +44,30 @@ import org.springframework.web.servlet.ModelAndView; @ControllerAdvice public class FusionExceptionResolver { + private final String error = "error"; + private final String errMsg = "errMsg"; + @ExceptionHandler(UrlAccessRestrictedException.class) public ModelAndView handleUrlAccessException(UrlAccessRestrictedException ex) { - ModelAndView model = new ModelAndView("error"); - model.addObject("errMsg", ex.getMessage()); + 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()); + 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()); + 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/onap/portalsdk/core/exception/SessionExpiredException.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/exception/SessionExpiredException.java index 7d2f28ef..51521d0b 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/exception/SessionExpiredException.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/exception/SessionExpiredException.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -40,14 +40,14 @@ package org.onap.portalsdk.core.exception; import org.onap.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 static final String MESSAGE = "Your session has expired. Please login again."; - public SessionExpiredException() { - super(MESSAGE); - } + public SessionExpiredException() { + super(MESSAGE); + } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/exception/UrlAccessRestrictedException.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/exception/UrlAccessRestrictedException.java index 67bf87b0..46e785c6 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/exception/UrlAccessRestrictedException.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/exception/UrlAccessRestrictedException.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -40,14 +40,14 @@ package org.onap.portalsdk.core.exception; import org.onap.portalsdk.core.exception.support.FusionRuntimeException; public class UrlAccessRestrictedException extends FusionRuntimeException { - + /** * */ private static final long serialVersionUID = 1L; - public static final String MESSAGE = "Authorization Denied"; + public static final String MESSAGE = "Authorization Denied"; - public UrlAccessRestrictedException() { - super(MESSAGE); - } + public UrlAccessRestrictedException() { + super(MESSAGE); + } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/exception/support/FusionException.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/exception/support/FusionException.java index 012b9474..f3b27047 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/exception/support/FusionException.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/exception/support/FusionException.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -39,4 +39,5 @@ package org.onap.portalsdk.core.exception.support; import org.onap.portalsdk.core.FusionObject; -public interface FusionException extends FusionObject {} +public interface FusionException extends FusionObject { +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/exception/support/FusionRuntimeException.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/exception/support/FusionRuntimeException.java index ea0e7a13..c5f6554b 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/exception/support/FusionRuntimeException.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/exception/support/FusionRuntimeException.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -42,12 +42,13 @@ public class FusionRuntimeException extends RuntimeException implements FusionEx * */ private static final long serialVersionUID = 1L; - public FusionRuntimeException() { - this(""); - } - public FusionRuntimeException(String message) { - super(message); - } + public FusionRuntimeException() { + this(""); + } + + public FusionRuntimeException(String message) { + super(message); + } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/interceptor/ResourceInterceptor.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/interceptor/ResourceInterceptor.java index a0b88dc7..4b4d721c 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/interceptor/ResourceInterceptor.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/interceptor/ResourceInterceptor.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -79,8 +79,8 @@ public class ResourceInterceptor extends HandlerInterceptorAdapter { private AbstractCacheManager cacheManager; @Autowired - UrlAccessService urlAccessService; - + private UrlAccessService urlAccessService; + @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { @@ -98,19 +98,20 @@ public class ResourceInterceptor extends HandlerInterceptorAdapter { try { if (!webServiceCallService.verifyRESTCredential(secretKey, request.getHeader("username"), request.getHeader("password"))) { - logger.error(EELFLoggerDelegate.errorLogger, "Error accesing RESTful service. Un-authorized",AlarmSeverityEnum.MINOR); + 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; + logger.error(EELFLoggerDelegate.errorLogger, "Error authenticating RESTful service :" + e, + AlarmSeverityEnum.MINOR); + response.setStatus(HttpURLConnection.HTTP_UNAUTHORIZED); + return false; } } if (!urlAccessService.isUrlAccessible(request, url)) { - logger.error(EELFLoggerDelegate.errorLogger, "Error accesing URL. Un-authorized",AlarmSeverityEnum.MINOR); + logger.error(EELFLoggerDelegate.errorLogger, "Error accesing URL. Un-authorized", + AlarmSeverityEnum.MINOR); throw new UrlAccessRestrictedException(); } } @@ -130,7 +131,7 @@ public class ResourceInterceptor extends HandlerInterceptorAdapter { */ protected void handleSessionUpdates(HttpServletRequest request) { - App app = null; + App app; Object appObj = getCacheManager().getObject(APP_METADATA); if (appObj == null) { app = findApp(); @@ -141,12 +142,12 @@ public class ResourceInterceptor extends HandlerInterceptorAdapter { } String ecompRestURL = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL); - String decreptedPwd = ""; + String decreptedPwd = null; 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); + logger.error(EELFLoggerDelegate.errorLogger, "handleSessionUpdates failed to decrypt password", e); } PortalTimeoutHandler.handleSessionUpdatesNative(request, app.getUsername(), decreptedPwd, @@ -155,10 +156,10 @@ public class ResourceInterceptor extends HandlerInterceptorAdapter { public App findApp() { List<?> list = null; - StringBuffer criteria = new StringBuffer(); + StringBuilder criteria = new StringBuilder(); 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); + return (list == null || list.isEmpty()) ? null : (App) list.get(0); } public DataAccessService getDataAccessService() { diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/interceptor/SessionTimeoutInterceptor.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/interceptor/SessionTimeoutInterceptor.java index 2b0f0007..809266d4 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/interceptor/SessionTimeoutInterceptor.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/interceptor/SessionTimeoutInterceptor.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -56,14 +56,12 @@ import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; public class SessionTimeoutInterceptor extends HandlerInterceptorAdapter { private static final 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. + * Checks all requests for valid session information. If not found, redirects to + * a controller that will establish a valid session. */ + @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (handler instanceof HandlerMethod) { @@ -83,7 +81,7 @@ public class SessionTimeoutInterceptor extends HandlerInterceptorAdapter { 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 + // map, and with session replication the listener will // fire in all tomcat instances session.setAttribute(CollaborateListBindingListener.SESSION_ATTR_NAME, new CollaborateListBindingListener(user.getOrgUserId())); @@ -96,22 +94,25 @@ public class SessionTimeoutInterceptor extends HandlerInterceptorAdapter { 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; + // 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" + // 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; } - } + } } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/interfaces/SecurityInterface.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/interfaces/SecurityInterface.java index f6bf974f..0e03b03c 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/interfaces/SecurityInterface.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/interfaces/SecurityInterface.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/listener/ApplicationContextListener.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/listener/ApplicationContextListener.java index 4d266be4..89e9382f 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/listener/ApplicationContextListener.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/listener/ApplicationContextListener.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -40,7 +40,6 @@ package org.onap.portalsdk.core.listener; import javax.servlet.ServletContext; import javax.servlet.annotation.WebListener; -import org.onap.portalsdk.core.lm.FusionLicenseManager; import org.onap.portalsdk.core.lm.FusionLicenseManagerUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; @@ -52,14 +51,12 @@ import org.springframework.stereotype.Component; public class ApplicationContextListener implements ApplicationListener<ContextRefreshedEvent> { @Autowired - ServletContext context; + private ServletContext context; @Autowired - FusionLicenseManager lm; - @Autowired - FusionLicenseManagerUtils fusionLicenseManagerUtils; - - - public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent ) { + private FusionLicenseManagerUtils fusionLicenseManagerUtils; + + @Override + 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/onap/portalsdk/core/listener/CollaborateListBindingListener.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/listener/CollaborateListBindingListener.java index 5dcd438c..4f368eff 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/listener/CollaborateListBindingListener.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/listener/CollaborateListBindingListener.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -50,20 +50,19 @@ public class CollaborateListBindingListener implements HttpSessionBindingListene private String userName; public static final String SESSION_ATTR_NAME = "CollaborateListSessionAttrName"; - public CollaborateListBindingListener(String _userName) { - userName = _userName; + public CollaborateListBindingListener(final String userName) { + this.userName = userName; } @Override public void valueBound(HttpSessionBindingEvent event) { - final CollaborateListBindingListener value = ((CollaborateListBindingListener) event.getValue()); + final CollaborateListBindingListener value = (CollaborateListBindingListener) event.getValue(); CollaborateList.addUserName(value.getUserName()); - } @Override public void valueUnbound(HttpSessionBindingEvent event) { - final CollaborateListBindingListener value = ((CollaborateListBindingListener) event.getValue()); + final CollaborateListBindingListener value = (CollaborateListBindingListener) event.getValue(); if (value != null) CollaborateList.delUserName(value.getUserName()); } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/listener/UserSessionListener.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/listener/UserSessionListener.java index 19b1f0f2..5e6b5dba 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/listener/UserSessionListener.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/listener/UserSessionListener.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -45,36 +45,26 @@ import javax.servlet.http.HttpSessionListener; import org.onap.portalsdk.core.logging.format.AlarmSeverityEnum; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; - @WebListener -public class UserSessionListener implements HttpSessionListener{ - +public class UserSessionListener implements HttpSessionListener { + private static final 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); - } - } + + @Override + public void sessionCreated(HttpSessionEvent event) { + logger.trace(EELFLoggerDelegate.debugLogger, "sessionCreated"); + } + + /** + * 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); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "sessionDestroyed" + e.getMessage(), AlarmSeverityEnum.MINOR); + } + } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/lm/FusionLicenseManager.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/lm/FusionLicenseManager.java index 7f1f2273..1943c390 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/lm/FusionLicenseManager.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/lm/FusionLicenseManager.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -43,11 +43,8 @@ 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; @@ -66,8 +63,6 @@ public interface FusionLicenseManager { 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); diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/lm/FusionLicenseManagerUtils.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/lm/FusionLicenseManagerUtils.java index c52abf44..9fb576f5 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/lm/FusionLicenseManagerUtils.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/lm/FusionLicenseManagerUtils.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -50,42 +50,30 @@ 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) { + 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) { + } 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(); + WebApplicationContext ctx = RequestContextUtils.getWebApplicationContext(request); + return ((FusionLicenseManager) ctx.getBean("fusionLicenseManager")).getExpiredDate(); } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/lm/LicenseableClass.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/lm/LicenseableClass.java index cd49f5a5..4d14a359 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/lm/LicenseableClass.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/lm/LicenseableClass.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,20 +37,26 @@ */ package org.onap.portalsdk.core.lm; -import java.io.*; +import java.io.FileNotFoundException; +import java.io.InputStream; /** - * created by Alvin Alexander of http://devdaily.com. - * modified by Sundar Ramalingam + * 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(); - +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/onap/portalsdk/core/logging/aspect/AuditLog.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/aspect/AuditLog.java index 93075937..6a5ce910 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/aspect/AuditLog.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/aspect/AuditLog.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -42,9 +42,8 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - -@Target({ElementType.METHOD, ElementType.TYPE}) +@Target({ ElementType.METHOD, ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) public @interface AuditLog { - String value() default ""; + String value() default ""; }
\ No newline at end of file diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/aspect/EELFLoggerAdvice.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/aspect/EELFLoggerAdvice.java index 269d4b9c..779a24fc 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/aspect/EELFLoggerAdvice.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/aspect/EELFLoggerAdvice.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -105,16 +105,14 @@ public class EELFLoggerAdvice { 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]; + HttpServletRequest req = (HttpServletRequest) args[0]; logger.setRequestBasedDefaultsIntoGlobalLoggingContext(req, appName); } } - logger.debug(EELFLoggerDelegate.debugLogger, (methodName + " was invoked.")); + logger.debug(EELFLoggerDelegate.debugLogger, "{} was invoked.", methodName); } catch (Exception e) { - adviceLogger.error(EELFLoggerDelegate.errorLogger, - "Exception occurred in EELFLoggerAdvice.before() method. Details: " + e.getMessage()); + adviceLogger.error(EELFLoggerDelegate.errorLogger, "before failed", e); } return new Object[] { "" }; @@ -197,8 +195,7 @@ public class EELFLoggerAdvice { 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()); + adviceLogger.error(EELFLoggerDelegate.errorLogger, "after failed", e); } } @@ -212,7 +209,6 @@ public class EELFLoggerAdvice { 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)); @@ -224,7 +220,7 @@ public class EELFLoggerAdvice { additionalInfoAppender.append(" Request-URL:" + MDC.get(SystemProperties.FULL_URL)); } - auditMessage = AuditLogFormatter.getInstance().createMessage(MDC.get(SystemProperties.PROTOCOL), + String auditMessage = AuditLogFormatter.getInstance().createMessage(MDC.get(SystemProperties.PROTOCOL), securityEventType.name(), MDC.get(SystemProperties.MDC_LOGIN_ID), additionalInfoAppender.toString()); logger.info(EELFLoggerDelegate.auditLogger, auditMessage); @@ -243,9 +239,7 @@ public class EELFLoggerAdvice { 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()); + adviceLogger.error(EELFLoggerDelegate.errorLogger, "calculateDateTimeDifference failed", e); } } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/aspect/EELFLoggerAspect.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/aspect/EELFLoggerAspect.java index 8c958924..3ffd0894 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/aspect/EELFLoggerAspect.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/aspect/EELFLoggerAspect.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -44,20 +44,21 @@ import org.aspectj.lang.annotation.Pointcut; import org.onap.portalsdk.core.util.SystemProperties.SecurityEventTypeEnum; import org.springframework.beans.factory.annotation.Autowired; - @Aspect @org.springframework.context.annotation.Configuration public class EELFLoggerAspect { - + @Autowired - EELFLoggerAdvice advice; - + private EELFLoggerAdvice advice; + /* * Point-cut expression to handle all INCOMING_REST_MESSAGES */ @Pointcut("execution(public * org.onap.portalsdk.core.controller.*.*(..))") - public void incomingAuditMessages() {} - + public void incomingAuditMessages() { + // Nothing is logged on incoming message + } + @Around("incomingAuditMessages() && @annotation(auditLog)") public Object logAuditMethodAround(ProceedingJoinPoint joinPoint, AuditLog auditLog) throws Throwable { return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.INCOMING_REST_MESSAGE); @@ -67,40 +68,44 @@ public class EELFLoggerAspect { 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() {} - + public void publicMethod() { + // By default do nothing + } + @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()}; + + 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 + + // Execute the actual method Object result = null; String restStatus = "COMPLETE"; try { result = joinPoint.proceed(); - } catch(Exception e) { + } catch (Exception e) { restStatus = "ERROR"; } - - //After + + // After advice.after(securityEventType, restStatus, joinPoint.getArgs(), returnArgs, passOnArgs); - + return result; } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/aspect/MetricsLog.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/aspect/MetricsLog.java index 7d552774..3e089aeb 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/aspect/MetricsLog.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/aspect/MetricsLog.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -42,9 +42,8 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - -@Target({ElementType.METHOD, ElementType.TYPE}) +@Target({ ElementType.METHOD, ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) public @interface MetricsLog { - String value() default ""; + String value() default ""; } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/format/AlarmSeverityEnum.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/format/AlarmSeverityEnum.java index f2481e34..5e202475 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/format/AlarmSeverityEnum.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/format/AlarmSeverityEnum.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -38,9 +38,5 @@ package org.onap.portalsdk.core.logging.format; public enum AlarmSeverityEnum { - CRITICAL, - MAJOR, - MINOR, - INFORMATIONAL, - NONE, + CRITICAL, MAJOR, MINOR, INFORMATIONAL, NONE, } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/format/AppMessagesEnum.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/format/AppMessagesEnum.java index 84790f6b..569f9392 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/format/AppMessagesEnum.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/format/AppMessagesEnum.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -39,164 +39,213 @@ package org.onap.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."), - + * 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; @@ -205,9 +254,10 @@ public enum AppMessagesEnum { String errorDescription; String details; String resolution; - - AppMessagesEnum(ErrorCodesEnum messageCode, ErrorTypeEnum eType, AlarmSeverityEnum alarmSeverity, 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; @@ -217,30 +267,31 @@ public enum AppMessagesEnum { 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; } @@ -248,7 +299,7 @@ public enum AppMessagesEnum { public void setMessageCode(ErrorCodesEnum messageCode) { this.messageCode = messageCode; } - + public AlarmSeverityEnum getAlarmSeverity() { return alarmSeverity; } @@ -256,7 +307,7 @@ public enum AppMessagesEnum { public void setAlarmSeverity(AlarmSeverityEnum alarmSeverity) { this.alarmSeverity = alarmSeverity; } - + public ErrorTypeEnum getErrorType() { return eType; } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/format/AuditLogFormatter.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/format/AuditLogFormatter.java index 4ea932a3..d7a80ee5 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/format/AuditLogFormatter.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/format/AuditLogFormatter.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -43,51 +43,47 @@ import java.util.Map; import org.onap.portalsdk.core.util.SystemProperties; public class AuditLogFormatter { - //Singleton + // 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 ); - + + 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. + * 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 + * @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; + 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; + 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. + * 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 @@ -97,28 +93,19 @@ public class AuditLogFormatter { * @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 - }; + 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) - ); - + + 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/onap/portalsdk/core/logging/format/ErrorCodesEnum.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/format/ErrorCodesEnum.java index 6dc7e99d..9ae1fbf0 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/format/ErrorCodesEnum.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/format/ErrorCodesEnum.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -41,67 +41,37 @@ 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, - + 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"); - //} + * 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/onap/portalsdk/core/logging/format/ErrorSeverityEnum.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/format/ErrorSeverityEnum.java index 468a2b9a..83f4c1a5 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/format/ErrorSeverityEnum.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/format/ErrorSeverityEnum.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -38,8 +38,5 @@ package org.onap.portalsdk.core.logging.format; public enum ErrorSeverityEnum { - INFO, - WARN, - ERROR, - FATAL, + INFO, WARN, ERROR, FATAL, } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/format/ErrorTypeEnum.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/format/ErrorTypeEnum.java index 77477ca1..4f9962b4 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/format/ErrorTypeEnum.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/format/ErrorTypeEnum.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -38,10 +38,5 @@ package org.onap.portalsdk.core.logging.format; public enum ErrorTypeEnum { - RECOVERY, - CONFIG_ERROR, - SYSTEM_ERROR, - DATA_ERROR, - CONNECTION_PROBLEM, - AUTHENTICATION_PROBLEM + RECOVERY, CONFIG_ERROR, SYSTEM_ERROR, DATA_ERROR, CONNECTION_PROBLEM, AUTHENTICATION_PROBLEM } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/logic/EELFLoggerDelegate.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/logic/EELFLoggerDelegate.java index 2eef3793..1d3ac743 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/logic/EELFLoggerDelegate.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/logic/EELFLoggerDelegate.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -67,17 +67,18 @@ 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(); + public static final EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger(); + public static final EELFLogger applicationLogger = EELFManager.getInstance().getApplicationLogger(); + public static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger(); + public static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); + public static final EELFLogger debugLogger = EELFManager.getInstance().getDebugLogger(); + private String className; - private static ConcurrentMap<String, EELFLoggerDelegate> classMap = new ConcurrentHashMap<String, EELFLoggerDelegate>(); + private static ConcurrentMap<String, EELFLoggerDelegate> classMap = new ConcurrentHashMap<>(); - public EELFLoggerDelegate(String _className) { - super(_className); - className = _className; + public EELFLoggerDelegate(final String className) { + super(className); + this.className = className; } /** @@ -93,17 +94,17 @@ public class EELFLoggerDelegate extends SLF4jWrapper implements EELFLogger { } /** - * Gets a logger for the specified class name. If the logger does not - * already exist in the map, this creates a new logger. + * 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); + public static EELFLoggerDelegate getLogger(final String className) { + String classNameNeverNull = className == null || "".equals(className) ? EELFLoggerDelegate.class.getName() + : className; + EELFLoggerDelegate delegate = classMap.get(classNameNeverNull); if (delegate == null) { delegate = new EELFLoggerDelegate(className); classMap.put(className, delegate); @@ -355,9 +356,9 @@ public class EELFLoggerDelegate extends SLF4jWrapper implements EELFLogger { } /** - * 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. + * 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 @@ -381,7 +382,7 @@ public class EELFLoggerDelegate extends SLF4jWrapper implements EELFLogger { errorLogger.error(resolution); } } catch (Exception e) { - errorLogger.error("Failed to log the error code. Details: " + UserUtils.getStackTrace(e)); + errorLogger.error("logEcompError failed", e); } finally { MDC.remove("ErrorCode"); MDC.remove("ErrorDescription"); @@ -419,6 +420,7 @@ public class EELFLoggerDelegate extends SLF4jWrapper implements EELFLogger { MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress()); MDC.put(MDC_INSTANCE_UUID, SystemProperties.getProperty(SystemProperties.INSTANCE_UUID)); } catch (Exception e) { + errorLogger.error("setGlobalLoggingContext failed", e); } } @@ -435,9 +437,9 @@ public class EELFLoggerDelegate extends SLF4jWrapper implements EELFLogger { } /** - * 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. + * 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 @@ -453,19 +455,17 @@ public class EELFLoggerDelegate extends SLF4jWrapper implements EELFLogger { 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") + String accessingClient = req.getHeader(SystemProperties.USERAGENT_NAME); + if (accessingClient != null && !"".equals(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); + String restURL = UserUtils.getFullURL(req); if (restURL != null && restURL != "") { MDC.put(SystemProperties.FULL_URL, restURL); if (restURL.toLowerCase().contains("https")) { @@ -478,8 +478,7 @@ public class EELFLoggerDelegate extends SLF4jWrapper implements EELFLogger { // Client IPAddress i.e. IPAddress of the remote host who is making // this request. - String clientIPAddress = ""; - clientIPAddress = req.getHeader("X-FORWARDED-FOR"); + String clientIPAddress = req.getHeader("X-FORWARDED-FOR"); if (clientIPAddress == null) { clientIPAddress = req.getRemoteAddr(); } @@ -487,12 +486,12 @@ public class EELFLoggerDelegate extends SLF4jWrapper implements EELFLogger { // 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(); - } + 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/onap/portalsdk/core/menu/MenuBuilder.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/menu/MenuBuilder.java index ac1e9396..9bd8f44d 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/menu/MenuBuilder.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/menu/MenuBuilder.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -54,128 +54,118 @@ import org.springframework.beans.factory.annotation.Autowired; @SuppressWarnings("rawtypes") public class MenuBuilder implements FusionObject { - @Autowired - private DataAccessService dataAccessService; + @Autowired + private DataAccessService dataAccessService; - public MenuBuilder() { - } + @SuppressWarnings("unchecked") + public Set getMenu(String menuSetName, DataAccessService dataAccessService) { - @SuppressWarnings("unchecked") - public Set getMenu(String menuSetName, DataAccessService dataAccessService) { + Set menu = null; - Set menu = null; - MenuData root = null; + HashMap params = new HashMap(); - HashMap params = new HashMap(); + params.put("menu_set_cd", menuSetName); - 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); - // 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()) { + MenuData root = (MenuData) i.next(); + menu = root.getChildMenus(); + } - Iterator i = menuItems.iterator(); - if (i.hasNext()) { - root = (MenuData)i.next(); - menu = root.getChildMenus(); - } - - return menu; - } - - @SuppressWarnings("unchecked") - public Set getMenu(String menuSetName) { + return menu; + } - Set menu = null; - MenuData root = null; + @SuppressWarnings("unchecked") + public Set getMenu(String menuSetName) { - HashMap params = new HashMap(); + Set menu = null; - params.put("menu_set_cd", menuSetName); + HashMap params = new HashMap(); - // 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); + params.put("menu_set_cd", menuSetName); - Iterator i = menuItems.iterator(); - if (i.hasNext()) { - root = (MenuData)i.next(); - menu = root.getChildMenus(); - } + // 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); - return menu; - } + Iterator i = menuItems.iterator(); + if (i.hasNext()) { + MenuData root = (MenuData) i.next(); + menu = root.getChildMenus(); + } - public static Set filterMenu(Set menus, HttpServletRequest request) { - Iterator j = menus.iterator(); + return menu; + } - while (j.hasNext()) { - MenuData menuItem = (MenuData)j.next(); + public static Set filterMenu(Set menus, HttpServletRequest request) { + Iterator j = menus.iterator(); - 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 + while (j.hasNext()) { + MenuData menuItem = (MenuData) j.next(); - Set childMenus = menuItem.getChildMenus(); - if (childMenus != null && childMenus.size() > 0) { - filterMenu(childMenus, request); - } + 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.isEmpty()) { + filterMenu(childMenus, request); + } - return menus; - } + } + } - - public static String getUrlHtml(MenuData menuData) { - String html = ""; + return menus; + } - 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(); - } + public static String getUrlHtml(MenuData menuData) { + String html = ""; - return 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 = ""; + public static String getTargetHtml(MenuData menuData) { + String html = ""; - if (menuData.getTarget() != null && menuData.getTarget().length() > 0) { - html = "target=\"" + menuData.getTarget() + "\""; - } + if (menuData.getTarget() != null && menuData.getTarget().length() > 0) { + html = "target=\"" + menuData.getTarget() + "\""; + } - return html; - } + return html; + } + public static String getQueryStringHtml(MenuData menuData) { + String html = ""; - public static String getQueryStringHtml(MenuData menuData) { - String html = ""; + if (menuData.getQueryString() != null && menuData.getQueryString().length() > 0) { + html = "?" + menuData.getQueryString(); + } - if (menuData.getQueryString() != null && menuData.getQueryString().length() > 0) { - html = "?" + menuData.getQueryString(); - } + return html; + } - return html; - } - - public DataAccessService getDataAccessService() { + public DataAccessService getDataAccessService() { return dataAccessService; } - public void setDataAccessService(DataAccessService dataAccessService) { this.dataAccessService = dataAccessService; } } - - diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/menu/MenuProperties.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/menu/MenuProperties.java index 18f3f83e..67ea3bf6 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/menu/MenuProperties.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/menu/MenuProperties.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -45,88 +45,82 @@ import javax.servlet.ServletContext; import org.onap.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); - } + // 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("rawtypes") + private static HashMap menuProperties = new HashMap(); + + private MenuProperties() { + // cannot instantiate + } + + @SuppressWarnings("unchecked") + public static void loadFromFile(ServletContext servletContext, String filename, String menuSetName) + throws IOException { + if (filename == null) + filename = SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_PROPERTIES_NAME); + Properties p = new Properties(); + p.load(servletContext.getResourceAsStream( + SystemProperties.getProperty(SystemProperties.MENU_PROPERTIES_FILE_LOCATION) + filename)); + menuProperties.put(menuSetName, p); + } + + 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/onap/portalsdk/core/objectcache/AbstractCacheManager.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/objectcache/AbstractCacheManager.java index 8bbf34cd..16b763a1 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/objectcache/AbstractCacheManager.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/objectcache/AbstractCacheManager.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,42 +37,40 @@ */ package org.onap.portalsdk.core.objectcache; -import java.io.*; - -import org.onap.portalsdk.core.objectcache.support.*; +import java.io.IOException; +import org.onap.portalsdk.core.objectcache.support.FusionCacheManager; 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 AbstractCacheManager() { + super(); + } - public void putObject(String key, Object objectToCache) { - // TODO Auto-generated method stub - } + @Override + public Object getObject(String key) { + return null; + } - public boolean isObjectInCache(String key) { - // TODO Auto-generated method stub - return false; - } + @Override + public void putObject(String key, Object objectToCache) { + } - public void removeObject(String key) { - // TODO Auto-generated method stub - } + @Override + public boolean isObjectInCache(String key) { + return false; + } - public void clearCache() { - // TODO Auto-generated method stub - } + @Override + public void removeObject(String key) { + } - public void configure() throws IOException { - // TODO Auto-generated method stub + @Override + public void clearCache() { + } - } -} + @Override + public void configure() throws IOException { + } +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/objectcache/jcs/JCSCacheEventHandler.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/objectcache/jcs/JCSCacheEventHandler.java index 8660d9f9..71357f34 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/objectcache/jcs/JCSCacheEventHandler.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/objectcache/jcs/JCSCacheEventHandler.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -43,36 +43,46 @@ import org.apache.jcs.engine.control.event.behavior.IElementEventHandler; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; public class JCSCacheEventHandler implements IElementEventHandler, IElementEventConstants { - - private static final 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); - } - } + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JCSCacheEventHandler.class); + + public JCSCacheEventHandler() { + super(); + } + + @Override + 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); + default: + logger.error(EELFLoggerDelegate.errorLogger, "handleElementEvent: unknown event " + event); + } + } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/objectcache/jcs/JCSCacheManager.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/objectcache/jcs/JCSCacheManager.java index f169754f..2fa5e856 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/objectcache/jcs/JCSCacheManager.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/objectcache/jcs/JCSCacheManager.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -39,8 +39,9 @@ package org.onap.portalsdk.core.objectcache.jcs; import java.io.IOException; import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; import java.util.Properties; -import java.util.Vector; import javax.annotation.PostConstruct; import javax.servlet.ServletContext; @@ -60,19 +61,19 @@ public abstract class JCSCacheManager extends AbstractCacheManager implements Ca private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JCSCacheManager.class); - 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"; + public static final String LOOKUP_OBJECT_CACHE_NAME = "lookUpObjectCache"; + public static final String JCS_CONFIG_FILE_PATH = "cache_config_file_path"; + public static final String CACHE_LOAD_ON_STARTUP = "cache_load_on_startup"; + public static final String CACHE_PROPERTY_VALUE_TRUE = "true"; + public static final String CACHE_CONTROL_SWITCH_ON = "1"; + public static final String CACHE_CONTROL_SWITCH_OFF = "0"; + public static final String CACHE_CONTROL_SWITCH = "cache_switch"; - private static JCS lookUpCache; + private JCS lookUpCache; private ServletContext servletContext; private Properties cacheConfigProperties = null; - private final Vector<String> jscManagedCacheList = new Vector<String>(); + private final ArrayList<String> jscManagedCacheList = new ArrayList<>(); private DataAccessService dataAccessService; @@ -81,6 +82,7 @@ public abstract class JCSCacheManager extends AbstractCacheManager implements Ca jscManagedCacheList.add(LOOKUP_OBJECT_CACHE_NAME); } + @Override @PostConstruct public void configure() throws IOException { super.configure(); @@ -93,8 +95,8 @@ public abstract class JCSCacheManager extends AbstractCacheManager implements Ca 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); + logger.debug(EELFLoggerDelegate.debugLogger, "configure: loading cache properties from classpath resource {} ", + jcsConfigFilePath); Properties p = new Properties(); p.load(jcsConfigInputStream); jcsConfigInputStream.close(); @@ -126,6 +128,7 @@ public abstract class JCSCacheManager extends AbstractCacheManager implements Ca } } + @Override public Object getObject(String key) { if (CACHE_CONTROL_SWITCH_ON.equalsIgnoreCase(SystemProperties.getProperty(CACHE_CONTROL_SWITCH))) { if (lookUpCache == null) @@ -136,12 +139,12 @@ public abstract class JCSCacheManager extends AbstractCacheManager implements Ca return null; } + @Override 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); - } + if (CACHE_CONTROL_SWITCH_ON.equalsIgnoreCase(SystemProperties.getProperty(CACHE_CONTROL_SWITCH)) + && lookUpCache != null) { + lookUpCache.put(key, objectToCache); } } catch (CacheException ce) { logger.error(EELFLoggerDelegate.errorLogger, "putObject: failed to put the object with key " + key, ce); @@ -158,6 +161,7 @@ public abstract class JCSCacheManager extends AbstractCacheManager implements Ca } } + @Override public void clearCache() { clearCache(LOOKUP_OBJECT_CACHE_NAME); } @@ -181,7 +185,7 @@ public abstract class JCSCacheManager extends AbstractCacheManager implements Ca this.cacheConfigProperties = cacheConfigProperties; } - public Vector<String> getJscManagedCacheList() { + public List<String> getJscManagedCacheList() { return jscManagedCacheList; } @@ -197,6 +201,7 @@ public abstract class JCSCacheManager extends AbstractCacheManager implements Ca return servletContext; } + @Override public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/objectcache/support/FusionCacheManager.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/objectcache/support/FusionCacheManager.java index e2a8ca14..af8b24b7 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/objectcache/support/FusionCacheManager.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/objectcache/support/FusionCacheManager.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,18 +37,21 @@ */ package org.onap.portalsdk.core.objectcache.support; -import java.io.*; +import java.io.IOException; import org.onap.portalsdk.core.FusionObject; public interface FusionCacheManager extends FusionObject { - Object getObject(String key); - void putObject(String key, Object objectToCache); - boolean isObjectInCache(String key); + Object getObject(String key); - void removeObject(String key); - void clearCache(); - void configure() throws IOException; -} + 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/onap/portalsdk/core/onboarding/client/AppContextManager.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/client/AppContextManager.java index a446c435..02452506 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/client/AppContextManager.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/client/AppContextManager.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -42,22 +42,21 @@ 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. + * Use this class to get access to ApplicationContext for classes that were not + * created by Spring. */ - @Component -public class AppContextManager implements ApplicationContextAware{ - private static ApplicationContext _appCtx; +public class AppContextManager implements ApplicationContextAware { + + private static ApplicationContext appContext; - @Override - public void setApplicationContext(ApplicationContext ctx){ - _appCtx = ctx; - } + @Override + public void setApplicationContext(final ApplicationContext ctx) { + this.appContext = ctx; + } - public static ApplicationContext getAppContext(){ - return _appCtx; - } + public static ApplicationContext getAppContext() { + return appContext; + } }
\ No newline at end of file diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/session/TestClass.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/session/TestClass.java deleted file mode 100644 index ff21d641..00000000 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/session/TestClass.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * ============LICENSE_START========================================== - * ONAP Portal SDK - * =================================================================== - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * =================================================================== - * - * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); - * you may not use this software except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); - * you may not use this documentation except in compliance with the License. - * You may obtain a copy of the License at - * - * https://creativecommons.org/licenses/by/4.0/ - * - * Unless required by applicable law or agreed to in writing, documentation - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================ - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ -package org.onap.portalsdk.core.onboarding.session; - -public class TestClass { - -} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/sso/TestClass.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/sso/TestClass.java deleted file mode 100644 index 0bf193eb..00000000 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/sso/TestClass.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * ============LICENSE_START========================================== - * ONAP Portal SDK - * =================================================================== - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * =================================================================== - * - * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); - * you may not use this software except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); - * you may not use this documentation except in compliance with the License. - * You may obtain a copy of the License at - * - * https://creativecommons.org/licenses/by/4.0/ - * - * Unless required by applicable law or agreed to in writing, documentation - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================ - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ -package org.onap.portalsdk.core.onboarding.sso; - -public class TestClass { - -} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/Consumer.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/Consumer.java index 6f76d1aa..be8e71f8 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/Consumer.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/Consumer.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -39,9 +39,9 @@ package org.onap.portalsdk.core.onboarding.ueb; import java.io.IOException; import java.security.GeneralSecurityException; -import java.util.LinkedList; +import java.util.List; +import java.util.Queue; import java.util.UUID; -import java.util.concurrent.ConcurrentLinkedQueue; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -60,14 +60,17 @@ 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 List<String> urlList = Helper.uebUrlList(); + private final Queue<UebMsg> queue; private final WaitingRequestersQueueList waitingRequestersList; - private final String consumerKey, consumerSecret, topicName, consumerGroupName; + private final String consumerKey; + private final String consumerSecret; + private final String topicName; + private final String consumerGroupName; /** - * Accepts coordinates needed to subscribe to a UEB topic, as well as the - * queues for passing along messages that arrive. + * 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 @@ -75,16 +78,18 @@ public class Consumer implements Runnable { * UEB secret used to subscribe to the topic * @param topicName * UEB topic name + * @param consumerGroupName + * consumer group name * @param queue - * Queue to receive UEB messages. All inbound messages are - * enqueued here; ignored if null. + * 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. + * 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) { + Queue<UebMsg> queue, WaitingRequestersQueueList waitingRequestersList) { this.consumerKey = consumerKey; this.consumerSecret = consumerSecret; this.topicName = topicName; @@ -98,28 +103,21 @@ public class Consumer implements Runnable { * 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. + * <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. + * 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(); + CambriaConsumer 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()) { @@ -133,17 +131,16 @@ public class Consumer implements Runnable { // listener queue. queue.add(uebMsg); if (logger.isDebugEnabled()) - logger.debug("Added msg to queue " + this.queue + " queue count = " + queue.size() + " msg :" - + uebMsg.getPayload()); + logger.debug("Added msg to queue " + this.queue + " msg :" + uebMsg.getPayload()); } - if (waitingRequestersList != null && uebMsg.getMsgId() != null) { + if (waitingRequestersList != null // + && uebMsg.getMsgId() != null // + && !(uebMsg.getMsgId() + .equals(PortalApiProperties.getProperty(PortalApiConstants.ECOMP_DEFAULT_MSG_ID)))) { // 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); - } + waitingRequestersList.addMsg(uebMsg.getMsgId(), uebMsg); } } if (Thread.interrupted()) { diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/FunctionalMenu.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/FunctionalMenu.java index 29a3b567..6f9ffd4a 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/FunctionalMenu.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/FunctionalMenu.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -61,18 +61,17 @@ public class FunctionalMenu { 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); + UebMsg 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; } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/Helper.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/Helper.java index 02f64bd4..be1a686b 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/Helper.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/Helper.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -38,6 +38,7 @@ package org.onap.portalsdk.core.onboarding.ueb; import java.util.LinkedList; +import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -45,7 +46,7 @@ import org.onap.portalsdk.core.onboarding.util.PortalApiConstants; import org.onap.portalsdk.core.onboarding.util.PortalApiProperties; /** - * Provides utility methods. + * Provides utility methods. */ public class Helper { @@ -57,17 +58,16 @@ public class Helper { * * @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()); - } + public static List<String> uebUrlList() { + String url = PortalApiProperties.getProperty(PortalApiConstants.UEB_URL_LIST); + if (url == null) { + logger.error("uebUrlList: failed to get property " + PortalApiConstants.UEB_URL_LIST); + return new LinkedList<String>(); + } + LinkedList<String> urlList = new LinkedList<>(); + for (String u : url.split(",")) { + urlList.add(u.trim()); + } return urlList; } @@ -75,7 +75,7 @@ public class Helper { try { Thread.sleep(milliseconds); } catch (InterruptedException e) { - e.printStackTrace(); + logger.warn("sleep was interrupted", e); } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/Publisher.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/Publisher.java index 9536fee8..b73b0110 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/Publisher.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/Publisher.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -40,7 +40,7 @@ package org.onap.portalsdk.core.onboarding.ueb; import java.io.IOException; import java.net.MalformedURLException; import java.security.GeneralSecurityException; -import java.util.LinkedList; +import java.util.List; import java.util.concurrent.TimeUnit; import org.apache.commons.logging.Log; @@ -56,13 +56,13 @@ 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. + * 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(); + protected final List<String> urlList = Helper.uebUrlList(); private final String topicName; private final String publisherKey; @@ -86,11 +86,11 @@ public class Publisher { } /** - * 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. + * 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. @@ -103,12 +103,9 @@ public class Publisher { 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) { + pub = new CambriaClientBuilders.PublisherBuilder().authenticatedBy(publisherKey, publisherSecret) + .usingHosts(urlList).onTopic(topicName).build(); + } catch (MalformedURLException | GeneralSecurityException e1) { logger.error("pub.build Exception ", e1); throw new UebException(PortalApiConstants.ECOMP_UEB_UNKNOWN_PUBLISH_ERROR, e1, topicName, null, msg); } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/PublisherList.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/PublisherList.java index 0556e045..d7dbb323 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/PublisherList.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/PublisherList.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -56,17 +56,16 @@ public class PublisherList { private final Log logger = LogFactory.getLog(getClass()); private final Map<String, Publisher> map; - + public PublisherList() { - map = new ConcurrentHashMap<>(); + map = new ConcurrentHashMap<>(); } - + public void addPublisherToMap(String topicName, Publisher publisher) { - if (this.map.containsKey(topicName)) { + if (this.map.containsKey(topicName)) logger.error("Publisher already exists for " + topicName); - } else { + else this.map.put(topicName, publisher); - } } public Publisher getPublisher(String topicName) { @@ -77,14 +76,13 @@ public class PublisherList { this.map.remove(topicName); } + @Override public String toString() { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); 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); - } + for (Map.Entry<String, Publisher> entry : this.map.entrySet()) + sb.append("Entry msgId, " + entry.getKey() + " publisher" + entry.getValue()); + return sb.toString(); } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/TopicManager.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/TopicManager.java index a19e2de6..36f259e8 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/TopicManager.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/TopicManager.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -39,7 +39,7 @@ package org.onap.portalsdk.core.onboarding.ueb; import java.io.IOException; import java.security.GeneralSecurityException; -import java.util.LinkedList; +import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -55,7 +55,7 @@ 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. + * Utilizes UEB/Cambria subscriber/publisher messaging service. */ public class TopicManager { @@ -78,25 +78,24 @@ public class TopicManager { */ public void createTopic(String key, String secret, String topicName, String topicDescription) throws HttpException, CambriaApiException, IOException { - final LinkedList<String> urlList = Helper.uebUrlList(); + final List<String> urlList = Helper.uebUrlList(); if (logger.isInfoEnabled()) { logger.info("==> createTopic"); logger.info("topicName: " + topicName); logger.info("topicDescription: " + topicDescription); } - CambriaTopicManager tm =null; + CambriaTopicManager tm = null; try { tm = CambriaClientFactory.createTopicManager(null, urlList, key, secret); } catch (GeneralSecurityException e) { - logger.error("pub.build Exception ", 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. + * Modifies the specified topic to accept a subscriber using the specified key. * * @param topicOwnerKey * @param topicOwnerSecret @@ -109,10 +108,11 @@ public class TopicManager { 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(); + final List<String> urlList = Helper.uebUrlList(); CambriaTopicManager tm = null; try { - tm = new CambriaClientBuilders.TopicManagerBuilder().usingHosts(urlList).authenticatedBy(topicOwnerKey, topicOwnerSecret).build(); + tm = new CambriaClientBuilders.TopicManagerBuilder().usingHosts(urlList) + .authenticatedBy(topicOwnerKey, topicOwnerSecret).build(); tm.allowConsumer(topicName, subscriberKey); } catch (Exception e) { // TODO Auto-generated catch block @@ -121,8 +121,7 @@ public class TopicManager { } /** - * Modifies the specified topic to accept a publisher using the specified - * key. + * Modifies the specified topic to accept a publisher using the specified key. * * @param topicOwnerKey * @param topicOwnerSecret @@ -137,13 +136,13 @@ public class TopicManager { 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; + final List<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); + 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/onap/portalsdk/core/onboarding/ueb/UebException.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/UebException.java index 462345ee..61d67295 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/UebException.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/UebException.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -43,15 +43,20 @@ package org.onap.portalsdk.core.onboarding.ueb; public class UebException extends Exception { private static final long serialVersionUID = 1L; - private String topicName = null; - private String msgId = null; - private String msg = null; + private final String topicName; + private final String msgId; + private final String msg; + + public UebException(Throwable ex) { + this(null, ex); + } + + public UebException(String msg, Throwable ex) { + this(null, ex, null, null, msg); + } public UebException(String errorMsg, String topicName, String msgId, String msg) { - super(errorMsg); - this.topicName = topicName; - this.msgId = msgId; - this.msg = msg; + this(errorMsg, null, topicName, msgId, msg); } public UebException(String errorMsg, Throwable ex, String topicName, String msgId, String msg) { @@ -61,14 +66,6 @@ public class UebException extends Exception { this.msg = msg; } - public UebException(String msg, Throwable ex) { - super(msg, ex); - } - - public UebException(Throwable ex) { - super(ex); - } - public String getUebMsg() { return this.msg; } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/UebManager.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/UebManager.java index 1608add1..235746e5 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/UebManager.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/UebManager.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -39,8 +39,8 @@ package org.onap.portalsdk.core.onboarding.ueb; import java.io.IOException; import java.util.List; +import java.util.Queue; import java.util.UUID; -import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.LinkedBlockingQueue; import org.apache.commons.logging.Log; @@ -68,11 +68,9 @@ public class UebManager { private Publisher appPublisher; private Thread listenerThread; - private boolean bThisIsEcompPortalServer = false; /** - * Constructor initializes fields and validates values obtained from - * properties. + * 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: @@ -115,11 +113,12 @@ public class UebManager { 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) + if (uebUrlList == null || uebUrlList.isEmpty()) 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); + consumerGroupName = PortalApiConstants.UEB_APP_CONSUMER_GROUP_NAME_GENERATOR.equals(consGrp) + ? UUID.randomUUID().toString() + : consGrp; } /** @@ -152,8 +151,9 @@ public class UebManager { * @param inboxQueue * Queue supplied to the consumer. If not null, the consumer will * enqueue every message it receives. + * @throws UebException */ - public void initListener(ConcurrentLinkedQueue<UebMsg> inboxQueue) throws UebException { + public void initListener(Queue<UebMsg> inboxQueue) throws UebException { waitingRequestersQueueList = new WaitingRequestersQueueList(); Consumer runnable = new Consumer(appUebKey, appUebSecret, inTopicName, consumerGroupName, inboxQueue, waitingRequestersQueueList); @@ -167,13 +167,13 @@ public class UebManager { /* * 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. + * 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; + // This is ECOMP POrtal server.1 } else { appPublisher = new Publisher(appUebKey, appUebSecret, outTopicName); Helper.sleep(400); @@ -181,9 +181,9 @@ public class UebManager { } /** - * 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 + * 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 */ @@ -196,8 +196,8 @@ public class UebManager { /** * 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 + * This should only be called by the ECOMP Portal App, other Apps have just one + * publisher and use appPublisher * * @param topicName */ @@ -207,8 +207,8 @@ public class UebManager { } /** - * Adds the default ECOMP message ID to the message and sends the message to - * the topic. + * Adds the default ECOMP message ID to the message and sends the message to the + * topic. * * @param msg * @throws UebException @@ -230,8 +230,7 @@ public class UebManager { } /** - * Sends the message using the appropriate publisher for the specified - * topic. + * Sends the message using the appropriate publisher for the specified topic. * * @param msg * @param topicName @@ -246,8 +245,7 @@ public class UebManager { } /** - * Publishes a reply using the appropriate publisher for the specified - * topic. + * Publishes a reply using the appropriate publisher for the specified topic. * * @param msg * @param topicName @@ -262,9 +260,9 @@ public class UebManager { } /** - * 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. + * 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 @@ -281,10 +279,10 @@ public class UebManager { msg.putMsgId(UUID.randomUUID().toString()); /* - * Create a queue for this request, the consumer thread will insert - * the reply on this queue + * Create a queue for this request, the consumer thread will insert the reply on + * this queue */ - LinkedBlockingQueue<UebMsg> replyQueue = new LinkedBlockingQueue<UebMsg>(); + LinkedBlockingQueue<UebMsg> replyQueue = new LinkedBlockingQueue<>(); waitingRequestersQueueList.addQueueToMap(msg.getMsgId(), replyQueue); /* @@ -332,8 +330,8 @@ public class UebManager { } /** - * Sends the specified message using the publisher appropriate for the - * specified topic name, and waits for a reply. + * Sends the specified message using the publisher appropriate for the specified + * topic name, and waits for a reply. * * @param msg * @param topicName diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/UebMsg.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/UebMsg.java index b05fae68..a393823a 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/UebMsg.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/UebMsg.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -63,17 +63,16 @@ public class UebMsg { private String sourceHostName; /** - * Creates a new object and populates the fields source IP, source topic, - * time stamp, version, and message id. + * 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) { + logger.warn("UebMsg::ctor failed", e); sourceHostName = "unknown"; sourceIP = "unknown"; } @@ -82,7 +81,7 @@ public class UebMsg { 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); + 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); } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/UebMsgTypes.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/UebMsgTypes.java index ba94cdc9..da4f4f0e 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/UebMsgTypes.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/UebMsgTypes.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/WaitingRequestersQueueList.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/WaitingRequestersQueueList.java index 768f1beb..5e2ee5d6 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/WaitingRequestersQueueList.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/onboarding/ueb/WaitingRequestersQueueList.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -52,6 +52,7 @@ import org.apache.commons.logging.LogFactory; * 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; @@ -59,7 +60,7 @@ public class WaitingRequestersQueueList { public WaitingRequestersQueueList() { map = new ConcurrentHashMap<>(); } - + public void addQueueToMap(String msgId, LinkedBlockingQueue<UebMsg> queue) { this.map.put(msgId, queue); } @@ -77,13 +78,12 @@ public class WaitingRequestersQueueList { this.map.remove(msgId); } + @Override public String toString() { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); 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); + sb.append("Entry msgId, " + entry.getKey() + " queue " + entry.getValue()); } return sb.toString(); } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/restful/client/HttpStatusAndResponse.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/restful/client/HttpStatusAndResponse.java index 7caba3d8..47a35d4f 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/restful/client/HttpStatusAndResponse.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/restful/client/HttpStatusAndResponse.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/restful/client/PortalRestClientBase.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/restful/client/PortalRestClientBase.java index 5ccb715b..2c4da43d 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/restful/client/PortalRestClientBase.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/restful/client/PortalRestClientBase.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -39,13 +39,9 @@ package org.onap.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; @@ -56,6 +52,7 @@ import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.onap.portalsdk.core.domain.App; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.onboarding.exception.CipherUtilException; import org.onap.portalsdk.core.onboarding.util.CipherUtil; import org.onap.portalsdk.core.onboarding.util.PortalApiConstants; import org.onap.portalsdk.core.onboarding.util.PortalApiProperties; @@ -80,7 +77,7 @@ public class PortalRestClientBase { private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalRestClientBase.class); @Autowired - AppService appService; + private AppService appService; /** * Constructs and sends a GET request for the URI, with REST application @@ -89,47 +86,45 @@ public class PortalRestClientBase { * @param uri * URI of the service * @return Result of the get; null if an error happens - * @throws Exception + * @throws CipherUtilException + * If the app password cannot be decrypted + * @throws IOException + * If the remote end cannot be contacted */ - public HttpStatusAndResponse getRestWithCredentials(final URI uri) throws Exception { + public HttpStatusAndResponse getRestWithCredentials(final URI uri) throws CipherUtilException, IOException { 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 IllegalArgumentException("Missing one or more required properties and/or database entries"); + throw new IllegalArgumentException( + "getRestWithCredentials: 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; + logger.info(EELFLoggerDelegate.debugLogger, "getRestWithCredentials: URL {}", uri); 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()); + logger.debug(EELFLoggerDelegate.debugLogger, "getRestWithCredentials: status " + response.getStatusLine()); HttpEntity entity = response.getEntity(); if (entity == null) { - logger.info(EELFLoggerDelegate.debugLogger, "Entity is null!"); + logger.debug(EELFLoggerDelegate.debugLogger, "getRestWithCredentials: 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); + logger.debug(EELFLoggerDelegate.debugLogger, "getRestWithCredentials: JSON {}", responseJson); EntityUtils.consume(entity); } } finally { if (response != null) response.close(); - if (httpClient != null) - httpClient.close(); } - if (response == null) - return null; + httpClient.close(); return new HttpStatusAndResponse(response.getStatusLine().getStatusCode(), responseJson); } @@ -142,49 +137,49 @@ public class PortalRestClientBase { * @param json * Content to post * @return Result of the post; null if an error happens - * @throws Exception + * @throws CipherUtilException + * If the app password cannot be decrypted + * @throws IOException + * If the remote end cannot be contacted */ - public HttpStatusAndResponse postRestWithCredentials(final URI uri, final String json) throws Exception { + public HttpStatusAndResponse postRestWithCredentials(final URI uri, final String json) + throws CipherUtilException, IOException { 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"); - + throw new IllegalArgumentException( + "postRestWithCredentials: missing one or more required properties and/or database entries"); + String decryptedPassword = CipherUtil.decrypt(app.getAppPassword()); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(uri); httpPost.setHeader("uebkey", uebKey); httpPost.setHeader("username", app.getUsername()); - httpPost.setHeader("password", app.getAppPassword()); - + httpPost.setHeader("password", decryptedPassword); 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); + logger.debug(EELFLoggerDelegate.debugLogger, "postRestWithCredentials: 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()); - + logger.debug(EELFLoggerDelegate.debugLogger, "postRestWithCredentials: status {} ", + response.getStatusLine()); HttpEntity entity = response.getEntity(); if (entity == null) { - logger.info(EELFLoggerDelegate.debugLogger, "Entity is null!"); + logger.debug(EELFLoggerDelegate.debugLogger, "postRestWithCredentials: 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); + logger.debug(EELFLoggerDelegate.debugLogger, "postRestWithCredentials: JSON {}", responseJson); EntityUtils.consume(entity); } } finally { if (response != null) response.close(); - if (httpClient != null) - httpClient.close(); } + httpClient.close(); return new HttpStatusAndResponse(response.getStatusLine().getStatusCode(), responseJson); } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/restful/client/SharedContextRestClient.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/restful/client/SharedContextRestClient.java index 89ebbe5a..e58a1957 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/restful/client/SharedContextRestClient.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/restful/client/SharedContextRestClient.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,23 +37,23 @@ */ package org.onap.portalsdk.core.restful.client; +import java.io.IOException; import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.http.client.utils.URIBuilder; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.onboarding.exception.CipherUtilException; import org.onap.portalsdk.core.onboarding.util.PortalApiConstants; import org.onap.portalsdk.core.onboarding.util.PortalApiProperties; import org.onap.portalsdk.core.restful.domain.SharedContext; -import org.onap.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; /** @@ -82,13 +82,13 @@ public class SharedContextRestClient extends PortalRestClientBase { * 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 + * @throws IllegalArgumentException + * if the ECOMP_REST_URL property is not found */ - private String getSharedContextUrl() throws Exception { + private String getSharedContextUrl() throws IllegalArgumentException { String restUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL); if (restUrl == null || restUrl.length() == 0) - throw new Exception("getSharedContextUrl: no property " + PortalApiConstants.ECOMP_REST_URL); + throw new IllegalArgumentException("getSharedContextUrl: no property " + PortalApiConstants.ECOMP_REST_URL); String contextUrl = restUrl + (restUrl.endsWith("/") ? "" : "/") + "context/"; return contextUrl; } @@ -102,6 +102,7 @@ public class SharedContextRestClient extends PortalRestClientBase { * Key for the shared-context entry; e.g., "lastName" * @return SharedContext object; null if not found. * @throws Exception + * If URI cannot be built, host cannot be reached, etc. */ public SharedContext getContextValue(String contextId, String key) throws Exception { HttpStatusAndResponse hsr = getContext("get", contextId, key); @@ -110,16 +111,8 @@ public class SharedContextRestClient extends PortalRestClientBase { 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()); - } + SharedContext jsonObj = mapper.readValue(hsr.getResponse(), SharedContext.class); + // Response means no data. if (jsonObj != null && jsonObj.getResponse() != null) return null; return jsonObj; @@ -130,37 +123,28 @@ public class SharedContextRestClient extends PortalRestClientBase { * * @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. + * @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 + * If URI cannot be built, host cannot be reached, etc. */ 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 new ArrayList<>(); } + TypeReference<List<SharedContext>> typeRef = new TypeReference<List<SharedContext>>() { + }; + List<SharedContext> jsonList = mapper.readValue(hsr.getResponse(), typeRef); return jsonList; } /** - * Checks whether a shared-context entry exists for the specified context ID - * and key. + * Checks whether a shared-context entry exists for the specified context ID and + * key. * * @param contextId * An Ecomp Portal session ID @@ -168,6 +152,7 @@ public class SharedContextRestClient extends PortalRestClientBase { * Key for the shared-context entry; e.g., "lastName" * @return True if the object exists, false otherwise; null on error. * @throws Exception + * If URI cannot be built, host cannot be reached, etc. */ public Boolean checkSharedContext(String contextId, String key) throws Exception { HttpStatusAndResponse hsr = getContext("check", contextId, key); @@ -176,20 +161,11 @@ public class SharedContextRestClient extends PortalRestClientBase { 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()); - } + SharedContext jsonObj = mapper.readValue(hsr.getResponse(), SharedContext.class); + String response = jsonObj.getResponse(); if (response == null) return null; - return ("exists".equals(response)); + return "exists".equals(response); } /** @@ -201,6 +177,7 @@ public class SharedContextRestClient extends PortalRestClientBase { * Key for the shared-context entry; e.g., "lastName" * @return True if the entry was removed, false otherwise; null on error. * @throws Exception + * If URI cannot be built, host cannot be reached, etc. */ public Boolean removeSharedContext(String contextId, String key) throws Exception { HttpStatusAndResponse hsr = getContext("remove", contextId, key); @@ -209,20 +186,11 @@ public class SharedContextRestClient extends PortalRestClientBase { 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()); - } + SharedContext jsonObj = mapper.readValue(hsr.getResponse(), SharedContext.class); if (jsonObj == null) return null; String response = jsonObj.getResponse(); - return ("removed".equals(response)); + return "removed".equals(response); } /** @@ -231,9 +199,10 @@ public class SharedContextRestClient extends PortalRestClientBase { * * @param contextId * An Ecomp Portal session ID - * @return Number of key-value pairs removed; -1 if not found or any - * problems occur. + * @return Number of key-value pairs removed; -1 if not found or any problems + * occur. * @throws Exception + * If URI cannot be built, host cannot be reached, etc. */ public int clearSharedContext(String contextId) throws Exception { HttpStatusAndResponse hsr = getContext("remove", contextId, null); @@ -242,16 +211,7 @@ public class SharedContextRestClient extends PortalRestClientBase { 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()); - } + SharedContext jsonObj = mapper.readValue(hsr.getResponse(), SharedContext.class); if (jsonObj == null) return -1; String response = jsonObj.getResponse(); @@ -269,9 +229,10 @@ public class SharedContextRestClient extends PortalRestClientBase { * Key for the shared-context entry; e.g., "lastName" * @param value * Value for the entry + * @return True if the object previously existed, false otherwise; null if any + * problem happened. * @throws Exception - * @return True if the object previously existed, false otherwise; null if - * any problem happened. + * If URI cannot be built, host cannot be reached, etc. */ public Boolean setSharedContext(String contextId, String key, String value) throws Exception { String body = buildContext(contextId, key, value); @@ -281,33 +242,28 @@ public class SharedContextRestClient extends PortalRestClientBase { 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()); - } + SharedContext jsonObj = mapper.readValue(hsr.getResponse(), SharedContext.class); if (jsonObj == null) return null; String response = jsonObj.getResponse(); - return ("replaced".equals(response)); + return "replaced".equals(response); } /** - * Builds the full URL with the specified parameters, then calls the method - * that adds credentials and GETs. + * 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 + * @throws URISyntaxException + * @throws IllegalArgumentException + * @throws IOException + * @throws CipherUtilException */ - private HttpStatusAndResponse getContext(String requestPath, String contextId, String contextKey) throws Exception { + private HttpStatusAndResponse getContext(String requestPath, String contextId, String contextKey) + throws IllegalArgumentException, URISyntaxException, CipherUtilException, IOException { URIBuilder uriBuilder = new URIBuilder(getSharedContextUrl() + requestPath); uriBuilder.addParameter("context_id", contextId); if (contextKey != null) @@ -317,16 +273,19 @@ public class SharedContextRestClient extends PortalRestClientBase { } /** - * Builds the full URL, then calls the method that adds credentials and - * POSTs. + * 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 + * @throws IOException + * @throws CipherUtilException + * @throws URISyntaxException + * @throws IllegalArgumentException */ - private HttpStatusAndResponse postContext(String requestPath, String json) throws Exception { + private HttpStatusAndResponse postContext(String requestPath, String json) + throws CipherUtilException, IOException, IllegalArgumentException, URISyntaxException { URIBuilder uriBuilder = new URIBuilder(getSharedContextUrl() + requestPath); URI uri = uriBuilder.build(); return postRestWithCredentials(uri, json); @@ -344,8 +303,7 @@ public class SharedContextRestClient extends PortalRestClientBase { * @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>(); + HashMap<String, String> stringMap = new HashMap<>(); stringMap.put("context_id", cxid); stringMap.put("ckey", ckey); stringMap.put("cvalue", cvalue); @@ -355,9 +313,6 @@ public class SharedContextRestClient extends PortalRestClientBase { // 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/onap/portalsdk/core/scheduler/CoreRegister.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/scheduler/CoreRegister.java index 68907d3d..d37b0d13 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/scheduler/CoreRegister.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/scheduler/CoreRegister.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -49,60 +49,35 @@ import org.springframework.context.annotation.DependsOn; import org.springframework.stereotype.Component; @Component -@DependsOn({"systemProperties"}) +@DependsOn({ "systemProperties" }) public class CoreRegister { private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CoreRegister.class); - - Trigger trigger[] = new Trigger[1]; - protected List<Trigger> scheduleTriggers = new ArrayList<Trigger>(); + protected List<Trigger> scheduleTriggers = new ArrayList<>(); 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 - + 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) { + if (SystemProperties.getProperty(cron) != null) { getScheduleTriggers().add(cronRegistryTrigger); } - - } catch(IllegalStateException ies) { + } 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/onap/portalsdk/core/scheduler/CronRegistry.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/scheduler/CronRegistry.java index 3b1c7030..3e805f3e 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/scheduler/CronRegistry.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/scheduler/CronRegistry.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -49,94 +49,89 @@ import org.springframework.scheduling.quartz.QuartzJobBean; import com.mchange.v2.c3p0.ComboPooledDataSource; -public abstract class CronRegistry { - +public abstract class CronRegistry { + private static final 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()); + jobDetailFactoryBean(); + cronTriggerFactoryBean(); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "CronRegistry::ctor 1 failed", e); } } - - //@Autowired + + // @Autowired public CronRegistry(ComboPooledDataSource dataSource) { try { - this.dataSource = dataSource; - jobDetailFactoryBean(); - cronTriggerFactoryBean(); - } - catch(Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AlarmSeverityEnum.MAJOR); + this.dataSource = dataSource; + jobDetailFactoryBean(); + cronTriggerFactoryBean(); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AlarmSeverityEnum.MAJOR); } } - - //@Autowired + + // @Autowired public CronRegistry(Object... initializeObjects) { try { initializeObjects(initializeObjects); jobDetailFactoryBean(); cronTriggerFactoryBean(); - } - catch(Exception e) { - logger.info(EELFLoggerDelegate.errorLogger, e.getMessage()); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "CronRegistry::ctor 3 failed", e); } } - - protected void initializeObjects(Object... initializeObjects) { + + 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 { + + 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.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/onap/portalsdk/core/scheduler/Registerable.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/scheduler/Registerable.java index 33af9d1a..83480910 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/scheduler/Registerable.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/scheduler/Registerable.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -40,9 +40,9 @@ package org.onap.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/onap/portalsdk/core/service/AccessConfiguration.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AccessConfiguration.java index d369199d..9feeb3a2 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AccessConfiguration.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AccessConfiguration.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AppService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AppService.java index 6ca1d013..07d8fec7 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AppService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AppService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -68,10 +68,11 @@ public interface AppService { * FN_APP table. */ App getDefaultApp(); - + /** - * Fetches the application name once from database - * and keep refers to the same name later on as required. + * 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/onap/portalsdk/core/service/AppServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AppServiceImpl.java index 179b0864..e0f8fc24 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AppServiceImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AppServiceImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -47,19 +47,18 @@ import org.springframework.transaction.annotation.Transactional; @Service("appService") @Transactional -public class AppServiceImpl implements AppService{ +public class AppServiceImpl implements AppService { private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppServiceImpl.class); - + @Autowired - private DataAccessService dataAccessService; + private DataAccessService dataAccessService; /** - * Loads the appName once from database and - * keep refers to it as required. + * Loads the appName once from database and keep refers to it as required. */ private static String defaultAppName = ""; - + @SuppressWarnings("unchecked") @Override public List<App> getApps() { @@ -68,16 +67,17 @@ public class AppServiceImpl implements AppService{ @Override public App getApp(Long appId) { - return (App)getDataAccessService().getDomainObject(App.class, appId, null); + return (App) getDataAccessService().getDomainObject(App.class, appId, null); } @Override public App getDefaultApp() { return getApp(1L); } - + /** * Gets the data access service. + * * @return DataAccessService */ public DataAccessService getDataAccessService() { @@ -86,25 +86,28 @@ public class AppServiceImpl implements AppService{ /** * 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. + * 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=="") { + if (AppServiceImpl.defaultAppName == null || AppServiceImpl.defaultAppName == "") { App app = getApp(1L); - if (app!=null) { - AppServiceImpl.defaultAppName = app.getName(); + if (app != null) { + AppServiceImpl.defaultAppName = app.getName(); } else { - logger.warn(EELFLoggerDelegate.errorLogger, ("Unable to locate the app information from the database.")); + 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/onap/portalsdk/core/service/AuditService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AuditService.java index ec0c7ce7..40fc2f08 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AuditService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AuditService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,7 +37,7 @@ */ package org.onap.portalsdk.core.service; -import java.util.HashMap; +import java.util.Map; import org.onap.portalsdk.core.domain.AuditLog; @@ -49,7 +49,7 @@ public interface AuditService { * @param auditLog * @param additionalParams */ - + @SuppressWarnings("rawtypes") - void logActivity(AuditLog auditLog, HashMap additionalParams); + void logActivity(AuditLog auditLog, Map additionalParams); } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AuditServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AuditServiceImpl.java index 77db3681..1bc81d9a 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AuditServiceImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AuditServiceImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,7 +37,7 @@ */ package org.onap.portalsdk.core.service; -import java.util.HashMap; +import java.util.Map; import org.onap.portalsdk.core.domain.AuditLog; import org.springframework.beans.factory.annotation.Autowired; @@ -47,15 +47,18 @@ 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) { + + @Autowired + private DataAccessService dataAccessService; + + public AuditServiceImpl() { + } + + @Override + @SuppressWarnings("rawtypes") + public void logActivity(AuditLog auditLog, Map additionalParams) { getDataAccessService().saveDomainObject(auditLog, additionalParams); - } + } public DataAccessService getDataAccessService() { return dataAccessService; @@ -64,5 +67,5 @@ public class AuditServiceImpl implements AuditService { public void setDataAccessService(DataAccessService dataAccessService) { this.dataAccessService = dataAccessService; } - + } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/BroadcastService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/BroadcastService.java index bef46450..3cbf6644 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/BroadcastService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/BroadcastService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,7 +37,7 @@ */ package org.onap.portalsdk.core.service; -import java.util.*; +import java.util.Map; import javax.servlet.http.HttpServletRequest; @@ -45,10 +45,16 @@ import org.onap.portalsdk.core.domain.BroadcastMessage; @SuppressWarnings("rawtypes") public interface BroadcastService { - HashMap getBcModel(HttpServletRequest request); - Hashtable getBroadcastMessages(); - void loadMessages(); - BroadcastMessage getBroadcastMessage(HttpServletRequest request); + + Map getBcModel(HttpServletRequest request); + + Map 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/onap/portalsdk/core/service/BroadcastServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/BroadcastServiceImpl.java index 19803d94..5d14ee47 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/BroadcastServiceImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/BroadcastServiceImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -42,6 +42,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.Hashtable; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.TreeSet; @@ -49,6 +50,7 @@ import javax.servlet.http.HttpServletRequest; import org.onap.portalsdk.core.domain.BroadcastMessage; import org.onap.portalsdk.core.domain.Lookup; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.service.support.FusionService; import org.onap.portalsdk.core.util.SystemProperties; import org.onap.portalsdk.core.web.support.AppUtils; @@ -62,199 +64,201 @@ import org.springframework.web.bind.ServletRequestUtils; @Service("broadcastService") @Transactional public class BroadcastServiceImpl extends FusionService implements BroadcastService { - - public BroadcastServiceImpl() { - } + + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(BroadcastServiceImpl.class); @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 (!messagesExist) - return false; - - 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(); + private DataAccessService dataAccessService; + + private static Hashtable broadcastMessages = new Hashtable(); + + public BroadcastServiceImpl() { + super(); + } + + @Override + @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)); + } + } + + @Override + @SuppressWarnings("unchecked") + public Map getBcModel(HttpServletRequest request) { + HashMap bcModel = new HashMap(); + + 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 && ("delete".equals(task) || "toggleActive".equals(task))) { + BroadcastMessage message = (BroadcastMessage) getDataAccessService().getDomainObject(BroadcastMessage.class, + new Long(messageId), null); + + if ("delete".equals(task)) { + getDataAccessService().deleteDomainObject(message, null); + } else if ("toggleActive".equals(task)) { + HashMap additionalParams = new HashMap(); + additionalParams.put(Parameters.PARAM_HTTP_REQUEST, request); + + message.setActive(new Boolean(!message.getActive().booleanValue())); + getDataAccessService().saveDomainObject(message, additionalParams); + } + loadMessages(); + } + + List 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); } - message.setActive(Boolean.TRUE); - } - return message; - } + 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); + } + + @Override + public Map 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) { + StringBuilder html = new StringBuilder(); + 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.isEmpty()); + if (!messagesExist) + return false; + + 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; + } + } + + @Override + 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 | ServletRequestBindingException e) { + logger.error(EELFLoggerDelegate.errorLogger, "getBroadcastMessage failed", e); + } + message.setActive(Boolean.TRUE); + } + + return message; + } + + public DataAccessService getDataAccessService() { + return dataAccessService; + } + + public void setDataAccessService(final DataAccessService dataAccessService) { + this.dataAccessService = dataAccessService; + } @Override public void saveBroadcastMessage(BroadcastMessage broadcastMessage) { @@ -265,5 +269,5 @@ public class BroadcastServiceImpl extends FusionService implements BroadcastServ public void removeBroadcastMessage(BroadcastMessage broadcastMessage) { dataAccessService.deleteDomainObject(broadcastMessage, null); } - + } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/CentralAccessCondition.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/CentralAccessCondition.java index 65ee9460..e4b7a163 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/CentralAccessCondition.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/CentralAccessCondition.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -44,22 +44,21 @@ import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; public class CentralAccessCondition implements Condition { - + /** * returns true if the application is centralized */ @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { boolean isRemote = false; - - if(PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED) == null) - { + + if (PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED) == null) { isRemote = false; + } else if (PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED) != null + && "remote".equals(PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED))) { + isRemote = true; } - else if(PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED) != null && PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED).equals("remote")){ - isRemote = true; - } - - return isRemote; - } + + return isRemote; + } }
\ No newline at end of file diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/DataAccessService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/DataAccessService.java index 737d6a6f..8eacefa9 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/DataAccessService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/DataAccessService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,9 +37,7 @@ */ package org.onap.portalsdk.core.service; - import java.io.Serializable; -import java.util.HashMap; import java.util.List; import java.util.Map; @@ -52,47 +50,68 @@ import org.onap.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); + // generic view, save, delete methods + DomainVo getDomainObject(Class domainClass, Serializable id, Map additionalParams); + + void deleteDomainObject(DomainVo domainObject, Map additionalParams); + + void deleteDomainObjects(Class domainClass, String whereClause, Map additionalParams); + + void saveDomainObject(DomainVo domainObject, Map additionalParams); + + // generic get list method(s) + List getList(Class domainClass, Map additionalParams); + + List getList(Class domainClass, String filter, String orderBy, Map additionalParams); + + List getList(Class domainClass, String filter, int fromIndex, int toIndex, String orderBy, + Map 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, Map<String, FetchMode> fetchModeMap); + + List getLookupList(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy, + Map additionalParams); + + // generic native-SQL execution methods + List executeSQLQuery(String sql, Class domainClass, Map additionalParams); + + List executeSQLQuery(String sql, Class domainClass, Integer fromIndex, Integer toIndex, Map additionalParams); + + // generic HQL execution methods + List executeQuery(String hql, Map additionalParams); + + List executeQuery(String hql, Integer fromIndex, Integer toIndex, Map additionalParams); + + // generic named query execution methods + List executeNamedQuery(String queryName, Integer fromIndex, Integer toIndex, Map additionalParams); + + List executeNamedQuery(String queryName, Map params, Map additionalParams); + + List executeNamedQuery(String queryName, Map params, Integer fromIndex, Integer toIndex, Map additionalParams); + + // with Where Clause for RAPTOR ZK + List executeNamedQueryWithOrderBy(Class entity, String queryName, Map params, String orderBy, boolean asc, + Integer fromIndex, Integer toIndex, Map 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, Map additionalParams); + + List executeNamedQueryWithOrderBy(Class entity, String queryName, String whereClause, Map params, String orderBy, + boolean asc, Integer fromIndex, Integer toIndex, Map additionalParams); + + // generic update query execution method + int executeUpdateQuery(String sql, Map additionalParams); + + // generic named update query execution method + int executeNamedUpdateQuery(String queryName, Map params, Map additionalParams); + + // synchronizes the local updates with the database (and vice versa) + void synchronize(Map additionalParams); } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/DataAccessServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/DataAccessServiceImpl.java index e53260db..f34610cb 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/DataAccessServiceImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/DataAccessServiceImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -41,7 +41,6 @@ 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; @@ -75,66 +74,55 @@ public class DataAccessServiceImpl extends FusionService implements DataAccessSe private SessionFactory sessionFactory; @Override - public DomainVo getDomainObject(Class domainClass, Serializable id, HashMap additionalParams) { - DomainVo vo = null; + public DomainVo getDomainObject(Class domainClass, Serializable id, Map additionalParams) { Session session = sessionFactory.getCurrentSession(); - logger.info(EELFLoggerDelegate.debugLogger, "Getting " + domainClass.getName() + " record for id - " + id.toString()); - vo = (DomainVo) session.get(domainClass, id); - + logger.info(EELFLoggerDelegate.debugLogger, + "Getting " + domainClass.getName() + " record for id - " + id.toString()); + DomainVo 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()); + logger.error(EELFLoggerDelegate.errorLogger, + "getDomainObject failed while instantiating class " + domainClass.getName(), e); } } return vo; } @Override - public void deleteDomainObject(DomainVo domainObject, HashMap additionalParams) { + public void deleteDomainObject(DomainVo domainObject, Map additionalParams) { Session session = sessionFactory.getCurrentSession(); session.delete(domainObject); } @Override - public void deleteDomainObjects(Class domainClass, String whereClause, HashMap additionalParams) { - int rowsAffected = 0; + public void deleteDomainObjects(Class domainClass, String whereClause, Map additionalParams) { 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; */ + Query query = session.createQuery(sql.toString()); + query.executeUpdate(); } @Override - public void saveDomainObject(DomainVo vo, HashMap additionalParams) { + public void saveDomainObject(DomainVo vo, Map 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. + * 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 @@ -178,7 +166,6 @@ public class DataAccessServiceImpl extends FusionService implements DataAccessSe */ private List getListCommon(Class domainClass, String filterClause, Integer fromIndex, Integer toIndex, String orderBy) { - List list = null; String className = domainClass.getName(); Session session = sessionFactory.getCurrentSession(); @@ -187,13 +174,12 @@ public class DataAccessServiceImpl extends FusionService implements DataAccessSe + ((fromIndex != null) ? " from rows " + fromIndex.toString() + " to " + toIndex.toString() : "") + "..."); if (filterClause != null && filterClause.length() > 0) - logger.info(EELFLoggerDelegate.debugLogger, "Filtering " + className + " by: " + filterClause); + logger.info(EELFLoggerDelegate.debugLogger, "Filtering " + className + " by: " + filterClause); } - list = session.createQuery("from " + className + Utilities.nvl(filterClause, "") + List 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); @@ -201,18 +187,18 @@ public class DataAccessServiceImpl extends FusionService implements DataAccessSe } @Override - public List getList(Class domainClass, HashMap additionalParams) { + public List getList(Class domainClass, Map additionalParams) { return getListCommon(domainClass, null, null, null, null); } @Override - public List getList(Class domainClass, String filter, String orderBy, HashMap additionalParams) { + public List getList(Class domainClass, String filter, String orderBy, Map additionalParams) { return getListCommon(domainClass, filter, null, null, orderBy); } @Override public List getList(Class domainClass, String filter, int fromIndex, int toIndex, String orderBy, - HashMap additionalParams) { + Map additionalParams) { return getListCommon(domainClass, filter, new Integer(fromIndex), new Integer(toIndex), orderBy); } @@ -237,36 +223,28 @@ public class DataAccessServiceImpl extends FusionService implements DataAccessSe 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(); } @Override public List getLookupList(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy, - HashMap additionalParams) { + Map additionalParams) { if (logger.isInfoEnabled()) - logger.info(EELFLoggerDelegate.debugLogger, "Retrieving " + dbTable + " lookup list..."); + logger.info(EELFLoggerDelegate.debugLogger, "Retrieving " + dbTable + " lookup list..."); String dbOrderByCol = dbOrderBy; Session session = sessionFactory.getCurrentSession(); - // default the orderBy if null; + // 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(" ")); - } + } else if (dbOrderBy.lastIndexOf(" ") > -1) { + dbOrderByCol = dbOrderBy.substring(0, dbOrderBy.lastIndexOf(" ")); } - StringBuffer sql = new StringBuffer(); - + StringBuilder sql = new StringBuilder(); 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 ") @@ -276,7 +254,7 @@ public class DataAccessServiceImpl extends FusionService implements DataAccessSe 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()); + logger.error(EELFLoggerDelegate.errorLogger, "getLookupList failed on query query [" + sql + "]", e); } return list; } @@ -287,13 +265,13 @@ public class DataAccessServiceImpl extends FusionService implements DataAccessSe */ @Override - public List executeSQLQuery(String sql, Class domainClass, HashMap additionalParams) { + public List executeSQLQuery(String sql, Class domainClass, Map additionalParams) { return executeSQLQuery(sql, domainClass, null, null, additionalParams); } @Override public List executeSQLQuery(String sql, Class domainClass, Integer fromIndex, Integer toIndex, - HashMap additionalParams) { + Map additionalParams) { Session session = sessionFactory.getCurrentSession(); SQLQuery query = session.createSQLQuery(sql).addEntity(domainClass.getName().toLowerCase(), domainClass); @@ -308,12 +286,12 @@ public class DataAccessServiceImpl extends FusionService implements DataAccessSe } @Override - public List executeQuery(String sql, HashMap additionalParams) { + public List executeQuery(String sql, Map additionalParams) { return executeQuery(sql, null, null, additionalParams); } @Override - public List executeQuery(String sql, Integer fromIndex, Integer toIndex, HashMap additionalParams) { + public List executeQuery(String sql, Integer fromIndex, Integer toIndex, Map additionalParams) { Session session = sessionFactory.getCurrentSession(); Query query = session.createQuery(sql); @@ -328,18 +306,18 @@ public class DataAccessServiceImpl extends FusionService implements DataAccessSe } @Override - public List executeNamedQuery(String queryName, Integer fromIndex, Integer toIndex, HashMap additionalParams) { + public List executeNamedQuery(String queryName, Integer fromIndex, Integer toIndex, Map additionalParams) { return executeNamedQuery(queryName, null, fromIndex, toIndex, additionalParams); } @Override - public List executeNamedQuery(String queryName, Map params, HashMap additionalParams) { + public List executeNamedQuery(String queryName, Map params, Map additionalParams) { return executeNamedQuery(queryName, params, null, null, additionalParams); } @Override public List executeNamedQuery(String queryName, Map params, Integer fromIndex, Integer toIndex, - HashMap additionalParams) { + Map additionalParams) { Session session = sessionFactory.getCurrentSession(); Query query = session.getNamedQuery(queryName); bindQueryParameters(query, params); @@ -364,15 +342,16 @@ public class DataAccessServiceImpl extends FusionService implements DataAccessSe 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); + } else { + logger.error(EELFLoggerDelegate.errorLogger, "bindQueryParameters: no match for value {}", + parameterValue); } } } @@ -381,62 +360,55 @@ public class DataAccessServiceImpl extends FusionService implements DataAccessSe // With Where Clause & RAPTOR's ZK @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; + public List executeNamedQueryWithOrderBy(Class entity, String queryName, Map params, String orderBy, boolean asc, + Integer fromIndex, Integer toIndex, Map additionalParams) { + logger.error(EELFLoggerDelegate.errorLogger, "Not implemented"); + throw new UnsupportedOperationException(); } @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; + logger.error(EELFLoggerDelegate.errorLogger, "Not implemented"); + throw new UnsupportedOperationException(); } @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; + Integer toIndex, Map additionalParams) { + logger.error(EELFLoggerDelegate.errorLogger, "Not implemented"); + throw new UnsupportedOperationException(); } @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; + String orderBy, boolean asc, Integer fromIndex, Integer toIndex, Map additionalParams) { + logger.error(EELFLoggerDelegate.errorLogger, "Not implemented"); + throw new UnsupportedOperationException(); } @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; + List<Order> orderByList, Map<String, FetchMode> fetchModeMap) { + logger.error(EELFLoggerDelegate.errorLogger, "Not implemented"); + throw new UnsupportedOperationException(); } @Override - public int executeUpdateQuery(String sql, HashMap additionalParams) throws RuntimeException { - // TODO Auto-generated method stub - logger.info(EELFLoggerDelegate.debugLogger, "Not implemented"); - return 0; + public int executeUpdateQuery(String sql, Map additionalParams) { + logger.error(EELFLoggerDelegate.errorLogger, "Not implemented"); + throw new UnsupportedOperationException(); } @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; + public int executeNamedUpdateQuery(String queryName, Map params, Map additionalParams) { + logger.error(EELFLoggerDelegate.errorLogger, "Not implemented"); + throw new UnsupportedOperationException(); } @Override - public void synchronize(HashMap additionalParams) { - // TODO Auto-generated method stub - logger.info(EELFLoggerDelegate.debugLogger, "Not implemented"); + public void synchronize(Map additionalParams) { + logger.error(EELFLoggerDelegate.errorLogger, "Not implemented"); + throw new UnsupportedOperationException(); } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ElementLinkService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ElementLinkService.java index d9c25377..e096d832 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ElementLinkService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ElementLinkService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -44,22 +44,25 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; import org.onap.portalsdk.core.util.YamlUtils; public class ElementLinkService { + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ElementLinkService.class); + /** * 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. + * 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 + * @throws IOException */ - public String buildElementLinkYaml(String[] args) throws Exception { + public String buildElementLinkYaml(String[] args) throws IOException { String relFilePath; if (args[1].startsWith("custom")) relFilePath = SystemProperties.getProperty("customCallFlow_path"); @@ -82,69 +85,26 @@ public class ElementLinkService { 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 { - + throws IOException { 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) { - + logger.error(EELFLoggerDelegate.errorLogger, "createLinkFileAdditional failed", e); return ""; } @@ -154,22 +114,18 @@ public class ElementLinkService { 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>>(); + Map<String, List<String>> checkDuplicateMap = new HashMap<>(); 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>> links = new ArrayList<>(); 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>(); + Map<String, Object> link = new HashMap<>(); String source = (String) subStep.get("source_tosca_id"); String destination = (String) subStep.get("destination_tosca_id"); @@ -177,12 +133,12 @@ public class ElementLinkService { 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>(); + List<String> toscaList = new ArrayList<>(); checkDuplicateMap.put(destination, toscaList); } if (checkDuplicateMap.get(source) == null) { - List<String> toscaList = new ArrayList<String>(); + List<String> toscaList = new ArrayList<>(); checkDuplicateMap.put(source, toscaList); } @@ -195,30 +151,14 @@ public class ElementLinkService { 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>(); + Map<String, Object> callFlowUI = new HashMap<>(); callFlowUI.put("linkList", links); return YamlUtils.returnYaml(callFlowUI); - - // YamlUtils.writeYamlFile(filePath, callFlowStepName, - // callFlowUI); } } @@ -232,25 +172,24 @@ public class ElementLinkService { 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>(); + Map<String, Object> callFlowUI = new HashMap<>(); try { List<Map<String, Object>> links = addLinkVertices(callStep); callFlowUI.put("linkList", links); } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "addLinksAdditional failed", e); } try { List<String> activeIds = addActiveNodes(callStep); callFlowUI.put("activeIds", activeIds); } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "addLinksAdditional failed", e); } try { List<Map<String, Object>> disconnectLinks = addDisconnectLinks(callStep); callFlowUI.put("disconnectLinks", disconnectLinks); } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "addLinksAdditional failed", e); } return YamlUtils.returnYaml(callFlowUI); @@ -274,13 +213,13 @@ public class ElementLinkService { @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>> links = new ArrayList<>(); 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); + Map<String, Object> vertex = vertices.get(i); + Map<String, Object> vertexNext = vertices.get(i + 1); Integer sourceX = (Integer) vertex.get("x"); Integer sourceY = (Integer) vertex.get("y"); @@ -297,7 +236,7 @@ public class ElementLinkService { if (destinationX == -999) // there is a break in the linkage continue; - Map<String, Object> link = new HashMap<String, Object>(); + Map<String, Object> link = new HashMap<>(); link.put("s", sourceX + "," + sourceY + "," + sourceD + "," + sourceL); link.put("d", destinationX + "," + destinationY + "," + destinationD); @@ -305,4 +244,12 @@ public class ElementLinkService { } return links; } + + 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.createLinkFileAdditional(filePath, callFlowBusinessYml, "Step_2")); + } + } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ElementMapService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ElementMapService.java index 2c89dccd..d24bd503 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ElementMapService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ElementMapService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -38,6 +38,7 @@ package org.onap.portalsdk.core.service; import java.io.File; +import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -63,28 +64,39 @@ public class ElementMapService { private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ElementMapService.class); + private static HashMap<String, Object> toscaElementsMap = new HashMap<>(); + private static HashMap<String, Element> elementMap = new HashMap<>(); + private static HashMap<String, Element> miscElementMap = new HashMap<>(); + private static HashMap<String, Container> outercontainers = new HashMap<>(); + private static HashMap<String, Container> innercontainers = new HashMap<>(); + private static HashMap<String, Domain> domainMap = new HashMap<>(); + + 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"; + /** * * @param contextRealPath * @param layout * @return - * @throws Exception + * @throws IOException */ - private String convertToYAML(String contextRealPath, Layout layout) throws Exception { + private String convertToYAML(String contextRealPath, Layout layout) throws IOException { // Used to build image file relative URLs - final String iconRelPath = SystemProperties.getProperty("element_map_icon_path"); // "static/img/map/icons/"; + final String iconRelPath = SystemProperties.getProperty("element_map_icon_path"); - Map<String, Domain> resultAICDomain = layout.domainRowCol; - Map<String, List<Domain>> domainMap = new HashMap<String, List<Domain>>(); - List<Domain> domainList = new ArrayList<Domain>(); + Map<String, Domain> resultAICDomain = layout.getDomainRowCol(); + Map<String, List<Domain>> domainMap = new HashMap<>(); + List<Domain> domainList = new ArrayList<>(); 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>(); + List<Container> containerList = new ArrayList<>(); for (Container c : d.getContainerRowCol().values()) { c.setWidth(10 * c.computeSize().getWidth()); c.setHeight(10 * c.computeSize().getHeight()); @@ -97,7 +109,7 @@ public class ElementMapService { } if (c.getContainerRowCol() != null) { - List<Container> innerContainerList = new ArrayList<Container>(); + List<Container> innerContainerList = new ArrayList<>(); for (Container innerC : c.getContainerRowCol().values()) { innerC.setName(innerC.getName()); innerC.setWidth(10 * innerC.computeSize().getWidth()); @@ -106,9 +118,8 @@ public class ElementMapService { innerC.setTop(10 * innerC.getP().getY()); if (innerC.getElementRowCol() != null) { - List<Element> innerContainerEList = new ArrayList<Element>(); + List<Element> innerContainerEList = new ArrayList<>(); 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()); @@ -128,9 +139,8 @@ public class ElementMapService { } if (c.getElementRowCol() != null) { - List<Element> elementList = new ArrayList<Element>(); + List<Element> elementList = new ArrayList<>(); 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()); @@ -157,7 +167,7 @@ public class ElementMapService { } domainMap.put("domainList", domainList); - List<Domain> collapsedDomains = new ArrayList<Domain>(); + List<Domain> collapsedDomains = new ArrayList<>(); // nline for (Domain collapsed : layout.getCollapsedDomainsNewList()) { @@ -183,30 +193,17 @@ public class ElementMapService { } - 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. + * 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 + * arg 0 - collapsedDomains; arg 1 - expandedDomains; arg 2 - context + * real path; arg 3 - contentFileName; arg 4 - layoutFileName * @return Renderable model of elements - * @throws Exception + * @throws IOException */ - public String buildElementMapYaml(String args[]) throws Exception { + public String buildElementMapYaml(String args[]) throws IOException { final String yamlDirPath = new File(args[2], filePath).getPath(); if (args != null && args.length > 4) { @@ -219,12 +216,12 @@ public class ElementMapService { 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>(); + toscaElementsMap = new HashMap<>(); + elementMap = new HashMap<>(); + domainMap = new HashMap<>(); + outercontainers = new HashMap<>(); + innercontainers = new HashMap<>(); + miscElementMap = new HashMap<>(); if (toscaYaml != null) { for (String key : toscaYaml.keySet()) { @@ -238,12 +235,6 @@ public class ElementMapService { toscaElementsMap = (HashMap<String, Object>) toscaTopologyDetails.get(detailsKey); - // for (String toscaElementKey : - // toscaElementsMap.keySet()) { - //// System.out.println("Element - "+ "key :" + - //// toscaElementKey); - // } - } } } @@ -267,8 +258,6 @@ public class ElementMapService { 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) { @@ -279,7 +268,7 @@ public class ElementMapService { column = "0"; for (String detailsKey : elementDetails.keySet()) { if ("tosca_id".equalsIgnoreCase(detailsKey)) - elementName = elementDetails.get(detailsKey).toString(); + elementName = elementDetails.get(detailsKey); if ("id".equalsIgnoreCase(detailsKey)) { elementID = String.valueOf(elementDetails.get(detailsKey)); } @@ -290,7 +279,7 @@ public class ElementMapService { column = String.valueOf(elementDetails.get(detailsKey)); } if ("icon".equalsIgnoreCase(detailsKey)) - imgPath = elementDetails.get(detailsKey).toString(); + imgPath = elementDetails.get(detailsKey); } if (elementMap.containsKey(elementName.concat("/").concat(row).concat(column))) { @@ -313,12 +302,11 @@ public class ElementMapService { for (String elementkey : elementMap.keySet()) { Element c = (Element) elementMap.get(elementkey); - // System.out.println("Element - "+ "key :" +elementkey +" - - // " + "value :" + c.getName()); + logger.trace(EELFLoggerDelegate.debugLogger, "buildElementMapYaml: element {}", c); } if (!elementMap.isEmpty()) { - miscElementMap = new HashMap<String, Element>(elementMap); + miscElementMap = new HashMap<>(elementMap); } } @@ -349,12 +337,12 @@ public class ElementMapService { for (String detailsKey : containerDetails.keySet()) { if ("logical_group_name".equalsIgnoreCase(detailsKey)) - containerName = containerDetails.get(detailsKey).toString(); + containerName = containerDetails.get(detailsKey); if ("id".equalsIgnoreCase(detailsKey)) { containerID = String.valueOf(containerDetails.get(detailsKey)); } if ("domain".equalsIgnoreCase(detailsKey)) { - domain = containerDetails.get(detailsKey).toString(); + domain = containerDetails.get(detailsKey); } if ("row".equalsIgnoreCase(detailsKey)) { row = String.valueOf(containerDetails.get(detailsKey)); @@ -401,12 +389,12 @@ public class ElementMapService { for (String detailsKey : containerDetails.keySet()) { if ("logical_group_name".equalsIgnoreCase(detailsKey)) - containerName = containerDetails.get(detailsKey).toString(); + containerName = containerDetails.get(detailsKey); if ("id".equalsIgnoreCase(detailsKey)) { containerID = String.valueOf(containerDetails.get(detailsKey)); } if ("domain".equalsIgnoreCase(detailsKey)) { - domain = containerDetails.get(detailsKey).toString(); + domain = containerDetails.get(detailsKey); } if ("row".equalsIgnoreCase(detailsKey)) { row = String.valueOf(containerDetails.get(detailsKey)); @@ -430,9 +418,6 @@ public class ElementMapService { outercontainers.put(mapKey, fetchContainerObject(containerID, containerName, false, containerName, domain)); } - // else innercontainers.put(domain +":"+ - // containerName, - // fetchContainerObject(containerID,containerName.substring(containerName.indexOf("/")+1),false,containerName,domain)); } } @@ -442,10 +427,12 @@ public class ElementMapService { for (String innerContainerkey : innercontainers.keySet()) { Container c = (Container) innercontainers.get(innerContainerkey); + logger.trace(EELFLoggerDelegate.debugLogger, "buildElementMapYaml: inner container {}", c); } for (String outerContainerkey : outercontainers.keySet()) { Container c = (Container) outercontainers.get(outerContainerkey); + logger.trace(EELFLoggerDelegate.debugLogger, "buildElementMapYaml: outer container {}", c); } } @@ -463,10 +450,8 @@ public class ElementMapService { if (domainlist != null) { - HashMap<String, String> domainStagingMap = new HashMap<String, String>(); + HashMap<String, String> domainStagingMap = new HashMap<>(); 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) { @@ -476,7 +461,7 @@ public class ElementMapService { column = "0"; for (String detailsKey : domainDetails.keySet()) { if ("name".equalsIgnoreCase(detailsKey)) - domainName = domainDetails.get(detailsKey).toString(); + domainName = domainDetails.get(detailsKey); if ("id".equalsIgnoreCase(detailsKey)) { domainID = String.valueOf(domainDetails.get(detailsKey)); } @@ -510,11 +495,6 @@ public class ElementMapService { } } - // for (String domainkey : domainMap.keySet()) { - // Domain c = (Domain) domainMap.get(domainkey); - // System.out.println("Domain - "+ "key :" +domainkey +" - " - // + "value :" + c.getName()); - // } } } @@ -522,35 +502,20 @@ public class ElementMapService { 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(","); + String[] collapsedDomains = args[0].split(","); for (String collapsedDomain : collapsedDomains) - // dynamicLayout.collapseDomainModified(collapsedDomain); dynamicLayout.collapseDomainNew(collapsedDomain); } if (args[1] != null) { - String expandedDomains[] = args[1].split(","); + String[] expandedDomains = args[1].split(","); for (String expandedDomain : expandedDomains) - // dynamicLayout.uncollapseDomainNew(expandedDomain); dynamicLayout.uncollapseDomainNew1(expandedDomain); } @@ -605,7 +570,7 @@ public class ElementMapService { private static Container fetchContainerObject(String id, String name, boolean isInner, String logicalGroupName, String domain) { - Map<String, Element> containerElementsMap = new HashMap<String, Element>(); + Map<String, Element> containerElementsMap = new HashMap<>(); containerElementsMap = fetchElementsMapForContainer(name, isInner, logicalGroupName, domain); int rows = 1; @@ -620,7 +585,6 @@ public class ElementMapService { Container thisContainer = new Container(id, name, rows, columns, 1, 4, 8, 12, 1, 2); thisContainer.setElements(containerElementsMap); - // thisContainer.setVisibilityType(""); return thisContainer; } else { @@ -629,7 +593,7 @@ public class ElementMapService { if (innerContainersMap != null && !innerContainersMap.isEmpty()) { if (containerElementsMap != null && !containerElementsMap.isEmpty()) { - Set<String> keys = new HashSet<String>(innerContainersMap.keySet()); + Set<String> keys = new HashSet<>(innerContainersMap.keySet()); keys.addAll(containerElementsMap.keySet()); rows = computeRows(keys); columns = computeColumns(keys); @@ -648,8 +612,7 @@ public class ElementMapService { if (containerElementsMap != null && !containerElementsMap.isEmpty()) { for (Element thisElement : containerElementsMap.values()) { - if (thisElement.getId() != null - ) { + if (thisElement.getId() != null) { thisContainer.setVisibilityType("invisible"); } } @@ -660,7 +623,7 @@ public class ElementMapService { } private static Domain fetchDomainObject(String id, String name) { - HashMap<String, Container> domainContainersMap = fetchContainersForDomain(name); + Map<String, Container> domainContainersMap = fetchContainersForDomain(name); int rows = 1; int columns = 1; @@ -671,31 +634,25 @@ public class ElementMapService { double domainWidth = 11; Domain thisDomain; - if (domainMap != null && !domainMap.isEmpty()) { int domainsCountSoFar = domainMap.size(); switch (domainsCountSoFar) { - case 1: { + case 1: domainWidth = 12.1; break; - } - case 2: { + case 2: domainWidth = 13.3; break; - } - case 3: { + case 3: domainWidth = 14.5; break; - } - case 4: { + case 4: domainWidth = 15.6; break; - } - default: { + default: domainWidth = 11; break; } - } for (String domainsKey : new TreeSet<String>(domainMap.keySet())) { Domain eachDomain = domainMap.get(domainsKey); @@ -707,8 +664,6 @@ public class ElementMapService { 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(); @@ -716,42 +671,18 @@ public class ElementMapService { for (Container thisContainer : domainContainersMap.values()) { thisContainer.computeSize(); thisContainer.computeElementPositions(); - Map<String, Element> resultElementMap = thisContainer.elementRowCol; + Map<String, Element> resultElementMap = thisContainer.getElementRowCol(); for (String key : resultElementMap.keySet()) { if (resultElementMap.get(key) == null || resultElementMap.get(key).getP() == null) { - // System.out.println("culprit " +key); + logger.debug(EELFLoggerDelegate.debugLogger, "fetchDomainObject: {}", 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()); - * - * } - */ } } } @@ -760,29 +691,12 @@ public class ElementMapService { return thisDomain; } - private static HashMap<String, Container> fetchContainersForDomain(String domain) { - HashMap<String, Container> domainContainersMap = new HashMap<String, Container>(); - - domainContainersMap = fetchFromOuterContainers(domain); - + private static Map<String, Container> fetchContainersForDomain(String domain) { + Map<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)) { @@ -791,35 +705,33 @@ public class ElementMapService { for (String detailsKey : toscaElementDetails.keySet()) { if ("properties".equalsIgnoreCase(detailsKey) - && toscaElementDetails.get(detailsKey) instanceof HashMap) { - HashMap<String, String> elementDetails = (HashMap<String, String>) toscaElementDetails - .get(detailsKey); + && toscaElementDetails.get(detailsKey) instanceof Map) { + Map<String, String> elementDetails = (Map<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(); + String logical_group = elementDetails.get("logical_group") == null ? "" + : elementDetails.get("logical_group"); + String display_longname = elementDetails.get("display_longname") == null ? "" + : elementDetails.get("display_longname"); + String display_shortname = elementDetails.get("display_shortname") == null ? "" + : elementDetails.get("display_shortname"); + String description = elementDetails.get("description") == null ? "" + : elementDetails.get("description"); + String primary_function = elementDetails.get("primary_function") == null ? "" + : elementDetails.get("primary_function"); + String key_interfaces = elementDetails.get("key_interfaces") == null ? "" + : elementDetails.get("key_interfaces"); + String location = elementDetails.get("location") == null ? "" + : elementDetails.get("location"); + String vendor = elementDetails.get("vendor") == null ? "" : elementDetails.get("vendor"); + String vendor_shortname = elementDetails.get("vendor_shortname") == null ? "" + : elementDetails.get("vendor_shortname"); + String enclosingContainer = logical_group.replace("/", "-"); + String network_function = elementDetails.get("network_function"); + String borderType = elementDetails.get("network_function") == null ? "P" + : elementDetails.get("network_function").toUpperCase(); + String bgColor = elementDetails.get("background_color") == null ? "bgColor" + : elementDetails.get("background_color"); ElementDetails details = new ElementDetails(logical_group, display_longname, description, primary_function, network_function, key_interfaces, location, vendor, @@ -833,10 +745,6 @@ public class ElementMapService { } - // Element(id, name, imgPath, bgColor, logical_group, - // display_longname, - // description, primary_function, key_interfaces, location, vendor, - // vendor_shortname); } else { return new Element(id, name); } @@ -857,7 +765,7 @@ public class ElementMapService { .get(detailsKey); if (elementDetails != null) { - return elementDetails.get("domain") == null ? "" : elementDetails.get("domain").toString(); + return elementDetails.get("domain") == null ? "" : elementDetails.get("domain"); } } @@ -872,34 +780,29 @@ public class ElementMapService { return ""; } - private static HashMap<String, Container> fetchInnerContainersMapForOuter(String name, boolean isInner, + private static Map<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, + private static Map<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; + private static Map<String, Container> fetchInnerContainersMap(String name, String logicalGroupName, String domain) { + HashMap<String, Container> containersMap = new HashMap<>(); if (innercontainers != null && !innercontainers.isEmpty()) { for (String key : innercontainers.keySet()) { - Container eachContainer = innercontainers.get(key); - if (key.toUpperCase().contains((domain + ":" + name).toUpperCase())) { + String rowColumnKey = ""; if (key.contains("/")) { rowColumnKey = key.substring(key.lastIndexOf("/") + 1); } - if (rowColumnKey.isEmpty() || containersMap.containsKey(rowColumnKey)) { - count = 0; + int count = 0; while (count <= 9) { if (containersMap.containsKey(String.valueOf(count).concat(String.valueOf(count)))) { count++; @@ -920,22 +823,21 @@ public class ElementMapService { } - private static HashMap<String, Container> fetchFromOuterContainers(String domain) { - HashMap<String, Container> thisContainersMap = new HashMap<String, Container>(); - String rowColumnKey = ""; - int count = 0; + private static Map<String, Container> fetchFromOuterContainers(String domain) { + HashMap<String, Container> thisContainersMap = new HashMap<>(); if (outercontainers != null && !outercontainers.isEmpty()) { for (String key : outercontainers.keySet()) { Container eachContainer = outercontainers.get(key); if (key.toUpperCase().contains((domain + ":").toUpperCase())) { + String rowColumnKey = ""; if (key.contains("/")) { rowColumnKey = key.substring(key.lastIndexOf("/") + 1); } if (rowColumnKey.isEmpty() || thisContainersMap.containsKey(rowColumnKey)) { - count = 0; + int count = 0; while (count <= 9) { if (thisContainersMap.containsKey(String.valueOf(count).concat(String.valueOf(count)))) { count++; @@ -962,9 +864,10 @@ public class ElementMapService { String domainName = fetchDomainNameOfElement(elementName); if (domain.equalsIgnoreCase(domainName)) { + String rowColumnKey = ""; Container eachContainer = new Container(domainName + ":" + elementName, elementName, 1, 1, 3, 6, 2, 5, 0, 0); - count = 0; + int count = 0; while (count <= 9) { if (thisContainersMap.containsKey(String.valueOf(count).concat(String.valueOf(count)))) { count++; @@ -984,45 +887,25 @@ public class ElementMapService { 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; + private static Map<String, Element> fetchElementsMap(String logicalGroupName, String domain) { + HashMap<String, Element> innerElementMap = new HashMap<>(); 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; + String elementLogicalGroup = eachElement.getDetails() == null ? "" + : eachElement.getDetails().getLogical_group(); if (elementLogicalGroup.equalsIgnoreCase(logicalGroupName) && domain.equalsIgnoreCase(fetchDomainNameOfElement(elementName))) { + String rowColumnKey = ""; if (key.contains("/")) { rowColumnKey = key.substring(key.indexOf("/") + 1); } if (rowColumnKey.isEmpty() || innerElementMap.containsKey(rowColumnKey)) { - count = 0; + int count = 0; while (count <= 9) { if (innerElementMap.containsKey(String.valueOf(count).concat(String.valueOf(count)))) { count++; diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FnMenuService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FnMenuService.java index 12203671..c426f2b5 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FnMenuService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FnMenuService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FnMenuServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FnMenuServiceImpl.java index 8c445a46..6d7251ec 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FnMenuServiceImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FnMenuServiceImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -56,6 +56,7 @@ public class FnMenuServiceImpl implements FnMenuService { @Autowired private DataAccessService dataAccessService; + @Override @SuppressWarnings("unchecked") public List<MenuData> getFnMenuItems() { return getDataAccessService().getList(MenuData.class, null, "1", null); @@ -77,7 +78,7 @@ public class FnMenuServiceImpl implements FnMenuService { @SuppressWarnings("unchecked") @Override public List<Long> getParentId(String label) { - Map<String, String> params = new HashMap<String, String>(); + Map<String, String> params = new HashMap<>(); params.put("paramLabel", label); return getDataAccessService().executeNamedQuery("IdForLabelList", params, null); } @@ -98,6 +99,7 @@ public class FnMenuServiceImpl implements FnMenuService { getDataAccessService().deleteDomainObject(domainFnMenu, null); } + @Override public MenuData getMenuItemRow(Long id) { return (MenuData) getDataAccessService().getDomainObject(MenuData.class, id, null); } @@ -121,7 +123,7 @@ public class FnMenuServiceImpl implements FnMenuService { parentData.setAction(menu.getAction()); parentData.setImageSrc(menu.getImageSrc()); parentList.add(parentData); - List<MenuData> tempList = new ArrayList<MenuData>(); + List<MenuData> tempList = new ArrayList<>(); for (Object o : menu.getChildMenus()) { MenuData m = (MenuData) o; MenuData data = new MenuData(); diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FunctionalMenuListService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FunctionalMenuListService.java index e2e6349d..53328315 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FunctionalMenuListService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FunctionalMenuListService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -45,7 +45,7 @@ import javax.servlet.http.HttpServletRequest; import org.onap.portalsdk.core.domain.RoleFunction; public interface FunctionalMenuListService { - + List<RoleFunction> getFunctionCDList(HttpServletRequest request) throws IOException; } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FunctionalMenuListServiceCentralizedImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FunctionalMenuListServiceCentralizedImpl.java index 7192198d..d4d04538 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FunctionalMenuListServiceCentralizedImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FunctionalMenuListServiceCentralizedImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -50,7 +50,7 @@ import org.springframework.beans.factory.annotation.Autowired; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.type.TypeFactory; -public class FunctionalMenuListServiceCentralizedImpl implements FunctionalMenuListService{ +public class FunctionalMenuListServiceCentralizedImpl implements FunctionalMenuListService { @Autowired private RestApiRequestBuilder restApiRequestBuilder; diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FunctionalMenuListServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FunctionalMenuListServiceImpl.java index b9e70e6e..becb1734 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FunctionalMenuListServiceImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FunctionalMenuListServiceImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -45,10 +45,10 @@ import javax.servlet.http.HttpServletRequest; import org.onap.portalsdk.core.domain.RoleFunction; import org.springframework.beans.factory.annotation.Autowired; -public class FunctionalMenuListServiceImpl implements FunctionalMenuListService{ - +public class FunctionalMenuListServiceImpl implements FunctionalMenuListService { + @Autowired - private DataAccessService dataAccessService; + private DataAccessService dataAccessService; public DataAccessService getDataAccessService() { return dataAccessService; diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LdapService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LdapService.java index 9156c8a7..c810c19d 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LdapService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LdapService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,13 +37,15 @@ */ package org.onap.portalsdk.core.service; +import javax.naming.NamingException; + import org.onap.portalsdk.core.command.support.SearchResult; import org.onap.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; + // 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 NamingException; } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LdapServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LdapServiceImpl.java index ca2e13aa..6470ca63 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LdapServiceImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LdapServiceImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -62,225 +62,189 @@ import org.springframework.transaction.annotation.Transactional; @Service("ldapService") @Transactional public class LdapServiceImpl extends FusionService implements LdapService { - + private static final 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; - } + @Override + @SuppressWarnings({ "unchecked", "rawtypes" }) + public SearchResult searchPost(DomainVo searchCriteria, String sortBy1, String sortBy2, String sortBy3, int pageNo, + int dataSize, int userId) throws NamingException { + + // 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(); + + 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); + + StringBuilder filterClause = new StringBuilder("(&(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 (!"(&(objectClass=*))".equals(filterClause.toString())) { + 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 + + dirContext.close(); + + return searchResult; + } @SuppressWarnings({ "rawtypes", "unchecked" }) - private ArrayList processResults(NamingEnumeration e) throws NamingException { - ArrayList results = new ArrayList(); - int count = 0; + 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++; + 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; - } + if (count > Integer.parseInt(SystemProperties.getProperty(SystemProperties.POST_MAX_RESULT_SIZE))) { + break; + } - } + } - return results; - } + 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()); - } - - return user; - - } - + private DomainVo processAttributes(Attributes resultAttributes) { + User user = new User(); + try { + if (resultAttributes == null) { + logger.debug(EELFLoggerDelegate.debugLogger, "processAttributes: 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()); + } + + return user; + + } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LocalAccessCondition.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LocalAccessCondition.java index 772b2559..c7636f10 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LocalAccessCondition.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LocalAccessCondition.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -43,14 +43,16 @@ import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; -public class LocalAccessCondition implements Condition{ - +public class LocalAccessCondition implements Condition { + /** * returns true if the application is not centralized */ @Override - public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { - return PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED) == null || (PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED) != null && ! PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED).equals("remote")); - } + public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { + return PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED) == null + || (PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED) != null && !"remote" + .equals(PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED))); + } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LoginService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LoginService.java index f3a62de7..b03be694 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LoginService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LoginService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,36 +37,34 @@ */ package org.onap.portalsdk.core.service; +import java.io.IOException; +import java.util.Map; -import java.util.*; - -import org.onap.portalsdk.core.command.*; - +import org.onap.portalsdk.core.command.LoginBean; public interface LoginService { /** - * + * validate user exists in the system * @param bean * @param menuPropertiesFilename * @param additionalParams * @return returns login user bean - * @throws Exception + * @throws IOException */ - // validate user exists in the system @SuppressWarnings("rawtypes") - LoginBean findUser(LoginBean bean, String menuPropertiesFilename, HashMap additionalParams) throws Exception; - - + LoginBean findUser(LoginBean bean, String menuPropertiesFilename, Map additionalParams) throws IOException; + /** * * @param bean * @param menuPropertiesFilename * @param additionalParams * @param matchPassword - * @return returns login user bean - * @throws Exception + * @return returns login user bean + * @throws IOException */ @SuppressWarnings("rawtypes") - LoginBean findUser(LoginBean bean, String menuPropertiesFilename, HashMap additionalParams, boolean matchPassword) throws Exception; + LoginBean findUser(LoginBean bean, String menuPropertiesFilename, Map additionalParams, boolean matchPassword) + throws IOException; } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LoginServiceCentralizedImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LoginServiceCentralizedImpl.java index 9956cc48..749fdc38 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LoginServiceCentralizedImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LoginServiceCentralizedImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,6 +37,7 @@ */ package org.onap.portalsdk.core.service; +import java.io.IOException; import java.util.Date; import java.util.HashMap; import java.util.HashSet; @@ -48,6 +49,7 @@ import java.util.Set; import org.onap.portalsdk.core.command.LoginBean; import org.onap.portalsdk.core.domain.Role; import org.onap.portalsdk.core.domain.User; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.menu.MenuBuilder; import org.onap.portalsdk.core.service.support.FusionService; import org.onap.portalsdk.core.util.SystemProperties; @@ -56,19 +58,17 @@ import org.onap.portalsdk.core.web.support.UserUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; - @Transactional public class LoginServiceCentralizedImpl extends FusionService implements LoginService { - @Autowired - private AppService appService; + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LoginServiceCentralizedImpl.class); @Autowired private DataAccessService dataAccessService; - + @Autowired private RestApiRequestBuilder restApiRequestBuilder; - + @Autowired private UserService userService; @@ -76,28 +76,26 @@ public class LoginServiceCentralizedImpl extends FusionService implements LoginS private MenuBuilder menuBuilder; @Override - public LoginBean findUser(LoginBean bean, String menuPropertiesFilename, HashMap additionalParams) - throws Exception { + public LoginBean findUser(LoginBean bean, String menuPropertiesFilename, Map additionalParams) throws IOException { return findUser(bean, menuPropertiesFilename, additionalParams, true); } + @Override @SuppressWarnings("rawtypes") - public LoginBean findUser(LoginBean bean, String menuPropertiesFilename, HashMap additionalParams, - boolean matchPassword) throws Exception { - User user = null; - User userCopy = null; + public LoginBean findUser(LoginBean bean, String menuPropertiesFilename, Map additionalParams, + boolean matchPassword) throws IOException { - if (bean.getUserid() != null && bean.getUserid() != null) { - user = (User) findUser(bean); + User user; + if (bean.getUserid() != null) { + user = findUser(bean); } else { if (matchPassword) - user = (User) findUser(bean.getLoginId(), bean.getLoginPwd()); + user = findUser(bean.getLoginId(), bean.getLoginPwd()); else - user = (User) findUserWithoutPwd(bean.getLoginId()); + user = findUserWithoutPwd(bean.getLoginId()); } if (user != null) { - if (AppUtils.isApplicationLocked() && !UserUtils.hasRole(user, SystemProperties.getProperty(SystemProperties.SYS_ADMIN_ROLE_ID))) { bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_APPLICATION_LOCKED); @@ -116,14 +114,19 @@ public class LoginServiceCentralizedImpl extends FusionService implements LoginS // this will be a snapshot of the user's information as // retrieved from the database - userCopy = (User) user.clone(); + User userCopy = null; + try { + userCopy = (User) user.clone(); + } catch (CloneNotSupportedException ex) { + // Never happens + logger.error(EELFLoggerDelegate.errorLogger, "findUser failed", ex); + } User appuser = getUser(userCopy); appuser.setLastLoginDate(new Date()); // update the last logged in date for the user - // user.setLastLoginDate(new Date()); getDataAccessService().saveDomainObject(appuser, additionalParams); // update the audit log of the user @@ -162,17 +165,15 @@ public class LoginServiceCentralizedImpl extends FusionService implements LoginS return hasActiveRole; } - @SuppressWarnings("null") - public User findUser(LoginBean bean) throws Exception { - User user = null; + public User findUser(LoginBean bean) throws IOException { String repsonse = restApiRequestBuilder.getViaREST("/user/" + bean.getUserid(), true, bean.getUserid()); - user = userService.userMapper(repsonse); + User user = userService.userMapper(repsonse); user.setId(getUserIdByOrgUserId(user.getOrgUserId())); return user; } - + public Long getUserIdByOrgUserId(String orgUserId) { - Map<String, String> params = new HashMap<String, String>(); + Map<String, String> params = new HashMap<>(); params.put("orgUserId", orgUserId); @SuppressWarnings("rawtypes") List list = getDataAccessService().executeNamedQuery("getUserIdByorgUserId", params, null); @@ -181,26 +182,20 @@ public class LoginServiceCentralizedImpl extends FusionService implements LoginS userId = (Long) list.get(0); return userId; } - public User findUser(String loginId, String password) { - - List list = null; - - StringBuffer criteria = new StringBuffer(); + StringBuilder criteria = new StringBuilder(); 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); + List list = getDataAccessService().getList(User.class, criteria.toString(), null, null); + return (list == null || list.isEmpty()) ? null : (User) list.get(0); } private User findUserWithoutPwd(String loginId) { - List list = null; - StringBuffer criteria = new StringBuffer(); + StringBuilder criteria = new StringBuilder(); 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); + List list = getDataAccessService().getList(User.class, criteria.toString(), null, null); + return (list == null || list.isEmpty()) ? null : (User) list.get(0); } public DataAccessService getDataAccessService() { @@ -220,14 +215,10 @@ public class LoginServiceCentralizedImpl extends FusionService implements LoginS } public User getUser(User user) { - List list = null; - - StringBuffer criteria = new StringBuffer(); + StringBuilder criteria = new StringBuilder(); criteria.append(" where login_id = '").append(user.getLoginId()).append("'"); - - list = getDataAccessService().getList(User.class, criteria.toString(), null, null); - return (list == null || list.size() == 0) ? null : (User) list.get(0); - + List list = getDataAccessService().getList(User.class, criteria.toString(), null, null); + return (list == null || list.isEmpty()) ? null : (User) list.get(0); } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LoginServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LoginServiceImpl.java index 6965bf3c..4d240972 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LoginServiceImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LoginServiceImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -38,15 +38,16 @@ package org.onap.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.Map; import java.util.Set; import org.onap.portalsdk.core.command.LoginBean; import org.onap.portalsdk.core.domain.Role; import org.onap.portalsdk.core.domain.User; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.menu.MenuBuilder; import org.onap.portalsdk.core.service.support.FusionService; import org.onap.portalsdk.core.util.SystemProperties; @@ -58,161 +59,144 @@ import org.springframework.transaction.annotation.Transactional; @Transactional public class LoginServiceImpl extends FusionService implements LoginService { + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LoginServiceImpl.class); + @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; - @SuppressWarnings("rawtypes") - Iterator roles = user.getRoles().iterator(); - while (roles.hasNext()) { - Role role = (Role)roles.next(); - if (role.getActive()) { - hasActiveRole = true; - break; - } - } - return hasActiveRole; - } + private MenuBuilder menuBuilder; - @SuppressWarnings("rawtypes") - public User findUser(String loginId, String password) { - List list = null; + @Autowired + private DataAccessService dataAccessService; - 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); + @Override + @SuppressWarnings("rawtypes") + public LoginBean findUser(LoginBean bean, String menuPropertiesFilename, Map additionalParams) { + return findUser(bean, menuPropertiesFilename, additionalParams, true); + } - return (list == null || list.size() == 0) ? null : (User)list.get(0); - } - - @SuppressWarnings("rawtypes") - private User findUserWithoutPwd(String loginId) { - List list = null; + @Override + @SuppressWarnings("rawtypes") + public LoginBean findUser(LoginBean bean, String menuPropertiesFilename, Map additionalParams, + boolean matchPassword) { + + User user; + if (bean.getUserid() != null && bean.getUserid() != null) { + user = findUser(bean); + } else { + if (matchPassword) + user = findUser(bean.getLoginId(), bean.getLoginPwd()); + else + user = findUserWithoutPwd(bean.getLoginId()); + } - StringBuffer criteria = new StringBuffer(); - criteria.append(" where login_id = '").append(loginId).append("'"); - - list = getDataAccessService().getList(User.class, criteria.toString(), null, null); + 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); + } + + 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 + User userCopy = null; + try { + userCopy = (User) user.clone(); + } catch (CloneNotSupportedException ex) { + // Never happens + logger.error(EELFLoggerDelegate.errorLogger, "findUser failed", ex); + } + + // 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 (list == null || list.size() == 0) ? null : (User)list.get(0); - } + } - @SuppressWarnings("rawtypes") - public User findUser(LoginBean bean) { - List list = null; + return bean; + } - StringBuffer criteria = new StringBuffer(); - criteria.append(" where org_user_id = '").append(bean.getUserid()).append("'"); - - list = getDataAccessService().getList(User.class, criteria.toString(), null, null); + private boolean userHasActiveRoles(User user) { + boolean hasActiveRole = false; + @SuppressWarnings("rawtypes") + Iterator roles = user.getRoles().iterator(); + while (roles.hasNext()) { + Role role = (Role) roles.next(); + if (role.getActive()) { + hasActiveRole = true; + break; + } + } + return hasActiveRole; + } - return (list == null || list.size() == 0) ? null : (User)list.get(0); - } + @SuppressWarnings("rawtypes") + public User findUser(String loginId, String password) { + StringBuilder criteria = new StringBuilder(); + criteria.append(" where login_id = '").append(loginId).append("'").append(" and login_pwd = '").append(password) + .append("'"); + List list = getDataAccessService().getList(User.class, criteria.toString(), null, null); + return (list == null || list.isEmpty()) ? null : (User) list.get(0); + } + @SuppressWarnings("rawtypes") + private User findUserWithoutPwd(String loginId) { + StringBuilder criteria = new StringBuilder(); + criteria.append(" where login_id = '").append(loginId).append("'"); + List list = getDataAccessService().getList(User.class, criteria.toString(), null, null); + return (list == null || list.isEmpty()) ? null : (User) list.get(0); + } - public MenuBuilder getMenuBuilder() { - return new MenuBuilder(); - } + @SuppressWarnings("rawtypes") + public User findUser(LoginBean bean) { + StringBuilder criteria = new StringBuilder(); + criteria.append(" where org_user_id = '").append(bean.getUserid()).append("'"); + List list = getDataAccessService().getList(User.class, criteria.toString(), null, null); + return (list == null || list.isEmpty()) ? null : (User) list.get(0); + } + public MenuBuilder getMenuBuilder() { + return new MenuBuilder(); + } - public void setMenuBuilder(MenuBuilder menuBuilder) { - this.menuBuilder = menuBuilder; - } + public void setMenuBuilder(MenuBuilder menuBuilder) { + this.menuBuilder = menuBuilder; + } - - public DataAccessService getDataAccessService() { + public DataAccessService getDataAccessService() { return dataAccessService; } - public void setDataAccessService(DataAccessService dataAccessService) { this.dataAccessService = dataAccessService; } - } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/PostDroolsService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/PostDroolsService.java index b299f021..831b2734 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/PostDroolsService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/PostDroolsService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -44,9 +44,9 @@ import org.onap.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/onap/portalsdk/core/service/PostDroolsServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/PostDroolsServiceImpl.java index 1d5d9cc9..faa15329 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/PostDroolsServiceImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/PostDroolsServiceImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -38,8 +38,6 @@ package org.onap.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; @@ -65,14 +63,10 @@ import org.springframework.transaction.annotation.Transactional; import com.fasterxml.jackson.databind.ObjectMapper; -/** - * TODO REFACTOR - * - */ @Service("postDroolsService") @Transactional -public class PostDroolsServiceImpl implements PostDroolsService{ - +public class PostDroolsServiceImpl implements PostDroolsService { + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PostDroolsServiceImpl.class); @Override @@ -82,29 +76,26 @@ public class PostDroolsServiceImpl implements PostDroolsService{ return resultsString; } - + @Override public List<PostDroolsBean> fetchDroolBeans() { - - List<PostDroolsBean> beanList = new ArrayList<PostDroolsBean>(); + + List<PostDroolsBean> beanList = new ArrayList<>(); 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 + 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()); + } + } catch (Exception ex) { + logger.error(EELFLoggerDelegate.errorLogger, "fetchDroolBeans failed", ex); } - return beanList; + return beanList; } - + @Override public String retrieveClass(String fileName) { String resultsString = ""; @@ -113,51 +104,43 @@ public class PostDroolsServiceImpl implements PostDroolsService{ final KnowledgeBuilder kbuilder = loadKBuilder(fileName); final Collection<KnowledgePackage> pkgs = kbuilder.getKnowledgePackages(); return pkgs.iterator().next().getFactTypes().iterator().next().getFactClass().getName(); - + } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "retrieveClass failed", e); } - + 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), + kbuilder.add( + ResourceFactory.newFileResource( + SystemProperties.getProperty(SystemProperties.FILES_PATH) + File.separator + fileName), 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\"."); - + throw new IllegalArgumentException("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). @@ -168,37 +151,29 @@ public class PostDroolsServiceImpl implements PostDroolsService{ final StatefulKnowledgeSession kSession = kbase.newStatefulKnowledgeSession(); ObjectMapper mapper = new ObjectMapper(); - if(ruleValue == null || ruleValue.equals("")) { + if (ruleValue == null || "".equals(ruleValue)) { 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){ + List<String> ruleResponse = new ArrayList<>(); + + for (String rule : selectedRules) { Class<DroolsRuleService> clazz = (Class<DroolsRuleService>) Class.forName(className); - DroolsRuleService droolsIntroduction =clazz.newInstance(); + 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 (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "executeDemoRules failed", e); } - + return resultsString; } - - } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/PostSearchService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/PostSearchService.java index 91d21776..248fdbfb 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/PostSearchService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/PostSearchService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/PostSearchServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/PostSearchServiceImpl.java index e799e313..4bf78eed 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/PostSearchServiceImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/PostSearchServiceImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ProfileService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ProfileService.java index 2ee612a6..b2831c5b 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ProfileService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ProfileService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,42 +37,42 @@ */ package org.onap.portalsdk.core.service; +import java.io.IOException; import java.util.List; import org.onap.portalsdk.core.domain.Profile; import org.onap.portalsdk.core.domain.User; - public interface ProfileService { - + /** * * @return returns list of profiles - * @throws Exception + * @throws IOException */ - List<Profile> findAll() throws Exception; - + List<Profile> findAll() throws IOException; + /** * * @param id * @return returns profile of requested ID - * @throws Exception + * @throws IOException */ - Profile getProfile(int id) throws Exception; - - + Profile getProfile(int id) throws IOException; + /** * - * @param id loginId + * @param id + * loginId * @return returns User info of requested ID - * @throws Exception + * @throws IOException */ - User getUser(String id) throws Exception; - + User getUser(String id) throws IOException; + /** * * @param user - *saveUser method saves the user object + * saveUser method saves the user object */ void saveUser(User user); } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ProfileServiceCentralizedImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ProfileServiceCentralizedImpl.java index 91661e61..6503dd34 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ProfileServiceCentralizedImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ProfileServiceCentralizedImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,27 +37,25 @@ */ package org.onap.portalsdk.core.service; +import java.io.IOException; import java.util.List; import org.onap.portalsdk.core.domain.Profile; import org.onap.portalsdk.core.domain.User; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import com.fasterxml.jackson.databind.ObjectMapper; @Transactional -public class ProfileServiceCentralizedImpl implements ProfileService{ - - private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ProfileServiceCentralizedImpl.class); - +public class ProfileServiceCentralizedImpl implements ProfileService { + @Autowired - AppService appService; - + private DataAccessService dataAccessService; + @Autowired - private DataAccessService dataAccessService; - + private RestApiRequestBuilder restApiRequestBuilder; + public DataAccessService getDataAccessService() { return dataAccessService; } @@ -66,40 +64,30 @@ public class ProfileServiceCentralizedImpl implements ProfileService{ this.dataAccessService = dataAccessService; } - @Autowired - RestApiRequestBuilder restApiRequestBuilder ; - @SuppressWarnings("unchecked") @Override - public List<Profile> findAll() throws Exception{ + public List<Profile> findAll() throws IOException { return getDataAccessService().getList(Profile.class, null); } @Override - public Profile getProfile(int id) throws Exception{ + public Profile getProfile(int id) throws IOException { ObjectMapper mapper = new ObjectMapper(); - Profile user = null; - String responseString = restApiRequestBuilder.getViaREST("/getProfile/" + id, true,Integer.toString(id)); - user = mapper.readValue(responseString, Profile.class); - return user; + String responseString = restApiRequestBuilder.getViaREST("/getProfile/" + id, true, Integer.toString(id)); + Profile profile = mapper.readValue(responseString, Profile.class); + return profile; } @Override - public User getUser(String id) throws Exception{ + public User getUser(String id) throws IOException { ObjectMapper mapper = new ObjectMapper(); - User user = new User(); - String responseString =restApiRequestBuilder.getViaREST("/user/" + id, true,id); - user = mapper.readValue(responseString, User.class); - + String responseString = restApiRequestBuilder.getViaREST("/user/" + id, true, id); + User user = mapper.readValue(responseString, User.class); return user; } @Override public void saveUser(User user) { - try { - getDataAccessService().saveDomainObject(user, null); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "saveUser failed", e); - } - } + getDataAccessService().saveDomainObject(user, null); + } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ProfileServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ProfileServiceImpl.java index ac7c2d01..20b14eb6 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ProfileServiceImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ProfileServiceImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -46,44 +46,41 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; @Transactional -public class ProfileServiceImpl implements ProfileService{ +public class ProfileServiceImpl implements ProfileService { @Autowired private ProfileDao profileDao; - + @Autowired private DataAccessService dataAccessService; - + + @Override @SuppressWarnings("unchecked") public List<Profile> findAll() { - //List msgDB = getDataAccessService().getList(Profile.class, null); return getDataAccessService().getList(Profile.class, null); } - - public User getUser(String userId){ + + @Override + public User getUser(String userId) { return (User) getDataAccessService().getDomainObject(User.class, Long.parseLong(userId), null); } - - public void saveUser(User user){ - + + @Override + public void saveUser(User user) { getDataAccessService().saveDomainObject(user, null); } - - + + @Override 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/onap/portalsdk/core/service/RestApiRequestBuilder.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/RestApiRequestBuilder.java index 5870dc29..c6c40b70 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/RestApiRequestBuilder.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/RestApiRequestBuilder.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -54,11 +54,11 @@ public class RestApiRequestBuilder { private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestApiRequestBuilder.class); + private static final String APPLICATION_JSON = "application/json"; + @Autowired private AppService appService; - private static final String content_type = "application/json"; - /** * * @param restEndPoint @@ -69,9 +69,9 @@ public class RestApiRequestBuilder { */ public String getViaREST(String restEndPoint, boolean isBasicAuth, String userId) throws IOException { logger.info(EELFLoggerDelegate.debugLogger, "getViaRest: endpoint {}", restEndPoint); - String appName = ""; - String appUserName = ""; - String decryptedPwd = ""; + String appName; + String appUserName; + String decryptedPwd = null; App app = appService.getDefaultApp(); if (app != null) { appName = app.getName(); @@ -81,12 +81,13 @@ public class RestApiRequestBuilder { SystemProperties.getProperty(SystemProperties.Decryption_Key)); } catch (CipherUtilException e) { logger.error(EELFLoggerDelegate.errorLogger, "getViaREST failed", e); - throw new IOException(e.toString()); + throw new IOException("getViaREST failed", e); } } else { logger.warn(EELFLoggerDelegate.errorLogger, "getViaREST: Unable to locate the app information from the database."); appName = SystemProperties.SDK_NAME; + appUserName = "unknown"; } String requestId = MDC.get(MDC_KEY_REQUEST_ID); String response = RestWebServiceClient.getInstance().getPortalContent(restEndPoint, userId, appName, requestId, @@ -106,9 +107,9 @@ public class RestApiRequestBuilder { public void postViaREST(String restEndPoint, boolean isBasicAuth, String content, String userId) throws IOException { logger.info(EELFLoggerDelegate.debugLogger, "postViaRest: endpoint {}", restEndPoint); - String appName = ""; - String appUserName = ""; - String decryptedPwd = ""; + String appName; + String appUserName; + String decryptedPwd = null; App app = appService.getDefaultApp(); if (app != null) { appName = app.getName(); @@ -118,16 +119,17 @@ public class RestApiRequestBuilder { SystemProperties.getProperty(SystemProperties.Decryption_Key)); } catch (CipherUtilException e) { logger.error(EELFLoggerDelegate.errorLogger, "postViaREST failed", e); - throw new IOException(e.toString()); + throw new IOException("postViaREST failed", e); } } else { logger.warn(EELFLoggerDelegate.errorLogger, "postViaRest: Unable to locate the app information from the database."); appName = SystemProperties.SDK_NAME; + appUserName = "unknown"; } String requestId = MDC.get(MDC_KEY_REQUEST_ID); String response = RestWebServiceClient.getInstance().postPortalContent(restEndPoint, userId, appName, requestId, - appUserName, decryptedPwd, content_type, content, isBasicAuth); + appUserName, decryptedPwd, APPLICATION_JSON, content, isBasicAuth); logger.debug(EELFLoggerDelegate.debugLogger, "postViaRest response: {}", response); } @@ -142,9 +144,9 @@ public class RestApiRequestBuilder { public void deleteViaRest(String restEndPoint, boolean isBasicAuth, String content, String userId) throws IOException { logger.info(EELFLoggerDelegate.debugLogger, "deleteViaRest: endpoint {}", restEndPoint); - String appName = ""; - String appUserName = ""; - String decryptedPwd = ""; + String appName; + String appUserName; + String decryptedPwd = null; App app = appService.getDefaultApp(); if (app != null) { appName = app.getName(); @@ -153,17 +155,18 @@ public class RestApiRequestBuilder { decryptedPwd = CipherUtil.decrypt(app.getAppPassword(), SystemProperties.getProperty(SystemProperties.Decryption_Key)); } catch (CipherUtilException e) { - logger.error(EELFLoggerDelegate.errorLogger, "postViaREST failed", e); - throw new IOException(e.toString()); + logger.error(EELFLoggerDelegate.errorLogger, "deleteViaRest failed", e); + throw new IOException("deleteViaRest failed", e); } } else { logger.warn(EELFLoggerDelegate.errorLogger, "deleteViaRest: Unable to locate the app information from the database."); appName = SystemProperties.SDK_NAME; + appUserName = "unknown"; } String requestId = MDC.get(MDC_KEY_REQUEST_ID); String response = RestWebServiceClient.getInstance().deletePortalContent(restEndPoint, userId, appName, - requestId, appUserName, decryptedPwd, content_type, content, isBasicAuth); + requestId, appUserName, decryptedPwd, APPLICATION_JSON, content, isBasicAuth); logger.debug(EELFLoggerDelegate.debugLogger, "deleteViaRest response: {}", response); } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/RoleService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/RoleService.java index 12c9d59e..b0730859 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/RoleService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/RoleService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,111 +37,118 @@ */ package org.onap.portalsdk.core.service; +import java.io.IOException; import java.util.List; import org.onap.portalsdk.core.domain.Role; import org.onap.portalsdk.core.domain.RoleFunction; - public interface RoleService { /** + * returns list of Role Functions * - * @param requestedLoginId loginId + * @param requestedLoginId + * loginId * @return returns List of RoleFunction - * @throws Exception - * Method getRoleFunctions returns list of Role Functions + * @throws IOException */ - List<RoleFunction> getRoleFunctions(String requestedLoginId) throws Exception; - - + List<RoleFunction> getRoleFunctions(String requestedLoginId) throws IOException; + /** + * returns list of avialable child roles * * @param requestedLoginId * @param roleId * @return returns List of Role - * @throws Exception - * Method getAvailableChildRoles returns list of avialable child roles + * @throws IOException */ - List<Role> getAvailableChildRoles(String requestedLoginId,Long roleId) throws Exception; - - + List<Role> getAvailableChildRoles(String requestedLoginId, Long roleId) throws IOException; + /** + * returns Role object with requested roleID * * @param requestedLoginId - * @param id roleId - * @return returns role - * @throws Exception - * Method getRole returns Role object if requested roleID + * @param id + * roleId + * @return returns role + * @throws IOException */ - Role getRole(String requestedLoginId,Long id) throws Exception; - + Role getRole(String requestedLoginId, Long id) throws IOException; + /** + * saves the Role Object * * @param requestedLoginId - * @param domainRole Object to be saved - * Method saveRole saves the Role Object + * @param domainRole + * Object to be saved + * @throws IOException */ - void saveRole(String requestedLoginId,Role domainRole) throws Exception; - + void saveRole(String requestedLoginId, Role domainRole) throws IOException; + /** * + * deletes the requested Role Object + * * @param requestedLoginId - * @param domainRole Object to be removed - * Method deleteRole deletes the requested Role Object + * @param domainRole + * Object to be removed + * @throws IOException */ - void deleteRole(String requestedLoginId,Role domainRole) throws Exception; - + void deleteRole(String requestedLoginId, Role domainRole) throws IOException; + /** + * gets the list of available roles * * @param requestedLoginId * @return returns list of available roles - * @throws Exception - * Method getAvailableRoles gets the list of available roles + * @throws IOException */ - - List<Role> getAvailableRoles(String requestedLoginId) throws Exception; - + List<Role> getAvailableRoles(String requestedLoginId) throws IOException; + /** + * gets the list of active roles of application * * @param requestedLoginId * @return List of active roles - * @throws Exception - * Method getActiveRoles gets the list of active roles of application - * + * @throws IOException */ - List<Role> getActiveRoles(String requestedLoginId) throws Exception; + List<Role> getActiveRoles(String requestedLoginId) throws IOException; /** + * returns RoleFunction of requested function code * * @param requestedLoginId - * @param code function code + * @param code + * function code * @return RoleFunction of requested function code - * @throws Exception - * Method getRoleFunction returns RoleFunction of requested function code + * @throws IOException */ - RoleFunction getRoleFunction(String requestedLoginId,String code) throws Exception; - + RoleFunction getRoleFunction(String requestedLoginId, String code) throws IOException; + /** + * saves the requested RoleFunction object * * @param requestedLoginId * @param domainRoleFunction - * Method saveRoleFunction saves the requested RoleFunction object + * @throws IOException */ - void saveRoleFunction(String requestedLoginId,RoleFunction domainRoleFunction) throws Exception; - + void saveRoleFunction(String requestedLoginId, RoleFunction domainRoleFunction) throws IOException; + /** + * deletes the requested RoleFunction object * * @param requestedLoginId * @param domainRoleFunction - * Method deleteRoleFunction deletes the requested RoleFunction object + * @throws IOException */ - void deleteRoleFunction(String requestedLoginId,RoleFunction domainRoleFunction) throws Exception; - + void deleteRoleFunction(String requestedLoginId, RoleFunction domainRoleFunction) throws IOException; + /** + * deletes the requested object * * @param requestedLoginId * @param id - * Method deleteDependcyRoleRecord deletes the requested object + * @throws IOException */ - void deleteDependcyRoleRecord(String requestedLoginId,Long id); + void deleteDependcyRoleRecord(String requestedLoginId, Long id) throws IOException; } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/RoleServiceCentralizedAccess.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/RoleServiceCentralizedAccess.java index 13da750c..3ef7cb8b 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/RoleServiceCentralizedAccess.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/RoleServiceCentralizedAccess.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,6 +37,7 @@ */ package org.onap.portalsdk.core.service; +import java.io.IOException; import java.util.HashSet; import java.util.Iterator; import java.util.List; @@ -61,26 +62,23 @@ public class RoleServiceCentralizedAccess implements RoleService { private RestApiRequestBuilder restApiRequestBuilder; @Override - public List<RoleFunction> getRoleFunctions(String loginId) throws Exception { - - List<RoleFunction> roleFunctionList = null; - String role_function_list = ""; - role_function_list = restApiRequestBuilder.getViaREST("/functions", true, loginId); + public List<RoleFunction> getRoleFunctions(String loginId) throws IOException { + String roleFunctionString = restApiRequestBuilder.getViaREST("/functions", true, loginId); ObjectMapper mapper = new ObjectMapper(); - roleFunctionList = mapper.readValue(role_function_list, + List<RoleFunction> roleFunctionList = mapper.readValue(roleFunctionString, TypeFactory.defaultInstance().constructCollectionType(List.class, RoleFunction.class)); return roleFunctionList; } @Override - public List<Role> getAvailableChildRoles(String loginId, Long roleId) throws Exception { + public List<Role> getAvailableChildRoles(String loginId, Long roleId) throws IOException { List<Role> availableChildRoles = getAvailableRoles(loginId); if (roleId == null || roleId == 0) { return availableChildRoles; } Role currentRole = getRole(loginId, roleId); - Set<Role> allParentRoles = new TreeSet<Role>(); + Set<Role> allParentRoles = new TreeSet<>(); allParentRoles = getAllParentRolesAsList(loginId, currentRole, allParentRoles); Iterator<Role> availableChildRolesIterator = availableChildRoles.iterator(); @@ -105,11 +103,10 @@ public class RoleServiceCentralizedAccess implements RoleService { } @Override - public Role getRole(String loginId, Long id) throws Exception { + public Role getRole(String loginId, Long id) throws IOException { ObjectMapper mapper = new ObjectMapper(); String roleString = restApiRequestBuilder.getViaREST("/role/" + id, true, loginId); - Role role = new Role(); - role = mapper.readValue(roleString, Role.class); + Role role = mapper.readValue(roleString, Role.class); if (role.getRoleFunctions() != null) { @SuppressWarnings("unchecked") Set<RoleFunction> roleFunctionList = role.getRoleFunctions(); @@ -129,50 +126,38 @@ public class RoleServiceCentralizedAccess implements RoleService { } @Override - public void saveRole(String loginId, Role domainRole) throws Exception { + public void saveRole(String loginId, Role domainRole) throws IOException { ObjectMapper mapper = new ObjectMapper(); String role = mapper.writeValueAsString(domainRole); - try { - restApiRequestBuilder.postViaREST("/role", true, role, loginId); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "saveRole Failed", e); - throw new Exception(e.getMessage()); - } + restApiRequestBuilder.postViaREST("/role", true, role, loginId); } @Override - public void deleteRole(String loginId, Role domainRole) throws Exception { + public void deleteRole(String loginId, Role domainRole) throws IOException { String roleName = domainRole.getName().replaceAll(" ", "%20"); - try { - restApiRequestBuilder.deleteViaRest("/deleteRole/"+ roleName, true, null, loginId); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "deleteRole Failed", e); - throw new Exception(e.getMessage()); - } + restApiRequestBuilder.deleteViaRest("/deleteRole/" + roleName, true, null, loginId); } + @Override - public List<Role> getAvailableRoles(String requestedLoginId) throws Exception { + public List<Role> getAvailableRoles(String requestedLoginId) throws IOException { ObjectMapper mapper = new ObjectMapper(); String roleList = restApiRequestBuilder.getViaREST("/roles", true, requestedLoginId); - List<Role> roles = null; - roles = mapper.readValue(roleList, + List<Role> roles = mapper.readValue(roleList, TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class)); return roles; } @Override - public List<Role> getActiveRoles(String requestedLoginId) throws Exception { + public List<Role> getActiveRoles(String requestedLoginId) throws IOException { ObjectMapper mapper = new ObjectMapper(); String roleString = restApiRequestBuilder.getViaREST("/activeRoles", true, requestedLoginId); - List<Role> roles = null; - roles = mapper.readValue(roleString, + List<Role> roles = mapper.readValue(roleString, TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class)); return roles; - } @Override - public RoleFunction getRoleFunction(String requestedLoginId, String code) throws Exception { + public RoleFunction getRoleFunction(String requestedLoginId, String code) throws IOException { ObjectMapper mapper = new ObjectMapper(); String responseString = restApiRequestBuilder.getViaREST("/function/" + code, true, requestedLoginId); RoleFunction roleFunction = new RoleFunction(); @@ -183,35 +168,21 @@ public class RoleServiceCentralizedAccess implements RoleService { } @Override - public void saveRoleFunction(String requestedLoginId, RoleFunction domainRoleFunction) throws Exception { + public void saveRoleFunction(String requestedLoginId, RoleFunction domainRoleFunction) throws IOException { ObjectMapper mapper = new ObjectMapper(); String roleFunction = mapper.writeValueAsString(domainRoleFunction); - try{ restApiRequestBuilder.postViaREST("/roleFunction", true, roleFunction, requestedLoginId); - }catch(Exception e){ - logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction Failed", e); - throw new Exception(e.getMessage()); - } } @Override - public void deleteRoleFunction(String requestedLoginId, RoleFunction domainRoleFunction) throws Exception { + public void deleteRoleFunction(String requestedLoginId, RoleFunction domainRoleFunction) throws IOException { String code = domainRoleFunction.getCode(); - try { - restApiRequestBuilder.deleteViaRest("/roleFunction/"+ code, true, null, requestedLoginId); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleFunction Failed ", e); - throw new Exception(e.getMessage()); - } + restApiRequestBuilder.deleteViaRest("/roleFunction/" + code, true, null, requestedLoginId); } @Override - public void deleteDependcyRoleRecord(String requestedLoginId, Long id) { - try { - restApiRequestBuilder.deleteViaRest("/deleteDependcyRoleRecord/" + id, true, null, requestedLoginId); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "deleteDependcyRoleRecord Failed", e); - } + public void deleteDependcyRoleRecord(String requestedLoginId, Long id) throws IOException { + restApiRequestBuilder.deleteViaRest("/deleteDependcyRoleRecord/" + id, true, null, requestedLoginId); } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/RoleServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/RoleServiceImpl.java index abf785a0..e0e2d2e3 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/RoleServiceImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/RoleServiceImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -61,7 +61,7 @@ public class RoleServiceImpl implements RoleService { @Autowired private DataAccessService dataAccessService; - DataSource dataSource; + private DataSource dataSource; public DataSource getDataSource() { return dataSource; @@ -72,22 +72,23 @@ public class RoleServiceImpl implements RoleService { this.dataSource = dataSource; } + @Override @SuppressWarnings("unchecked") public List<RoleFunction> getRoleFunctions(String loginId) { - // List msgDB = getDataAccessService().getList(Profile.class, null); return getDataAccessService().getList(RoleFunction.class, null); } + @Override @SuppressWarnings("unchecked") - public List<Role> getAvailableChildRoles(String loginId,Long roleId) { + public List<Role> getAvailableChildRoles(String loginId, 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(loginId,currentRole, allParentRoles); + Set<Role> allParentRoles = new TreeSet<>(); + allParentRoles = getAllParentRolesAsList(loginId, currentRole, allParentRoles); Iterator<Role> availableChildRolesIterator = availableChildRoles.iterator(); while (availableChildRolesIterator.hasNext()) { @@ -100,47 +101,54 @@ public class RoleServiceImpl implements RoleService { } @SuppressWarnings("unchecked") - private Set<Role> getAllParentRolesAsList(String loginId,Role role, Set<Role> allParentRoles) { + private Set<Role> getAllParentRolesAsList(String loginId, Role role, Set<Role> allParentRoles) { Set<Role> parentRoles = role.getParentRoles(); allParentRoles.addAll(parentRoles); Iterator<Role> parentRolesIterator = parentRoles.iterator(); while (parentRolesIterator.hasNext()) { - getAllParentRolesAsList( loginId,parentRolesIterator.next(), allParentRoles); + getAllParentRolesAsList(loginId, parentRolesIterator.next(), allParentRoles); } return allParentRoles; } - public RoleFunction getRoleFunction(String loginId,String code) { + @Override + public RoleFunction getRoleFunction(String loginId, String code) { return (RoleFunction) getDataAccessService().getDomainObject(RoleFunction.class, code, null); } - public void saveRoleFunction(String loginId,RoleFunction domainRoleFunction) { + @Override + public void saveRoleFunction(String loginId, RoleFunction domainRoleFunction) { getDataAccessService().saveDomainObject(domainRoleFunction, null); } - public void deleteRoleFunction(String loginId,RoleFunction domainRoleFunction) { + @Override + public void deleteRoleFunction(String loginId, RoleFunction domainRoleFunction) { getDataAccessService().deleteDomainObject(domainRoleFunction, null); } - public Role getRole(String loginId,Long id) { + @Override + public Role getRole(String loginId, Long id) { return (Role) getDataAccessService().getDomainObject(Role.class, id, null); } - public void saveRole(String loginId,Role domainRole) { + @Override + public void saveRole(String loginId, Role domainRole) { getDataAccessService().saveDomainObject(domainRole, null); } - public void deleteRole(String loginId,Role domainRole) { + @Override + public void deleteRole(String loginId, Role domainRole) { getDataAccessService().deleteDomainObject(domainRole, null); } + @Override @SuppressWarnings("unchecked") public List<Role> getAvailableRoles(String loginId) { return getDataAccessService().getList(Role.class, null); } - @SuppressWarnings("unchecked") @Override + @SuppressWarnings("unchecked") public List<Role> getActiveRoles(String loginId) { String filter = " where active_yn = 'Y' "; return getDataAccessService().getList(Role.class, filter, null, null); @@ -155,7 +163,7 @@ public class RoleServiceImpl implements RoleService { } @Override - public void deleteDependcyRoleRecord(String loginId,Long id) { + public void deleteDependcyRoleRecord(String loginId, Long id) { Connection conn = null; Statement stmt = null; try { @@ -163,22 +171,16 @@ public class RoleServiceImpl implements RoleService { 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); + logger.error(EELFLoggerDelegate.errorLogger, "deleteDependcyRoleRecord failed to close", se); } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UrlAccessImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UrlAccessImpl.java index 2a9718a6..4dde6116 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UrlAccessImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UrlAccessImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -64,11 +64,10 @@ public class UrlAccessImpl implements UrlAccessService { List list = dataAccessService.executeNamedQuery("restrictedUrls", params, null); // loop through the list of restricted URL's - if (list != null && list.size() > 0) { + if (list != null && !list.isEmpty()) { for (int i = 0; i < list.size(); i++) { UrlsAccessible urlFunctions = (UrlsAccessible) list.get(i); - // String url = (String) urlFunctions.getUrl(); - String functionCd = (String) urlFunctions.getFunctionCd(); + String functionCd = urlFunctions.getFunctionCd(); if (UserUtils.isAccessible(request, functionCd)) { isAccessible = true; } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UrlAccessService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UrlAccessService.java index 7b915854..106dcb1b 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UrlAccessService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UrlAccessService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -40,7 +40,7 @@ package org.onap.portalsdk.core.service; import javax.servlet.http.HttpServletRequest; public interface UrlAccessService { - + /** * Answers whether the specified URL is accessible. * @@ -48,5 +48,5 @@ public interface UrlAccessService { * @param currentUrl * @return true if yes, false if no. */ - public boolean isUrlAccessible(HttpServletRequest request, String currentUrl); + public boolean isUrlAccessible(HttpServletRequest request, String currentUrl); } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserProfileService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserProfileService.java index a7537959..c9dfae12 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserProfileService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserProfileService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -41,11 +41,14 @@ import java.util.List; import org.onap.portalsdk.core.domain.User; - public interface UserProfileService { List<User> findAll(); + 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/onap/portalsdk/core/service/UserProfileServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserProfileServiceImpl.java index 5a123393..184ec85b 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserProfileServiceImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserProfileServiceImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -38,9 +38,9 @@ package org.onap.portalsdk.core.service; import java.util.ArrayList; -import java.util.HashSet; import java.util.Iterator; import java.util.List; +import java.util.Set; import java.util.SortedSet; import org.hibernate.criterion.Criterion; @@ -54,75 +54,78 @@ import org.springframework.transaction.annotation.Transactional; @Service("userProfile") @Transactional -public class UserProfileServiceImpl implements UserProfileService{ +public class UserProfileServiceImpl implements UserProfileService { - @Autowired - private DataAccessService dataAccessService; - + private DataAccessService dataAccessService; + + @Override @SuppressWarnings("unchecked") public List<User> findAll() { return getDataAccessService().getList(User.class, null); } - + + @Override @SuppressWarnings("unchecked") - public User getUserByLoginId(String loginId){ - User user=null; + public User getUserByLoginId(String loginId) { + User user = null; List<Criterion> restrictionsList = new ArrayList<Criterion>(); - Criterion criterion1= Restrictions.eq("loginId",loginId); + 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) + 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){ - + + @Override + public void saveUser(User user) { getDataAccessService().saveDomainObject(user, null); } - + public DataAccessService getDataAccessService() { return dataAccessService; } - public void setDataAccessService(DataAccessService dataAccessService) { this.dataAccessService = dataAccessService; } - + + @Override @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())) + Set<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) { + if (u.getOrgUserId() != null) { + if (originOrgUserId.compareTo(u.getOrgUserId()) > 0) { u.setChatId(originOrgUserId + "-" + u.getOrgUserId()); - } else u.setChatId(u.getOrgUserId() + "-" + originOrgUserId ); + } else + u.setChatId(u.getOrgUserId() + "-" + originOrgUserId); } } return users; - + } - + + @Override public List<User> findAllActive() { @SuppressWarnings("unchecked") - List<User> users = getDataAccessService().getList(User.class, null); + 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 + while (itr.hasNext()) { + User u = 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 + while (itrRoles.hasNext()) { + Role role = itrRoles.next(); + if (!role.getActive()) + u.removeRole(role.getId());// if not active remove role from list } } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserService.java index 8a667462..1f6e240d 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -41,8 +41,6 @@ import java.io.IOException; import org.onap.portalsdk.core.domain.User; -import com.fasterxml.jackson.core.JsonProcessingException; - public interface UserService { /** @@ -61,7 +59,6 @@ public interface UserService { * @param response * @return User object * @throws IOException - * @throws JsonProcessingException */ - User userMapper(String response) throws IOException, JsonProcessingException; + User userMapper(String response) throws IOException; } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserServiceCentalizedImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserServiceCentalizedImpl.java index 17735bd6..d1b05695 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserServiceCentalizedImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserServiceCentalizedImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -54,7 +54,6 @@ import org.onap.portalsdk.core.domain.UserApp; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; -import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; @Transactional @@ -94,7 +93,7 @@ public class UserServiceCentalizedImpl implements UserService { } @Override - public User userMapper(String res) throws IOException, JsonProcessingException { + public User userMapper(String res) throws IOException { ObjectMapper mapper = new ObjectMapper(); User user = mapper.readValue(res, User.class); Set<RoleFunction> roleFunctionListNew = new HashSet<>(); @@ -108,9 +107,9 @@ public class UserServiceCentalizedImpl implements UserService { Role role = nextApp.getRole(); @SuppressWarnings("unchecked") Set<RoleFunction> roleFunctionList = role.getRoleFunctions(); - Iterator<RoleFunction> itetaror = roleFunctionList.iterator(); - while (itetaror.hasNext()) { - Object nextValue = itetaror.next(); + Iterator<RoleFunction> roleFnIter = roleFunctionList.iterator(); + while (roleFnIter.hasNext()) { + Object nextValue = roleFnIter.next(); RoleFunction roleFunction = mapper.convertValue(nextValue, RoleFunction.class); roleFunctionListNew.add(roleFunction); } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserServiceImpl.java index d41499a0..0318020d 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserServiceImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserServiceImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -45,13 +45,13 @@ import org.springframework.transaction.annotation.Transactional; public class UserServiceImpl implements UserService { @Autowired - private DataAccessService dataAccessService; - + private DataAccessService dataAccessService; + @Override public User getUser(String id) { return (User) dataAccessService.getDomainObject(User.class, Long.parseLong(id), null); } - + @Override public User userMapper(String response) { throw new UnsupportedOperationException("method cannot be used"); diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/WebServiceCallService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/WebServiceCallService.java index 6db9cb86..23ff1f99 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/WebServiceCallService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/WebServiceCallService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,8 +37,9 @@ */ package org.onap.portalsdk.core.service; +import org.onap.portalsdk.core.onboarding.exception.CipherUtilException; public interface WebServiceCallService { - public boolean verifyRESTCredential(String secretKey, String requestAppName, String requestPassword)throws Exception; - /*public String get(String restURL, String restPath);*/ + public boolean verifyRESTCredential(String secretKey, String requestAppName, String requestPassword) + throws CipherUtilException; } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/WebServiceCallServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/WebServiceCallServiceImpl.java index f1a0cb28..71479820 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/WebServiceCallServiceImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/WebServiceCallServiceImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -40,7 +40,7 @@ package org.onap.portalsdk.core.service; import java.util.List; import org.onap.portalsdk.core.domain.App; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.onboarding.exception.CipherUtilException; import org.onap.portalsdk.core.onboarding.util.CipherUtil; import org.onap.portalsdk.core.util.SystemProperties; import org.springframework.beans.factory.annotation.Autowired; @@ -49,159 +49,51 @@ import org.springframework.transaction.annotation.Transactional; @Service("webServiceCallService") @Transactional -public class WebServiceCallServiceImpl implements WebServiceCallService{ - - private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WebServiceCallServiceImpl.class); +public class WebServiceCallServiceImpl implements WebServiceCallService { @Autowired - private DataAccessService dataAccessService; - + private DataAccessService dataAccessService; + @Autowired private AppService appService; - + /** - * Verify REST Credential + * Verify REST Credential + * * @return true if the credential is accepted; else false. */ @Override - public boolean verifyRESTCredential(String secretKey, String requestAppName, String requestPassword)throws Exception { + public boolean verifyRESTCredential(String secretKey, String requestAppName, String requestPassword) + throws CipherUtilException { App app = appService.getDefaultApp(); - if (app!=null) { + 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)) { + 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 App findApp() { + List list = getDataAccessService().getList(App.class, " where id = 1", null, null); + return (list == null || list.isEmpty()) ? 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/onap/portalsdk/core/service/support/FusionService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/support/FusionService.java index 601afc66..da043820 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/support/FusionService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/support/FusionService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,9 +37,8 @@ */ package org.onap.portalsdk.core.service.support; - import org.onap.portalsdk.core.FusionObject; public class FusionService implements FusionObject { - /** Logger for this class and subclasses */ + /** Logger for this class and subclasses */ } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/support/ServiceLocator.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/support/ServiceLocator.java index bcd55878..ef12d3db 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/support/ServiceLocator.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/support/ServiceLocator.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -39,7 +39,6 @@ package org.onap.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/onap/portalsdk/core/service/support/ServiceLocatorImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/support/ServiceLocatorImpl.java index b72d5d51..704cd39a 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/support/ServiceLocatorImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/support/ServiceLocatorImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -55,68 +55,58 @@ import org.springframework.stereotype.Service; @Service("serviceLocator") public class ServiceLocatorImpl implements ServiceLocator { - private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ServiceLocatorImpl.class); + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ServiceLocatorImpl.class); - 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) + 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() { + } - // 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? - } + /* + * 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; } - return ldapContext; - }*/ + // 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; } + */ } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/util/CacheManager.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/util/CacheManager.java index 774943d4..ba68539d 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/util/CacheManager.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/util/CacheManager.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -39,23 +39,26 @@ package org.onap.portalsdk.core.util; import org.onap.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); + + public CacheManager() { + super(); + } - if (result != null) { - putObject("lookupRoles", result); - }*/ - } + /* + * 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. + */ + @Override + public void loadLookUpCache() { + // Example code removed to silence Sonar. + } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/util/EncDecUtilTest.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/util/EncDecUtilTest.java index 3a13e362..926ed347 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/util/EncDecUtilTest.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/util/EncDecUtilTest.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -36,12 +36,13 @@ * ECOMP is a trademark and service mark of AT&T Intellectual Property. */ package org.onap.portalsdk.core.util; + +import java.io.UnsupportedEncodingException; import java.security.AlgorithmParameters; +import java.security.GeneralSecurityException; 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; @@ -49,82 +50,60 @@ 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; - } + + private static final String WORD = "test"; + private static final String SALT = "r n�HN~��|f��X�"; + private static final int ITERATIONS = 65536; + private static final int KEY_SIZE = 256; + private byte[] ivBytes; + + public String encrypt(String plainText) throws UnsupportedEncodingException, GeneralSecurityException { + + // get salt + // salt = generateSalt(); + byte[] saltBytes = SALT.getBytes("UTF-8"); + + // Derive the key + SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); + PBEKeySpec spec = new PBEKeySpec(WORD.toCharArray(), saltBytes, ITERATIONS, KEY_SIZE); + + 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 Base64.encodeBase64String(encryptedTextBytes); + } + + public String decrypt(String encryptedText) throws UnsupportedEncodingException, GeneralSecurityException { + byte[] saltBytes = SALT.getBytes("UTF-8"); + byte[] encryptedTextBytes = Base64.decodeBase64(encryptedText); + + // Derive the key + SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); + PBEKeySpec spec = new PBEKeySpec(WORD.toCharArray(), saltBytes, ITERATIONS, KEY_SIZE); + + 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 = cipher.doFinal(encryptedTextBytes); + return new String(decryptedTextBytes); + } + + public String generateSalt() { + SecureRandom random = new SecureRandom(); + byte [] bytes = new byte[20]; + random.nextBytes(bytes); + return new String(bytes); + } }
\ No newline at end of file diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/util/JSONUtil.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/util/JSONUtil.java index 8bbd791a..3375bee7 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/util/JSONUtil.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/util/JSONUtil.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -46,14 +46,19 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; public class JSONUtil { - public static String convertResponseToJSON(String response) throws JsonProcessingException{ + + private JSONUtil() { + // Class has only static methods + } + + public static String convertResponseToJSON(String response) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); - Map<String, String> responseMap = new HashMap<String, String>(); + Map<String, String> responseMap = new HashMap<>(); responseMap.put("response", response); - response = mapper.writeValueAsString(responseMap); - return response; + String result = mapper.writeValueAsString(responseMap); + return result; } - + public static User mapToDomainUser(User domainUser, User editUser) { domainUser.setOrgId(editUser.getOrgId()); domainUser.setManagerId(editUser.getManagerId()); diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/util/SystemProperties.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/util/SystemProperties.java index 31d2f04d..6f119104 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/util/SystemProperties.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/util/SystemProperties.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -69,82 +69,6 @@ public class SystemProperties { 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 Property 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. - * - * @param key - * Property key - * @return Property value; the empty string if the environment was not - * autowired, which should never happen. - * @throws IllegalStateException - * if the key cannot be resolved - */ - 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"; @@ -228,7 +152,6 @@ public class SystemProperties { public static final String LOGIN_METHOD_BACKDOOR = "login_method_backdoor"; public static final String LOGIN_METHOD_ATTRIBUTE_NAME = "login_method_attribute_name"; public static final String ROLE_FUNCTION_LIST = "role_function_list"; - // login error message keys public static final String MESSAGE_KEY_LOGIN_ERROR_COOKIE_EMPTY = "login.error.hrid.empty"; @@ -265,7 +188,7 @@ public class SystemProperties { public static final String HB_DIALECT = "hb.dialect"; public static final String HB_SHOW_SQL = "hb.show_sql"; public static final String IDLE_CONNECTION_TEST_PERIOD = "hb.idle_connection_test_period"; - + // DataSource public static final String DB_DRIVER = "db.driver"; public static final String DB_CONNECTIONURL = "db.connectionURL"; @@ -333,7 +256,14 @@ public class SystemProperties { public static final String HTTP = "HTTP"; public static final String HTTPS = "HTTPS"; public static final String SSO_VALUE = "sso"; - + + // 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"; + public enum RESULT_ENUM { SUCCESS, FAILURE } @@ -342,10 +272,81 @@ public class SystemProperties { 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"; + public SystemProperties() { + super(); + } + + 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 + * Property 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. + * + * @param key + * Property key + * @return Property value; the empty string if the environment was not + * autowired, which should never happen. + * @throws IllegalStateException + * if the key is not found + */ + 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); + } - // 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/onap/portalsdk/core/util/UsageUtils.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/util/UsageUtils.java index faf410fc..569c2b87 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/util/UsageUtils.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/util/UsageUtils.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -40,8 +40,9 @@ package org.onap.portalsdk.core.util; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; -import java.util.HashMap; import java.util.Iterator; +import java.util.List; +import java.util.Map; import javax.servlet.http.HttpSession; @@ -49,62 +50,61 @@ import org.onap.portalsdk.core.command.UserRowBean; import org.onap.portalsdk.core.domain.User; public class UsageUtils { + + private UsageUtils() { + // Class has only static methods + } + @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"); + public static List<UserRowBean> getActiveUsers(Map activeUsers) { + ArrayList<UserRowBean> rows = new ArrayList<>(); + 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 + if (null == userBean) + continue; - 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())); - 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); - // - // 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)); - userRow.setLastAccess((lastAccessed / 60) + ":" + String.format("%02d", (lastAccessed % 60))); - userRow.setRemaining((minutesRemaining / 60) + ":" + String.format("%02d", (minutesRemaining % 60))); + rows.add(userRow); + } - rows.add(userRow); - } - - return rows; + return rows; } - + @SuppressWarnings("rawtypes") - public static ArrayList<UserRowBean> getActiveUsersAfterDelete(HashMap activeUsers, final java.lang.Object data) { - return getActiveUsers(deleteSession(activeUsers,data)); - + public static List<UserRowBean> getActiveUsersAfterDelete(Map 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); + private static Map deleteSession(Map 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/onap/portalsdk/core/util/YamlUtils.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/util/YamlUtils.java index 38206d55..38bd2075 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/util/YamlUtils.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/util/YamlUtils.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -38,7 +38,6 @@ package org.onap.portalsdk.core.util; import java.io.File; -import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; @@ -48,43 +47,34 @@ import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.representer.Representer; public class YamlUtils { - - static Yaml yaml; - - static { + private YamlUtils() { + // Class has only static methods + } + + private static Yaml yaml; + + static { Representer representer = new Representer(); - //representer.addClassTag(Domain.class, Tag.MAP); - - - yaml = new Yaml(representer); - + yaml = new Yaml(representer); } - - public static void writeYamlFile(String filePath, String fileName, - Map<String, Object> model) throws IOException { + + 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); + yaml.dump(model, writer); writer.close(); } - - public static String returnYaml( - Map<String, Object> model) throws IOException { - - return yaml.dump(model); - + + 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 { + public static Map<String, Object> readYamlFile(String filePath, String fileName) throws IOException { FileReader reader = new FileReader(filePath + File.separator + fileName); - - Map<String,Object> callFlowBs = (Map<String,Object>)yaml.load(reader); + 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/onap/portalsdk/core/web/socket/PeerBroadcastSocket.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/web/socket/PeerBroadcastSocket.java index e00e05b7..122f1333 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/web/socket/PeerBroadcastSocket.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/web/socket/PeerBroadcastSocket.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -56,14 +56,13 @@ public class PeerBroadcastSocket { private static final 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(); + private final static Map<String, Object> channelMap = new Hashtable<>(); + private final Map<String, String> sessionMap = new Hashtable<>(); + private final 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 { @@ -73,7 +72,7 @@ public class PeerBroadcastSocket { sessionMap.put(session.getId(), from.toString()); } } catch (Exception je) { - logger.error(EELFLoggerDelegate.errorLogger, "Failed to read value" + je.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, "Failed to read value", je); } try { @@ -82,24 +81,23 @@ public class PeerBroadcastSocket { return; Object toSessionObj = channelMap.get(to); if (toSessionObj != null) { - Session toSession = null; - toSession = (Session) toSessionObj; + Session toSession = (Session) toSessionObj; toSession.getBasicRemote().sendText(message); } } catch (Exception ex) { - logger.error(EELFLoggerDelegate.errorLogger, "Failed to send text" + ex.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, "Failed to send text", ex); } } catch (Exception ex) { - logger.error(EELFLoggerDelegate.errorLogger, "Failed" + ex.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, "Failed", ex); } } @OnOpen public void open(Session session) { - logger.info(EELFLoggerDelegate.debugLogger, "Channel opened"); + logger.debug(EELFLoggerDelegate.debugLogger, "Session opened {}", session); } @OnClose @@ -111,12 +109,12 @@ public class PeerBroadcastSocket { try { ((Session) sessObj).close(); } catch (IOException e) { - logger.error(EELFLoggerDelegate.errorLogger, "Failed to close" + e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, "Failed to close", e); } } channelMap.remove(channel); } - logger.info(EELFLoggerDelegate.debugLogger, "Channel closed"); + logger.debug(EELFLoggerDelegate.debugLogger, "Channel closed"); } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/web/socket/WebRTCSocket.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/web/socket/WebRTCSocket.java index 76cb3b8f..f65a07cc 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/web/socket/WebRTCSocket.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/web/socket/WebRTCSocket.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -46,116 +46,92 @@ import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; + 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"); + + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WebRTCSocket.class); + + private final static Map<String, Hashtable<String, Object[]>> channelMap = new Hashtable<String, Hashtable<String, Object[]>>(); + private final Map<String, String> sessionMap = new Hashtable<String, String>(); + private final ObjectMapper mapper = new ObjectMapper(); + + @OnMessage + public void message(String message, Session session) { + try { + @SuppressWarnings("unchecked") + Map<String, Object> jsonObject = mapper.readValue(message, Map.class); + try { + Object isOpen = jsonObject.get("open"); + if (isOpen != null && (Boolean) isOpen) { + 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"); - } + Hashtable<String, Object[]> sourceDestMap; + if (value == null) + sourceDestMap = new Hashtable<>(); + 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) { + logger.error(EELFLoggerDelegate.errorLogger, "mesage failed", je); + } + + try { + Object dataObj = jsonObject.get("data"); + if (dataObj == null) + return; + Map<String, Object> dataMapObj = (Map<String, Object>) dataObj; + String channel = null; + try { + Object channelObj = dataMapObj.get("sessionid"); + if (channelObj != null) + channel = (String) channelObj; + else + channel = (String) jsonObject.get("channel"); + } catch (Exception json) { + logger.error(EELFLoggerDelegate.errorLogger, "mesage failed", json); + } + + + Hashtable<String, Object[]> sourceDestMap = channelMap.get(channel); + if (sourceDestMap != null) + for (String id : sourceDestMap.keySet()) { + if (!id.equals(session.getId())) { + Session otherSession = (Session) (sourceDestMap.get(id))[0]; + if (otherSession.isOpen()) + otherSession.getBasicRemote().sendText(mapper.writeValueAsString(dataObj)); + } + + } + } catch (Exception je) { + logger.error(EELFLoggerDelegate.errorLogger, "mesage failed", je); + } + + } catch (Exception je) { + logger.error(EELFLoggerDelegate.errorLogger, "mesage failed", je); + } + } + + @OnOpen + public void open(Session session) { + logger.debug(EELFLoggerDelegate.debugLogger, "Session opened {}", session); + } + + @OnClose + public void close(Session session) { + String channel = sessionMap.get(session.getId()); + if (channel != null) { + channelMap.remove(channel); + } + logger.debug(EELFLoggerDelegate.debugLogger, "Channel closed"); + } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/web/support/AppUtils.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/web/support/AppUtils.java index f6655399..135fb4cf 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/web/support/AppUtils.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/web/support/AppUtils.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,19 +37,8 @@ */ package org.onap.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; @@ -59,112 +48,99 @@ import org.hibernate.Session; import org.onap.portalsdk.core.exception.SessionExpiredException; import org.onap.portalsdk.core.objectcache.AbstractCacheManager; import org.onap.portalsdk.core.service.DataAccessService; -import org.onap.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 DataAccessService dataAccessService; + + private static AbstractCacheManager cacheManager; + + private static boolean applicationLocked; - private static Hashtable feedback = new Hashtable(); - - private static DataSource datasource; + private static DataSource datasource; - public static DataSource getDatasource() { + public static DataSource getDatasource() { return datasource; } - - @Autowired + + public AppUtils() { + super(); + } + + @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) { + + public static HttpSession getSession(HttpServletRequest request) { + if (request != null) { + HttpSession session = request.getSession(false); + if (session == null) + throw new SessionExpiredException(); + else + return session; + } else { + throw new SessionExpiredException(); + } + } + + 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; - } + return cacheManager; + } + + public static boolean isCacheManagerAvailable() { + return getCacheManager() != null; + } + + public static boolean isApplicationLocked() { + return applicationLocked; + } public static DataAccessService getDataAccessService() { return dataAccessService; @@ -176,56 +152,50 @@ public class AppUtils { } 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.onap.portalsdk.core.domain.Lookup> lstResult = getLookupListNoCache(dbTable, dbValueCol, dbLabelCol, dbLabelCol + "='" + label.replaceAll("'", "''") + "'", ""); - if (lstResult == null) { - return ""; - } - if (lstResult.size() > 0) { - return ((org.onap.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.onap.portalsdk.core.domain.Lookup lookup = (org.onap.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 + applicationLocked = locked; + } + public static String getLookupValueByLabel(String label, String dbTable, String dbValueCol, String dbLabelCol) { + if (label == null || label.equals("")) { + return ""; + } + + List<org.onap.portalsdk.core.domain.Lookup> lstResult = getLookupListNoCache(dbTable, dbValueCol, dbLabelCol, + dbLabelCol + "='" + label.replaceAll("'", "''") + "'", ""); + if (lstResult == null) { + return ""; + } + if (!lstResult.isEmpty()) { + return ((org.onap.portalsdk.core.domain.Lookup) lstResult.toArray()[0]).getValue(); + } else { + return ""; + } + } - 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 - - + public static String getLookupValueByLabel(String label, List lookupList) { + if (label == null || "".equals(label)) + return ""; + if (lookupList == null || lookupList.size() == 0) + return ""; + + Iterator i = lookupList.iterator(); + while (i.hasNext()) { + org.onap.portalsdk.core.domain.Lookup lookup = (org.onap.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); + } -} // AppUtils + 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); + } + +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/web/support/ControllerProperties.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/web/support/ControllerProperties.java index c1c2f24a..31b810db 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/web/support/ControllerProperties.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/web/support/ControllerProperties.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -39,21 +39,21 @@ package org.onap.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"; + 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/onap/portalsdk/core/web/support/FeedbackMessage.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/web/support/FeedbackMessage.java index e2dadb50..013d153b 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/web/support/FeedbackMessage.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/web/support/FeedbackMessage.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -39,60 +39,60 @@ package org.onap.portalsdk.core.web.support; public class FeedbackMessage { - private String message; - private int messageType; - private boolean keyed; + 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 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_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 static final String DEFAULT_MESSAGE_SYSTEM_ADMINISTRATOR = "If the problem persists, please contact your Administrator."; - public FeedbackMessage() { - } + public FeedbackMessage() { + this(null); + } - public FeedbackMessage(String message) { - this(message, MESSAGE_TYPE_ERROR); - } + 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) { + this(message, messageType, false); + } - public FeedbackMessage(String message, int messageType, boolean keyed) { - this.message = message; - this.messageType = messageType; - this.keyed = keyed; - } + public FeedbackMessage(String message, int messageType, boolean keyed) { + this.message = message; + this.messageType = messageType; + this.keyed = keyed; + } - public String getMessage() { - return message; - } + public String getMessage() { + return message; + } - public int getMessageType() { - return messageType; - } + public int getMessageType() { + return messageType; + } - public boolean isKeyed() { - return keyed; - } + public boolean isKeyed() { + return keyed; + } - public void setMessage(String message) { - this.message = message; - } + public void setMessage(String message) { + this.message = message; + } - public void setMessageType(int messageType) { - this.messageType = messageType; - } - - public void setKeyed(boolean keyed) { - this.keyed = keyed; - } + 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/onap/portalsdk/core/web/support/JsonMessage.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/web/support/JsonMessage.java index 9b7a65ca..ce4cab3a 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/web/support/JsonMessage.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/web/support/JsonMessage.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -40,6 +40,7 @@ package org.onap.portalsdk.core.web.support; import java.io.PrintWriter; import java.io.StringWriter; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.onboarding.crossapi.PortalAPIResponse; import com.fasterxml.jackson.core.JsonProcessingException; @@ -47,26 +48,30 @@ import com.fasterxml.jackson.databind.ObjectMapper; public class JsonMessage { + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JsonMessage.class); + private String data; private String data2; private String data3; + public JsonMessage(String data) { super(); this.data = data; } - public JsonMessage(String data,String data2) { + + public JsonMessage(String data, String data2) { super(); this.data = data; this.data2 = data2; } - public JsonMessage(String data,String data2,String data3) { + public JsonMessage(String data, String data2, String data3) { super(); this.data = data; this.data2 = data2; this.data3 = data3; } - + public String getData() { return data; } @@ -74,20 +79,23 @@ public class JsonMessage { 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. * @@ -107,15 +115,16 @@ public class JsonMessage { try { json = new ObjectMapper().writeValueAsString(response); } catch (JsonProcessingException ex) { - // Truly should never, ever happen + // Truly should never happen + logger.error(EELFLoggerDelegate.errorLogger, "buildJsonResponse failed", ex); json = "{ \"status\": \"error\",\"message\":\"" + ex.toString() + "\" }"; } return json; } /** - * Builds JSON object with status of error and message containing stack - * trace for the specified throwable. + * 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 @@ -131,6 +140,5 @@ public class JsonMessage { t.printStackTrace(pw); return buildJsonResponse(false, sw.toString()); } - - + } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/web/support/MessagesList.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/web/support/MessagesList.java index a3ab7896..a1d3e276 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/web/support/MessagesList.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/web/support/MessagesList.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,74 +37,73 @@ */ package org.onap.portalsdk.core.web.support; -import java.util.*; +import java.util.ArrayList; +import java.util.List; public class MessagesList { - private boolean successMessageDisplayed = true; - private boolean includeCauseInCustomExceptions = false; + private boolean successMessageDisplayed = true; + private boolean includeCauseInCustomExceptions = false; - private List successMessages; - private List exceptionMessages; + private List successMessages; + private List exceptionMessages; - public MessagesList() { - setExceptionMessages(new ArrayList()); - setSuccessMessages(new ArrayList()); - } + public MessagesList() { + setExceptionMessages(new ArrayList()); + setSuccessMessages(new ArrayList()); + } - public MessagesList(boolean displaySuccess) { - this(); - setSuccessMessageDisplayed(displaySuccess); - } + public MessagesList(boolean displaySuccess) { + this(); + setSuccessMessageDisplayed(displaySuccess); + } - public List getExceptionMessages() { - return exceptionMessages; - } + public List getExceptionMessages() { + return exceptionMessages; + } - public List getSuccessMessages() { - return successMessages; - } + public List getSuccessMessages() { + return successMessages; + } - public boolean isSuccessMessageDisplayed() { - return successMessageDisplayed; - } + public boolean isSuccessMessageDisplayed() { + return successMessageDisplayed; + } - public boolean isIncludeCauseInCustomExceptions() { - return includeCauseInCustomExceptions; - } + public boolean isIncludeCauseInCustomExceptions() { + return includeCauseInCustomExceptions; + } + public void setExceptionMessages(List exceptionMessages) { + this.exceptionMessages = exceptionMessages; + } - public void setExceptionMessages(List exceptionMessages) { - this.exceptionMessages = exceptionMessages; - } + public void setSuccessMessages(List successMessages) { + this.successMessages = successMessages; + } - public void setSuccessMessages(List successMessages) { - this.successMessages = successMessages; - } + public void setSuccessMessageDisplayed(boolean successMessageDisplayed) { + this.successMessageDisplayed = successMessageDisplayed; + } - public void setSuccessMessageDisplayed(boolean successMessageDisplayed) { - this.successMessageDisplayed = successMessageDisplayed; - } + public void setIncludeCauseInCustomExceptions(boolean includeCauseInCustomExceptions) { + this.includeCauseInCustomExceptions = includeCauseInCustomExceptions; + } - 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 void addSuccessMessage(FeedbackMessage message) { - getSuccessMessages().add(message); - } + public boolean hasExceptionMessages() { + return !getExceptionMessages().isEmpty(); + } - public void addExceptionMessage(FeedbackMessage message) { - getExceptionMessages().add(message); - } - - public boolean hasExceptionMessages() { - return!getExceptionMessages().isEmpty(); - } - - public boolean hasSuccessMessages() { - return!getSuccessMessages().isEmpty(); - } + public boolean hasSuccessMessages() { + return !getSuccessMessages().isEmpty(); + } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/web/support/UserUtils.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/web/support/UserUtils.java index 98e437d9..5395521b 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/web/support/UserUtils.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/web/support/UserUtils.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -44,6 +44,7 @@ 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; @@ -61,9 +62,7 @@ import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.menu.MenuBuilder; import org.onap.portalsdk.core.restful.domain.EcompRole; import org.onap.portalsdk.core.restful.domain.EcompUser; -import org.onap.portalsdk.core.service.DataAccessService; import org.onap.portalsdk.core.util.SystemProperties; -import org.springframework.beans.factory.annotation.Autowired; @SuppressWarnings("rawtypes") public class UserUtils { @@ -72,10 +71,8 @@ public class UserUtils { 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 , List<RoleFunction> roleFunctionList) { + Set businessDirectMenuData, String loginMethod, List<RoleFunction> roleFunctionList) { HttpSession session = request.getSession(true); UserUtils.clearUserSession(request); // let's clear the current user @@ -97,7 +94,7 @@ public class UserUtils { try { licenseVarificationFlag = (Integer) context.getAttribute("licenseVerification"); } catch (Exception e) { - logger.error(EELFLoggerDelegate.debugLogger, "Error while get license varification " + e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, "setUserSession failed on license verification", e); } String displayName = ""; if (SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME) != null) @@ -146,14 +143,12 @@ public class UserUtils { @SuppressWarnings("unchecked") public static Set getRoleFunctions(HttpServletRequest request) { - HashSet roleFunctions = null; -// HashSet<RoleFunction> rolefun = null; HttpSession session = request.getSession(); - roleFunctions = (HashSet) session + HashSet roleFunctions = (HashSet) session .getAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME)); if (roleFunctions == null) { - HashMap roles = getRoles(request); + Map roles = getRoles(request); roleFunctions = new HashSet(); Iterator i = roles.keySet().iterator(); @@ -175,12 +170,10 @@ public class UserUtils { return roleFunctions; } - public static HashMap getRoles(HttpServletRequest request) { - HashMap roles = null; - + public static Map getRoles(HttpServletRequest request) { // HttpSession session = request.getSession(); HttpSession session = AppUtils.getSession(request); - roles = (HashMap) session.getAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME)); + Map roles = (Map) session.getAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME)); // if roles are not already cached, let's grab them from the user // session @@ -208,7 +201,7 @@ public class UserUtils { } @SuppressWarnings("unchecked") - public static HashMap getAllUserRoles(User user) { + public static Map getAllUserRoles(User user) { HashMap roles = new HashMap(); Iterator i = user.getRoles().iterator(); @@ -228,9 +221,9 @@ public class UserUtils { } @SuppressWarnings("unchecked") - private static void addChildRoles(Role role, HashMap roles) { + private static void addChildRoles(Role role, Map roles) { Set childRoles = role.getChildRoles(); - if (childRoles != null && childRoles.size() > 0) { + if (childRoles != null && !childRoles.isEmpty()) { Iterator j = childRoles.iterator(); while (j.hasNext()) { Role childRole = (Role) j.next(); @@ -243,8 +236,6 @@ public class UserUtils { } - - public static boolean hasRole(HttpServletRequest request, String roleKey) { return getRoles(request).keySet().contains(new Long(roleKey)); } @@ -268,27 +259,15 @@ public class UserUtils { .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) { + if (request != null && getUserSession(request) != null) userId = getUserSession(request).getId(); - } - } + return userId; } @@ -313,8 +292,7 @@ public class UserUtils { } /** - * Gets the full URL of the request by joining the request and any query - * string. + * 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 @@ -334,8 +312,8 @@ public class UserUtils { } /** - * Gets or generates a request ID by searching for header X-ECOMP-RequestID. - * If not found, generates a new random UUID. + * 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 @@ -346,7 +324,7 @@ public class UserUtils { String requestId = ""; try { while (headerNames.hasMoreElements()) { - String headerName = (String) headerNames.nextElement(); + String headerName = headerNames.nextElement(); if (logger.isTraceEnabled()) logger.trace(EELFLoggerDelegate.debugLogger, "getRequestId: header {} = {}", headerName, request.getHeader(headerName)); @@ -386,7 +364,7 @@ public class UserUtils { userJson.setOrgId(user.getOrgId()); userJson.setPhone(user.getPhone()); userJson.setOrgUserId(user.getOrgUserId()); - Set<EcompRole> ecompRoles = new TreeSet<EcompRole>(); + Set<EcompRole> ecompRoles = new TreeSet<>(); for (Role role : user.getRoles()) { ecompRoles.add(convertToEcompRole(role)); } @@ -408,6 +386,4 @@ public class UserUtils { return ecompRole; } - } - - +} |